SCrypt.cs 8.9 KB

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