SCrypt.cs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. #if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR)
  2. #pragma warning disable
  3. using System;
  4. using System.Diagnostics;
  5. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Digests;
  6. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Engines;
  7. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Parameters;
  8. using BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Utilities;
  9. using BestHTTP.SecureProtocol.Org.BouncyCastle.Utilities;
  10. namespace BestHTTP.SecureProtocol.Org.BouncyCastle.Crypto.Generators
  11. {
  12. /// <summary>Implementation of the scrypt a password-based key derivation function.</summary>
  13. /// <remarks>
  14. /// Scrypt was created by Colin Percival and is specified in
  15. /// <a href="http://tools.ietf.org/html/draft-josefsson-scrypt-kdf-01">draft-josefsson-scrypt-kd</a>.
  16. /// </remarks>
  17. public class SCrypt
  18. {
  19. /// <summary>Generate a key using the scrypt key derivation function.</summary>
  20. /// <param name="P">the bytes of the pass phrase.</param>
  21. /// <param name="S">the salt to use for this invocation.</param>
  22. /// <param name="N">CPU/Memory cost parameter. Must be larger than 1, a power of 2 and less than
  23. /// <code>2^(128 * r / 8)</code>.</param>
  24. /// <param name="r">the block size, must be >= 1.</param>
  25. /// <param name="p">Parallelization parameter. Must be a positive integer less than or equal to
  26. /// <code>Int32.MaxValue / (128 * r * 8)</code>.</param>
  27. /// <param name="dkLen">the length of the key to generate.</param>
  28. /// <returns>the generated key.</returns>
  29. public static byte[] Generate(byte[] P, byte[] S, int N, int r, int p, int dkLen)
  30. {
  31. if (P == null)
  32. throw new ArgumentNullException("Passphrase P must be provided.");
  33. if (S == null)
  34. throw new ArgumentNullException("Salt S must be provided.");
  35. if (N <= 1 || !IsPowerOf2(N))
  36. throw new ArgumentException("Cost parameter N must be > 1 and a power of 2.");
  37. // Only value of r that cost (as an int) could be exceeded for is 1
  38. if (r == 1 && N >= 65536)
  39. throw new ArgumentException("Cost parameter N must be > 1 and < 65536.");
  40. if (r < 1)
  41. throw new ArgumentException("Block size r must be >= 1.");
  42. int maxParallel = Int32.MaxValue / (128 * r * 8);
  43. if (p < 1 || p > maxParallel)
  44. {
  45. throw new ArgumentException("Parallelisation parameter p must be >= 1 and <= " + maxParallel
  46. + " (based on block size r of " + r + ")");
  47. }
  48. if (dkLen < 1)
  49. throw new ArgumentException("Generated key length dkLen must be >= 1.");
  50. return MFcrypt(P, S, N, r, p, dkLen);
  51. }
  52. private static byte[] MFcrypt(byte[] P, byte[] S, int N, int r, int p, int dkLen)
  53. {
  54. int MFLenBytes = r * 128;
  55. byte[] bytes = SingleIterationPBKDF2(P, S, p * MFLenBytes);
  56. uint[] B = null;
  57. try
  58. {
  59. int BLen = bytes.Length >> 2;
  60. B = new uint[BLen];
  61. Pack.LE_To_UInt32(bytes, 0, B);
  62. /*
  63. * Chunk memory allocations; We choose 'd' so that there will be 2**d chunks, each not
  64. * larger than 32KiB, except that the minimum chunk size is 2 * r * 32.
  65. */
  66. int d = 0, total = N * r;
  67. while ((N - d) > 2 && total > (1 << 10))
  68. {
  69. ++d;
  70. total >>= 1;
  71. }
  72. int MFLenWords = MFLenBytes >> 2;
  73. for (int BOff = 0; BOff < BLen; BOff += MFLenWords)
  74. {
  75. // TODO These can be done in parallel threads
  76. SMix(B, BOff, N, d, r);
  77. }
  78. Pack.UInt32_To_LE(B, bytes, 0);
  79. return SingleIterationPBKDF2(P, bytes, dkLen);
  80. }
  81. finally
  82. {
  83. ClearAll(bytes, B);
  84. }
  85. }
  86. private static byte[] SingleIterationPBKDF2(byte[] P, byte[] S, int dkLen)
  87. {
  88. PbeParametersGenerator pGen = new Pkcs5S2ParametersGenerator(new Sha256Digest());
  89. pGen.Init(P, S, 1);
  90. KeyParameter key = (KeyParameter)pGen.GenerateDerivedMacParameters(dkLen * 8);
  91. return key.GetKey();
  92. }
  93. private static void SMix(uint[] B, int BOff, int N, int d, int r)
  94. {
  95. int powN = Integers.NumberOfTrailingZeros(N);
  96. int blocksPerChunk = N >> d;
  97. int chunkCount = 1 << d, chunkMask = blocksPerChunk - 1, chunkPow = powN - d;
  98. int BCount = r * 32;
  99. uint[] blockX1 = new uint[16];
  100. uint[] blockX2 = new uint[16];
  101. uint[] blockY = new uint[BCount];
  102. uint[] X = new uint[BCount];
  103. uint[][] VV = new uint[chunkCount][];
  104. try
  105. {
  106. Array.Copy(B, BOff, X, 0, BCount);
  107. for (int c = 0; c < chunkCount; ++c)
  108. {
  109. uint[] V = new uint[blocksPerChunk * BCount];
  110. VV[c] = V;
  111. int off = 0;
  112. for (int i = 0; i < blocksPerChunk; i += 2)
  113. {
  114. Array.Copy(X, 0, V, off, BCount);
  115. off += BCount;
  116. BlockMix(X, blockX1, blockX2, blockY, r);
  117. Array.Copy(blockY, 0, V, off, BCount);
  118. off += BCount;
  119. BlockMix(blockY, blockX1, blockX2, X, r);
  120. }
  121. }
  122. uint mask = (uint)N - 1;
  123. for (int i = 0; i < N; ++i)
  124. {
  125. int j = (int)(X[BCount - 16] & mask);
  126. uint[] V = VV[j >> chunkPow];
  127. int VOff = (j & chunkMask) * BCount;
  128. Array.Copy(V, VOff, blockY, 0, BCount);
  129. Xor(blockY, X, 0, blockY);
  130. BlockMix(blockY, blockX1, blockX2, X, r);
  131. }
  132. Array.Copy(X, 0, B, BOff, BCount);
  133. }
  134. finally
  135. {
  136. ClearAll(VV);
  137. ClearAll(X, blockX1, blockX2, blockY);
  138. }
  139. }
  140. private static void BlockMix(uint[] B, uint[] X1, uint[] X2, uint[] Y, int r)
  141. {
  142. Array.Copy(B, B.Length - 16, X1, 0, 16);
  143. int BOff = 0, YOff = 0, halfLen = B.Length >> 1;
  144. for (int i = 2 * r; i > 0; --i)
  145. {
  146. Xor(X1, B, BOff, X2);
  147. Salsa20Engine.SalsaCore(8, X2, X1);
  148. Array.Copy(X1, 0, Y, YOff, 16);
  149. YOff = halfLen + BOff - YOff;
  150. BOff += 16;
  151. }
  152. }
  153. private static void Xor(uint[] a, uint[] b, int bOff, uint[] output)
  154. {
  155. for (int i = output.Length - 1; i >= 0; --i)
  156. {
  157. output[i] = a[i] ^ b[bOff + i];
  158. }
  159. }
  160. private static void Clear(Array array)
  161. {
  162. if (array != null)
  163. {
  164. Array.Clear(array, 0, array.Length);
  165. }
  166. }
  167. private static void ClearAll(params Array[] arrays)
  168. {
  169. foreach (Array array in arrays)
  170. {
  171. Clear(array);
  172. }
  173. }
  174. // note: we know X is non-zero
  175. private static bool IsPowerOf2(int x)
  176. {
  177. Debug.Assert(x != 0);
  178. return (x & (x - 1)) == 0;
  179. }
  180. }
  181. }
  182. #pragma warning restore
  183. #endif