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