@decryption/hashes 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +75 -0
  3. package/_blake.d.ts +20 -0
  4. package/_blake.js +56 -0
  5. package/_md.d.ts +98 -0
  6. package/_md.js +207 -0
  7. package/_u64.d.ts +62 -0
  8. package/_u64.js +106 -0
  9. package/argon2.d.ts +111 -0
  10. package/argon2.js +525 -0
  11. package/blake1.d.ts +155 -0
  12. package/blake1.js +599 -0
  13. package/blake2.d.ts +183 -0
  14. package/blake2.js +540 -0
  15. package/blake3.d.ts +67 -0
  16. package/blake3.js +287 -0
  17. package/eskdf.d.ts +91 -0
  18. package/eskdf.js +223 -0
  19. package/esm/_blake.js +51 -0
  20. package/esm/_md.js +201 -0
  21. package/esm/_u64.js +83 -0
  22. package/esm/argon2.js +516 -0
  23. package/esm/blake1.js +559 -0
  24. package/esm/blake2.js +500 -0
  25. package/esm/blake3.js +283 -0
  26. package/esm/eskdf.js +217 -0
  27. package/esm/hkdf.js +119 -0
  28. package/esm/hmac.js +92 -0
  29. package/esm/index.js +34 -0
  30. package/esm/legacy.js +326 -0
  31. package/esm/pbkdf2.js +134 -0
  32. package/esm/scrypt.js +256 -0
  33. package/esm/sha2.js +457 -0
  34. package/esm/sha3-addons.js +782 -0
  35. package/esm/sha3.js +430 -0
  36. package/esm/utils.js +577 -0
  37. package/esm/webcrypto.js +163 -0
  38. package/hkdf.d.ts +63 -0
  39. package/hkdf.js +125 -0
  40. package/hmac.d.ts +46 -0
  41. package/hmac.js +96 -0
  42. package/index.d.ts +0 -0
  43. package/index.js +34 -0
  44. package/legacy.d.ts +101 -0
  45. package/legacy.js +332 -0
  46. package/package.json +47 -0
  47. package/pbkdf2.d.ts +55 -0
  48. package/pbkdf2.js +138 -0
  49. package/scrypt.d.ts +64 -0
  50. package/scrypt.js +260 -0
  51. package/sha2.d.ts +248 -0
  52. package/sha2.js +499 -0
  53. package/sha3-addons.d.ts +460 -0
  54. package/sha3-addons.js +791 -0
  55. package/sha3.d.ts +198 -0
  56. package/sha3.js +435 -0
  57. package/utils.d.ts +518 -0
  58. package/utils.js +606 -0
  59. package/webcrypto.d.ts +119 -0
  60. package/webcrypto.js +168 -0
package/esm/hmac.js ADDED
@@ -0,0 +1,92 @@
1
+ /**
2
+ * HMAC: RFC2104 message authentication code.
3
+ * @module
4
+ */
5
+ import { abytes, aexists, ahash, aoutput, clean, } from './utils';
6
+ /**
7
+ * Internal class for HMAC.
8
+ * Accepts any byte key, although RFC 2104 §3 recommends keys at least
9
+ * `HashLen` bytes long.
10
+ */
11
+ export class _HMAC {
12
+ oHash;
13
+ iHash;
14
+ blockLen;
15
+ outputLen;
16
+ canXOF = false;
17
+ finished = false;
18
+ destroyed = false;
19
+ constructor(hash, key) {
20
+ ahash(hash);
21
+ abytes(key, undefined, 'key');
22
+ this.iHash = hash.create();
23
+ if (typeof this.iHash.update !== 'function')
24
+ throw new Error('Expected instance of class which extends utils.Hash');
25
+ this.blockLen = this.iHash.blockLen;
26
+ this.outputLen = this.iHash.outputLen;
27
+ const blockLen = this.blockLen;
28
+ const pad = new Uint8Array(blockLen);
29
+ // blockLen can be bigger than outputLen
30
+ pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
31
+ for (let i = 0; i < pad.length; i++)
32
+ pad[i] ^= 0x36;
33
+ this.iHash.update(pad);
34
+ // By doing update (processing of the first block) of the outer hash here,
35
+ // we can re-use it between multiple calls via clone.
36
+ this.oHash = hash.create();
37
+ // Undo internal XOR && apply outer XOR
38
+ for (let i = 0; i < pad.length; i++)
39
+ pad[i] ^= 0x36 ^ 0x5c;
40
+ this.oHash.update(pad);
41
+ clean(pad);
42
+ }
43
+ update(buf) {
44
+ aexists(this);
45
+ this.iHash.update(buf);
46
+ return this;
47
+ }
48
+ digestInto(out) {
49
+ aexists(this);
50
+ aoutput(out, this);
51
+ this.finished = true;
52
+ const buf = out.subarray(0, this.outputLen);
53
+ // Reuse the first outputLen bytes for the inner digest; the outer hash consumes them before
54
+ // overwriting that same prefix with the final tag, leaving any oversized tail untouched.
55
+ this.iHash.digestInto(buf);
56
+ this.oHash.update(buf);
57
+ this.oHash.digestInto(buf);
58
+ this.destroy();
59
+ }
60
+ digest() {
61
+ const out = new Uint8Array(this.oHash.outputLen);
62
+ this.digestInto(out);
63
+ return out;
64
+ }
65
+ _cloneInto(to) {
66
+ // Create new instance without calling constructor since the key
67
+ // is already in state and we don't know it.
68
+ to ||= Object.create(Object.getPrototypeOf(this), {});
69
+ const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
70
+ to = to;
71
+ to.finished = finished;
72
+ to.destroyed = destroyed;
73
+ to.blockLen = blockLen;
74
+ to.outputLen = outputLen;
75
+ to.oHash = oHash._cloneInto(to.oHash);
76
+ to.iHash = iHash._cloneInto(to.iHash);
77
+ return to;
78
+ }
79
+ clone() {
80
+ return this._cloneInto();
81
+ }
82
+ destroy() {
83
+ this.destroyed = true;
84
+ this.oHash.destroy();
85
+ this.iHash.destroy();
86
+ }
87
+ }
88
+ export const hmac = /* @__PURE__ */ (() => {
89
+ const hmac_ = ((hash, key, message) => new _HMAC(hash, key).update(message).digest());
90
+ hmac_.create = (hash, key) => new _HMAC(hash, key);
91
+ return hmac_;
92
+ })();
package/esm/index.js ADDED
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ /**
3
+ * Audited & minimal JS implementation of hash functions, MACs, and KDFs.
4
+ * Check out individual modules.
5
+ * @module
6
+ * @example
7
+ ```js
8
+ import {
9
+ sha256, sha384, sha512, sha224, sha512_224, sha512_256
10
+ } from '@decryption/hashes/sha2.js';
11
+ import {
12
+ sha3_224, sha3_256, sha3_384, sha3_512,
13
+ keccak_224, keccak_256, keccak_384, keccak_512,
14
+ shake128, shake256
15
+ } from '@decryption/hashes/sha3.js';
16
+ import {
17
+ cshake128, cshake256,
18
+ turboshake128, turboshake256,
19
+ kt128, kt256,
20
+ kmac128, kmac256,
21
+ tuplehash256, parallelhash256,
22
+ keccakprg
23
+ } from '@decryption/hashes/sha3-addons.js';
24
+ import { blake3 } from '@decryption/hashes/blake3.js';
25
+ import { blake2b, blake2s } from '@decryption/hashes/blake2.js';
26
+ import { hmac } from '@decryption/hashes/hmac.js';
27
+ import { hkdf } from '@decryption/hashes/hkdf.js';
28
+ import { pbkdf2, pbkdf2Async } from '@decryption/hashes/pbkdf2.js';
29
+ import { scrypt, scryptAsync } from '@decryption/hashes/scrypt.js';
30
+ import { md5, ripemd160, sha1 } from '@decryption/hashes/legacy.js';
31
+ import * as utils from '@decryption/hashes/utils.js';
32
+ ```
33
+ */
34
+ throw new Error('root module cannot be imported: import submodules instead. Check out README');
package/esm/legacy.js ADDED
@@ -0,0 +1,326 @@
1
+ /**
2
+
3
+ SHA1 (RFC 3174), MD5 (RFC 1321), and RIPEMD160 legacy, weak hash functions.
4
+ RFC 2286 only covers HMAC-RIPEMD160 wrapper material and test vectors,
5
+ not the base RIPEMD-160 compression spec.
6
+ Don't use them in a new protocol. What "weak" means:
7
+
8
+ - Collisions can be made with 2^18 effort in MD5, 2^60 in SHA1, 2^80 in RIPEMD160.
9
+ - No practical pre-image attacks (only theoretical, 2^123.4)
10
+ - HMAC seems kinda ok: https://www.rfc-editor.org/rfc/rfc6151
11
+ * @module
12
+ */
13
+ import { Chi, HashMD, Maj } from './_md';
14
+ import { clean, createHasher, rotl } from './utils';
15
+ /** Initial SHA-1 state from RFC 3174 §6.1. */
16
+ const SHA1_IV = /* @__PURE__ */ Uint32Array.from([
17
+ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0,
18
+ ]);
19
+ // Reusable 80-word SHA-1 message schedule buffer.
20
+ const SHA1_W = /* @__PURE__ */ new Uint32Array(80);
21
+ /** Internal SHA1 legacy hash class. */
22
+ export class _SHA1 extends HashMD {
23
+ A = SHA1_IV[0] | 0;
24
+ B = SHA1_IV[1] | 0;
25
+ C = SHA1_IV[2] | 0;
26
+ D = SHA1_IV[3] | 0;
27
+ E = SHA1_IV[4] | 0;
28
+ constructor() {
29
+ super(64, 20, 8, false);
30
+ }
31
+ get() {
32
+ const { A, B, C, D, E } = this;
33
+ return [A, B, C, D, E];
34
+ }
35
+ set(A, B, C, D, E) {
36
+ this.A = A | 0;
37
+ this.B = B | 0;
38
+ this.C = C | 0;
39
+ this.D = D | 0;
40
+ this.E = E | 0;
41
+ }
42
+ process(view, offset) {
43
+ for (let i = 0; i < 16; i++, offset += 4)
44
+ SHA1_W[i] = view.getUint32(offset, false);
45
+ for (let i = 16; i < 80; i++)
46
+ SHA1_W[i] = rotl(SHA1_W[i - 3] ^ SHA1_W[i - 8] ^ SHA1_W[i - 14] ^ SHA1_W[i - 16], 1);
47
+ // Compression function main loop, 80 rounds
48
+ let { A, B, C, D, E } = this;
49
+ for (let i = 0; i < 80; i++) {
50
+ let F, K;
51
+ if (i < 20) {
52
+ F = Chi(B, C, D);
53
+ K = 0x5a827999;
54
+ }
55
+ else if (i < 40) {
56
+ F = B ^ C ^ D;
57
+ K = 0x6ed9eba1;
58
+ }
59
+ else if (i < 60) {
60
+ F = Maj(B, C, D);
61
+ K = 0x8f1bbcdc;
62
+ }
63
+ else {
64
+ F = B ^ C ^ D;
65
+ K = 0xca62c1d6;
66
+ }
67
+ const T = (rotl(A, 5) + F + E + K + SHA1_W[i]) | 0;
68
+ E = D;
69
+ D = C;
70
+ C = rotl(B, 30);
71
+ B = A;
72
+ A = T;
73
+ }
74
+ // Add the compressed chunk to the current hash value
75
+ A = (A + this.A) | 0;
76
+ B = (B + this.B) | 0;
77
+ C = (C + this.C) | 0;
78
+ D = (D + this.D) | 0;
79
+ E = (E + this.E) | 0;
80
+ this.set(A, B, C, D, E);
81
+ }
82
+ roundClean() {
83
+ clean(SHA1_W);
84
+ }
85
+ destroy() {
86
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
87
+ // update()/digest() callable on reused instances.
88
+ this.destroyed = true;
89
+ this.set(0, 0, 0, 0, 0);
90
+ clean(this.buffer);
91
+ }
92
+ }
93
+ /**
94
+ * SHA1 (RFC 3174) legacy hash function. It was cryptographically broken.
95
+ * @param msg - message bytes to hash
96
+ * @returns Digest bytes.
97
+ * @example
98
+ * Hash a message with SHA1.
99
+ * ```ts
100
+ * sha1(new Uint8Array([97, 98, 99]));
101
+ * ```
102
+ */
103
+ export const sha1 = /* @__PURE__ */ createHasher(() => new _SHA1());
104
+ /** RFC 1321 `T[i]` uses `floor(2^32 * abs(sin(i)))`; this is the shared `2^32` scale factor. */
105
+ const p32 = /* @__PURE__ */ Math.pow(2, 32);
106
+ /** RFC 1321 `T[1..64]` table. */
107
+ const K = /* @__PURE__ */ Array.from({ length: 64 }, (_, i) => Math.floor(p32 * Math.abs(Math.sin(i + 1))));
108
+ /** MD5 initial state from RFC 1321, stored as 4 u32 words. */
109
+ const MD5_IV = /* @__PURE__ */ SHA1_IV.slice(0, 4);
110
+ // Reusable 16-word MD5 message block buffer.
111
+ const MD5_W = /* @__PURE__ */ new Uint32Array(16);
112
+ /** Internal MD5 legacy hash class. */
113
+ export class _MD5 extends HashMD {
114
+ A = MD5_IV[0] | 0;
115
+ B = MD5_IV[1] | 0;
116
+ C = MD5_IV[2] | 0;
117
+ D = MD5_IV[3] | 0;
118
+ constructor() {
119
+ super(64, 16, 8, true);
120
+ }
121
+ get() {
122
+ const { A, B, C, D } = this;
123
+ return [A, B, C, D];
124
+ }
125
+ set(A, B, C, D) {
126
+ this.A = A | 0;
127
+ this.B = B | 0;
128
+ this.C = C | 0;
129
+ this.D = D | 0;
130
+ }
131
+ process(view, offset) {
132
+ for (let i = 0; i < 16; i++, offset += 4)
133
+ MD5_W[i] = view.getUint32(offset, true);
134
+ // Compression function main loop, 64 rounds
135
+ let { A, B, C, D } = this;
136
+ for (let i = 0; i < 64; i++) {
137
+ let F, g, s;
138
+ if (i < 16) {
139
+ F = Chi(B, C, D);
140
+ g = i;
141
+ s = [7, 12, 17, 22];
142
+ }
143
+ else if (i < 32) {
144
+ // RFC 1321 round 2 uses G(B,C,D) = (B & D) | (C & ~D), which is `Chi(D, B, C)`.
145
+ F = Chi(D, B, C);
146
+ g = (5 * i + 1) % 16;
147
+ s = [5, 9, 14, 20];
148
+ }
149
+ else if (i < 48) {
150
+ F = B ^ C ^ D;
151
+ g = (3 * i + 5) % 16;
152
+ s = [4, 11, 16, 23];
153
+ }
154
+ else {
155
+ F = C ^ (B | ~D);
156
+ g = (7 * i) % 16;
157
+ s = [6, 10, 15, 21];
158
+ }
159
+ F = F + A + K[i] + MD5_W[g];
160
+ A = D;
161
+ D = C;
162
+ C = B;
163
+ B = B + rotl(F, s[i % 4]);
164
+ }
165
+ // Add the compressed chunk to the current hash value
166
+ A = (A + this.A) | 0;
167
+ B = (B + this.B) | 0;
168
+ C = (C + this.C) | 0;
169
+ D = (D + this.D) | 0;
170
+ this.set(A, B, C, D);
171
+ }
172
+ roundClean() {
173
+ clean(MD5_W);
174
+ }
175
+ destroy() {
176
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
177
+ // update()/digest() callable on reused instances.
178
+ this.destroyed = true;
179
+ this.set(0, 0, 0, 0);
180
+ clean(this.buffer);
181
+ }
182
+ }
183
+ /**
184
+ * MD5 (RFC 1321) legacy hash function. It was cryptographically broken.
185
+ * MD5 architecture is similar to SHA1, with some differences:
186
+ * - Reduced output length: 16 bytes (128 bit) instead of 20
187
+ * - 64 rounds, instead of 80
188
+ * - Little-endian: could be faster, but will require more code
189
+ * - Non-linear index selection: huge speed-up for unroll
190
+ * - Per round constants: more memory accesses, additional speed-up for unroll
191
+ * @param msg - message bytes to hash
192
+ * @returns Digest bytes.
193
+ * @example
194
+ * Hash a message with MD5.
195
+ * ```ts
196
+ * md5(new Uint8Array([97, 98, 99]));
197
+ * ```
198
+ */
199
+ export const md5 = /* @__PURE__ */ createHasher(() => new _MD5());
200
+ // RIPEMD-160
201
+ // Permutation repeatedly applied to derive the later RIPEMD-160 message-order tables.
202
+ const Rho160 = /* @__PURE__ */ Uint8Array.from([
203
+ 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
204
+ ]);
205
+ const Id160 = /* @__PURE__ */ (() => Uint8Array.from(new Array(16).fill(0).map((_, i) => i)))();
206
+ const Pi160 = /* @__PURE__ */ (() => Id160.map((i) => (9 * i + 5) % 16))();
207
+ // Five left/right message-word orderings for the RIPEMD-160 dual-lane rounds.
208
+ const idxLR = /* @__PURE__ */ (() => {
209
+ const L = [Id160];
210
+ const R = [Pi160];
211
+ const res = [L, R];
212
+ for (let i = 0; i < 4; i++)
213
+ for (let j of res)
214
+ j.push(j[i].map((k) => Rho160[k]));
215
+ return res;
216
+ })();
217
+ const idxL = /* @__PURE__ */ (() => idxLR[0])();
218
+ const idxR = /* @__PURE__ */ (() => idxLR[1])();
219
+ // const [idxL, idxR] = idxLR;
220
+ // Base per-group shift table before the left/right message-order permutations are applied.
221
+ const shifts160 = /* @__PURE__ */ [
222
+ [11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8],
223
+ [12, 13, 11, 15, 6, 9, 9, 7, 12, 15, 11, 13, 7, 8, 7, 7],
224
+ [13, 15, 14, 11, 7, 7, 6, 8, 13, 14, 13, 12, 5, 5, 6, 9],
225
+ [14, 11, 12, 14, 8, 6, 5, 5, 15, 12, 15, 14, 9, 9, 8, 6],
226
+ [15, 12, 13, 13, 9, 5, 8, 6, 14, 11, 12, 11, 8, 6, 5, 5],
227
+ ].map((i) => Uint8Array.from(i));
228
+ const shiftsL160 = /* @__PURE__ */ idxL.map((idx, i) => idx.map((j) => shifts160[i][j]));
229
+ const shiftsR160 = /* @__PURE__ */ idxR.map((idx, i) => idx.map((j) => shifts160[i][j]));
230
+ // Five left-lane additive constants for RIPEMD-160.
231
+ const Kl160 = /* @__PURE__ */ Uint32Array.from([
232
+ 0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e,
233
+ ]);
234
+ // Five right-lane additive constants for RIPEMD-160.
235
+ const Kr160 = /* @__PURE__ */ Uint32Array.from([
236
+ 0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000,
237
+ ]);
238
+ // Called `f()` in the spec; valid `group` values are 0..4, and out-of-range
239
+ // inputs currently fall through to the group-4 branch.
240
+ function ripemd_f(group, x, y, z) {
241
+ if (group === 0)
242
+ return x ^ y ^ z;
243
+ if (group === 1)
244
+ return (x & y) | (~x & z);
245
+ if (group === 2)
246
+ return (x | ~y) ^ z;
247
+ if (group === 3)
248
+ return (x & z) | (y & ~z);
249
+ return x ^ (y | ~z);
250
+ }
251
+ // Reusable 16-word RIPEMD-160 message block buffer.
252
+ const BUF_160 = /* @__PURE__ */ new Uint32Array(16);
253
+ /**
254
+ * Internal RIPEMD-160 legacy hash class.
255
+ * RFC 2286 only adds HMAC-RIPEMD160 material, not the core hash specification.
256
+ */
257
+ export class _RIPEMD160 extends HashMD {
258
+ h0 = 0x67452301 | 0;
259
+ h1 = 0xefcdab89 | 0;
260
+ h2 = 0x98badcfe | 0;
261
+ h3 = 0x10325476 | 0;
262
+ h4 = 0xc3d2e1f0 | 0;
263
+ constructor() {
264
+ super(64, 20, 8, true);
265
+ }
266
+ get() {
267
+ const { h0, h1, h2, h3, h4 } = this;
268
+ return [h0, h1, h2, h3, h4];
269
+ }
270
+ set(h0, h1, h2, h3, h4) {
271
+ this.h0 = h0 | 0;
272
+ this.h1 = h1 | 0;
273
+ this.h2 = h2 | 0;
274
+ this.h3 = h3 | 0;
275
+ this.h4 = h4 | 0;
276
+ }
277
+ process(view, offset) {
278
+ for (let i = 0; i < 16; i++, offset += 4)
279
+ BUF_160[i] = view.getUint32(offset, true);
280
+ // prettier-ignore
281
+ let al = this.h0 | 0, ar = al, bl = this.h1 | 0, br = bl, cl = this.h2 | 0, cr = cl, dl = this.h3 | 0, dr = dl, el = this.h4 | 0, er = el;
282
+ // Instead of iterating 0 to 80, we split it into 5 groups
283
+ // And use the groups in constants, functions, etc. Much simpler
284
+ for (let group = 0; group < 5; group++) {
285
+ const rGroup = 4 - group;
286
+ const hbl = Kl160[group], hbr = Kr160[group]; // prettier-ignore
287
+ const rl = idxL[group], rr = idxR[group]; // prettier-ignore
288
+ const sl = shiftsL160[group], sr = shiftsR160[group]; // prettier-ignore
289
+ for (let i = 0; i < 16; i++) {
290
+ const tl = (rotl(al + ripemd_f(group, bl, cl, dl) + BUF_160[rl[i]] + hbl, sl[i]) + el) | 0;
291
+ al = el, el = dl, dl = rotl(cl, 10) | 0, cl = bl, bl = tl; // prettier-ignore
292
+ }
293
+ // 2 loops are 10% faster
294
+ for (let i = 0; i < 16; i++) {
295
+ const tr = (rotl(ar + ripemd_f(rGroup, br, cr, dr) + BUF_160[rr[i]] + hbr, sr[i]) + er) | 0;
296
+ ar = er, er = dr, dr = rotl(cr, 10) | 0, cr = br, br = tr; // prettier-ignore
297
+ }
298
+ }
299
+ // Add the compressed chunk to the current hash value
300
+ // Final recombination cross-adds the left/right lane accumulators into the next h0..h4 order.
301
+ this.set((this.h1 + cl + dr) | 0, (this.h2 + dl + er) | 0, (this.h3 + el + ar) | 0, (this.h4 + al + br) | 0, (this.h0 + bl + cr) | 0);
302
+ }
303
+ roundClean() {
304
+ clean(BUF_160);
305
+ }
306
+ destroy() {
307
+ this.destroyed = true;
308
+ clean(this.buffer);
309
+ this.set(0, 0, 0, 0, 0);
310
+ }
311
+ }
312
+ /**
313
+ * RIPEMD-160 - a legacy hash function from 1990s.
314
+ * RFC 2286 only covers HMAC-RIPEMD160 test material; the links below point
315
+ * at the base RIPEMD-160 references.
316
+ * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160.html}
317
+ * * {@link https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf}
318
+ * @param msg - message bytes to hash
319
+ * @returns Digest bytes.
320
+ * @example
321
+ * Hash a message with RIPEMD-160.
322
+ * ```ts
323
+ * ripemd160(new Uint8Array([97, 98, 99]));
324
+ * ```
325
+ */
326
+ export const ripemd160 = /* @__PURE__ */ createHasher(() => new _RIPEMD160());
package/esm/pbkdf2.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * PBKDF (RFC 2898). Can be used to create a key from password and salt.
3
+ * @module
4
+ */
5
+ import { hmac } from './hmac';
6
+ // prettier-ignore
7
+ import { ahash, anumber, asyncLoop, checkOpts, clean, createView, kdfInputToBytes } from './utils';
8
+ // Common start and end for sync/async functions
9
+ function pbkdf2Init(hash, _password, _salt, _opts) {
10
+ ahash(hash);
11
+ const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
12
+ const { c, dkLen, asyncTick } = opts;
13
+ anumber(c, 'c');
14
+ anumber(dkLen, 'dkLen');
15
+ anumber(asyncTick, 'asyncTick');
16
+ if (c < 1)
17
+ throw new Error('iterations (c) must be >= 1');
18
+ // RFC 8018 §5.2 defines `dkLen` as "a positive integer".
19
+ if (dkLen < 1)
20
+ throw new Error('"dkLen" must be >= 1');
21
+ // RFC 8018 §5.2 step 1 requires rejecting oversize `dkLen`
22
+ // before allocating the destination buffer.
23
+ if (dkLen > (2 ** 32 - 1) * hash.outputLen)
24
+ throw new Error('derived key too long');
25
+ const password = kdfInputToBytes(_password, 'password');
26
+ const salt = kdfInputToBytes(_salt, 'salt');
27
+ // DK = PBKDF2(PRF, Password, Salt, c, dkLen);
28
+ const DK = new Uint8Array(dkLen);
29
+ // U1 = PRF(Password, Salt + INT_32_BE(i))
30
+ const PRF = hmac.create(hash, password);
31
+ // Cache PRF(P, S || ...) prefix state so each block only appends INT_32_BE(i).
32
+ const PRFSalt = PRF._cloneInto().update(salt);
33
+ return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
34
+ }
35
+ function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
36
+ // Shared sync/async cleanup point: wipe transient PRF state
37
+ // while preserving the derived key buffer.
38
+ PRF.destroy();
39
+ PRFSalt.destroy();
40
+ if (prfW)
41
+ prfW.destroy();
42
+ clean(u);
43
+ return DK;
44
+ }
45
+ /**
46
+ * PBKDF2-HMAC: RFC 8018 key derivation function.
47
+ * @param hash - hash function that would be used e.g. sha256
48
+ * @param password - password from which a derived key is generated;
49
+ * JS string inputs are UTF-8 encoded first
50
+ * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
51
+ * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
52
+ * must be `>= 1` per RFC 8018 §5.2. See {@link Pbkdf2Opt}.
53
+ * @returns Derived key bytes.
54
+ * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
55
+ * @example
56
+ * PBKDF2-HMAC: RFC 2898 key derivation function.
57
+ * ```ts
58
+ * import { pbkdf2 } from '@decryption/hashes/pbkdf2.js';
59
+ * import { sha256 } from '@decryption/hashes/sha2.js';
60
+ * const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
61
+ * ```
62
+ */
63
+ export function pbkdf2(hash, password, salt, opts) {
64
+ const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
65
+ let prfW; // Working copy
66
+ const arr = new Uint8Array(4);
67
+ const view = createView(arr);
68
+ const u = new Uint8Array(PRF.outputLen);
69
+ // DK = T1 + T2 + ⋯ + Tdklen/hlen
70
+ for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
71
+ // Ti = F(Password, Salt, c, i)
72
+ // The last Ti view can be shorter than hLen, which applies
73
+ // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
74
+ const Ti = DK.subarray(pos, pos + PRF.outputLen);
75
+ view.setInt32(0, ti, false);
76
+ // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
77
+ // U1 = PRF(Password, Salt + INT_32_BE(i))
78
+ (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
79
+ Ti.set(u.subarray(0, Ti.length));
80
+ for (let ui = 1; ui < c; ui++) {
81
+ // Uc = PRF(Password, Uc−1)
82
+ PRF._cloneInto(prfW).update(u).digestInto(u);
83
+ for (let i = 0; i < Ti.length; i++)
84
+ Ti[i] ^= u[i];
85
+ }
86
+ }
87
+ return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
88
+ }
89
+ /**
90
+ * PBKDF2-HMAC: RFC 8018 key derivation function. Async version.
91
+ * @param hash - hash function that would be used e.g. sha256
92
+ * @param password - password from which a derived key is generated;
93
+ * JS string inputs are UTF-8 encoded first
94
+ * @param salt - cryptographic salt; JS string inputs are UTF-8 encoded first
95
+ * @param opts - PBKDF2 work factor and output settings. `dkLen`, if provided,
96
+ * must be `>= 1` per RFC 8018 §5.2. `asyncTick` is only a local
97
+ * scheduler-yield knob for this JS wrapper, not part of RFC 8018.
98
+ * See {@link Pbkdf2Opt}.
99
+ * @returns Promise resolving to derived key bytes.
100
+ * @throws If the PBKDF2 iteration count or derived-key settings are invalid. {@link Error}
101
+ * @example
102
+ * PBKDF2-HMAC: RFC 2898 key derivation function.
103
+ * ```ts
104
+ * import { pbkdf2Async } from '@decryption/hashes/pbkdf2.js';
105
+ * import { sha256 } from '@decryption/hashes/sha2.js';
106
+ * const key = await pbkdf2Async(sha256, 'password', 'salt', { dkLen: 32, c: 500_000 });
107
+ * ```
108
+ */
109
+ export async function pbkdf2Async(hash, password, salt, opts) {
110
+ const { c, dkLen, asyncTick, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
111
+ let prfW; // Working copy
112
+ const arr = new Uint8Array(4);
113
+ const view = createView(arr);
114
+ const u = new Uint8Array(PRF.outputLen);
115
+ // DK = T1 + T2 + ⋯ + Tdklen/hlen
116
+ for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
117
+ // Ti = F(Password, Salt, c, i)
118
+ // The last Ti view can be shorter than hLen, which applies
119
+ // RFC 8018 §5.2 step 4's T_l<0..r-1> truncation without extra copies.
120
+ const Ti = DK.subarray(pos, pos + PRF.outputLen);
121
+ view.setInt32(0, ti, false);
122
+ // F(Password, Salt, c, i) = U1 ^ U2 ^ ⋯ ^ Uc
123
+ // U1 = PRF(Password, Salt + INT_32_BE(i))
124
+ (prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
125
+ Ti.set(u.subarray(0, Ti.length));
126
+ await asyncLoop(c - 1, asyncTick, () => {
127
+ // Uc = PRF(Password, Uc−1)
128
+ PRF._cloneInto(prfW).update(u).digestInto(u);
129
+ for (let i = 0; i < Ti.length; i++)
130
+ Ti[i] ^= u[i];
131
+ });
132
+ }
133
+ return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
134
+ }