RC564Engine.cs 9.2 KB

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