RC532Engine.cs 8.9 KB

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