RC564Engine.cs 9.1 KB

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