@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/blake3.js ADDED
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Blake3 fast hash is Blake2 with reduced security (round count). Can also be used as MAC & KDF.
3
+ *
4
+ * It is advertised as "the fastest cryptographic hash". However, it isn't true in JS.
5
+ * Why is this so slow? While it must be 6x faster than blake2b, perf diff is only 20%:
6
+ *
7
+ * * There is only 30% reduction in number of rounds from blake2s
8
+ * * Speed-up comes from tree structure, which is parallelized using SIMD & threading.
9
+ * These features are not present in JS, so we only get overhead from trees.
10
+ * * Parallelization only happens on 1024-byte chunks: there is no benefit for small inputs.
11
+ * * It is still possible to make it faster using: a) loop unrolling b) web workers c) wasm
12
+ * @module
13
+ */
14
+ import { SHA256_IV } from './_md';
15
+ import { fromBig } from './_u64';
16
+ import { _BLAKE2, compress } from './blake2';
17
+ // prettier-ignore
18
+ import { abytes, aexists, anumber, aoutput, clean, copyBytes, createHasher, swap32IfBE, u32, u8 } from './utils';
19
+ // Constructor-time mode flags (`KEYED_HASH`, `DERIVE_*`) plus per-node tree
20
+ // flags (`CHUNK_*`, `PARENT`, `ROOT`).
21
+ const B3_Flags = {
22
+ CHUNK_START: 0b1,
23
+ CHUNK_END: 0b10,
24
+ PARENT: 0b100,
25
+ ROOT: 0b1000,
26
+ KEYED_HASH: 0b10000,
27
+ DERIVE_KEY_CONTEXT: 0b100000,
28
+ DERIVE_KEY_MATERIAL: 0b1000000,
29
+ };
30
+ // Default BLAKE3 IV, cloned from the shared BLAKE2s / SHA-256 IV basis.
31
+ const B3_IV = /* @__PURE__ */ SHA256_IV.slice();
32
+ // Seven 16-word rounds of BLAKE3 message schedule, generated by repeatedly
33
+ // permuting the identity row.
34
+ const B3_SIGMA = /* @__PURE__ */ (() => {
35
+ const Id = Array.from({ length: 16 }, (_, i) => i);
36
+ const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
37
+ const res = [];
38
+ for (let i = 0, v = Id; i < 7; i++, v = permute(v))
39
+ res.push(...v);
40
+ return Uint8Array.from(res);
41
+ })();
42
+ /** Blake3 hash. Can be used as MAC and KDF with caller-encoded context bytes. */
43
+ export class _BLAKE3 extends _BLAKE2 {
44
+ canXOF = true;
45
+ chunkPos = 0; // Position of current block in chunk
46
+ // How many chunks we already have; exact while this stays within
47
+ // JS's safe-integer range.
48
+ chunksDone = 0;
49
+ flags = 0 | 0;
50
+ IV;
51
+ state;
52
+ stack = [];
53
+ // Output
54
+ posOut = 0;
55
+ bufferOut32 = new Uint32Array(16);
56
+ bufferOut;
57
+ // Index of output chunk; exact while this stays within JS's
58
+ // safe-integer range.
59
+ chunkOut = 0;
60
+ enableXOF = true;
61
+ constructor(opts = {}, flags = 0) {
62
+ super(64, opts.dkLen === undefined ? 32 : opts.dkLen);
63
+ const { key, context } = opts;
64
+ const hasContext = context !== undefined;
65
+ if (key !== undefined) {
66
+ if (hasContext)
67
+ throw new Error('Only "key" or "context" can be specified at same time');
68
+ abytes(key, 32, 'key');
69
+ const k = copyBytes(key);
70
+ this.IV = u32(k);
71
+ swap32IfBE(this.IV);
72
+ this.flags = flags | B3_Flags.KEYED_HASH;
73
+ }
74
+ else if (hasContext) {
75
+ abytes(context, undefined, 'context');
76
+ const ctx = context;
77
+ const contextKey = new _BLAKE3({ dkLen: 32 }, B3_Flags.DERIVE_KEY_CONTEXT)
78
+ .update(ctx)
79
+ .digest();
80
+ this.IV = u32(contextKey);
81
+ swap32IfBE(this.IV);
82
+ this.flags = flags | B3_Flags.DERIVE_KEY_MATERIAL;
83
+ }
84
+ else {
85
+ this.IV = B3_IV.slice();
86
+ this.flags = flags;
87
+ }
88
+ this.state = this.IV.slice();
89
+ this.bufferOut = u8(this.bufferOut32);
90
+ }
91
+ // _BLAKE2's scalar-state hooks are unused here: BLAKE3 keeps its tree/XOF state in arrays and
92
+ // copies it directly in _cloneInto().
93
+ get() {
94
+ return [];
95
+ }
96
+ set() { }
97
+ // Truncated chunk/parent compression: seed v8..v15 as IV[0..3], t0, t1,
98
+ // block length, and flags, then keep only the first 8 output words.
99
+ b2Compress(counter, flags, buf, bufPos = 0) {
100
+ const { state: s, pos } = this;
101
+ const { h, l } = fromBig(BigInt(counter), true);
102
+ // prettier-ignore
103
+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, bufPos, buf, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], h, l, pos, flags);
104
+ s[0] = v0 ^ v8;
105
+ s[1] = v1 ^ v9;
106
+ s[2] = v2 ^ v10;
107
+ s[3] = v3 ^ v11;
108
+ s[4] = v4 ^ v12;
109
+ s[5] = v5 ^ v13;
110
+ s[6] = v6 ^ v14;
111
+ s[7] = v7 ^ v15;
112
+ }
113
+ compress(buf, bufPos = 0, isLast = false) {
114
+ // Compress last block
115
+ let flags = this.flags;
116
+ if (!this.chunkPos)
117
+ flags |= B3_Flags.CHUNK_START;
118
+ if (this.chunkPos === 15 || isLast)
119
+ flags |= B3_Flags.CHUNK_END;
120
+ if (!isLast)
121
+ this.pos = this.blockLen;
122
+ this.b2Compress(this.chunksDone, flags, buf, bufPos);
123
+ this.chunkPos += 1;
124
+ // If current block is last in chunk (16 blocks), then compress chunks
125
+ if (this.chunkPos === 16 || isLast) {
126
+ let chunk = this.state;
127
+ this.state = this.IV.slice();
128
+ // If not the last one, compress only when there are trailing zeros in chunk counter
129
+ // Chunks are used as a binary tree where the current stack is the path.
130
+ // Zero means the current leaf is finished and can be compressed.
131
+ // 1 (001) - leaf not finished (just push current chunk to stack)
132
+ // 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
133
+ // 3 (011) - last leaf not finished
134
+ // 4 (100) - leafs finished at depth=1 and depth=2
135
+ for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
136
+ if (!(last = this.stack.pop()))
137
+ break;
138
+ this.buffer32.set(last, 0);
139
+ this.buffer32.set(chunk, 8);
140
+ this.pos = this.blockLen;
141
+ this.b2Compress(0, this.flags | B3_Flags.PARENT, this.buffer32, 0);
142
+ chunk = this.state;
143
+ this.state = this.IV.slice();
144
+ }
145
+ this.chunksDone++;
146
+ this.chunkPos = 0;
147
+ this.stack.push(chunk);
148
+ }
149
+ this.pos = 0;
150
+ }
151
+ _cloneInto(to) {
152
+ to = super._cloneInto(to);
153
+ const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
154
+ to.state.set(state.slice());
155
+ // Clone each CV stack entry by value so extending or destroying the clone
156
+ // cannot alias the source tree state.
157
+ to.stack = stack.map((i) => Uint32Array.from(i));
158
+ to.IV.set(IV);
159
+ to.flags = flags;
160
+ to.chunkPos = chunkPos;
161
+ to.chunksDone = chunksDone;
162
+ to.posOut = posOut;
163
+ to.chunkOut = chunkOut;
164
+ to.enableXOF = this.enableXOF;
165
+ to.bufferOut32.set(this.bufferOut32);
166
+ return to;
167
+ }
168
+ destroy() {
169
+ this.destroyed = true;
170
+ clean(this.state, this.buffer32, this.IV, this.bufferOut32);
171
+ clean(...this.stack);
172
+ }
173
+ // Root/XOF compression: rerun the same ROOT inputs with incrementing output
174
+ // counter `t` and materialize all 16 output words.
175
+ // Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
176
+ b2CompressOut() {
177
+ const { state: s, pos, flags, buffer32, bufferOut32: out32 } = this;
178
+ const { h, l } = fromBig(BigInt(this.chunkOut++));
179
+ swap32IfBE(buffer32);
180
+ // prettier-ignore
181
+ const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(B3_SIGMA, 0, buffer32, 7, s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7], B3_IV[0], B3_IV[1], B3_IV[2], B3_IV[3], l, h, pos, flags);
182
+ out32[0] = v0 ^ v8;
183
+ out32[1] = v1 ^ v9;
184
+ out32[2] = v2 ^ v10;
185
+ out32[3] = v3 ^ v11;
186
+ out32[4] = v4 ^ v12;
187
+ out32[5] = v5 ^ v13;
188
+ out32[6] = v6 ^ v14;
189
+ out32[7] = v7 ^ v15;
190
+ out32[8] = s[0] ^ v8;
191
+ out32[9] = s[1] ^ v9;
192
+ out32[10] = s[2] ^ v10;
193
+ out32[11] = s[3] ^ v11;
194
+ out32[12] = s[4] ^ v12;
195
+ out32[13] = s[5] ^ v13;
196
+ out32[14] = s[6] ^ v14;
197
+ out32[15] = s[7] ^ v15;
198
+ swap32IfBE(buffer32);
199
+ swap32IfBE(out32);
200
+ this.posOut = 0;
201
+ }
202
+ finish() {
203
+ if (this.finished)
204
+ return;
205
+ this.finished = true;
206
+ // Padding
207
+ clean(this.buffer.subarray(this.pos));
208
+ // Process last chunk
209
+ let flags = this.flags | B3_Flags.ROOT;
210
+ if (this.stack.length) {
211
+ // Finalize the current chunk first, then rerun the last parent
212
+ // compression as ROOT with t = 0 and b = 64.
213
+ flags |= B3_Flags.PARENT;
214
+ swap32IfBE(this.buffer32);
215
+ this.compress(this.buffer32, 0, true);
216
+ swap32IfBE(this.buffer32);
217
+ this.chunksDone = 0;
218
+ this.pos = this.blockLen;
219
+ }
220
+ else {
221
+ flags |= (!this.chunkPos ? B3_Flags.CHUNK_START : 0) | B3_Flags.CHUNK_END;
222
+ }
223
+ this.flags = flags;
224
+ this.b2CompressOut();
225
+ }
226
+ writeInto(out) {
227
+ aexists(this, false);
228
+ abytes(out);
229
+ this.finish();
230
+ const { blockLen, bufferOut } = this;
231
+ for (let pos = 0, len = out.length; pos < len;) {
232
+ if (this.posOut >= blockLen)
233
+ this.b2CompressOut();
234
+ const take = Math.min(blockLen - this.posOut, len - pos);
235
+ out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
236
+ this.posOut += take;
237
+ pos += take;
238
+ }
239
+ return out;
240
+ }
241
+ xofInto(out) {
242
+ if (!this.enableXOF)
243
+ throw new Error('XOF is not possible after digest call');
244
+ return this.writeInto(out);
245
+ }
246
+ xof(bytes) {
247
+ anumber(bytes);
248
+ return this.xofInto(new Uint8Array(bytes));
249
+ }
250
+ digestInto(out) {
251
+ aoutput(out, this);
252
+ if (this.finished)
253
+ throw new Error('digest() was already called');
254
+ this.enableXOF = false;
255
+ // `aoutput(...)` allows oversized buffers; digestInto() must fill only the configured digest.
256
+ this.writeInto(out.subarray(0, this.outputLen));
257
+ this.destroy();
258
+ }
259
+ digest() {
260
+ const out = new Uint8Array(this.outputLen);
261
+ this.digestInto(out);
262
+ return out;
263
+ }
264
+ }
265
+ /**
266
+ * BLAKE3 hash function. Can be used as MAC and KDF.
267
+ * @param msg - message that would be hashed
268
+ * @param opts - Optional output, MAC, or KDF configuration. `key` must be
269
+ * exactly 32 bytes, `context` is caller-encoded bytes, and `dkLen` can be
270
+ * 0..2^64-1 via the XOF-backed output path. See {@link Blake3Opts}.
271
+ * @returns Digest bytes.
272
+ * @example
273
+ * Hash, MAC, or derive key material with BLAKE3.
274
+ * ```ts
275
+ * import { blake3 } from '@decryption/hashes/blake3.js';
276
+ * import { utf8ToBytes } from '@decryption/hashes/utils.js';
277
+ * const data = new Uint8Array(32);
278
+ * const hash = blake3(data);
279
+ * const mac = blake3(data, { key: new Uint8Array(32) });
280
+ * const kdf = blake3(data, { context: utf8ToBytes('application name') });
281
+ * ```
282
+ */
283
+ export const blake3 = /* @__PURE__ */ createHasher((opts = {}) => new _BLAKE3(opts));
package/esm/eskdf.js ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * Experimental KDF for AES.
3
+ * @module
4
+ */
5
+ import { hkdf } from './hkdf';
6
+ import { pbkdf2 as _pbkdf2 } from './pbkdf2';
7
+ import { scrypt as _scrypt } from './scrypt';
8
+ import { sha256 } from './sha2';
9
+ import { abytes, bytesToHex, clean, createView, hexToBytes, kdfInputToBytes, } from './utils';
10
+ // A tiny KDF for various applications like AES key-gen.
11
+ // Uses HKDF in a non-standard way, so it's not "KDF-secure", only "PRF-secure".
12
+ // Which is good enough: assume sha2-256 retained preimage resistance.
13
+ // Fixed ESKDF scrypt work factor: interactive-latency target with about 512 MiB RAM per derivation.
14
+ const SCRYPT_FACTOR = /* @__PURE__ */ (() => 2 ** 19)();
15
+ // Fixed ESKDF PBKDF2 work factor: CPU-only companion branch in the same rough
16
+ // interactive-latency range.
17
+ const PBKDF2_FACTOR = /* @__PURE__ */ (() => 2 ** 17)();
18
+ /**
19
+ * Scrypt KDF with the fixed ESKDF policy tuple `{ N: 2^19, r: 8, p: 1, dkLen: 32 }`.
20
+ * @param password - user password string, UTF-8 encoded before entering RFC 7914
21
+ * @param salt - unique salt string, UTF-8 encoded before entering RFC 7914
22
+ * @returns Derived 32-byte key.
23
+ * @example
24
+ * Derive the 32-byte scrypt key used by ESKDF.
25
+ * ```ts
26
+ * scrypt('password123', 'user@example.com');
27
+ * ```
28
+ */
29
+ export function scrypt(password, salt) {
30
+ return _scrypt(password, salt, { N: SCRYPT_FACTOR, r: 8, p: 1, dkLen: 32 });
31
+ }
32
+ /**
33
+ * PBKDF2-HMAC-SHA256 with the fixed ESKDF policy tuple `{ sha256, c: 2^17, dkLen: 32 }`.
34
+ * @param password - user password string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
35
+ * @param salt - unique salt string, UTF-8 encoded before entering PBKDF2-HMAC-SHA-256
36
+ * @returns Derived 32-byte key.
37
+ * @example
38
+ * Derive the 32-byte PBKDF2 key used by ESKDF.
39
+ * ```ts
40
+ * pbkdf2('password123', 'user@example.com');
41
+ * ```
42
+ */
43
+ export function pbkdf2(password, salt) {
44
+ return _pbkdf2(sha256, password, salt, { c: PBKDF2_FACTOR, dkLen: 32 });
45
+ }
46
+ // Combines two 32-byte byte arrays into a fresh 32-byte result without aliasing either input.
47
+ function xor32(a, b) {
48
+ abytes(a, 32);
49
+ abytes(b, 32);
50
+ const arr = new Uint8Array(32);
51
+ for (let i = 0; i < 32; i++) {
52
+ arr[i] = a[i] ^ b[i];
53
+ }
54
+ return arr;
55
+ }
56
+ // All local string length checks are in JS UTF-16 code units, not UTF-8 bytes.
57
+ function strHasLength(str, min, max) {
58
+ return typeof str === 'string' && str.length >= min && str.length <= max;
59
+ }
60
+ /**
61
+ * Derives main seed. Takes a lot of time; prefer the higher-level `eskdf(...)`
62
+ * flow unless you specifically need the raw main seed.
63
+ * Derives the main seed by xor'ing two branches:
64
+ * the scrypt branch uses a `0x01` separator byte on username/password,
65
+ * and the PBKDF2 branch uses `0x02`.
66
+ * Username and password strings are encoded by the underlying KDFs after the
67
+ * local separator bytes are appended.
68
+ * @param username - account identifier used as public salt
69
+ * @param password - user password string
70
+ * @returns Main 32-byte seed for the account.
71
+ * @throws If the username or password length is invalid. {@link Error}
72
+ * @example
73
+ * Derive the main ESKDF seed from username and password.
74
+ * ```ts
75
+ * deriveMainSeed('example-user', 'example-password');
76
+ * ```
77
+ */
78
+ export function deriveMainSeed(username, password) {
79
+ if (!strHasLength(username, 8, 255))
80
+ throw new Error('invalid username');
81
+ if (!strHasLength(password, 8, 255))
82
+ throw new Error('invalid password');
83
+ // Keep the protocol separators as the literal bytes 0x01 / 0x02 even after minification.
84
+ // Embedding them as non-printable characters directly can be awkward across
85
+ // JS tooling and environments.
86
+ const codes = { _1: 1, _2: 2 };
87
+ const sep = { s: String.fromCharCode(codes._1), p: String.fromCharCode(codes._2) };
88
+ const scr = scrypt(password + sep.s, username + sep.s);
89
+ const pbk = pbkdf2(password + sep.p, username + sep.p);
90
+ const res = xor32(scr, pbk);
91
+ clean(scr, pbk);
92
+ return res;
93
+ }
94
+ /**
95
+ * Converts protocol & accountId pair to HKDF params:
96
+ * `info` is UTF-8 protocol bytes, numeric ids become 4-byte BE `salt`,
97
+ * and string ids become UTF-8 `salt` bytes.
98
+ */
99
+ function getSaltInfo(protocol, accountId = 0) {
100
+ // Note that length here also repeats two lines below
101
+ // We do an additional length check here to reduce the scope of DoS attacks
102
+ if (!(strHasLength(protocol, 3, 15) && /^[a-z0-9]{3,15}$/.test(protocol))) {
103
+ throw new Error('invalid protocol');
104
+ }
105
+ // Exact-match only: substring matches like `assh` / `mentor` must not widen the public whitelist.
106
+ const allowsStr = /^(password\d{0,3}|ssh|tor|file)$/.test(protocol);
107
+ let salt; // Assigned below: either 4-byte BE account bytes or UTF-8 account bytes.
108
+ if (typeof accountId === 'string') {
109
+ if (!allowsStr)
110
+ throw new Error('accountId must be a number');
111
+ if (!strHasLength(accountId, 1, 255))
112
+ throw new Error('accountId must be string of length 1..255');
113
+ salt = kdfInputToBytes(accountId);
114
+ }
115
+ else if (Number.isSafeInteger(accountId)) {
116
+ if (accountId < 0 || accountId > Math.pow(2, 32) - 1)
117
+ throw new Error('invalid accountId');
118
+ // Convert to Big Endian Uint32
119
+ salt = new Uint8Array(4);
120
+ createView(salt).setUint32(0, accountId, false);
121
+ }
122
+ else {
123
+ throw new Error('accountId must be a number' + (allowsStr ? ' or string' : ''));
124
+ }
125
+ const info = kdfInputToBytes(protocol);
126
+ return { salt, info };
127
+ }
128
+ // Local modulus-size helper, not a general bigint-byte-length primitive:
129
+ // `<= 128n` is rejected by ESKDF policy.
130
+ function countBytes(num) {
131
+ if (typeof num !== 'bigint' || num <= BigInt(128))
132
+ throw new Error('invalid number');
133
+ return Math.ceil(num.toString(2).length / 8);
134
+ }
135
+ /**
136
+ * Parses keyLength and modulus options to extract length of result key.
137
+ * If modulus is used, adds 64 bits to it per the FIPS 186-5 Appendix A.3.1 /
138
+ * A.4.1 extra-bits guidance.
139
+ */
140
+ function getKeyLength(options) {
141
+ if (!options || typeof options !== 'object')
142
+ return 32;
143
+ const hasLen = 'keyLength' in options;
144
+ const hasMod = 'modulus' in options;
145
+ if (hasLen && hasMod)
146
+ throw new Error('cannot combine keyLength and modulus options');
147
+ if (!hasLen && !hasMod)
148
+ throw new Error('must have either keyLength or modulus option');
149
+ // FIPS 186-5 Appendix A.3.1 / A.4.1 calls for at least 64 extra bits.
150
+ const l = hasMod ? countBytes(options.modulus) + 8 : options.keyLength;
151
+ if (!(typeof l === 'number' && l >= 16 && l <= 8192))
152
+ throw new Error('invalid keyLength');
153
+ return l;
154
+ }
155
+ /**
156
+ * Converts key to bigint and divides it by modulus. Big Endian.
157
+ * Adapts FIPS 186-5 Appendix A.4.1: `getKeyLength()` already requested the
158
+ * extra 64-bit margin, and this step maps the result into `1..modulus-1`.
159
+ */
160
+ function modReduceKey(key, modulus) {
161
+ const _1 = BigInt(1);
162
+ const num = BigInt('0x' + bytesToHex(key)); // check for ui8a, then bytesToNumber()
163
+ const res = (num % (modulus - _1)) + _1; // Remove 0 from output
164
+ if (res < _1)
165
+ throw new Error('expected positive number'); // Guard against bad values
166
+ // Strip the extra 64-bit margin that `getKeyLength()` requested
167
+ // for bias reduction.
168
+ const len = key.length - 8;
169
+ const hex = res.toString(16).padStart(len * 2, '0'); // numberToHex()
170
+ const bytes = hexToBytes(hex);
171
+ if (bytes.length !== len)
172
+ throw new Error('invalid length of result key');
173
+ return bytes;
174
+ }
175
+ /**
176
+ * ESKDF
177
+ * @param username - username, email, or identifier, min: 8 characters, should have enough entropy
178
+ * @param password - password, min: 8 characters, should have enough entropy
179
+ * @returns Frozen API that derives child keys and exposes the account fingerprint.
180
+ * @throws If the username or password length is invalid. {@link Error}
181
+ * @example
182
+ * Derive account-specific child keys from the main ESKDF seed.
183
+ * ```ts
184
+ * const kdf = await eskdf('example-university', 'beginning-new-example');
185
+ * const key = kdf.deriveChildKey('aes', 0);
186
+ * const fingerprint = kdf.fingerprint;
187
+ * kdf.expire();
188
+ * ```
189
+ */
190
+ export async function eskdf(username, password) {
191
+ // We are using closure + object instead of class because
192
+ // we want to make `seed` non-accessible for any external function.
193
+ let seed = deriveMainSeed(username, password);
194
+ function deriveCK(protocol, accountId = 0, options) {
195
+ // Reject expired instances before deriving any HKDF inputs from the closure-held seed.
196
+ abytes(seed, 32);
197
+ const { salt, info } = getSaltInfo(protocol, accountId); // validate protocol & accountId
198
+ // Validate option shape and coarse length bounds;
199
+ // `hkdf()` still rejects non-integer lengths.
200
+ const keyLength = getKeyLength(options);
201
+ const key = hkdf(sha256, seed, salt, info, keyLength);
202
+ // Modulus has already been validated
203
+ return options && 'modulus' in options ? modReduceKey(key, options.modulus) : key;
204
+ }
205
+ function expire() {
206
+ // Overwrite the closure-held seed before dropping the reference.
207
+ if (seed)
208
+ seed.fill(1);
209
+ seed = undefined;
210
+ }
211
+ // prettier-ignore
212
+ const fingerprint = Array.from(deriveCK('fingerprint', 0))
213
+ .slice(0, 6)
214
+ .map((char) => char.toString(16).padStart(2, '0').toUpperCase())
215
+ .join(':');
216
+ return Object.freeze({ deriveChildKey: deriveCK, expire, fingerprint });
217
+ }
package/esm/hkdf.js ADDED
@@ -0,0 +1,119 @@
1
+ /**
2
+ * HKDF (RFC 5869): extract + expand in one step.
3
+ * See {@link https://soatok.blog/2021/11/17/understanding-hkdf/}.
4
+ * @module
5
+ */
6
+ import { hmac } from './hmac';
7
+ import { abytes, ahash, anumber, clean } from './utils';
8
+ /**
9
+ * HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
10
+ * Arguments position differs from spec (IKM is first one, since it is not optional)
11
+ * Local validation only checks `hash`; `ikm` / `salt` byte validation is delegated to `hmac()`.
12
+ * @param hash - hash function that would be used (e.g. sha256)
13
+ * @param ikm - input keying material, the initial key
14
+ * @param salt - optional salt value (a non-secret random value)
15
+ * @returns Pseudorandom key derived from input keying material.
16
+ * @example
17
+ * Run the HKDF extract step.
18
+ * ```ts
19
+ * import { extract } from '@decryption/hashes/hkdf.js';
20
+ * import { sha256 } from '@decryption/hashes/sha2.js';
21
+ * extract(sha256, new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6]));
22
+ * ```
23
+ */
24
+ export function extract(hash, ikm, salt) {
25
+ ahash(hash);
26
+ // NOTE: some libraries treat zero-length array as 'not provided';
27
+ // we don't, since we have undefined as 'not provided'
28
+ // https://github.com/RustCrypto/KDFs/issues/15
29
+ if (salt === undefined)
30
+ salt = new Uint8Array(hash.outputLen);
31
+ return hmac(hash, salt, ikm);
32
+ }
33
+ // Shared mutable scratch byte for the RFC 5869 block counter `N`.
34
+ // Safe to reuse because `expand()` is synchronous and resets it with `clean(...)` before returning.
35
+ const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
36
+ // Shared RFC 5869 empty string for both `info === undefined` and the first-block `T(0)` input.
37
+ const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
38
+ /**
39
+ * HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
40
+ * @param hash - hash function that would be used (e.g. sha256)
41
+ * @param prk - a pseudorandom key of at least HashLen octets
42
+ * (usually, the output from the extract step)
43
+ * @param info - optional context and application specific information (can be a zero-length string)
44
+ * @param length - length of output keying material in bytes.
45
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
46
+ * @returns Output keying material with the requested length.
47
+ * @throws If the requested output length exceeds the HKDF limit
48
+ * for the selected hash. {@link Error}
49
+ * @example
50
+ * Run the HKDF expand step.
51
+ * ```ts
52
+ * import { expand } from '@decryption/hashes/hkdf.js';
53
+ * import { sha256 } from '@decryption/hashes/sha2.js';
54
+ * expand(sha256, new Uint8Array(32), new Uint8Array([1, 2, 3]), 16);
55
+ * ```
56
+ */
57
+ export function expand(hash, prk, info, length = 32) {
58
+ ahash(hash);
59
+ anumber(length, 'length');
60
+ abytes(prk, undefined, 'prk');
61
+ const olen = hash.outputLen;
62
+ // RFC 5869 §2.3: PRK is "a pseudorandom key of at least HashLen octets".
63
+ if (prk.length < olen)
64
+ throw new Error('"prk" must be at least HashLen octets');
65
+ // RFC 5869 §2.3 only bounds `L` by `<= 255*HashLen`; `L=0` is valid and yields empty OKM.
66
+ if (length > 255 * olen)
67
+ throw new Error('Length must be <= 255*HashLen');
68
+ const blocks = Math.ceil(length / olen);
69
+ if (info === undefined)
70
+ info = EMPTY_BUFFER;
71
+ else
72
+ abytes(info, undefined, 'info');
73
+ // first L(ength) octets of T
74
+ const okm = new Uint8Array(blocks * olen);
75
+ // Re-use HMAC instance between blocks
76
+ const HMAC = hmac.create(hash, prk);
77
+ const HMACTmp = HMAC._cloneInto();
78
+ const T = new Uint8Array(HMAC.outputLen);
79
+ for (let counter = 0; counter < blocks; counter++) {
80
+ HKDF_COUNTER[0] = counter + 1;
81
+ // T(0) = empty string (zero length)
82
+ // T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
83
+ HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
84
+ .update(info)
85
+ .update(HKDF_COUNTER)
86
+ .digestInto(T);
87
+ okm.set(T, olen * counter);
88
+ HMAC._cloneInto(HMACTmp);
89
+ }
90
+ HMAC.destroy();
91
+ HMACTmp.destroy();
92
+ clean(T, HKDF_COUNTER);
93
+ return okm.slice(0, length);
94
+ }
95
+ /**
96
+ * HKDF (RFC 5869): derive keys from an initial input.
97
+ * Combines hkdf_extract + hkdf_expand in one step
98
+ * @param hash - hash function that would be used (e.g. sha256)
99
+ * @param ikm - input keying material, the initial key
100
+ * @param salt - optional salt value (a non-secret random value)
101
+ * @param info - optional context and application specific information bytes
102
+ * @param length - length of output keying material in bytes.
103
+ * RFC 5869 §2.3 allows `0..255*HashLen`, so `0` returns an empty OKM.
104
+ * @returns Output keying material derived from the input key.
105
+ * @throws If the requested output length exceeds the HKDF limit
106
+ * for the selected hash. {@link Error}
107
+ * @example
108
+ * HKDF (RFC 5869): derive keys from an initial input.
109
+ * ```ts
110
+ * import { hkdf } from '@decryption/hashes/hkdf.js';
111
+ * import { sha256 } from '@decryption/hashes/sha2.js';
112
+ * import { randomBytes, utf8ToBytes } from '@decryption/hashes/utils.js';
113
+ * const inputKey = randomBytes(32);
114
+ * const salt = randomBytes(32);
115
+ * const info = utf8ToBytes('application-key');
116
+ * const okm = hkdf(sha256, inputKey, salt, info, 32);
117
+ * ```
118
+ */
119
+ export const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);