scrypt.ts 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. import { number as assertNumber } from './_assert.js';
  2. import { sha256 } from './sha256.js';
  3. import { pbkdf2 } from './pbkdf2.js';
  4. import { rotl, asyncLoop, checkOpts, Input, u32, isLE, byteSwap32 } from './utils.js';
  5. // RFC 7914 Scrypt KDF
  6. // The main Scrypt loop: uses Salsa extensively.
  7. // Six versions of the function were tried, this is the fastest one.
  8. // prettier-ignore
  9. function XorAndSalsa(
  10. prev: Uint32Array,
  11. pi: number,
  12. input: Uint32Array,
  13. ii: number,
  14. out: Uint32Array,
  15. oi: number
  16. ) {
  17. // Based on https://cr.yp.to/salsa20.html
  18. // Xor blocks
  19. let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
  20. let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
  21. let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
  22. let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
  23. let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
  24. let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
  25. let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
  26. let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
  27. // Save state to temporary variables (salsa)
  28. let x00 = y00, x01 = y01, x02 = y02, x03 = y03,
  29. x04 = y04, x05 = y05, x06 = y06, x07 = y07,
  30. x08 = y08, x09 = y09, x10 = y10, x11 = y11,
  31. x12 = y12, x13 = y13, x14 = y14, x15 = y15;
  32. // Main loop (salsa)
  33. for (let i = 0; i < 8; i += 2) {
  34. x04 ^= rotl(x00 + x12 | 0, 7); x08 ^= rotl(x04 + x00 | 0, 9);
  35. x12 ^= rotl(x08 + x04 | 0, 13); x00 ^= rotl(x12 + x08 | 0, 18);
  36. x09 ^= rotl(x05 + x01 | 0, 7); x13 ^= rotl(x09 + x05 | 0, 9);
  37. x01 ^= rotl(x13 + x09 | 0, 13); x05 ^= rotl(x01 + x13 | 0, 18);
  38. x14 ^= rotl(x10 + x06 | 0, 7); x02 ^= rotl(x14 + x10 | 0, 9);
  39. x06 ^= rotl(x02 + x14 | 0, 13); x10 ^= rotl(x06 + x02 | 0, 18);
  40. x03 ^= rotl(x15 + x11 | 0, 7); x07 ^= rotl(x03 + x15 | 0, 9);
  41. x11 ^= rotl(x07 + x03 | 0, 13); x15 ^= rotl(x11 + x07 | 0, 18);
  42. x01 ^= rotl(x00 + x03 | 0, 7); x02 ^= rotl(x01 + x00 | 0, 9);
  43. x03 ^= rotl(x02 + x01 | 0, 13); x00 ^= rotl(x03 + x02 | 0, 18);
  44. x06 ^= rotl(x05 + x04 | 0, 7); x07 ^= rotl(x06 + x05 | 0, 9);
  45. x04 ^= rotl(x07 + x06 | 0, 13); x05 ^= rotl(x04 + x07 | 0, 18);
  46. x11 ^= rotl(x10 + x09 | 0, 7); x08 ^= rotl(x11 + x10 | 0, 9);
  47. x09 ^= rotl(x08 + x11 | 0, 13); x10 ^= rotl(x09 + x08 | 0, 18);
  48. x12 ^= rotl(x15 + x14 | 0, 7); x13 ^= rotl(x12 + x15 | 0, 9);
  49. x14 ^= rotl(x13 + x12 | 0, 13); x15 ^= rotl(x14 + x13 | 0, 18);
  50. }
  51. // Write output (salsa)
  52. out[oi++] = (y00 + x00) | 0; out[oi++] = (y01 + x01) | 0;
  53. out[oi++] = (y02 + x02) | 0; out[oi++] = (y03 + x03) | 0;
  54. out[oi++] = (y04 + x04) | 0; out[oi++] = (y05 + x05) | 0;
  55. out[oi++] = (y06 + x06) | 0; out[oi++] = (y07 + x07) | 0;
  56. out[oi++] = (y08 + x08) | 0; out[oi++] = (y09 + x09) | 0;
  57. out[oi++] = (y10 + x10) | 0; out[oi++] = (y11 + x11) | 0;
  58. out[oi++] = (y12 + x12) | 0; out[oi++] = (y13 + x13) | 0;
  59. out[oi++] = (y14 + x14) | 0; out[oi++] = (y15 + x15) | 0;
  60. }
  61. function BlockMix(input: Uint32Array, ii: number, out: Uint32Array, oi: number, r: number) {
  62. // The block B is r 128-byte chunks (which is equivalent of 2r 64-byte chunks)
  63. let head = oi + 0;
  64. let tail = oi + 16 * r;
  65. for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i]; // X ← B[2r−1]
  66. for (let i = 0; i < r; i++, head += 16, ii += 16) {
  67. // We write odd & even Yi at same time. Even: 0bXXXXX0 Odd: 0bXXXXX1
  68. XorAndSalsa(out, tail, input, ii, out, head); // head[i] = Salsa(blockIn[2*i] ^ tail[i-1])
  69. if (i > 0) tail += 16; // First iteration overwrites tmp value in tail
  70. XorAndSalsa(out, head, input, (ii += 16), out, tail); // tail[i] = Salsa(blockIn[2*i+1] ^ head[i])
  71. }
  72. }
  73. export type ScryptOpts = {
  74. N: number; // cost factor
  75. r: number; // block size
  76. p: number; // parallelization
  77. dkLen?: number; // key length
  78. asyncTick?: number; // block execution max time
  79. maxmem?: number;
  80. onProgress?: (progress: number) => void;
  81. };
  82. // Common prologue and epilogue for sync/async functions
  83. function scryptInit(password: Input, salt: Input, _opts?: ScryptOpts) {
  84. // Maxmem - 1GB+1KB by default
  85. const opts = checkOpts(
  86. {
  87. dkLen: 32,
  88. asyncTick: 10,
  89. maxmem: 1024 ** 3 + 1024,
  90. },
  91. _opts
  92. );
  93. const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = opts;
  94. assertNumber(N);
  95. assertNumber(r);
  96. assertNumber(p);
  97. assertNumber(dkLen);
  98. assertNumber(asyncTick);
  99. assertNumber(maxmem);
  100. if (onProgress !== undefined && typeof onProgress !== 'function')
  101. throw new Error('progressCb should be function');
  102. const blockSize = 128 * r;
  103. const blockSize32 = blockSize / 4;
  104. if (N <= 1 || (N & (N - 1)) !== 0 || N >= 2 ** (blockSize / 8) || N > 2 ** 32) {
  105. // NOTE: we limit N to be less than 2**32 because of 32 bit variant of Integrify function
  106. // There is no JS engines that allows alocate more than 4GB per single Uint8Array for now, but can change in future.
  107. throw new Error(
  108. 'Scrypt: N must be larger than 1, a power of 2, less than 2^(128 * r / 8) and less than 2^32'
  109. );
  110. }
  111. if (p < 0 || p > ((2 ** 32 - 1) * 32) / blockSize) {
  112. throw new Error(
  113. 'Scrypt: p must be a positive integer less than or equal to ((2^32 - 1) * 32) / (128 * r)'
  114. );
  115. }
  116. if (dkLen < 0 || dkLen > (2 ** 32 - 1) * 32) {
  117. throw new Error(
  118. 'Scrypt: dkLen should be positive integer less than or equal to (2^32 - 1) * 32'
  119. );
  120. }
  121. const memUsed = blockSize * (N + p);
  122. if (memUsed > maxmem) {
  123. throw new Error(
  124. `Scrypt: parameters too large, ${memUsed} (128 * r * (N + p)) > ${maxmem} (maxmem)`
  125. );
  126. }
  127. // [B0...Bp−1] ← PBKDF2HMAC-SHA256(Passphrase, Salt, 1, blockSize*ParallelizationFactor)
  128. // Since it has only one iteration there is no reason to use async variant
  129. const B = pbkdf2(sha256, password, salt, { c: 1, dkLen: blockSize * p });
  130. const B32 = u32(B);
  131. // Re-used between parallel iterations. Array(iterations) of B
  132. const V = u32(new Uint8Array(blockSize * N));
  133. const tmp = u32(new Uint8Array(blockSize));
  134. let blockMixCb = () => {};
  135. if (onProgress) {
  136. const totalBlockMix = 2 * N * p;
  137. // Invoke callback if progress changes from 10.01 to 10.02
  138. // Allows to draw smooth progress bar on up to 8K screen
  139. const callbackPer = Math.max(Math.floor(totalBlockMix / 10000), 1);
  140. let blockMixCnt = 0;
  141. blockMixCb = () => {
  142. blockMixCnt++;
  143. if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix))
  144. onProgress(blockMixCnt / totalBlockMix);
  145. };
  146. }
  147. return { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick };
  148. }
  149. function scryptOutput(
  150. password: Input,
  151. dkLen: number,
  152. B: Uint8Array,
  153. V: Uint32Array,
  154. tmp: Uint32Array
  155. ) {
  156. const res = pbkdf2(sha256, password, B, { c: 1, dkLen });
  157. B.fill(0);
  158. V.fill(0);
  159. tmp.fill(0);
  160. return res;
  161. }
  162. /**
  163. * Scrypt KDF from RFC 7914.
  164. * @param password - pass
  165. * @param salt - salt
  166. * @param opts - parameters
  167. * - `N` is cpu/mem work factor (power of 2 e.g. 2**18)
  168. * - `r` is block size (8 is common), fine-tunes sequential memory read size and performance
  169. * - `p` is parallelization factor (1 is common)
  170. * - `dkLen` is output key length in bytes e.g. 32.
  171. * - `asyncTick` - (default: 10) max time in ms for which async function can block execution
  172. * - `maxmem` - (default: `1024 ** 3 + 1024` aka 1GB+1KB). A limit that the app could use for scrypt
  173. * - `onProgress` - callback function that would be executed for progress report
  174. * @returns Derived key
  175. */
  176. export function scrypt(password: Input, salt: Input, opts: ScryptOpts) {
  177. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb } = scryptInit(
  178. password,
  179. salt,
  180. opts
  181. );
  182. if (!isLE) byteSwap32(B32);
  183. for (let pi = 0; pi < p; pi++) {
  184. const Pi = blockSize32 * pi;
  185. for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]
  186. for (let i = 0, pos = 0; i < N - 1; i++) {
  187. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  188. blockMixCb();
  189. }
  190. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  191. blockMixCb();
  192. for (let i = 0; i < N; i++) {
  193. // First u32 of the last 64-byte block (u32 is LE)
  194. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  195. for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  196. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  197. blockMixCb();
  198. }
  199. }
  200. if (!isLE) byteSwap32(B32);
  201. return scryptOutput(password, dkLen, B, V, tmp);
  202. }
  203. /**
  204. * Scrypt KDF from RFC 7914.
  205. */
  206. export async function scryptAsync(password: Input, salt: Input, opts: ScryptOpts) {
  207. const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(
  208. password,
  209. salt,
  210. opts
  211. );
  212. if (!isLE) byteSwap32(B32);
  213. for (let pi = 0; pi < p; pi++) {
  214. const Pi = blockSize32 * pi;
  215. for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i]; // V[0] = B[i]
  216. let pos = 0;
  217. await asyncLoop(N - 1, asyncTick, () => {
  218. BlockMix(V, pos, V, (pos += blockSize32), r); // V[i] = BlockMix(V[i-1]);
  219. blockMixCb();
  220. });
  221. BlockMix(V, (N - 1) * blockSize32, B32, Pi, r); // Process last element
  222. blockMixCb();
  223. await asyncLoop(N, asyncTick, () => {
  224. // First u32 of the last 64-byte block (u32 is LE)
  225. const j = B32[Pi + blockSize32 - 16] % N; // j = Integrify(X) % iterations
  226. for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k]; // tmp = B ^ V[j]
  227. BlockMix(tmp, 0, B32, Pi, r); // B = BlockMix(B ^ V[j])
  228. blockMixCb();
  229. });
  230. }
  231. if (!isLE) byteSwap32(B32);
  232. return scryptOutput(password, dkLen, B, V, tmp);
  233. }