RC6Engine.cs 11 KB

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