RC532Engine.cs 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. #if UNITY_WSA && !UNITY_EDITOR && !ENABLE_IL2CPP
  5. using System.TypeFix;
  6. #endif
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  9. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines
  10. {
  11. /**
  12. * The specification for RC5 came from the <code>RC5 Encryption Algorithm</code>
  13. * publication in RSA CryptoBytes, Spring of 1995.
  14. * <em>http://www.rsasecurity.com/rsalabs/cryptobytes</em>.
  15. * <p>
  16. * This implementation has a word size of 32 bits.</p>
  17. */
  18. public class RC532Engine
  19. : IBlockCipher
  20. {
  21. /*
  22. * the number of rounds to perform
  23. */
  24. private int _noRounds;
  25. /*
  26. * the expanded key array of size 2*(rounds + 1)
  27. */
  28. private int [] _S;
  29. /*
  30. * our "magic constants" for 32 32
  31. *
  32. * Pw = Odd((e-2) * 2^wordsize)
  33. * Qw = Odd((o-2) * 2^wordsize)
  34. *
  35. * where e is the base of natural logarithms (2.718281828...)
  36. * and o is the golden ratio (1.61803398...)
  37. */
  38. private static readonly int P32 = unchecked((int) 0xb7e15163);
  39. private static readonly int Q32 = unchecked((int) 0x9e3779b9);
  40. private bool forEncryption;
  41. /**
  42. * Create an instance of the RC5 encryption algorithm
  43. * and set some defaults
  44. */
  45. public RC532Engine()
  46. {
  47. _noRounds = 12; // the default
  48. // _S = null;
  49. }
  50. public virtual string AlgorithmName
  51. {
  52. get { return "RC5-32"; }
  53. }
  54. public virtual bool IsPartialBlockOkay
  55. {
  56. get { return false; }
  57. }
  58. public virtual int GetBlockSize()
  59. {
  60. return 2 * 4;
  61. }
  62. /**
  63. * initialise a RC5-32 cipher.
  64. *
  65. * @param forEncryption whether or not we are for encryption.
  66. * @param parameters the parameters required to set up the cipher.
  67. * @exception ArgumentException if the parameters argument is
  68. * inappropriate.
  69. */
  70. public virtual void Init(
  71. bool forEncryption,
  72. ICipherParameters parameters)
  73. {
  74. if (typeof(RC5Parameters).IsInstanceOfType(parameters))
  75. {
  76. RC5Parameters p = (RC5Parameters)parameters;
  77. _noRounds = p.Rounds;
  78. SetKey(p.GetKey());
  79. }
  80. else if (typeof(KeyParameter).IsInstanceOfType(parameters))
  81. {
  82. KeyParameter p = (KeyParameter)parameters;
  83. SetKey(p.GetKey());
  84. }
  85. else
  86. {
  87. throw new ArgumentException("invalid parameter passed to RC532 init - " + BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities.Platform.GetTypeName(parameters));
  88. }
  89. this.forEncryption = forEncryption;
  90. }
  91. public virtual int ProcessBlock(
  92. byte[] input,
  93. int inOff,
  94. byte[] output,
  95. int outOff)
  96. {
  97. return (forEncryption)
  98. ? EncryptBlock(input, inOff, output, outOff)
  99. : DecryptBlock(input, inOff, output, outOff);
  100. }
  101. public virtual void Reset()
  102. {
  103. }
  104. /**
  105. * Re-key the cipher.
  106. *
  107. * @param key the key to be used
  108. */
  109. private void SetKey(
  110. byte[] key)
  111. {
  112. //
  113. // KEY EXPANSION:
  114. //
  115. // There are 3 phases to the key expansion.
  116. //
  117. // Phase 1:
  118. // Copy the secret key K[0...b-1] into an array L[0..c-1] of
  119. // c = ceil(b/u), where u = 32/8 in little-endian order.
  120. // In other words, we fill up L using u consecutive key bytes
  121. // of K. Any unfilled byte positions in L are zeroed. In the
  122. // case that b = c = 0, set c = 1 and L[0] = 0.
  123. //
  124. int[] L = new int[(key.Length + (4 - 1)) / 4];
  125. for (int i = 0; i != key.Length; i++)
  126. {
  127. L[i / 4] += (key[i] & 0xff) << (8 * (i % 4));
  128. }
  129. //
  130. // Phase 2:
  131. // Initialize S to a particular fixed pseudo-random bit pattern
  132. // using an arithmetic progression modulo 2^wordsize determined
  133. // by the magic numbers, Pw & Qw.
  134. //
  135. _S = new int[2*(_noRounds + 1)];
  136. _S[0] = P32;
  137. for (int i=1; i < _S.Length; i++)
  138. {
  139. _S[i] = (_S[i-1] + Q32);
  140. }
  141. //
  142. // Phase 3:
  143. // Mix in the user's secret key in 3 passes over the arrays S & L.
  144. // The max of the arrays sizes is used as the loop control
  145. //
  146. int iter;
  147. if (L.Length > _S.Length)
  148. {
  149. iter = 3 * L.Length;
  150. }
  151. else
  152. {
  153. iter = 3 * _S.Length;
  154. }
  155. int A = 0, B = 0;
  156. int ii = 0, jj = 0;
  157. for (int k = 0; k < iter; k++)
  158. {
  159. A = _S[ii] = RotateLeft(_S[ii] + A + B, 3);
  160. B = L[jj] = RotateLeft( L[jj] + A + B, A+B);
  161. ii = (ii+1) % _S.Length;
  162. jj = (jj+1) % L.Length;
  163. }
  164. }
  165. /**
  166. * Encrypt the given block starting at the given offset and place
  167. * the result in the provided buffer starting at the given offset.
  168. *
  169. * @param in in byte buffer containing data to encrypt
  170. * @param inOff offset into src buffer
  171. * @param out out buffer where encrypted data is written
  172. * @param outOff offset into out buffer
  173. */
  174. private int EncryptBlock(
  175. byte[] input,
  176. int inOff,
  177. byte[] outBytes,
  178. int outOff)
  179. {
  180. int A = BytesToWord(input, inOff) + _S[0];
  181. int B = BytesToWord(input, inOff + 4) + _S[1];
  182. for (int i = 1; i <= _noRounds; i++)
  183. {
  184. A = RotateLeft(A ^ B, B) + _S[2*i];
  185. B = RotateLeft(B ^ A, A) + _S[2*i+1];
  186. }
  187. WordToBytes(A, outBytes, outOff);
  188. WordToBytes(B, outBytes, outOff + 4);
  189. return 2 * 4;
  190. }
  191. private int DecryptBlock(
  192. byte[] input,
  193. int inOff,
  194. byte[] outBytes,
  195. int outOff)
  196. {
  197. int A = BytesToWord(input, inOff);
  198. int B = BytesToWord(input, inOff + 4);
  199. for (int i = _noRounds; i >= 1; i--)
  200. {
  201. B = RotateRight(B - _S[2*i+1], A) ^ A;
  202. A = RotateRight(A - _S[2*i], B) ^ B;
  203. }
  204. WordToBytes(A - _S[0], outBytes, outOff);
  205. WordToBytes(B - _S[1], outBytes, outOff + 4);
  206. return 2 * 4;
  207. }
  208. //////////////////////////////////////////////////////////////
  209. //
  210. // PRIVATE Helper Methods
  211. //
  212. //////////////////////////////////////////////////////////////
  213. /**
  214. * Perform a left "spin" of the word. The rotation of the given
  215. * word <em>x</em> is rotated left by <em>y</em> bits.
  216. * Only the <em>lg(32)</em> low-order bits of <em>y</em>
  217. * are used to determine the rotation amount. Here it is
  218. * assumed that the wordsize used is a power of 2.
  219. *
  220. * @param x word to rotate
  221. * @param y number of bits to rotate % 32
  222. */
  223. private int RotateLeft(int x, int y) {
  224. return ((int) ( (uint) (x << (y & (32-1))) |
  225. ((uint) x >> (32 - (y & (32-1)))) )
  226. );
  227. }
  228. /**
  229. * Perform a right "spin" of the word. The rotation of the given
  230. * word <em>x</em> is rotated left by <em>y</em> bits.
  231. * Only the <em>lg(32)</em> low-order bits of <em>y</em>
  232. * are used to determine the rotation amount. Here it is
  233. * assumed that the wordsize used is a power of 2.
  234. *
  235. * @param x word to rotate
  236. * @param y number of bits to rotate % 32
  237. */
  238. private int RotateRight(int x, int y) {
  239. return ((int) ( ((uint) x >> (y & (32-1))) |
  240. (uint) (x << (32 - (y & (32-1)))) )
  241. );
  242. }
  243. private int BytesToWord(
  244. byte[] src,
  245. int srcOff)
  246. {
  247. return (src[srcOff] & 0xff) | ((src[srcOff + 1] & 0xff) << 8)
  248. | ((src[srcOff + 2] & 0xff) << 16) | ((src[srcOff + 3] & 0xff) << 24);
  249. }
  250. private void WordToBytes(
  251. int word,
  252. byte[] dst,
  253. int dstOff)
  254. {
  255. dst[dstOff] = (byte)word;
  256. dst[dstOff + 1] = (byte)(word >> 8);
  257. dst[dstOff + 2] = (byte)(word >> 16);
  258. dst[dstOff + 3] = (byte)(word >> 24);
  259. }
  260. }
  261. }
  262. #pragma warning restore
  263. #endif