RC6Engine.cs 11 KB

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