-
Notifications
You must be signed in to change notification settings - Fork 4
/
noble-hashes.js
2310 lines (2289 loc) · 101 KB
/
noble-hashes.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@noble/hashes/crypto')) :
typeof define === 'function' && define.amd ? define(['exports', '@noble/hashes/crypto'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.nobleHashes = {}, global.crypto));
})(this, (function (exports, crypto) { 'use strict';
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
// Cast array to different type
const u8 = (arr) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);
const u32 = (arr) => new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
// Cast array to view
const createView = (arr) => new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
// The rotate right (circular right shift) operation for uint32
const rotr = (word, shift) => (word << (32 - shift)) | (word >>> shift);
const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;
// There is almost no big endian hardware, but js typed arrays uses platform specific endianess.
// So, just to be sure not to corrupt anything.
if (!isLE)
throw new Error('Non little-endian hardware is not supported');
const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));
/**
* @example bytesToHex(Uint8Array.from([0xde, 0xad, 0xbe, 0xef]))
*/
function bytesToHex(uint8a) {
// pre-caching improves the speed 6x
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += hexes[uint8a[i]];
}
return hex;
}
// Currently avoid insertion of polyfills with packers (browserify/webpack/etc)
// But setTimeout is pretty slow, maybe worth to investigate howto do minimal polyfill here
const nextTick = (() => {
const nodeRequire = typeof module !== 'undefined' &&
typeof module.require === 'function' &&
module.require.bind(module);
try {
if (nodeRequire) {
const { setImmediate } = nodeRequire('timers');
return () => new Promise((resolve) => setImmediate(resolve));
}
}
catch (e) { }
return () => new Promise((resolve) => setTimeout(resolve, 0));
})();
// Returns control to thread each 'tick' ms to avoid blocking
async function asyncLoop(iters, tick, cb) {
let ts = Date.now();
for (let i = 0; i < iters; i++) {
cb(i);
// Date.now() is not monotonic, so in case if clock goes backwards we return return control too
const diff = Date.now() - ts;
if (diff >= 0 && diff < tick)
continue;
await nextTick();
ts += diff;
}
}
function utf8ToBytes(str) {
if (typeof str !== 'string') {
throw new TypeError(`utf8ToBytes expected string, got ${typeof str}`);
}
return new TextEncoder().encode(str);
}
function toBytes(data) {
if (typeof data === 'string')
data = utf8ToBytes(data);
if (!(data instanceof Uint8Array))
throw new TypeError(`Expected input type is Uint8Array (got ${typeof data})`);
return data;
}
function assertNumber(n) {
if (!Number.isSafeInteger(n) || n < 0)
throw new Error(`Wrong positive integer: ${n}`);
}
function assertBytes(bytes, ...lengths) {
if (bytes instanceof Uint8Array && (!lengths.length || lengths.includes(bytes.length))) {
return;
}
throw new TypeError(`Expected ${lengths} bytes, not ${typeof bytes} with length=${bytes.length}`);
}
function assertHash(hash) {
if (typeof hash !== 'function' || typeof hash.create !== 'function')
throw new Error('Hash should be wrapped by utils.wrapConstructor');
assertNumber(hash.outputLen);
assertNumber(hash.blockLen);
}
// For runtime check if class implements interface
class Hash {
// Safe version that clones internal state
clone() {
return this._cloneInto();
}
}
// Check if object doens't have custom constructor (like Uint8Array/Array)
const isPlainObject = (obj) => Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
function checkOpts(def, _opts) {
if (_opts !== undefined && (typeof _opts !== 'object' || !isPlainObject(_opts)))
throw new TypeError('Options should be object or undefined');
const opts = Object.assign(def, _opts);
return opts;
}
function wrapConstructor(hashConstructor) {
const hashC = (message) => hashConstructor().update(toBytes(message)).digest();
const tmp = hashConstructor();
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = () => hashConstructor();
return hashC;
}
function wrapConstructorWithOpts(hashCons) {
const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();
const tmp = hashCons({});
hashC.outputLen = tmp.outputLen;
hashC.blockLen = tmp.blockLen;
hashC.create = (opts) => hashCons(opts);
return hashC;
}
/**
* Secure PRNG
*/
function randomBytes(bytesLength = 32) {
if (crypto.crypto.web) {
return crypto.crypto.web.getRandomValues(new Uint8Array(bytesLength));
}
else if (crypto.crypto.node) {
return new Uint8Array(crypto.crypto.node.randomBytes(bytesLength).buffer);
}
else {
throw new Error("The environment doesn't have randomBytes function");
}
}
// prettier-ignore
const SIGMA$1 = new Uint8Array([
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4,
7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8,
9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13,
2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9,
12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11,
13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10,
6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5,
10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0,
// For BLAKE2b, the two extra permutations for rounds 10 and 11 are SIGMA[10..11] = SIGMA[0..1].
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3,
]);
class BLAKE2 extends Hash {
constructor(blockLen, outputLen, opts = {}, keyLen, saltLen, persLen) {
super();
this.blockLen = blockLen;
this.outputLen = outputLen;
this.length = 0;
this.pos = 0;
this.finished = false;
this.destroyed = false;
assertNumber(blockLen);
assertNumber(outputLen);
assertNumber(keyLen);
if (outputLen < 0 || outputLen > keyLen)
throw new Error('Blake2: outputLen bigger than keyLen');
if (opts.key !== undefined && (opts.key.length < 1 || opts.key.length > keyLen))
throw new Error(`Key should be up 1..${keyLen} byte long or undefined`);
if (opts.salt !== undefined && opts.salt.length !== saltLen)
throw new Error(`Salt should be ${saltLen} byte long or undefined`);
if (opts.personalization !== undefined && opts.personalization.length !== persLen)
throw new Error(`Personalization should be ${persLen} byte long or undefined`);
this.buffer32 = u32((this.buffer = new Uint8Array(blockLen)));
}
update(data) {
if (this.destroyed)
throw new Error('instance is destroyed');
// Main difference with other hashes: there is flag for last block,
// so we cannot process current block before we know that there
// is the next one. This significantly complicates logic and reduces ability
// to do zero-copy processing
const { finished, blockLen, buffer, buffer32 } = this;
if (finished)
throw new Error('digest() was already called');
data = toBytes(data);
const len = data.length;
for (let pos = 0; pos < len;) {
// If buffer is full and we still have input (don't process last block, same as blake2s)
if (this.pos === blockLen) {
this.compress(buffer32, 0, false);
this.pos = 0;
}
const take = Math.min(blockLen - this.pos, len - pos);
const dataOffset = data.byteOffset + pos;
// full block && aligned to 4 bytes && not last in input
if (take === blockLen && !(dataOffset % 4) && pos + take < len) {
const data32 = new Uint32Array(data.buffer, dataOffset, Math.floor((len - pos) / 4));
for (let pos32 = 0; pos + blockLen < len; pos32 += buffer32.length, pos += blockLen) {
this.length += blockLen;
this.compress(data32, pos32, false);
}
continue;
}
buffer.set(data.subarray(pos, pos + take), this.pos);
this.pos += take;
this.length += take;
pos += take;
}
return this;
}
digestInto(out) {
if (this.destroyed)
throw new Error('instance is destroyed');
if (!(out instanceof Uint8Array) || out.length < this.outputLen)
throw new Error('_Blake2: Invalid output buffer');
const { finished, pos, buffer32 } = this;
if (finished)
throw new Error('digest() was already called');
this.finished = true;
// Padding
this.buffer.subarray(pos).fill(0);
this.compress(buffer32, 0, true);
const out32 = u32(out);
this.get().forEach((v, i) => (out32[i] = v));
}
digest() {
const { buffer, outputLen } = this;
this.digestInto(buffer);
const res = buffer.slice(0, outputLen);
this.destroy();
return res;
}
_cloneInto(to) {
const { buffer, length, finished, destroyed, outputLen, pos } = this;
to || (to = new this.constructor({ dkLen: outputLen }));
to.set(...this.get());
to.length = length;
to.finished = finished;
to.destroyed = destroyed;
to.outputLen = outputLen;
to.buffer.set(buffer);
to.pos = pos;
return to;
}
}
const U32_MASK64 = BigInt(2 ** 32 - 1);
const _32n = BigInt(32);
function fromBig(n, le = false) {
if (le)
return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };
return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };
}
function split(lst, le = false) {
let Ah = new Uint32Array(lst.length);
let Al = new Uint32Array(lst.length);
for (let i = 0; i < lst.length; i++) {
const { h, l } = fromBig(lst[i], le);
[Ah[i], Al[i]] = [h, l];
}
return [Ah, Al];
}
// for Shift in [0, 32)
const shrSH = (h, l, s) => h >>> s;
const shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in [1, 32)
const rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));
const rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);
// Right rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));
const rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));
// Right rotate for shift===32 (just swaps l&h)
const rotr32H = (h, l) => l;
const rotr32L = (h, l) => h;
// Left rotate for Shift in [1, 32)
const rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));
const rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));
// Left rotate for Shift in (32, 64), NOTE: 32 is special case.
const rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));
const rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));
// JS uses 32-bit signed integers for bitwise operations which means we cannot
// simple take carry out of low bit sum by shift, we need to use division.
function add(Ah, Al, Bh, Bl) {
const l = (Al >>> 0) + (Bl >>> 0);
return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };
}
// Addition with more than 2 elements
const add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);
const add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;
const add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);
const add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;
const add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);
const add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;
// Same as SHA-512 but LE
// prettier-ignore
const IV$2 = new Uint32Array([
0xf3bcc908, 0x6a09e667, 0x84caa73b, 0xbb67ae85, 0xfe94f82b, 0x3c6ef372, 0x5f1d36f1, 0xa54ff53a,
0xade682d1, 0x510e527f, 0x2b3e6c1f, 0x9b05688c, 0xfb41bd6b, 0x1f83d9ab, 0x137e2179, 0x5be0cd19
]);
// Temporary buffer
const BUF$1 = new Uint32Array(32);
// Mixing function G splitted in two halfs
function G1$1(a, b, c, d, msg, x) {
// NOTE: V is LE here
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
let Al = BUF$1[2 * a], Ah = BUF$1[2 * a + 1]; // prettier-ignore
let Bl = BUF$1[2 * b], Bh = BUF$1[2 * b + 1]; // prettier-ignore
let Cl = BUF$1[2 * c], Ch = BUF$1[2 * c + 1]; // prettier-ignore
let Dl = BUF$1[2 * d], Dh = BUF$1[2 * d + 1]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = add3L(Al, Bl, Xl);
Ah = add3H(ll, Ah, Bh, Xh);
Al = ll | 0;
// v[d] = rotr(v[d] ^ v[a], 32)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: rotr32H(Dh, Dl), Dl: rotr32L(Dh) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 24)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: rotrSH(Bh, Bl, 24), Bl: rotrSL(Bh, Bl, 24) });
(BUF$1[2 * a] = Al), (BUF$1[2 * a + 1] = Ah);
(BUF$1[2 * b] = Bl), (BUF$1[2 * b + 1] = Bh);
(BUF$1[2 * c] = Cl), (BUF$1[2 * c + 1] = Ch);
(BUF$1[2 * d] = Dl), (BUF$1[2 * d + 1] = Dh);
}
function G2$1(a, b, c, d, msg, x) {
// NOTE: V is LE here
const Xl = msg[x], Xh = msg[x + 1]; // prettier-ignore
let Al = BUF$1[2 * a], Ah = BUF$1[2 * a + 1]; // prettier-ignore
let Bl = BUF$1[2 * b], Bh = BUF$1[2 * b + 1]; // prettier-ignore
let Cl = BUF$1[2 * c], Ch = BUF$1[2 * c + 1]; // prettier-ignore
let Dl = BUF$1[2 * d], Dh = BUF$1[2 * d + 1]; // prettier-ignore
// v[a] = (v[a] + v[b] + x) | 0;
let ll = add3L(Al, Bl, Xl);
Ah = add3H(ll, Ah, Bh, Xh);
Al = ll | 0;
// v[d] = rotr(v[d] ^ v[a], 16)
({ Dh, Dl } = { Dh: Dh ^ Ah, Dl: Dl ^ Al });
({ Dh, Dl } = { Dh: rotrSH(Dh, Dl, 16), Dl: rotrSL(Dh, Dl, 16) });
// v[c] = (v[c] + v[d]) | 0;
({ h: Ch, l: Cl } = add(Ch, Cl, Dh, Dl));
// v[b] = rotr(v[b] ^ v[c], 63)
({ Bh, Bl } = { Bh: Bh ^ Ch, Bl: Bl ^ Cl });
({ Bh, Bl } = { Bh: rotrBH(Bh, Bl, 63), Bl: rotrBL(Bh, Bl, 63) });
(BUF$1[2 * a] = Al), (BUF$1[2 * a + 1] = Ah);
(BUF$1[2 * b] = Bl), (BUF$1[2 * b + 1] = Bh);
(BUF$1[2 * c] = Cl), (BUF$1[2 * c + 1] = Ch);
(BUF$1[2 * d] = Dl), (BUF$1[2 * d + 1] = Dh);
}
class BLAKE2b extends BLAKE2 {
constructor(opts = {}) {
super(128, opts.dkLen === undefined ? 64 : opts.dkLen, opts, 64, 16, 16);
// Same as SHA-512, but LE
this.v0l = IV$2[0] | 0;
this.v0h = IV$2[1] | 0;
this.v1l = IV$2[2] | 0;
this.v1h = IV$2[3] | 0;
this.v2l = IV$2[4] | 0;
this.v2h = IV$2[5] | 0;
this.v3l = IV$2[6] | 0;
this.v3h = IV$2[7] | 0;
this.v4l = IV$2[8] | 0;
this.v4h = IV$2[9] | 0;
this.v5l = IV$2[10] | 0;
this.v5h = IV$2[11] | 0;
this.v6l = IV$2[12] | 0;
this.v6h = IV$2[13] | 0;
this.v7l = IV$2[14] | 0;
this.v7h = IV$2[15] | 0;
const keyLength = opts.key ? opts.key.length : 0;
this.v0l ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
if (opts.salt) {
const salt = u32(toBytes(opts.salt));
this.v4l ^= salt[0];
this.v4h ^= salt[1];
this.v5l ^= salt[2];
this.v5h ^= salt[3];
}
if (opts.personalization) {
const pers = u32(toBytes(opts.personalization));
this.v6l ^= pers[0];
this.v6h ^= pers[1];
this.v7l ^= pers[2];
this.v7h ^= pers[3];
}
if (opts.key) {
// Pad to blockLen and update
const tmp = new Uint8Array(this.blockLen);
tmp.set(toBytes(opts.key));
this.update(tmp);
}
}
// prettier-ignore
get() {
let { v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h } = this;
return [v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h];
}
// prettier-ignore
set(v0l, v0h, v1l, v1h, v2l, v2h, v3l, v3h, v4l, v4h, v5l, v5h, v6l, v6h, v7l, v7h) {
this.v0l = v0l | 0;
this.v0h = v0h | 0;
this.v1l = v1l | 0;
this.v1h = v1h | 0;
this.v2l = v2l | 0;
this.v2h = v2h | 0;
this.v3l = v3l | 0;
this.v3h = v3h | 0;
this.v4l = v4l | 0;
this.v4h = v4h | 0;
this.v5l = v5l | 0;
this.v5h = v5h | 0;
this.v6l = v6l | 0;
this.v6h = v6h | 0;
this.v7l = v7l | 0;
this.v7h = v7h | 0;
}
compress(msg, offset, isLast) {
this.get().forEach((v, i) => (BUF$1[i] = v)); // First half from state.
BUF$1.set(IV$2, 16); // Second half from IV.
let { h, l } = fromBig(BigInt(this.length));
BUF$1[24] = IV$2[8] ^ l; // Low word of the offset.
BUF$1[25] = IV$2[9] ^ h; // High word.
// Invert all bits for last block
if (isLast) {
BUF$1[28] = ~BUF$1[28];
BUF$1[29] = ~BUF$1[29];
}
let j = 0;
const s = SIGMA$1;
for (let i = 0; i < 12; i++) {
G1$1(0, 4, 8, 12, msg, offset + 2 * s[j++]);
G2$1(0, 4, 8, 12, msg, offset + 2 * s[j++]);
G1$1(1, 5, 9, 13, msg, offset + 2 * s[j++]);
G2$1(1, 5, 9, 13, msg, offset + 2 * s[j++]);
G1$1(2, 6, 10, 14, msg, offset + 2 * s[j++]);
G2$1(2, 6, 10, 14, msg, offset + 2 * s[j++]);
G1$1(3, 7, 11, 15, msg, offset + 2 * s[j++]);
G2$1(3, 7, 11, 15, msg, offset + 2 * s[j++]);
G1$1(0, 5, 10, 15, msg, offset + 2 * s[j++]);
G2$1(0, 5, 10, 15, msg, offset + 2 * s[j++]);
G1$1(1, 6, 11, 12, msg, offset + 2 * s[j++]);
G2$1(1, 6, 11, 12, msg, offset + 2 * s[j++]);
G1$1(2, 7, 8, 13, msg, offset + 2 * s[j++]);
G2$1(2, 7, 8, 13, msg, offset + 2 * s[j++]);
G1$1(3, 4, 9, 14, msg, offset + 2 * s[j++]);
G2$1(3, 4, 9, 14, msg, offset + 2 * s[j++]);
}
this.v0l ^= BUF$1[0] ^ BUF$1[16];
this.v0h ^= BUF$1[1] ^ BUF$1[17];
this.v1l ^= BUF$1[2] ^ BUF$1[18];
this.v1h ^= BUF$1[3] ^ BUF$1[19];
this.v2l ^= BUF$1[4] ^ BUF$1[20];
this.v2h ^= BUF$1[5] ^ BUF$1[21];
this.v3l ^= BUF$1[6] ^ BUF$1[22];
this.v3h ^= BUF$1[7] ^ BUF$1[23];
this.v4l ^= BUF$1[8] ^ BUF$1[24];
this.v4h ^= BUF$1[9] ^ BUF$1[25];
this.v5l ^= BUF$1[10] ^ BUF$1[26];
this.v5h ^= BUF$1[11] ^ BUF$1[27];
this.v6l ^= BUF$1[12] ^ BUF$1[28];
this.v6h ^= BUF$1[13] ^ BUF$1[29];
this.v7l ^= BUF$1[14] ^ BUF$1[30];
this.v7h ^= BUF$1[15] ^ BUF$1[31];
BUF$1.fill(0);
}
destroy() {
this.destroyed = true;
this.buffer32.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
}
}
/**
* BLAKE2b - optimized for 64-bit platforms. JS doesn't have uint64, so it's slower than BLAKE2s.
* @param msg - message that would be hashed
* @param opts - dkLen, key, salt, personalization
*/
const blake2b = wrapConstructorWithOpts((opts) => new BLAKE2b(opts));
// Initial state:
// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19)
// same as SHA-256
// prettier-ignore
const IV$1 = new Uint32Array([
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
]);
// Mixing function G splitted in two halfs
function G1(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 16);
c = (c + d) | 0;
b = rotr(b ^ c, 12);
return { a, b, c, d };
}
function G2(a, b, c, d, x) {
a = (a + b + x) | 0;
d = rotr(d ^ a, 8);
c = (c + d) | 0;
b = rotr(b ^ c, 7);
return { a, b, c, d };
}
// prettier-ignore
function compress(s, offset, msg, rounds, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) {
let j = 0;
for (let i = 0; i < rounds; i++) {
({ a: v0, b: v4, c: v8, d: v12 } = G1(v0, v4, v8, v12, msg[offset + s[j++]]));
({ a: v0, b: v4, c: v8, d: v12 } = G2(v0, v4, v8, v12, msg[offset + s[j++]]));
({ a: v1, b: v5, c: v9, d: v13 } = G1(v1, v5, v9, v13, msg[offset + s[j++]]));
({ a: v1, b: v5, c: v9, d: v13 } = G2(v1, v5, v9, v13, msg[offset + s[j++]]));
({ a: v2, b: v6, c: v10, d: v14 } = G1(v2, v6, v10, v14, msg[offset + s[j++]]));
({ a: v2, b: v6, c: v10, d: v14 } = G2(v2, v6, v10, v14, msg[offset + s[j++]]));
({ a: v3, b: v7, c: v11, d: v15 } = G1(v3, v7, v11, v15, msg[offset + s[j++]]));
({ a: v3, b: v7, c: v11, d: v15 } = G2(v3, v7, v11, v15, msg[offset + s[j++]]));
({ a: v0, b: v5, c: v10, d: v15 } = G1(v0, v5, v10, v15, msg[offset + s[j++]]));
({ a: v0, b: v5, c: v10, d: v15 } = G2(v0, v5, v10, v15, msg[offset + s[j++]]));
({ a: v1, b: v6, c: v11, d: v12 } = G1(v1, v6, v11, v12, msg[offset + s[j++]]));
({ a: v1, b: v6, c: v11, d: v12 } = G2(v1, v6, v11, v12, msg[offset + s[j++]]));
({ a: v2, b: v7, c: v8, d: v13 } = G1(v2, v7, v8, v13, msg[offset + s[j++]]));
({ a: v2, b: v7, c: v8, d: v13 } = G2(v2, v7, v8, v13, msg[offset + s[j++]]));
({ a: v3, b: v4, c: v9, d: v14 } = G1(v3, v4, v9, v14, msg[offset + s[j++]]));
({ a: v3, b: v4, c: v9, d: v14 } = G2(v3, v4, v9, v14, msg[offset + s[j++]]));
}
return { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 };
}
class BLAKE2s extends BLAKE2 {
constructor(opts = {}) {
super(64, opts.dkLen === undefined ? 32 : opts.dkLen, opts, 32, 8, 8);
// Internal state, same as SHA-256
this.v0 = IV$1[0] | 0;
this.v1 = IV$1[1] | 0;
this.v2 = IV$1[2] | 0;
this.v3 = IV$1[3] | 0;
this.v4 = IV$1[4] | 0;
this.v5 = IV$1[5] | 0;
this.v6 = IV$1[6] | 0;
this.v7 = IV$1[7] | 0;
const keyLength = opts.key ? opts.key.length : 0;
this.v0 ^= this.outputLen | (keyLength << 8) | (0x01 << 16) | (0x01 << 24);
if (opts.salt) {
const salt = u32(toBytes(opts.salt));
this.v4 ^= salt[0];
this.v5 ^= salt[1];
}
if (opts.personalization) {
const pers = u32(toBytes(opts.personalization));
this.v6 ^= pers[0];
this.v7 ^= pers[1];
}
if (opts.key) {
// Pad to blockLen and update
const tmp = new Uint8Array(this.blockLen);
tmp.set(toBytes(opts.key));
this.update(tmp);
}
}
get() {
const { v0, v1, v2, v3, v4, v5, v6, v7 } = this;
return [v0, v1, v2, v3, v4, v5, v6, v7];
}
// prettier-ignore
set(v0, v1, v2, v3, v4, v5, v6, v7) {
this.v0 = v0 | 0;
this.v1 = v1 | 0;
this.v2 = v2 | 0;
this.v3 = v3 | 0;
this.v4 = v4 | 0;
this.v5 = v5 | 0;
this.v6 = v6 | 0;
this.v7 = v7 | 0;
}
compress(msg, offset, isLast) {
const { h, l } = fromBig(BigInt(this.length));
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA$1, offset, msg, 10, this.v0, this.v1, this.v2, this.v3, this.v4, this.v5, this.v6, this.v7, IV$1[0], IV$1[1], IV$1[2], IV$1[3], l ^ IV$1[4], h ^ IV$1[5], isLast ? ~IV$1[6] : IV$1[6], IV$1[7]);
this.v0 ^= v0 ^ v8;
this.v1 ^= v1 ^ v9;
this.v2 ^= v2 ^ v10;
this.v3 ^= v3 ^ v11;
this.v4 ^= v4 ^ v12;
this.v5 ^= v5 ^ v13;
this.v6 ^= v6 ^ v14;
this.v7 ^= v7 ^ v15;
}
destroy() {
this.destroyed = true;
this.buffer32.fill(0);
this.set(0, 0, 0, 0, 0, 0, 0, 0);
}
}
/**
* BLAKE2s - optimized for 32-bit platforms. JS doesn't have uint64, so it's faster than BLAKE2b.
* @param msg - message that would be hashed
* @param opts - dkLen, key, salt, personalization
*/
const blake2s = wrapConstructorWithOpts((opts) => new BLAKE2s(opts));
// Flag bitset
var Flags;
(function (Flags) {
Flags[Flags["CHUNK_START"] = 1] = "CHUNK_START";
Flags[Flags["CHUNK_END"] = 2] = "CHUNK_END";
Flags[Flags["PARENT"] = 4] = "PARENT";
Flags[Flags["ROOT"] = 8] = "ROOT";
Flags[Flags["KEYED_HASH"] = 16] = "KEYED_HASH";
Flags[Flags["DERIVE_KEY_CONTEXT"] = 32] = "DERIVE_KEY_CONTEXT";
Flags[Flags["DERIVE_KEY_MATERIAL"] = 64] = "DERIVE_KEY_MATERIAL";
})(Flags || (Flags = {}));
const SIGMA = (() => {
const Id = Array.from({ length: 16 }, (_, i) => i);
const permute = (arr) => [2, 6, 3, 10, 7, 0, 4, 13, 1, 11, 12, 5, 9, 14, 15, 8].map((i) => arr[i]);
const res = [];
for (let i = 0, v = Id; i < 7; i++, v = permute(v))
res.push(...v);
return Uint8Array.from(res);
})();
// Why is this so slow? It should be 6x faster than blake2b.
// - There is only 30% reduction in number of rounds from blake2s
// - This function uses tree mode to achive parallelisation via SIMD and threading,
// however in JS we don't have threads and SIMD, so we get only overhead from tree structure
// - It is possible to speed it up via Web Workers, hovewer it will make code singnificantly more
// complicated, which we are trying to avoid, since this library is intended to be used
// for cryptographic purposes. Also, parallelization happens only on chunk level (1024 bytes),
// which won't really benefit small inputs.
class BLAKE3 extends BLAKE2 {
constructor(opts = {}, flags = 0) {
super(64, opts.dkLen === undefined ? 32 : opts.dkLen, {}, Number.MAX_SAFE_INTEGER, 0, 0);
this.flags = 0 | 0;
this.chunkPos = 0; // Position of current block in chunk
this.chunksDone = 0; // How many chunks we already have
this.stack = [];
// Output
this.posOut = 0;
this.bufferOut32 = new Uint32Array(16);
this.chunkOut = 0; // index of output chunk
this.enableXOF = true;
this.outputLen = opts.dkLen === undefined ? 32 : opts.dkLen;
assertNumber(this.outputLen);
if (opts.key !== undefined && opts.context !== undefined)
throw new Error('Blake3: only key or context can be specified at same time');
else if (opts.key !== undefined) {
const key = toBytes(opts.key);
if (key.length !== 32)
throw new Error('Blake3: key should be 32 byte');
this.IV = u32(key);
this.flags = flags | Flags.KEYED_HASH;
}
else if (opts.context !== undefined) {
const context_key = new BLAKE3({ dkLen: 32 }, Flags.DERIVE_KEY_CONTEXT)
.update(opts.context)
.digest();
this.IV = u32(context_key);
this.flags = flags | Flags.DERIVE_KEY_MATERIAL;
}
else {
this.IV = IV$1.slice();
this.flags = flags;
}
this.state = this.IV.slice();
this.bufferOut = u8(this.bufferOut32);
}
// Unused
get() {
return [];
}
set() { }
b2Compress(counter, flags, buf, bufPos = 0) {
const { state, pos } = this;
const { h, l } = fromBig(BigInt(counter), true);
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, bufPos, buf, 7, state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7], IV$1[0], IV$1[1], IV$1[2], IV$1[3], h, l, pos, flags);
state[0] = v0 ^ v8;
state[1] = v1 ^ v9;
state[2] = v2 ^ v10;
state[3] = v3 ^ v11;
state[4] = v4 ^ v12;
state[5] = v5 ^ v13;
state[6] = v6 ^ v14;
state[7] = v7 ^ v15;
}
compress(buf, bufPos = 0, isLast = false) {
// Compress last block
let flags = this.flags;
if (!this.chunkPos)
flags |= Flags.CHUNK_START;
if (this.chunkPos === 15 || isLast)
flags |= Flags.CHUNK_END;
if (!isLast)
this.pos = this.blockLen;
this.b2Compress(this.chunksDone, flags, buf, bufPos);
this.chunkPos += 1;
// If current block is last in chunk (16 blocks), then compress chunks
if (this.chunkPos === 16 || isLast) {
let chunk = this.state;
this.state = this.IV.slice();
// If not the last one, compress only when there are trailing zeros in chunk counter
// chunks used as binary tree where current stack is path. Zero means current leaf is finished and can be compressed.
// 1 (001) - leaf not finished (just push current chunk to stack)
// 2 (010) - leaf finished at depth=1 (merge with last elm on stack and push back)
// 3 (011) - last leaf not finished
// 4 (100) - leafs finished at depth=1 and depth=2
for (let last, chunks = this.chunksDone + 1; isLast || !(chunks & 1); chunks >>= 1) {
if (!(last = this.stack.pop()))
break;
this.buffer32.set(last, 0);
this.buffer32.set(chunk, 8);
this.pos = this.blockLen;
this.b2Compress(0, this.flags | Flags.PARENT, this.buffer32, 0);
chunk = this.state;
this.state = this.IV.slice();
}
this.chunksDone++;
this.chunkPos = 0;
this.stack.push(chunk);
}
this.pos = 0;
}
_cloneInto(to) {
to = super._cloneInto(to);
const { IV, flags, state, chunkPos, posOut, chunkOut, stack, chunksDone } = this;
to.state.set(state.slice());
to.stack = stack.map((i) => Uint32Array.from(i));
to.IV.set(IV);
to.flags = flags;
to.chunkPos = chunkPos;
to.chunksDone = chunksDone;
to.posOut = posOut;
to.chunkOut = chunkOut;
to.enableXOF = this.enableXOF;
to.bufferOut32.set(this.bufferOut32);
return to;
}
destroy() {
this.destroyed = true;
this.state.fill(0);
this.buffer32.fill(0);
this.IV.fill(0);
this.bufferOut32.fill(0);
for (let i of this.stack)
i.fill(0);
}
// Same as b2Compress, but doesn't modify state and returns 16 u32 array (instead of 8)
b2CompressOut() {
const { state, pos, flags, buffer32, bufferOut32 } = this;
const { h, l } = fromBig(BigInt(this.chunkOut++));
// prettier-ignore
const { v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15 } = compress(SIGMA, 0, buffer32, 7, state[0], state[1], state[2], state[3], state[4], state[5], state[6], state[7], IV$1[0], IV$1[1], IV$1[2], IV$1[3], l, h, pos, flags);
bufferOut32[0] = v0 ^ v8;
bufferOut32[1] = v1 ^ v9;
bufferOut32[2] = v2 ^ v10;
bufferOut32[3] = v3 ^ v11;
bufferOut32[4] = v4 ^ v12;
bufferOut32[5] = v5 ^ v13;
bufferOut32[6] = v6 ^ v14;
bufferOut32[7] = v7 ^ v15;
bufferOut32[8] = state[0] ^ v8;
bufferOut32[9] = state[1] ^ v9;
bufferOut32[10] = state[2] ^ v10;
bufferOut32[11] = state[3] ^ v11;
bufferOut32[12] = state[4] ^ v12;
bufferOut32[13] = state[5] ^ v13;
bufferOut32[14] = state[6] ^ v14;
bufferOut32[15] = state[7] ^ v15;
this.posOut = 0;
}
finish() {
if (this.finished)
return;
this.finished = true;
// Padding
this.buffer.fill(0, this.pos);
// Process last chunk
let flags = this.flags | Flags.ROOT;
if (this.stack.length) {
flags |= Flags.PARENT;
this.compress(this.buffer32, 0, true);
this.chunksDone = 0;
this.pos = this.blockLen;
}
else {
flags |= (!this.chunkPos ? Flags.CHUNK_START : 0) | Flags.CHUNK_END;
}
this.flags = flags;
this.b2CompressOut();
}
writeInto(out) {
if (this.destroyed)
throw new Error('instance is destroyed');
if (!(out instanceof Uint8Array))
throw new Error('Blake3: Invalid output buffer');
this.finish();
const { blockLen, bufferOut } = this;
for (let pos = 0, len = out.length; pos < len;) {
if (this.posOut >= blockLen)
this.b2CompressOut();
const take = Math.min(this.blockLen - this.posOut, len - pos);
out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);
this.posOut += take;
pos += take;
}
return out;
}
xofInto(out) {
if (!this.enableXOF)
throw new Error('XOF impossible after digest call');
return this.writeInto(out);
}
xof(bytes) {
assertNumber(bytes);
return this.xofInto(new Uint8Array(bytes));
}
digestInto(out) {
if (out.length < this.outputLen)
throw new Error('Blake3: Invalid output buffer');
if (this.finished)
throw new Error('digest() was already called');
this.enableXOF = false;
this.writeInto(out);
this.destroy();
return out;
}
digest() {
return this.digestInto(new Uint8Array(this.outputLen));
}
}
/**
* BLAKE3 hash function.
* @param msg - message that would be hashed
* @param opts - dkLen, key, context
*/
const blake3 = wrapConstructorWithOpts((opts) => new BLAKE3(opts));
// HMAC (RFC 2104)
class HMAC extends Hash {
constructor(hash, _key) {
super();
this.finished = false;
this.destroyed = false;
assertHash(hash);
const key = toBytes(_key);
this.iHash = hash.create();
if (!(this.iHash instanceof Hash))
throw new TypeError('Expected instance of class which extends utils.Hash');
const blockLen = (this.blockLen = this.iHash.blockLen);
this.outputLen = this.iHash.outputLen;
const pad = new Uint8Array(blockLen);
// blockLen can be bigger than outputLen
pad.set(key.length > this.iHash.blockLen ? hash.create().update(key).digest() : key);
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36;
this.iHash.update(pad);
// By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone
this.oHash = hash.create();
// Undo internal XOR && apply outer XOR
for (let i = 0; i < pad.length; i++)
pad[i] ^= 0x36 ^ 0x5c;
this.oHash.update(pad);
pad.fill(0);
}
update(buf) {
if (this.destroyed)
throw new Error('instance is destroyed');
this.iHash.update(buf);
return this;
}
digestInto(out) {
if (this.destroyed)
throw new Error('instance is destroyed');
if (!(out instanceof Uint8Array) || out.length !== this.outputLen)
throw new Error('HMAC: Invalid output buffer');
if (this.finished)
throw new Error('digest() was already called');
this.finished = true;
this.iHash.digestInto(out);
this.oHash.update(out);
this.oHash.digestInto(out);
this.destroy();
}
digest() {
const out = new Uint8Array(this.oHash.outputLen);
this.digestInto(out);
return out;
}
_cloneInto(to) {
// Create new instance without calling constructor since key already in state and we don't know it.
to || (to = Object.create(Object.getPrototypeOf(this), {}));
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
to = to;
to.finished = finished;
to.destroyed = destroyed;
to.blockLen = blockLen;
to.outputLen = outputLen;
to.oHash = oHash._cloneInto(to.oHash);
to.iHash = iHash._cloneInto(to.iHash);
return to;
}
destroy() {
this.destroyed = true;
this.oHash.destroy();
this.iHash.destroy();
}
}
/**
* HMAC: RFC2104 message authentication code.
* @param hash - function that would be used e.g. sha256
* @param key - message key
* @param message - message data
*/
const hmac = (hash, key, message) => new HMAC(hash, key).update(message).digest();
hmac.create = (hash, key) => new HMAC(hash, key);
// HKDF (RFC 5869)
// https://soatok.blog/2021/11/17/understanding-hkdf/
/**
* HKDF-Extract(IKM, salt) -> PRK
* Arguments position differs from spec (IKM is first one, since it is not optional)
* @param hash
* @param ikm
* @param salt
* @returns
*/
function extract(hash, ikm, salt) {
assertHash(hash);
// NOTE: some libraries treat zero-length array as 'not provided';
// we don't, since we have undefined as 'not provided'
// https://github.com/RustCrypto/KDFs/issues/15
if (salt === undefined)
salt = new Uint8Array(hash.outputLen); // if not provided, it is set to a string of HashLen zeros
return hmac(hash, toBytes(salt), toBytes(ikm));
}
// HKDF-Expand(PRK, info, L) -> OKM
const HKDF_COUNTER = new Uint8Array([0]);
const EMPTY_BUFFER = new Uint8Array();
/**
* HKDF-expand from the spec.
* @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
* @param info - optional context and application specific information (can be a zero-length string)
* @param length - length of output keying material in octets
*/
function expand(hash, prk, info, length = 32) {
assertHash(hash);
assertNumber(length);
if (length > 255 * hash.outputLen)
throw new Error('Length should be <= 255*HashLen');
const blocks = Math.ceil(length / hash.outputLen);
if (info === undefined)
info = EMPTY_BUFFER;
// first L(ength) octets of T
const okm = new Uint8Array(blocks * hash.outputLen);
// Re-use HMAC instance between blocks
const HMAC = hmac.create(hash, prk);
const HMACTmp = HMAC._cloneInto();
const T = new Uint8Array(HMAC.outputLen);
for (let counter = 0; counter < blocks; counter++) {
HKDF_COUNTER[0] = counter + 1;
// T(0) = empty string (zero length)
// T(N) = HMAC-Hash(PRK, T(N-1) | info | N)
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T)
.update(info)
.update(HKDF_COUNTER)
.digestInto(T);
okm.set(T, hash.outputLen * counter);
HMAC._cloneInto(HMACTmp);
}
HMAC.destroy();
HMACTmp.destroy();
T.fill(0);
HKDF_COUNTER.fill(0);
return okm.slice(0, length);
}
/**
* HKDF (RFC 5869): extract + expand in one step.
* @param hash - hash function that would be used (e.g. sha256)
* @param ikm - input keying material, the initial key
* @param salt - optional salt value (a non-secret random value)
* @param info - optional context and application specific information
* @param length - length of output keying material in octets
*/
const hkdf = (hash, ikm, salt, info, length) => expand(hash, extract(hash, ikm, salt), info, length);
// Common prologue and epilogue for sync/async functions
function pbkdf2Init(hash, _password, _salt, _opts) {
assertHash(hash);
const opts = checkOpts({ dkLen: 32, asyncTick: 10 }, _opts);
const { c, dkLen, asyncTick } = opts;
assertNumber(c);
assertNumber(dkLen);
assertNumber(asyncTick);
if (c < 1)
throw new Error('PBKDF2: iterations (c) should be >= 1');
const password = toBytes(_password);
const salt = toBytes(_salt);
// DK = PBKDF2(PRF, Password, Salt, c, dkLen);
const DK = new Uint8Array(dkLen);
// U1 = PRF(Password, Salt + INT_32_BE(i))
const PRF = hmac.create(hash, password);
const PRFSalt = PRF._cloneInto().update(salt);
return { c, dkLen, asyncTick, DK, PRF, PRFSalt };
}
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
PRF.destroy();
PRFSalt.destroy();