hpke 0.5.0 → 1.0.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.
package/index.js ADDED
@@ -0,0 +1,4190 @@
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
+ function ComputeNonce(base_nonce , seq , Nn ) {
46
+ const seq_bytes = I2OSP(seq, Nn)
47
+ return xor(base_nonce, seq_bytes)
48
+ }
49
+
50
+ function IncrementSeq(seq ) {
51
+
52
+
53
+
54
+ if (seq >= Number.MAX_SAFE_INTEGER) {
55
+ throw new MessageLimitReachedError('Sequence number overflow')
56
+ }
57
+ return ++seq
58
+ }
59
+
60
+ async function ContextExport(
61
+ suite ,
62
+ exporterSecret ,
63
+ exporterContext ,
64
+ L ,
65
+ ) {
66
+ checkUint8Array(exporterContext, 'exporterContext')
67
+ const stages = KDFStages(suite.KDF)
68
+ if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {
69
+ throw new TypeError('"L" must be a positive integer not exceeding 65535')
70
+ }
71
+ const Export = stages === 1 ? ExportOneStage : ExportTwoStage
72
+ return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)
73
+ }
74
+
75
+ class Mutex {
76
+ #locked = Promise.resolve()
77
+
78
+ async lock() {
79
+ let releaseLock
80
+ const nextLock = new Promise ((resolve) => {
81
+ releaseLock = resolve
82
+ })
83
+ const previousLock = this.#locked
84
+ this.#locked = nextLock
85
+ await previousLock
86
+ return releaseLock
87
+ }
88
+ }
89
+
90
+
91
+
92
+
93
+
94
+
95
+
96
+
97
+
98
+
99
+
100
+
101
+
102
+
103
+
104
+
105
+
106
+
107
+
108
+
109
+ class SenderContext {
110
+ #suite
111
+ #key
112
+ #base_nonce
113
+ #exporter_secret
114
+ #mode
115
+ #seq = 0
116
+ #mutex
117
+
118
+ constructor(
119
+ suite ,
120
+ mode ,
121
+ key ,
122
+ base_nonce ,
123
+ exporter_secret ,
124
+ ) {
125
+ this.#suite = suite
126
+ this.#mode = mode
127
+ this.#key = key
128
+ this.#base_nonce = base_nonce
129
+ this.#exporter_secret = exporter_secret
130
+ }
131
+
132
+
133
+ get mode() {
134
+ return this.#mode
135
+ }
136
+
137
+
138
+
139
+
140
+
141
+
142
+ get seq() {
143
+ return this.#seq
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
+ async Seal(plaintext , aad ) {
172
+ checkUint8Array(plaintext, 'plaintext')
173
+ aad ??= new Uint8Array()
174
+ checkUint8Array(aad, 'aad')
175
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
176
+ throw new TypeError('Export-only AEAD cannot be used with Seal')
177
+ }
178
+
179
+ this.#mutex ??= new Mutex()
180
+ const release = await this.#mutex.lock()
181
+ let ct
182
+ try {
183
+ ct = await this.#suite.AEAD.Seal(
184
+ this.#key,
185
+ ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
186
+ aad,
187
+ plaintext,
188
+ )
189
+ this.#seq = IncrementSeq(this.#seq)
190
+ return ct
191
+ } finally {
192
+ release()
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
+ async Export(exporterContext , length ) {
219
+ return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
220
+ }
221
+
222
+
223
+
224
+
225
+
226
+ get Nt() {
227
+ return this.#suite.AEAD.Nt
228
+ }
229
+ }
230
+
231
+
232
+
233
+
234
+
235
+
236
+
237
+
238
+
239
+
240
+
241
+
242
+
243
+
244
+
245
+
246
+
247
+
248
+
249
+
250
+
251
+ class RecipientContext {
252
+ #suite
253
+ #key
254
+ #base_nonce
255
+ #exporter_secret
256
+ #mode
257
+ #seq = 0
258
+ #mutex
259
+
260
+ constructor(
261
+ suite ,
262
+ mode ,
263
+ key ,
264
+ base_nonce ,
265
+ exporter_secret ,
266
+ ) {
267
+ this.#suite = suite
268
+ this.#mode = mode
269
+ this.#key = key
270
+ this.#base_nonce = base_nonce
271
+ this.#exporter_secret = exporter_secret
272
+ }
273
+
274
+
275
+ get mode() {
276
+ return this.#mode
277
+ }
278
+
279
+
280
+
281
+
282
+
283
+
284
+ get seq() {
285
+ return this.#seq
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
+ async Open(ciphertext , aad ) {
315
+ checkUint8Array(ciphertext, 'ciphertext')
316
+ aad ??= new Uint8Array()
317
+ checkUint8Array(aad, 'aad')
318
+
319
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
320
+ throw new TypeError('Export-only AEAD cannot be used with Open')
321
+ }
322
+
323
+ this.#mutex ??= new Mutex()
324
+ const release = await this.#mutex.lock()
325
+ try {
326
+ let pt
327
+ try {
328
+ pt = await this.#suite.AEAD.Open(
329
+ this.#key,
330
+ ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
331
+ aad,
332
+ ciphertext,
333
+ )
334
+ } catch (cause) {
335
+ if (cause instanceof MessageLimitReachedError || cause instanceof NotSupportedError) {
336
+ throw cause
337
+ }
338
+
339
+ throw new OpenError('AEAD decryption failed', { cause })
340
+ }
341
+ this.#seq = IncrementSeq(this.#seq)
342
+ return pt
343
+ } finally {
344
+ release()
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
+ async Export(exporterContext , length ) {
371
+ return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
372
+ }
373
+ }
374
+
375
+
376
+
377
+
378
+
379
+
380
+ const validate = (factory , type ) => {
381
+ try {
382
+ const result = factory()
383
+ if (result.type !== type) {
384
+ throw new Error(`Invalid "${type}" return discriminator`)
385
+ }
386
+ return result
387
+ } catch (cause) {
388
+ throw new TypeError(`Invalid "${type}"`, { cause })
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
+ export class CipherSuite {
416
+ #suite
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
+ constructor(KEM , KDF , AEAD ) {
480
+ const kem = validate(KEM, 'KEM')
481
+ const kdf = validate(KDF, 'KDF')
482
+ const aead = validate(AEAD, 'AEAD')
483
+
484
+ this.#suite = {
485
+ KEM: kem,
486
+ KDF: kdf,
487
+ AEAD: aead,
488
+ id: concat(encode('HPKE'), I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
489
+ }
490
+ }
491
+
492
+
493
+
494
+
495
+
496
+
497
+ get KEM()
498
+
499
+
500
+
501
+
502
+
503
+
504
+
505
+
506
+
507
+
508
+
509
+
510
+ {
511
+ return {
512
+ id: this.#suite.KEM.id,
513
+ name: this.#suite.KEM.name,
514
+ Nsecret: this.#suite.KEM.Nsecret,
515
+ Nenc: this.#suite.KEM.Nenc,
516
+ Npk: this.#suite.KEM.Npk,
517
+ Nsk: this.#suite.KEM.Nsk,
518
+ }
519
+ }
520
+
521
+
522
+
523
+
524
+
525
+
526
+ get KDF()
527
+
528
+
529
+
530
+
531
+
532
+
533
+
534
+
535
+
536
+
537
+
538
+
539
+
540
+
541
+
542
+
543
+ {
544
+ return {
545
+ id: this.#suite.KDF.id,
546
+ name: this.#suite.KDF.name,
547
+ stages: this.#suite.KDF.stages,
548
+ Nh: this.#suite.KDF.Nh,
549
+ }
550
+ }
551
+
552
+
553
+
554
+
555
+
556
+
557
+
558
+ get AEAD()
559
+
560
+
561
+
562
+
563
+
564
+
565
+
566
+
567
+
568
+
569
+ {
570
+ return {
571
+ id: this.#suite.AEAD.id,
572
+ name: this.#suite.AEAD.name,
573
+ Nk: this.#suite.AEAD.Nk,
574
+ Nn: this.#suite.AEAD.Nn,
575
+ Nt: this.#suite.AEAD.Nt,
576
+ }
577
+ }
578
+
579
+
580
+
581
+
582
+
583
+
584
+
585
+
586
+
587
+
588
+
589
+
590
+
591
+
592
+
593
+
594
+
595
+
596
+ async GenerateKeyPair(extractable ) {
597
+ extractable ??= false
598
+ checkExtractable(extractable)
599
+ return await this.#suite.KEM.GenerateKeyPair(extractable)
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
+ async DeriveKeyPair(ikm , extractable ) {
625
+ extractable ??= false
626
+ checkExtractable(extractable)
627
+ checkUint8Array(ikm, 'ikm')
628
+ if (ikm.byteLength < this.#suite.KEM.Nsk) {
629
+ throw new DeriveKeyPairError('Insufficient "ikm" length')
630
+ }
631
+ try {
632
+ return await this.#suite.KEM.DeriveKeyPair(ikm, extractable)
633
+ } catch (cause) {
634
+ if (cause instanceof NotSupportedError) {
635
+ throw cause
636
+ }
637
+ throw new DeriveKeyPairError('Key derivation failed', { cause })
638
+ }
639
+ }
640
+
641
+
642
+
643
+
644
+
645
+
646
+
647
+
648
+
649
+
650
+
651
+
652
+
653
+
654
+
655
+
656
+
657
+ async SerializePrivateKey(privateKey ) {
658
+ isKey(privateKey, 'private', true)
659
+
660
+ return await this.#suite.KEM.SerializePrivateKey(privateKey)
661
+ }
662
+
663
+
664
+
665
+
666
+
667
+
668
+
669
+
670
+
671
+
672
+
673
+
674
+
675
+
676
+
677
+
678
+
679
+ async SerializePublicKey(publicKey ) {
680
+ isKey(publicKey, 'public', true)
681
+
682
+ return await this.#suite.KEM.SerializePublicKey(publicKey)
683
+ }
684
+
685
+
686
+
687
+
688
+
689
+
690
+
691
+
692
+
693
+
694
+
695
+
696
+
697
+
698
+
699
+
700
+
701
+
702
+
703
+
704
+ async DeserializePrivateKey(privateKey , extractable ) {
705
+ extractable ??= false
706
+ checkExtractable(extractable)
707
+ checkUint8Array(privateKey, 'privateKey')
708
+
709
+ try {
710
+ if (privateKey.byteLength !== this.#suite.KEM.Nsk) {
711
+ throw new Error('Invalid "privateKey" length')
712
+ }
713
+ return await this.#suite.KEM.DeserializePrivateKey(privateKey, extractable)
714
+ } catch (cause) {
715
+ if (cause instanceof NotSupportedError) {
716
+ throw cause
717
+ }
718
+ throw new DeserializeError('Private key deserialization failed', { cause })
719
+ }
720
+ }
721
+
722
+
723
+
724
+
725
+
726
+
727
+
728
+
729
+
730
+
731
+
732
+
733
+
734
+
735
+
736
+
737
+
738
+
739
+ async DeserializePublicKey(publicKey ) {
740
+ checkUint8Array(publicKey, 'publicKey')
741
+
742
+ try {
743
+ if (publicKey.byteLength !== this.#suite.KEM.Npk) {
744
+ throw new Error('Invalid "publicKey" length')
745
+ }
746
+ return await this.#suite.KEM.DeserializePublicKey(publicKey)
747
+ } catch (cause) {
748
+ if (cause instanceof NotSupportedError) {
749
+ throw cause
750
+ }
751
+ throw new DeserializeError('Public key deserialization failed', { cause })
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
+ async Seal(
789
+ publicKey ,
790
+ plaintext ,
791
+ options ,
792
+ ) {
793
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
794
+ throw new TypeError('Export-only AEAD cannot be used with Seal')
795
+ }
796
+ const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
797
+ const ciphertext = await ctx.Seal(plaintext, options?.aad)
798
+ return { encapsulatedSecret, ciphertext }
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
+ async Open(
837
+ privateKey ,
838
+ encapsulatedSecret ,
839
+ ciphertext ,
840
+ options ,
841
+ ) {
842
+ if (this.#suite.AEAD.id === EXPORT_ONLY) {
843
+ throw new TypeError('Export-only AEAD cannot be used with Open')
844
+ }
845
+ const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
846
+ return await ctx.Open(ciphertext, options?.aad)
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
+ async SendExport(
884
+ publicKey ,
885
+ exporterContext ,
886
+ length ,
887
+ options ,
888
+ ) {
889
+ const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
890
+ const exportedSecret = await ctx.Export(exporterContext, length)
891
+ return { encapsulatedSecret, exportedSecret }
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
+ async ReceiveExport(
931
+ privateKey ,
932
+ encapsulatedSecret ,
933
+ exporterContext ,
934
+ length ,
935
+ options ,
936
+ ) {
937
+ const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
938
+ return await ctx.Export(exporterContext, length)
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
+ async SetupSender(
984
+ publicKey ,
985
+ options ,
986
+ ) {
987
+ isKey(publicKey, 'public')
988
+
989
+ let shared_secret
990
+ let enc
991
+ try {
992
+ const result = await this.#suite.KEM.Encap(publicKey)
993
+ shared_secret = result.shared_secret
994
+ enc = result.enc
995
+ } catch (cause) {
996
+ if (cause instanceof ValidationError || cause instanceof NotSupportedError) {
997
+ throw cause
998
+ }
999
+ throw new EncapError('Encapsulation failed', { cause })
1000
+ }
1001
+
1002
+ const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE
1003
+ const { key, base_nonce, exporter_secret } = await KeySchedule(
1004
+ this.#suite,
1005
+ mode,
1006
+ shared_secret,
1007
+ options?.info,
1008
+ options?.psk,
1009
+ options?.pskId,
1010
+ )
1011
+
1012
+ const ctx = new SenderContext(this.#suite, mode, key, base_nonce, exporter_secret)
1013
+ return { encapsulatedSecret: enc, ctx }
1014
+ }
1015
+
1016
+
1017
+
1018
+
1019
+
1020
+
1021
+
1022
+
1023
+
1024
+
1025
+
1026
+
1027
+
1028
+
1029
+
1030
+
1031
+
1032
+
1033
+
1034
+
1035
+
1036
+
1037
+
1038
+
1039
+
1040
+
1041
+
1042
+
1043
+
1044
+
1045
+
1046
+
1047
+
1048
+
1049
+
1050
+
1051
+
1052
+
1053
+
1054
+
1055
+
1056
+
1057
+
1058
+
1059
+
1060
+
1061
+
1062
+
1063
+ async SetupRecipient(
1064
+ privateKey ,
1065
+ encapsulatedSecret ,
1066
+ options ,
1067
+ ) {
1068
+ const { skR, pkR } = this.#extractRecipientKeys(privateKey)
1069
+ checkUint8Array(encapsulatedSecret, 'encapsulatedSecret')
1070
+ if (encapsulatedSecret.byteLength !== this.#suite.KEM.Nenc) {
1071
+ throw new DecapError('Invalid encapsulated secret length')
1072
+ }
1073
+
1074
+ let shared_secret
1075
+ try {
1076
+ shared_secret = await this.#suite.KEM.Decap(encapsulatedSecret, skR, pkR)
1077
+ } catch (cause) {
1078
+ if (cause instanceof ValidationError || cause instanceof NotSupportedError) {
1079
+ throw cause
1080
+ }
1081
+ throw new DecapError('Decapsulation failed', { cause })
1082
+ }
1083
+
1084
+ const mode = options?.psk?.byteLength ? MODE_PSK : MODE_BASE
1085
+ const { key, base_nonce, exporter_secret } = await KeySchedule(
1086
+ this.#suite,
1087
+ mode,
1088
+ shared_secret,
1089
+ options?.info,
1090
+ options?.psk,
1091
+ options?.pskId,
1092
+ )
1093
+
1094
+ return new RecipientContext(this.#suite, mode, key, base_nonce, exporter_secret)
1095
+ }
1096
+
1097
+ #extractRecipientKeys(skR ) {
1098
+ if (isKeyPair(skR)) {
1099
+ return { skR: skR.privateKey, pkR: skR.publicKey }
1100
+ }
1101
+
1102
+ isKey(skR, 'private')
1103
+ return { skR, pkR: undefined }
1104
+ }
1105
+ }
1106
+
1107
+
1108
+
1109
+
1110
+
1111
+
1112
+
1113
+
1114
+
1115
+
1116
+
1117
+ export class ValidationError extends Error {
1118
+ constructor(message , options ) {
1119
+ super(message, options)
1120
+ this.name = 'ValidationError'
1121
+
1122
+ Error.captureStackTrace?.(this, ValidationError)
1123
+ }
1124
+ }
1125
+
1126
+
1127
+
1128
+
1129
+
1130
+
1131
+
1132
+ export class DeserializeError extends Error {
1133
+ constructor(message , options ) {
1134
+ super(message, options)
1135
+ this.name = 'DeserializeError'
1136
+
1137
+ Error.captureStackTrace?.(this, DeserializeError)
1138
+ }
1139
+ }
1140
+
1141
+
1142
+
1143
+
1144
+
1145
+
1146
+
1147
+ export class EncapError extends Error {
1148
+ constructor(message , options ) {
1149
+ super(message, options)
1150
+ this.name = 'EncapError'
1151
+
1152
+ Error.captureStackTrace?.(this, EncapError)
1153
+ }
1154
+ }
1155
+
1156
+
1157
+
1158
+
1159
+
1160
+
1161
+
1162
+ export class DecapError extends Error {
1163
+ constructor(message , options ) {
1164
+ super(message, options)
1165
+ this.name = 'DecapError'
1166
+
1167
+ Error.captureStackTrace?.(this, DecapError)
1168
+ }
1169
+ }
1170
+
1171
+
1172
+
1173
+
1174
+
1175
+
1176
+
1177
+ export class OpenError extends Error {
1178
+ constructor(message , options ) {
1179
+ super(message, options)
1180
+ this.name = 'OpenError'
1181
+
1182
+ Error.captureStackTrace?.(this, OpenError)
1183
+ }
1184
+ }
1185
+
1186
+
1187
+
1188
+
1189
+
1190
+
1191
+
1192
+ export class MessageLimitReachedError extends Error {
1193
+ constructor(message , options ) {
1194
+ super(message, options)
1195
+ this.name = 'MessageLimitReachedError'
1196
+
1197
+ Error.captureStackTrace?.(this, MessageLimitReachedError)
1198
+ }
1199
+ }
1200
+
1201
+
1202
+
1203
+
1204
+
1205
+
1206
+
1207
+ export class DeriveKeyPairError extends Error {
1208
+ constructor(message , options ) {
1209
+ super(message, options)
1210
+ this.name = 'DeriveKeyPairError'
1211
+
1212
+ Error.captureStackTrace?.(this, DeriveKeyPairError)
1213
+ }
1214
+ }
1215
+
1216
+
1217
+
1218
+
1219
+
1220
+
1221
+
1222
+ export class NotSupportedError extends Error {
1223
+ constructor(message , options ) {
1224
+ super(message, options)
1225
+ this.name = 'NotSupportedError'
1226
+
1227
+ Error.captureStackTrace?.(this, NotSupportedError)
1228
+ }
1229
+ }
1230
+
1231
+
1232
+
1233
+
1234
+
1235
+
1236
+
1237
+
1238
+
1239
+
1240
+
1241
+
1242
+
1243
+ export const MODE_BASE = 0x00
1244
+
1245
+
1246
+ export const MODE_PSK = 0x01
1247
+
1248
+
1249
+
1250
+
1251
+
1252
+
1253
+
1254
+
1255
+
1256
+
1257
+
1258
+
1259
+
1260
+
1261
+
1262
+
1263
+
1264
+
1265
+
1266
+
1267
+
1268
+
1269
+
1270
+
1271
+
1272
+
1273
+
1274
+
1275
+
1276
+
1277
+
1278
+
1279
+
1280
+
1281
+
1282
+
1283
+
1284
+
1285
+
1286
+
1287
+
1288
+
1289
+
1290
+
1291
+
1292
+
1293
+
1294
+
1295
+
1296
+
1297
+
1298
+
1299
+
1300
+
1301
+
1302
+
1303
+
1304
+
1305
+
1306
+
1307
+
1308
+
1309
+
1310
+
1311
+
1312
+
1313
+
1314
+
1315
+
1316
+
1317
+
1318
+
1319
+
1320
+
1321
+
1322
+
1323
+
1324
+
1325
+
1326
+
1327
+
1328
+
1329
+
1330
+
1331
+
1332
+
1333
+
1334
+
1335
+
1336
+
1337
+
1338
+
1339
+
1340
+
1341
+
1342
+
1343
+
1344
+
1345
+
1346
+
1347
+
1348
+
1349
+
1350
+
1351
+
1352
+
1353
+
1354
+
1355
+
1356
+
1357
+
1358
+
1359
+
1360
+
1361
+
1362
+
1363
+
1364
+
1365
+
1366
+
1367
+
1368
+
1369
+
1370
+
1371
+
1372
+
1373
+
1374
+
1375
+
1376
+
1377
+ export function concat(...buffers ) {
1378
+ const size = buffers.reduce((acc, { length }) => acc + length, 0)
1379
+ const buf = new Uint8Array(size)
1380
+ let i = 0
1381
+ for (const buffer of buffers) {
1382
+ buf.set(buffer, i)
1383
+ i += buffer.length
1384
+ }
1385
+ return buf
1386
+ }
1387
+
1388
+ function slice(buffer , start , end ) {
1389
+ return Uint8Array.prototype.slice.call(buffer, start, end)
1390
+ }
1391
+
1392
+
1393
+
1394
+
1395
+
1396
+
1397
+
1398
+
1399
+
1400
+
1401
+
1402
+
1403
+ export function encode(string ) {
1404
+ const bytes = new Uint8Array(string.length)
1405
+ for (let i = 0; i < string.length; i++) {
1406
+ const code = string.charCodeAt(i)
1407
+ bytes[i] = code
1408
+ }
1409
+ return bytes
1410
+ }
1411
+
1412
+ function xor(a , b ) {
1413
+ if (a.byteLength !== b.byteLength) {
1414
+ throw new Error('XOR operands must have equal length')
1415
+ }
1416
+ const buf = new Uint8Array(a.byteLength)
1417
+ for (let i = 0; i < a.byteLength; i++) {
1418
+ buf[i] = a[i] ^ b[i]
1419
+ }
1420
+ return buf
1421
+ }
1422
+
1423
+ function lengthPrefixed(x ) {
1424
+ return concat(I2OSP(x.byteLength, 2), x)
1425
+ }
1426
+
1427
+
1428
+
1429
+
1430
+
1431
+
1432
+
1433
+
1434
+
1435
+
1436
+
1437
+
1438
+
1439
+
1440
+
1441
+
1442
+
1443
+
1444
+
1445
+
1446
+
1447
+
1448
+
1449
+ export async function LabeledDerive(
1450
+ KDF ,
1451
+ suite_id ,
1452
+ ikm ,
1453
+ label ,
1454
+ context ,
1455
+ L ,
1456
+ ) {
1457
+ const labeled_ikm = concat(
1458
+ ikm,
1459
+ encode('HPKE-v1'),
1460
+ suite_id,
1461
+ lengthPrefixed(label),
1462
+ I2OSP(L, 2),
1463
+ context,
1464
+ )
1465
+ return await KDF.Derive(labeled_ikm, L)
1466
+ }
1467
+
1468
+ async function ExportOneStage(
1469
+ KDF ,
1470
+ suite_id ,
1471
+ exporter_secret ,
1472
+ exporter_context ,
1473
+ L ,
1474
+ ) {
1475
+ checkLength(exporter_context, 'Exporter context', MAX_LENGTH_ONE_STAGE)
1476
+ return await LabeledDerive(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1477
+ }
1478
+
1479
+ async function CombineSecretsOneStage(
1480
+ suite ,
1481
+ mode ,
1482
+ shared_secret ,
1483
+ info ,
1484
+ psk ,
1485
+ psk_id ,
1486
+ ) {
1487
+ checkLength(psk, 'PSK', MAX_LENGTH_ONE_STAGE)
1488
+ checkLength(psk_id, 'PSK ID', MAX_LENGTH_ONE_STAGE)
1489
+ checkLength(info, 'Info', MAX_LENGTH_ONE_STAGE)
1490
+
1491
+ const secrets = concat(lengthPrefixed(psk), lengthPrefixed(shared_secret))
1492
+ const context = concat(I2OSP(mode, 1), lengthPrefixed(psk_id), lengthPrefixed(info))
1493
+
1494
+ const secret = await LabeledDerive(
1495
+ suite.KDF,
1496
+ suite.id,
1497
+ secrets,
1498
+ encode('secret'),
1499
+ context,
1500
+ suite.AEAD.Nk + suite.AEAD.Nn + suite.KDF.Nh,
1501
+ )
1502
+
1503
+ const key = slice(secret, 0, suite.AEAD.Nk)
1504
+ const base_nonce = slice(secret, suite.AEAD.Nk, suite.AEAD.Nk + suite.AEAD.Nn)
1505
+ const exporter_secret = slice(secret, suite.AEAD.Nk + suite.AEAD.Nn)
1506
+
1507
+ return { key, base_nonce, exporter_secret }
1508
+ }
1509
+
1510
+
1511
+
1512
+ const MAX_LENGTH_TWO_STAGE = 0xffff
1513
+
1514
+ const MAX_LENGTH_ONE_STAGE = 0xffff
1515
+
1516
+ function checkLength(data , name , maxLength ) {
1517
+ if (data.byteLength > maxLength) {
1518
+ throw new TypeError(`${name} length must not exceed ${maxLength} bytes`)
1519
+ }
1520
+ }
1521
+ function checkUint8Array(input , name ) {
1522
+ if (!(input instanceof Uint8Array)) {
1523
+ throw new TypeError(`"${name}" must be Uint8Array`)
1524
+ }
1525
+ }
1526
+ function checkExtractable(extractable ) {
1527
+ if (typeof extractable !== 'boolean') {
1528
+ throw new TypeError('"extractable" must be boolean')
1529
+ }
1530
+ }
1531
+
1532
+ async function CombineSecretsTwoStage(
1533
+ suite ,
1534
+ mode ,
1535
+ shared_secret ,
1536
+ info ,
1537
+ psk ,
1538
+ psk_id ,
1539
+ ) {
1540
+ checkLength(psk, 'PSK', MAX_LENGTH_TWO_STAGE)
1541
+ checkLength(psk_id, 'PSK ID', MAX_LENGTH_TWO_STAGE)
1542
+ checkLength(info, 'Info', MAX_LENGTH_TWO_STAGE)
1543
+
1544
+ const [psk_id_hash, info_hash] = await Promise.all([
1545
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('psk_id_hash'), psk_id),
1546
+ LabeledExtract(suite.KDF, suite.id, new Uint8Array(), encode('info_hash'), info),
1547
+ ])
1548
+
1549
+ const key_schedule_context = concat(I2OSP(mode, 1), psk_id_hash, info_hash)
1550
+ const secret = await LabeledExtract(suite.KDF, suite.id, shared_secret, encode('secret'), psk)
1551
+
1552
+
1553
+ if (suite.AEAD.id === EXPORT_ONLY) {
1554
+ const exporter_secret = await LabeledExpand(
1555
+ suite.KDF,
1556
+ suite.id,
1557
+ secret,
1558
+ encode('exp'),
1559
+ key_schedule_context,
1560
+ suite.KDF.Nh,
1561
+ )
1562
+ return { key: new Uint8Array(), base_nonce: new Uint8Array(), exporter_secret }
1563
+ }
1564
+
1565
+ const [key, base_nonce, exporter_secret] = await Promise.all([
1566
+ LabeledExpand(suite.KDF, suite.id, secret, encode('key'), key_schedule_context, suite.AEAD.Nk),
1567
+ LabeledExpand(
1568
+ suite.KDF,
1569
+ suite.id,
1570
+ secret,
1571
+ encode('base_nonce'),
1572
+ key_schedule_context,
1573
+ suite.AEAD.Nn,
1574
+ ),
1575
+ LabeledExpand(suite.KDF, suite.id, secret, encode('exp'), key_schedule_context, suite.KDF.Nh),
1576
+ ])
1577
+
1578
+ return { key, base_nonce, exporter_secret }
1579
+ }
1580
+
1581
+ async function ExportTwoStage(
1582
+ KDF ,
1583
+ suite_id ,
1584
+ exporter_secret ,
1585
+ exporter_context ,
1586
+ L ,
1587
+ ) {
1588
+ checkLength(exporter_context, 'Exporter context', MAX_LENGTH_TWO_STAGE)
1589
+ return await LabeledExpand(KDF, suite_id, exporter_secret, encode('sec'), exporter_context, L)
1590
+ }
1591
+
1592
+
1593
+
1594
+
1595
+
1596
+
1597
+
1598
+
1599
+
1600
+
1601
+
1602
+
1603
+
1604
+
1605
+
1606
+
1607
+
1608
+
1609
+
1610
+
1611
+
1612
+
1613
+
1614
+
1615
+
1616
+
1617
+
1618
+
1619
+
1620
+
1621
+
1622
+
1623
+
1624
+
1625
+
1626
+
1627
+
1628
+
1629
+
1630
+
1631
+
1632
+
1633
+
1634
+
1635
+
1636
+
1637
+
1638
+
1639
+
1640
+
1641
+
1642
+
1643
+
1644
+
1645
+
1646
+
1647
+
1648
+
1649
+
1650
+
1651
+
1652
+
1653
+
1654
+
1655
+
1656
+
1657
+
1658
+
1659
+
1660
+
1661
+
1662
+
1663
+
1664
+
1665
+
1666
+
1667
+
1668
+
1669
+
1670
+
1671
+
1672
+
1673
+
1674
+
1675
+
1676
+
1677
+
1678
+
1679
+
1680
+
1681
+
1682
+
1683
+
1684
+
1685
+
1686
+
1687
+
1688
+
1689
+
1690
+
1691
+
1692
+
1693
+
1694
+
1695
+
1696
+
1697
+
1698
+
1699
+
1700
+
1701
+
1702
+
1703
+
1704
+
1705
+
1706
+
1707
+
1708
+
1709
+
1710
+
1711
+
1712
+
1713
+
1714
+
1715
+
1716
+
1717
+
1718
+
1719
+
1720
+
1721
+
1722
+
1723
+
1724
+
1725
+
1726
+
1727
+
1728
+
1729
+
1730
+
1731
+ export async function LabeledExtract(
1732
+ KDF ,
1733
+ suite_id ,
1734
+ salt ,
1735
+ label ,
1736
+ ikm ,
1737
+ ) {
1738
+ const labeled_ikm = concat(encode('HPKE-v1'), suite_id, label, ikm)
1739
+ return await KDF.Extract(salt, labeled_ikm)
1740
+ }
1741
+
1742
+
1743
+
1744
+
1745
+
1746
+
1747
+
1748
+
1749
+
1750
+
1751
+
1752
+
1753
+
1754
+
1755
+
1756
+
1757
+
1758
+
1759
+
1760
+ export async function LabeledExpand(
1761
+ KDF ,
1762
+ suite_id ,
1763
+ prk ,
1764
+ label ,
1765
+ info ,
1766
+ L ,
1767
+ ) {
1768
+ const labeled_info = concat(I2OSP(L, 2), encode('HPKE-v1'), suite_id, label, info)
1769
+ return await KDF.Expand(prk, labeled_info, L)
1770
+ }
1771
+
1772
+
1773
+
1774
+
1775
+
1776
+
1777
+
1778
+
1779
+
1780
+
1781
+
1782
+
1783
+
1784
+
1785
+
1786
+
1787
+
1788
+
1789
+
1790
+
1791
+
1792
+
1793
+
1794
+
1795
+
1796
+
1797
+
1798
+
1799
+
1800
+
1801
+
1802
+
1803
+
1804
+
1805
+
1806
+
1807
+
1808
+
1809
+
1810
+
1811
+
1812
+
1813
+
1814
+
1815
+
1816
+
1817
+
1818
+
1819
+
1820
+
1821
+
1822
+
1823
+
1824
+
1825
+
1826
+
1827
+
1828
+
1829
+
1830
+
1831
+
1832
+
1833
+
1834
+
1835
+
1836
+
1837
+
1838
+
1839
+
1840
+
1841
+
1842
+
1843
+
1844
+
1845
+
1846
+
1847
+
1848
+
1849
+
1850
+
1851
+
1852
+
1853
+
1854
+
1855
+
1856
+
1857
+
1858
+
1859
+
1860
+
1861
+
1862
+
1863
+
1864
+
1865
+
1866
+
1867
+
1868
+
1869
+
1870
+
1871
+
1872
+
1873
+
1874
+
1875
+
1876
+
1877
+
1878
+
1879
+
1880
+
1881
+
1882
+
1883
+
1884
+
1885
+
1886
+
1887
+
1888
+
1889
+
1890
+
1891
+
1892
+
1893
+
1894
+
1895
+
1896
+
1897
+
1898
+
1899
+
1900
+
1901
+
1902
+
1903
+
1904
+
1905
+
1906
+
1907
+
1908
+
1909
+
1910
+
1911
+
1912
+
1913
+
1914
+
1915
+
1916
+
1917
+
1918
+
1919
+
1920
+
1921
+
1922
+
1923
+
1924
+
1925
+
1926
+
1927
+
1928
+
1929
+
1930
+
1931
+
1932
+
1933
+
1934
+
1935
+
1936
+
1937
+
1938
+
1939
+
1940
+
1941
+
1942
+
1943
+
1944
+
1945
+
1946
+
1947
+
1948
+
1949
+
1950
+
1951
+
1952
+
1953
+
1954
+
1955
+
1956
+
1957
+
1958
+
1959
+
1960
+
1961
+
1962
+
1963
+
1964
+
1965
+
1966
+
1967
+
1968
+
1969
+
1970
+
1971
+
1972
+
1973
+
1974
+
1975
+
1976
+ function isKeyPair(skR ) {
1977
+ if (!skR || typeof skR !== 'object') return false
1978
+ if ('publicKey' in skR && 'privateKey' in skR) {
1979
+ const pkR = skR.publicKey
1980
+ skR = skR.privateKey
1981
+ try {
1982
+ isKey(pkR, 'public')
1983
+ isKey(skR, 'private')
1984
+ if (pkR.algorithm.name !== skR.algorithm.name) {
1985
+ throw new TypeError('key pair algorithms do not match')
1986
+ }
1987
+ } catch (cause) {
1988
+ throw new TypeError('Invalid "privateKey"', { cause })
1989
+ }
1990
+ return true
1991
+ }
1992
+ return false
1993
+ }
1994
+
1995
+ function isKey(key , type , extractable ) {
1996
+ const k = key
1997
+ if (
1998
+ typeof k.algorithm !== 'object' ||
1999
+ typeof k.algorithm.name !== 'string' ||
2000
+ typeof k.extractable !== 'boolean' ||
2001
+ typeof k.type !== 'string' ||
2002
+ k.type !== type
2003
+ ) {
2004
+ throw new TypeError(`Invalid "${type}Key"`)
2005
+ }
2006
+
2007
+ if (extractable && k.extractable !== true) {
2008
+ throw new TypeError(`"${type}Key" must be extractable`)
2009
+ }
2010
+ }
2011
+
2012
+
2013
+
2014
+
2015
+
2016
+
2017
+
2018
+
2019
+
2020
+
2021
+
2022
+
2023
+
2024
+
2025
+
2026
+
2027
+
2028
+
2029
+
2030
+
2031
+
2032
+
2033
+
2034
+
2035
+
2036
+
2037
+
2038
+
2039
+
2040
+
2041
+
2042
+
2043
+
2044
+
2045
+
2046
+
2047
+
2048
+
2049
+
2050
+
2051
+
2052
+
2053
+
2054
+
2055
+
2056
+
2057
+
2058
+
2059
+
2060
+
2061
+
2062
+
2063
+
2064
+
2065
+
2066
+
2067
+
2068
+
2069
+
2070
+
2071
+
2072
+
2073
+
2074
+
2075
+
2076
+
2077
+
2078
+
2079
+
2080
+
2081
+
2082
+
2083
+
2084
+
2085
+
2086
+
2087
+
2088
+
2089
+
2090
+
2091
+
2092
+
2093
+
2094
+
2095
+
2096
+
2097
+
2098
+
2099
+
2100
+
2101
+
2102
+
2103
+
2104
+
2105
+
2106
+
2107
+
2108
+
2109
+
2110
+
2111
+
2112
+
2113
+
2114
+
2115
+
2116
+
2117
+
2118
+
2119
+
2120
+
2121
+
2122
+
2123
+
2124
+
2125
+
2126
+
2127
+
2128
+
2129
+
2130
+ export function I2OSP(n , w ) {
2131
+ if (!Number.isSafeInteger(w) || w <= 0) {
2132
+ throw new Error('w must be a positive safe integer')
2133
+ }
2134
+ if (!Number.isSafeInteger(n) || n < 0) {
2135
+ throw new Error('n must be a non-negative safe integer')
2136
+ }
2137
+ const max = Math.pow(256, w)
2138
+ if (n >= max) {
2139
+ throw new Error('n too large to fit in w-length byte string')
2140
+ }
2141
+ const ret = new Uint8Array(w)
2142
+ let num = n
2143
+ for (let i = 0; i < w && num; i++) {
2144
+ ret[w - (i + 1)] = num % 256
2145
+ num = Math.floor(num / 256)
2146
+ }
2147
+ return ret
2148
+ }
2149
+
2150
+ function KDFStages(KDF ) {
2151
+ if (KDF.stages === 1 || KDF.stages === 2) {
2152
+ return KDF.stages
2153
+ }
2154
+
2155
+ throw new Error('unreachable')
2156
+ }
2157
+
2158
+ async function KeySchedule(
2159
+ suite ,
2160
+ mode ,
2161
+ shared_secret ,
2162
+ info ,
2163
+ psk ,
2164
+ pskId ,
2165
+ ) {
2166
+ info ??= new Uint8Array()
2167
+ checkUint8Array(info, 'info')
2168
+ psk ??= new Uint8Array()
2169
+ checkUint8Array(psk, 'psk')
2170
+ pskId ??= new Uint8Array()
2171
+ checkUint8Array(pskId, 'pskId')
2172
+
2173
+ const stages = KDFStages(suite.KDF)
2174
+ const CombineSecrets = stages === 1 ? CombineSecretsOneStage : CombineSecretsTwoStage
2175
+
2176
+ VerifyPSKInputs(psk, pskId)
2177
+ return await CombineSecrets(suite, mode, shared_secret, info, psk, pskId)
2178
+ }
2179
+
2180
+ function VerifyPSKInputs(psk , psk_id ) {
2181
+ if (psk.byteLength && psk_id.byteLength) {
2182
+ if (psk.byteLength < 32) {
2183
+ throw new TypeError('Insufficient PSK length')
2184
+ }
2185
+ return
2186
+ }
2187
+ if (!psk.byteLength && !psk_id.byteLength) {
2188
+ return
2189
+ }
2190
+ throw new TypeError('Inconsistent PSK inputs')
2191
+ }
2192
+
2193
+
2194
+ const NotApplicable = () => {
2195
+ throw new Error('unreachable')
2196
+ }
2197
+
2198
+ const EXPORT_ONLY = 0xffff
2199
+
2200
+
2201
+
2202
+
2203
+
2204
+
2205
+
2206
+
2207
+
2208
+
2209
+
2210
+ export const AEAD_EXPORT_ONLY = function () {
2211
+ return {
2212
+ id: EXPORT_ONLY,
2213
+ type: 'AEAD',
2214
+ name: 'Export-only',
2215
+ Nk: 0,
2216
+ Nn: 0,
2217
+ Nt: 0,
2218
+ Seal: NotApplicable,
2219
+ Open: NotApplicable,
2220
+ }
2221
+ }
2222
+
2223
+
2224
+
2225
+
2226
+
2227
+ async function subtle (promise , name ) {
2228
+ try {
2229
+ return await promise()
2230
+ } catch (cause) {
2231
+ if (
2232
+ cause instanceof TypeError ||
2233
+ (cause instanceof DOMException && cause.name === 'NotSupportedError')
2234
+ ) {
2235
+ throw new NotSupportedError(`${name} is unsupported in this runtime`, { cause })
2236
+ }
2237
+ throw cause
2238
+ }
2239
+ }
2240
+
2241
+
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+ function sab(input ) {
2248
+ return typeof SharedArrayBuffer !== 'undefined' && input instanceof SharedArrayBuffer
2249
+ }
2250
+
2251
+ function ab(input ) {
2252
+ if (sab(input.buffer)) {
2253
+ throw new TypeError('input must not be a SharedArrayBuffer')
2254
+ }
2255
+ if (input.byteLength === input.buffer.byteLength) {
2256
+ return input.buffer
2257
+ }
2258
+ return input.buffer.slice(input.byteOffset, input.byteOffset + input.byteLength)
2259
+ }
2260
+
2261
+ function HKDF_SHARED() {
2262
+ return {
2263
+ stages: 2,
2264
+ Derive: NotApplicable,
2265
+ async Extract( _salt, _ikm) {
2266
+ let salt
2267
+ if (_salt.byteLength === 0) {
2268
+ salt = new ArrayBuffer(this.Nh)
2269
+ } else {
2270
+ salt = ab(_salt)
2271
+ }
2272
+ const ikm = ab(_ikm)
2273
+ return new Uint8Array(
2274
+ await subtle(
2275
+ async () =>
2276
+ crypto.subtle.sign(
2277
+ 'HMAC',
2278
+ await crypto.subtle.importKey('raw', salt, { name: 'HMAC', hash: this.hash }, false, [
2279
+ 'sign',
2280
+ ]),
2281
+ ikm,
2282
+ ),
2283
+ this.name,
2284
+ ),
2285
+ )
2286
+ },
2287
+ async Expand( _prk, info, L) {
2288
+ if (_prk.byteLength < this.Nh) {
2289
+ throw new Error('prk.byteLength < this.Nh')
2290
+ }
2291
+ if (L > 255 * this.Nh) {
2292
+ throw new Error('L must be <= 255*Nh')
2293
+ }
2294
+ const N = Math.ceil(L / this.Nh)
2295
+ const prk = ab(_prk)
2296
+ const key = await subtle(
2297
+ () =>
2298
+ crypto.subtle.importKey('raw', prk, { name: 'HMAC', hash: this.hash }, false, ['sign']),
2299
+ this.name,
2300
+ )
2301
+
2302
+ const T = new Uint8Array(N * this.Nh)
2303
+ let T_prev = new Uint8Array()
2304
+
2305
+ for (let i = 0; i < N; i++) {
2306
+ const input = new Uint8Array(T_prev.byteLength + info.byteLength + 1)
2307
+ input.set(T_prev)
2308
+ input.set(info, T_prev.byteLength)
2309
+ input[T_prev.byteLength + info.byteLength] = i + 1
2310
+
2311
+ const T_i = new Uint8Array(
2312
+ await subtle(() => crypto.subtle.sign('HMAC', key, input), this.name),
2313
+ )
2314
+
2315
+ T.set(T_i, i * this.Nh)
2316
+ T_prev = T_i
2317
+ }
2318
+
2319
+ return slice(T, 0, L)
2320
+ },
2321
+ }
2322
+ }
2323
+
2324
+
2325
+
2326
+
2327
+
2328
+
2329
+
2330
+
2331
+
2332
+
2333
+
2334
+
2335
+
2336
+
2337
+
2338
+
2339
+
2340
+
2341
+
2342
+
2343
+
2344
+
2345
+
2346
+ export const KDF_HKDF_SHA256 = function () {
2347
+ return { id: 0x0001, type: 'KDF', name: 'HKDF-SHA256', Nh: 32, hash: 'SHA-256', ...HKDF_SHARED() }
2348
+ }
2349
+
2350
+
2351
+
2352
+
2353
+
2354
+
2355
+
2356
+
2357
+
2358
+
2359
+
2360
+
2361
+
2362
+
2363
+
2364
+
2365
+
2366
+
2367
+
2368
+ export const KDF_HKDF_SHA384 = function () {
2369
+ return { id: 0x0002, type: 'KDF', name: 'HKDF-SHA384', Nh: 48, hash: 'SHA-384', ...HKDF_SHARED() }
2370
+ }
2371
+
2372
+
2373
+
2374
+
2375
+
2376
+
2377
+
2378
+
2379
+
2380
+
2381
+
2382
+
2383
+
2384
+
2385
+
2386
+
2387
+
2388
+
2389
+
2390
+ export const KDF_HKDF_SHA512 = function () {
2391
+ return { id: 0x0003, type: 'KDF', name: 'HKDF-SHA512', Nh: 64, hash: 'SHA-512', ...HKDF_SHARED() }
2392
+ }
2393
+
2394
+
2395
+
2396
+
2397
+
2398
+
2399
+
2400
+
2401
+
2402
+ async function ShakeDerive(name , variant , ikm , L ) {
2403
+ return new Uint8Array(
2404
+ await subtle(
2405
+ () =>
2406
+ crypto.subtle.digest(
2407
+ {
2408
+ name: variant,
2409
+
2410
+ length: L << 3,
2411
+ },
2412
+ ikm,
2413
+ ),
2414
+ name,
2415
+ ),
2416
+ )
2417
+ }
2418
+
2419
+ function SHAKE_SHARED() {
2420
+ return {
2421
+ stages: 1,
2422
+ async Derive( labeled_ikm, L ) {
2423
+ return await ShakeDerive(this.name, this.algorithm, ab(labeled_ikm), L)
2424
+ },
2425
+ Extract: NotApplicable,
2426
+ Expand: NotApplicable,
2427
+ }
2428
+ }
2429
+
2430
+
2431
+
2432
+
2433
+
2434
+
2435
+
2436
+
2437
+
2438
+
2439
+
2440
+
2441
+
2442
+
2443
+
2444
+
2445
+
2446
+
2447
+
2448
+ export const KDF_SHAKE128 = function () {
2449
+ return {
2450
+ id: 0x0010,
2451
+ type: 'KDF',
2452
+ name: 'SHAKE128',
2453
+ Nh: 32,
2454
+ algorithm: 'cSHAKE128',
2455
+ ...SHAKE_SHARED(),
2456
+ }
2457
+ }
2458
+
2459
+
2460
+
2461
+
2462
+
2463
+
2464
+
2465
+
2466
+
2467
+
2468
+
2469
+
2470
+
2471
+
2472
+
2473
+
2474
+
2475
+
2476
+
2477
+ export const KDF_SHAKE256 = function () {
2478
+ return {
2479
+ id: 0x0011,
2480
+ type: 'KDF',
2481
+ name: 'SHAKE256',
2482
+ Nh: 64,
2483
+ algorithm: 'cSHAKE256',
2484
+ ...SHAKE_SHARED(),
2485
+ }
2486
+ }
2487
+
2488
+ async function getPublicKeyByExport(
2489
+ name ,
2490
+ key ,
2491
+ usages ,
2492
+ ) {
2493
+ if (!key.extractable) {
2494
+ throw new TypeError(
2495
+ '"privateKey" must be extractable or a Key Pair must be used in this runtime',
2496
+ )
2497
+ }
2498
+
2499
+ return await subtle(async () => {
2500
+ const jwk = await crypto.subtle.exportKey('jwk', key)
2501
+ return await crypto.subtle.importKey(
2502
+ 'jwk',
2503
+ { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y } ,
2504
+ key.algorithm,
2505
+ true,
2506
+ usages,
2507
+ )
2508
+ }, name)
2509
+ }
2510
+
2511
+ async function getPublicKey(name , key , usages ) {
2512
+ return (
2513
+
2514
+ ((await subtle(() => crypto.subtle.getPublicKey?.(key, usages), name)) ) ||
2515
+ (await getPublicKeyByExport(name, key, usages))
2516
+ )
2517
+ }
2518
+
2519
+
2520
+ function checkNotAllZeros(buffer ) {
2521
+ let or = 0
2522
+ for (let i = 0; i < buffer.length; i++) {
2523
+ or |= buffer[i]
2524
+ }
2525
+ if (or === 0) {
2526
+ throw new ValidationError('DH shared secret is an all-zero value')
2527
+ }
2528
+ }
2529
+
2530
+
2531
+
2532
+
2533
+
2534
+
2535
+
2536
+
2537
+
2538
+
2539
+
2540
+
2541
+
2542
+
2543
+
2544
+
2545
+
2546
+
2547
+
2548
+
2549
+ function fromBase64(input ) {
2550
+ input = input.replace(/-/g, '+').replace(/_/g, '/')
2551
+ const binary = atob(input)
2552
+ const bytes = new Uint8Array(binary.length)
2553
+ for (let i = 0; i < binary.length; i++) {
2554
+ bytes[i] = binary.charCodeAt(i)
2555
+ }
2556
+ return bytes
2557
+ }
2558
+
2559
+ function toBase64Url(bytes ) {
2560
+ let binary = ''
2561
+ for (let i = 0; i < bytes.length; i++) {
2562
+ binary += String.fromCharCode(bytes[i] )
2563
+ }
2564
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
2565
+ }
2566
+
2567
+ function toB64u(input ) {
2568
+
2569
+ return input.toBase64?.({ alphabet: 'base64url', omitPadding: true }) || toBase64Url(input)
2570
+ }
2571
+
2572
+ function b64u(input ) {
2573
+
2574
+ return Uint8Array.fromBase64?.(input, { alphabet: 'base64url' }) || fromBase64(input)
2575
+ }
2576
+
2577
+
2578
+
2579
+
2580
+
2581
+ async function DeriveCandidate(
2582
+ DHKEM ,
2583
+ suite_id ,
2584
+ ikm ,
2585
+ counter ,
2586
+ ) {
2587
+ const dkp_prk = await LabeledExtract(
2588
+ DHKEM.kdf,
2589
+ suite_id,
2590
+ new Uint8Array(),
2591
+ encode('dkp_prk'),
2592
+ ikm,
2593
+ )
2594
+ return await LabeledExpand(
2595
+ DHKEM.kdf,
2596
+ suite_id,
2597
+ dkp_prk,
2598
+ encode('candidate'),
2599
+ I2OSP(counter, 1),
2600
+ DHKEM.Nsk,
2601
+ )
2602
+ }
2603
+
2604
+ function OS2IP(x ) {
2605
+ let result = 0n
2606
+ for (let i = 0; i < x.byteLength; i++) {
2607
+ result = result * 256n + BigInt(x[i] )
2608
+ }
2609
+ return result
2610
+ }
2611
+
2612
+ function bigIntToUint8Array(value , byteLength ) {
2613
+ const result = new Uint8Array(byteLength)
2614
+ let n = value
2615
+
2616
+ for (let i = byteLength - 1; i >= 0; i--) {
2617
+ result[i] = Number(n & 0xffn)
2618
+ n = n >> 8n
2619
+ }
2620
+
2621
+ return result
2622
+ }
2623
+
2624
+ function assertKeyAlgorithm(key , expectedAlgorithm ) {
2625
+ if (key.algorithm.name !== expectedAlgorithm.name) {
2626
+ throw new TypeError(`key algorithm must be ${expectedAlgorithm.name}`)
2627
+ }
2628
+ if (
2629
+ (key.algorithm ).namedCurve !==
2630
+ (expectedAlgorithm ).namedCurve
2631
+ ) {
2632
+ throw new TypeError(
2633
+ `key namedCurve must be ${(expectedAlgorithm ).namedCurve}`,
2634
+ )
2635
+ }
2636
+ }
2637
+
2638
+ function assertCryptoKey(key ) {
2639
+
2640
+ if (key[Symbol.toStringTag] !== 'CryptoKey') {
2641
+ if (key instanceof CryptoKey) return
2642
+ throw new TypeError('unexpected key constructor')
2643
+ }
2644
+ }
2645
+
2646
+
2647
+
2648
+
2649
+
2650
+ function DHKEM_SHARED() {
2651
+ return {
2652
+ async GenerateKeyPair( extractable) {
2653
+ return (await subtle(
2654
+ () => crypto.subtle.generateKey(this.algorithm, extractable, ['deriveBits']),
2655
+ this.name,
2656
+ ))
2657
+ },
2658
+ async SerializePublicKey( key) {
2659
+ assertKeyAlgorithm(key, this.algorithm)
2660
+ assertCryptoKey(key)
2661
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey('raw', key), this.name))
2662
+ },
2663
+ async DeserializePublicKey( _key) {
2664
+ const key = ab(_key)
2665
+ return await subtle(
2666
+ () => crypto.subtle.importKey('raw', key, this.algorithm, true, []),
2667
+ this.name,
2668
+ )
2669
+ },
2670
+ async SerializePrivateKey( key) {
2671
+ assertKeyAlgorithm(key, this.algorithm)
2672
+ assertCryptoKey(key)
2673
+ const { d } = await subtle(() => crypto.subtle.exportKey('jwk', key), this.name)
2674
+ return b64u(d )
2675
+ },
2676
+ async Encap( pkR) {
2677
+ assertKeyAlgorithm(pkR, this.algorithm)
2678
+ assertCryptoKey(pkR)
2679
+
2680
+ const ekp = (await this.GenerateKeyPair(false))
2681
+ const skE = ekp.privateKey
2682
+ const pkE = ekp.publicKey
2683
+
2684
+
2685
+
2686
+ const dh = new Uint8Array(
2687
+ await subtle(
2688
+ () =>
2689
+ crypto.subtle.deriveBits({ name: skE.algorithm.name, public: pkR }, skE, this.Ndh << 3),
2690
+ this.name,
2691
+ ),
2692
+ )
2693
+ checkNotAllZeros(dh)
2694
+
2695
+ const enc = await this.SerializePublicKey(pkE)
2696
+ const pkRm = await this.SerializePublicKey(pkR)
2697
+ const kem_context = concat(enc, pkRm)
2698
+ const eae_prk = await LabeledExtract(
2699
+ this.kdf,
2700
+ this.suite_id,
2701
+ new Uint8Array(),
2702
+ encode('eae_prk'),
2703
+ dh,
2704
+ )
2705
+ const shared_secret = await LabeledExpand(
2706
+ this.kdf,
2707
+ this.suite_id,
2708
+ eae_prk,
2709
+ encode('shared_secret'),
2710
+ kem_context,
2711
+ this.Nsecret,
2712
+ )
2713
+ return { shared_secret, enc }
2714
+ },
2715
+ async Decap( enc, skR, pkR) {
2716
+ assertKeyAlgorithm(skR, this.algorithm)
2717
+ assertCryptoKey(skR)
2718
+ if (pkR) {
2719
+ assertKeyAlgorithm(pkR, this.algorithm)
2720
+ assertCryptoKey(pkR)
2721
+ } else {
2722
+ pkR = await getPublicKey(this.name, skR, [])
2723
+ }
2724
+
2725
+ const pkE = (await this.DeserializePublicKey(enc))
2726
+
2727
+
2728
+
2729
+ const dh = new Uint8Array(
2730
+ await subtle(
2731
+ () =>
2732
+ crypto.subtle.deriveBits({ name: skR.algorithm.name, public: pkE }, skR, this.Ndh << 3),
2733
+ this.name,
2734
+ ),
2735
+ )
2736
+ checkNotAllZeros(dh)
2737
+
2738
+ const pkRm = await this.SerializePublicKey(pkR)
2739
+ const kem_context = concat(enc, pkRm)
2740
+ const eae_prk = await LabeledExtract(
2741
+ this.kdf,
2742
+ this.suite_id,
2743
+ new Uint8Array(),
2744
+ encode('eae_prk'),
2745
+ dh,
2746
+ )
2747
+ const shared_secret = await LabeledExpand(
2748
+ this.kdf,
2749
+ this.suite_id,
2750
+ eae_prk,
2751
+ encode('shared_secret'),
2752
+ kem_context,
2753
+ this.Nsecret,
2754
+ )
2755
+ return shared_secret
2756
+ },
2757
+ }
2758
+ }
2759
+
2760
+
2761
+
2762
+
2763
+
2764
+ async function createKeyPairFromPrivateKey(
2765
+ DHKEM ,
2766
+ key ,
2767
+ extractable ,
2768
+ ) {
2769
+ let privateKey
2770
+ let publicKey
2771
+
2772
+ if (!extractable && typeof crypto.subtle.getPublicKey !== 'function') {
2773
+ privateKey = (await DHKEM.DeserializePrivateKey(key, true))
2774
+ publicKey = await getPublicKey(DHKEM.name, privateKey, [])
2775
+ privateKey = (await DHKEM.DeserializePrivateKey(key, false))
2776
+ } else {
2777
+ privateKey = (await DHKEM.DeserializePrivateKey(key, extractable))
2778
+ publicKey = await getPublicKey(DHKEM.name, privateKey, [])
2779
+ }
2780
+ return { privateKey, publicKey }
2781
+ }
2782
+
2783
+ async function CurveKeyFromD(
2784
+ name ,
2785
+ Nsk ,
2786
+ template ,
2787
+ algorithm ,
2788
+ key ,
2789
+ extractable ,
2790
+ ) {
2791
+ const tmpl = slice(template)
2792
+ const pkcs8 = new Uint8Array(Nsk + tmpl.byteLength)
2793
+ pkcs8.set(tmpl)
2794
+ pkcs8.set(key, tmpl.byteLength)
2795
+ return await subtle(
2796
+ () => crypto.subtle.importKey('pkcs8', pkcs8, algorithm, extractable, ['deriveBits']),
2797
+ name,
2798
+ )
2799
+ }
2800
+
2801
+
2802
+
2803
+
2804
+
2805
+
2806
+
2807
+
2808
+
2809
+
2810
+
2811
+ function modInverse(a , m ) {
2812
+ a = ((a % m) + m) % m
2813
+ let [t, newT] = [0n, 1n]
2814
+ let [r, newR] = [m, a]
2815
+
2816
+ while (newR !== 0n) {
2817
+ const quotient = r / newR
2818
+ ;[t, newT] = [newT, t - quotient * newT]
2819
+ ;[r, newR] = [newR, r - quotient * newR]
2820
+ }
2821
+
2822
+ if (r > 1n) throw new Error('a is not invertible')
2823
+ if (t < 0n) t = t + m
2824
+ return t
2825
+ }
2826
+
2827
+
2828
+ function pointDouble(p , prime , a ) {
2829
+ const { x, y } = p
2830
+
2831
+
2832
+ const numerator = (((3n * x * x) % prime) + a) % prime
2833
+ const denominator = (2n * y) % prime
2834
+ const s = (numerator * modInverse(denominator, prime)) % prime
2835
+
2836
+
2837
+ const x3 = (((s * s) % prime) - ((2n * x) % prime) + prime) % prime
2838
+
2839
+
2840
+ const y3 = (((s * ((x - x3 + prime) % prime)) % prime) - y + prime) % prime
2841
+
2842
+ return { x: x3, y: y3 }
2843
+ }
2844
+
2845
+
2846
+ function pointAdd(p , q , prime , a ) {
2847
+ if (p.x === q.x && p.y === q.y) {
2848
+ return pointDouble(p, prime, a)
2849
+ }
2850
+
2851
+ const { x: x1, y: y1 } = p
2852
+ const { x: x2, y: y2 } = q
2853
+
2854
+
2855
+
2856
+ if (p.x === q.x) {
2857
+ throw new Error('Point addition resulted in point at infinity')
2858
+ }
2859
+
2860
+
2861
+ const numerator = (((y2 - y1) % prime) + prime) % prime
2862
+ const denominator = (((x2 - x1) % prime) + prime) % prime
2863
+ const s = (numerator * modInverse(denominator, prime)) % prime
2864
+
2865
+
2866
+ const x3 = (((s * s) % prime) - x1 - x2 + prime + prime) % prime
2867
+
2868
+
2869
+ const y3 = (((s * ((x1 - x3 + prime) % prime)) % prime) - y1 + prime) % prime
2870
+
2871
+ return { x: x3, y: y3 }
2872
+ }
2873
+
2874
+
2875
+ function scalarMult(k , G , prime , a , order ) {
2876
+ if (k === 0n || k >= order) {
2877
+ throw new Error('Invalid scalar')
2878
+ }
2879
+
2880
+ let result = null
2881
+ let addend = G
2882
+ let scalar = k
2883
+
2884
+ while (scalar > 0n) {
2885
+ if (scalar & 1n) {
2886
+ result = result === null ? addend : pointAdd(result, addend, prime, a)
2887
+ }
2888
+ addend = pointDouble(addend, prime, a)
2889
+ scalar = scalar >> 1n
2890
+ }
2891
+
2892
+ if (result === null) throw new Error('Invalid result')
2893
+ return result
2894
+ }
2895
+
2896
+
2897
+
2898
+
2899
+
2900
+
2901
+
2902
+
2903
+
2904
+
2905
+
2906
+
2907
+
2908
+ function getPrivateJwkNist(DHKEM , d ) {
2909
+
2910
+ const G = { x: DHKEM.Gx, y: DHKEM.Gy }
2911
+ const publicPoint = scalarMult(d, G, DHKEM.prime, DHKEM.prime - 3n, DHKEM.order)
2912
+
2913
+ const coordSize = (DHKEM.Npk - 1) / 2
2914
+ const xBytes = bigIntToUint8Array(publicPoint.x, coordSize)
2915
+ const yBytes = bigIntToUint8Array(publicPoint.y, coordSize)
2916
+ const dBytes = bigIntToUint8Array(d, DHKEM.Nsk)
2917
+
2918
+
2919
+ return {
2920
+ kty: 'EC',
2921
+ crv: DHKEM.algorithm.namedCurve,
2922
+ x: toB64u(xBytes),
2923
+ y: toB64u(yBytes),
2924
+ d: toB64u(dBytes),
2925
+ }
2926
+ }
2927
+
2928
+ async function DeserializePrivateKeyNist(
2929
+
2930
+ key ,
2931
+ extractable ,
2932
+ ) {
2933
+ const d = OS2IP(key)
2934
+ const jwk = getPrivateJwkNist(this, d)
2935
+
2936
+ const privateKey = await subtle(
2937
+ () => crypto.subtle.importKey('jwk', jwk, this.algorithm, extractable, ['deriveBits']),
2938
+ this.name,
2939
+ )
2940
+
2941
+ return privateKey
2942
+ }
2943
+
2944
+ async function DeriveKeyPairNist(
2945
+
2946
+ ikm ,
2947
+ extractable ,
2948
+ ) {
2949
+ let sk = 0n
2950
+ let counter = 0
2951
+ let bytes
2952
+ while (sk === 0n || sk >= this.order) {
2953
+ if (counter > 255) {
2954
+ throw new DeriveKeyPairError('Key derivation exceeded maximum iterations')
2955
+ }
2956
+ bytes = await DeriveCandidate(this, this.suite_id, ikm, counter)
2957
+ bytes[0] = bytes[0] & this.bitmask
2958
+ sk = OS2IP(bytes)
2959
+ counter = counter + 1
2960
+ }
2961
+
2962
+ return GetKeyPairNist(this, bytes , extractable, this.name)
2963
+ }
2964
+
2965
+ async function GetKeyPairNist(
2966
+ curveConfig ,
2967
+ sk ,
2968
+ extractable ,
2969
+ name ,
2970
+ ) {
2971
+ const jwk = getPrivateJwkNist(curveConfig, OS2IP(sk))
2972
+
2973
+ const privateKey = await subtle(
2974
+ () => crypto.subtle.importKey('jwk', jwk, curveConfig.algorithm, extractable, ['deriveBits']),
2975
+ name,
2976
+ )
2977
+
2978
+ delete jwk.d
2979
+ const publicKey = await subtle(
2980
+ () => crypto.subtle.importKey('jwk', jwk, curveConfig.algorithm, true, []),
2981
+ name,
2982
+ )
2983
+
2984
+ return { privateKey, publicKey }
2985
+ }
2986
+
2987
+
2988
+
2989
+
2990
+
2991
+ async function DeriveKeyPairX( ikm , extractable ) {
2992
+ const dkp_prk = await LabeledExtract(
2993
+ this.kdf,
2994
+ this.suite_id,
2995
+ new Uint8Array(),
2996
+ encode('dkp_prk'),
2997
+ ikm,
2998
+ )
2999
+ const sk = await LabeledExpand(
3000
+ this.kdf,
3001
+ this.suite_id,
3002
+ dkp_prk,
3003
+ encode('sk'),
3004
+ new Uint8Array(),
3005
+ this.Nsk,
3006
+ )
3007
+ return await createKeyPairFromPrivateKey(this, sk, extractable)
3008
+ }
3009
+
3010
+
3011
+
3012
+
3013
+
3014
+ const P256 = {
3015
+ algorithm: { name: 'ECDH', namedCurve: 'P-256' },
3016
+ Npk: 65,
3017
+ Nsk: 32,
3018
+ order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,
3019
+ bitmask: 0xff,
3020
+ prime: 0xffffffff00000001000000000000000000000000ffffffffffffffffffffffffn,
3021
+ Gx: 0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296n,
3022
+ Gy: 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5n,
3023
+ }
3024
+
3025
+
3026
+
3027
+
3028
+
3029
+
3030
+
3031
+
3032
+
3033
+
3034
+
3035
+
3036
+
3037
+
3038
+
3039
+
3040
+
3041
+
3042
+
3043
+
3044
+ export const KEM_DHKEM_P256_HKDF_SHA256 = function () {
3045
+ const id = 0x0010
3046
+ const name = 'DHKEM(P-256, HKDF-SHA256)'
3047
+ const kdf = KDF_HKDF_SHA256()
3048
+
3049
+ kdf.name = name
3050
+ return {
3051
+ id,
3052
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3053
+ type: 'KEM',
3054
+ name,
3055
+ kdf,
3056
+ Nsecret: 32,
3057
+ Nenc: 65,
3058
+ Ndh: 32,
3059
+ ...P256,
3060
+ DeriveKeyPair: DeriveKeyPairNist,
3061
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3062
+ ...DHKEM_SHARED(),
3063
+ }
3064
+ }
3065
+
3066
+ const P384 = {
3067
+ algorithm: { name: 'ECDH', namedCurve: 'P-384' },
3068
+ Npk: 97,
3069
+ Nsk: 48,
3070
+ order:
3071
+ 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,
3072
+ bitmask: 0xff,
3073
+ prime:
3074
+ 0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffffn,
3075
+ Gx: 0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7n,
3076
+ Gy: 0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5fn,
3077
+ }
3078
+
3079
+
3080
+
3081
+
3082
+
3083
+
3084
+
3085
+
3086
+
3087
+
3088
+
3089
+
3090
+
3091
+
3092
+
3093
+
3094
+
3095
+
3096
+
3097
+
3098
+ export const KEM_DHKEM_P384_HKDF_SHA384 = function () {
3099
+ const id = 0x0011
3100
+ const name = 'DHKEM(P-384, HKDF-SHA384)'
3101
+ const kdf = KDF_HKDF_SHA384()
3102
+
3103
+ kdf.name = name
3104
+ return {
3105
+ id,
3106
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3107
+ type: 'KEM',
3108
+ name,
3109
+ kdf,
3110
+ Nsecret: 48,
3111
+ Nenc: 97,
3112
+ Ndh: 48,
3113
+ ...P384,
3114
+ DeriveKeyPair: DeriveKeyPairNist,
3115
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3116
+ ...DHKEM_SHARED(),
3117
+ }
3118
+ }
3119
+
3120
+ const P521 = {
3121
+ Npk: 133,
3122
+ Nsk: 66,
3123
+ algorithm: { name: 'ECDH', namedCurve: 'P-521' },
3124
+ order:
3125
+ 0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409n,
3126
+ bitmask: 0x01,
3127
+ prime:
3128
+ 0x01ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn,
3129
+ Gx: 0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66n,
3130
+ Gy: 0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650n,
3131
+ }
3132
+
3133
+
3134
+
3135
+
3136
+
3137
+
3138
+
3139
+
3140
+
3141
+
3142
+
3143
+
3144
+
3145
+
3146
+
3147
+
3148
+
3149
+
3150
+
3151
+
3152
+ export const KEM_DHKEM_P521_HKDF_SHA512 = function () {
3153
+ const id = 0x0012
3154
+ const name = 'DHKEM(P-521, HKDF-SHA512)'
3155
+ const kdf = KDF_HKDF_SHA512()
3156
+
3157
+ kdf.name = name
3158
+ return {
3159
+ id,
3160
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3161
+ type: 'KEM',
3162
+ name,
3163
+ kdf,
3164
+ Nsecret: 64,
3165
+ Nenc: 133,
3166
+ Ndh: 66,
3167
+ ...P521,
3168
+ DeriveKeyPair: DeriveKeyPairNist,
3169
+ DeserializePrivateKey: DeserializePrivateKeyNist,
3170
+ ...DHKEM_SHARED(),
3171
+ }
3172
+ }
3173
+
3174
+
3175
+
3176
+
3177
+
3178
+
3179
+
3180
+
3181
+
3182
+
3183
+
3184
+
3185
+
3186
+
3187
+
3188
+
3189
+
3190
+
3191
+
3192
+
3193
+
3194
+
3195
+
3196
+
3197
+ export const KEM_DHKEM_X25519_HKDF_SHA256 = function () {
3198
+ const id = 0x0020
3199
+ const name = 'DHKEM(X25519, HKDF-SHA256)'
3200
+ const kdf = KDF_HKDF_SHA256()
3201
+
3202
+ kdf.name = name
3203
+ return {
3204
+ id,
3205
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3206
+ type: 'KEM',
3207
+ name,
3208
+ kdf,
3209
+ Nsecret: 32,
3210
+ Nenc: 32,
3211
+ Npk: 32,
3212
+ Nsk: 32,
3213
+ Ndh: 32,
3214
+ algorithm: { name: 'X25519' },
3215
+ pkcs8: Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20),
3216
+ DeriveKeyPair: DeriveKeyPairX,
3217
+ async DeserializePrivateKey(key, extractable) {
3218
+ return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)
3219
+ },
3220
+ ...DHKEM_SHARED(),
3221
+ }
3222
+ }
3223
+
3224
+
3225
+
3226
+
3227
+
3228
+
3229
+
3230
+
3231
+
3232
+
3233
+
3234
+
3235
+
3236
+
3237
+
3238
+
3239
+
3240
+
3241
+
3242
+
3243
+ export const KEM_DHKEM_X448_HKDF_SHA512 = function () {
3244
+ const id = 0x0021
3245
+ const name = 'DHKEM(X448, HKDF-SHA512)'
3246
+ const kdf = KDF_HKDF_SHA512()
3247
+
3248
+ kdf.name = name
3249
+ return {
3250
+ id,
3251
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3252
+ type: 'KEM',
3253
+ name,
3254
+ kdf,
3255
+ Nsecret: 64,
3256
+ Nenc: 56,
3257
+ Npk: 56,
3258
+ Nsk: 56,
3259
+ Ndh: 56,
3260
+ algorithm: { name: 'X448' },
3261
+ pkcs8: Uint8Array.of(0x30, 0x46, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6f, 0x04, 0x3a, 0x04, 0x38),
3262
+ DeriveKeyPair: DeriveKeyPairX,
3263
+ async DeserializePrivateKey(key, extractable) {
3264
+ return await CurveKeyFromD(name, this.Nsk, this.pkcs8, this.algorithm, key, extractable)
3265
+ },
3266
+ ...DHKEM_SHARED(),
3267
+ }
3268
+ }
3269
+
3270
+
3271
+
3272
+
3273
+
3274
+
3275
+
3276
+
3277
+
3278
+
3279
+
3280
+ function MLKEM_SHARED() {
3281
+ return {
3282
+ async DeriveKeyPair( ikm, extractable) {
3283
+ const dk = await LabeledDerive(
3284
+ this.kdf,
3285
+ this.suite_id,
3286
+ ikm,
3287
+ encode('DeriveKeyPair'),
3288
+ new Uint8Array(),
3289
+ this.Nsk,
3290
+ )
3291
+
3292
+ const privateKey = (await this.DeserializePrivateKey(dk, extractable))
3293
+
3294
+ const usages = ['encapsulateBits']
3295
+ const publicKey = await getPublicKey(this.name, privateKey, usages)
3296
+
3297
+ return { privateKey, publicKey }
3298
+ },
3299
+ async GenerateKeyPair( extractable) {
3300
+
3301
+ const usages = ['encapsulateBits', 'decapsulateBits']
3302
+ return (await subtle(
3303
+ () => crypto.subtle.generateKey(this.algorithm, extractable, usages),
3304
+ this.name,
3305
+ ))
3306
+ },
3307
+ async SerializePublicKey( key) {
3308
+ assertKeyAlgorithm(key, this.algorithm)
3309
+ assertCryptoKey(key)
3310
+
3311
+ const format = 'raw-public'
3312
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey(format, key), this.name))
3313
+ },
3314
+ async DeserializePublicKey( _key) {
3315
+
3316
+ const format = 'raw-public'
3317
+
3318
+ const usages = ['encapsulateBits']
3319
+ const key = ab(_key)
3320
+ return await subtle(
3321
+ () => crypto.subtle.importKey(format, key, this.algorithm, true, usages),
3322
+ this.name,
3323
+ )
3324
+ },
3325
+ async SerializePrivateKey( key) {
3326
+ assertKeyAlgorithm(key, this.algorithm)
3327
+ assertCryptoKey(key)
3328
+
3329
+ const format = 'raw-seed'
3330
+ return new Uint8Array(await subtle(() => crypto.subtle.exportKey(format, key), this.name))
3331
+ },
3332
+ async DeserializePrivateKey( _key, extractable) {
3333
+
3334
+ const format = 'raw-seed'
3335
+
3336
+ const usages = ['decapsulateBits']
3337
+ const key = ab(_key)
3338
+ return await subtle(
3339
+ () => crypto.subtle.importKey(format, key, this.algorithm, extractable, usages),
3340
+ this.name,
3341
+ )
3342
+ },
3343
+ async Encap( pkR) {
3344
+ assertKeyAlgorithm(pkR, this.algorithm)
3345
+
3346
+ const { sharedKey, ciphertext } = (await subtle(
3347
+ () =>
3348
+
3349
+ crypto.subtle.encapsulateBits(this.algorithm, pkR),
3350
+ this.name,
3351
+ ))
3352
+
3353
+ return { shared_secret: new Uint8Array(sharedKey), enc: new Uint8Array(ciphertext) }
3354
+ },
3355
+ async Decap( _enc, skR, _pkR) {
3356
+ assertKeyAlgorithm(skR, this.algorithm)
3357
+ const enc = ab(_enc)
3358
+ return new Uint8Array(
3359
+ await subtle(
3360
+ () =>
3361
+
3362
+ crypto.subtle.decapsulateBits(this.algorithm, skR, enc),
3363
+ this.name,
3364
+ ),
3365
+ )
3366
+ },
3367
+ }
3368
+ }
3369
+
3370
+
3371
+
3372
+
3373
+
3374
+
3375
+
3376
+
3377
+
3378
+
3379
+
3380
+
3381
+
3382
+
3383
+
3384
+
3385
+
3386
+
3387
+
3388
+
3389
+
3390
+
3391
+
3392
+ export const KEM_ML_KEM_512 = function () {
3393
+ const id = 0x0040
3394
+ const name = 'ML-KEM-512'
3395
+ const kdf = KDF_SHAKE256()
3396
+
3397
+ kdf.name = name
3398
+ return {
3399
+ id,
3400
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3401
+ type: 'KEM',
3402
+ name,
3403
+ Nsecret: 32,
3404
+ Nenc: 768,
3405
+ Npk: 800,
3406
+ Nsk: 64,
3407
+ algorithm: { name: 'ML-KEM-512' },
3408
+ kdf,
3409
+ ...MLKEM_SHARED(),
3410
+ }
3411
+ }
3412
+
3413
+
3414
+
3415
+
3416
+
3417
+
3418
+
3419
+
3420
+
3421
+
3422
+
3423
+
3424
+
3425
+
3426
+
3427
+
3428
+
3429
+
3430
+
3431
+ export const KEM_ML_KEM_768 = function () {
3432
+ const id = 0x0041
3433
+ const name = 'ML-KEM-768'
3434
+ const kdf = KDF_SHAKE256()
3435
+
3436
+ kdf.name = name
3437
+ return {
3438
+ id,
3439
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3440
+ type: 'KEM',
3441
+ name,
3442
+ Nsecret: 32,
3443
+ Nenc: 1088,
3444
+ Npk: 1184,
3445
+ Nsk: 64,
3446
+ algorithm: { name: 'ML-KEM-768' },
3447
+ kdf,
3448
+ ...MLKEM_SHARED(),
3449
+ }
3450
+ }
3451
+
3452
+
3453
+
3454
+
3455
+
3456
+
3457
+
3458
+
3459
+
3460
+
3461
+
3462
+
3463
+
3464
+
3465
+
3466
+
3467
+
3468
+
3469
+
3470
+ export const KEM_ML_KEM_1024 = function () {
3471
+ const id = 0x0042
3472
+ const name = 'ML-KEM-1024'
3473
+ const kdf = KDF_SHAKE256()
3474
+
3475
+ kdf.name = name
3476
+ return {
3477
+ id,
3478
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
3479
+ type: 'KEM',
3480
+ name,
3481
+ Nsecret: 32,
3482
+ Nenc: 1568,
3483
+ Npk: 1568,
3484
+ Nsk: 64,
3485
+ algorithm: { name: 'ML-KEM-1024' },
3486
+ kdf,
3487
+ ...MLKEM_SHARED(),
3488
+ }
3489
+ }
3490
+
3491
+
3492
+
3493
+
3494
+
3495
+
3496
+
3497
+
3498
+ function AEAD_SHARED() {
3499
+ return {
3500
+ async Seal( _key, _nonce, _aad, _pt) {
3501
+ const nonce = ab(_nonce)
3502
+ const aad = ab(_aad)
3503
+ const key = ab(_key)
3504
+ const pt = ab(_pt)
3505
+ return new Uint8Array(
3506
+ await subtle(
3507
+ async () =>
3508
+ crypto.subtle.encrypt(
3509
+ { name: this.algorithm, iv: nonce, additionalData: aad },
3510
+ await crypto.subtle.importKey(this.keyFormat, key, this.algorithm, false, [
3511
+ 'encrypt',
3512
+ ]),
3513
+ pt,
3514
+ ),
3515
+ this.name,
3516
+ ),
3517
+ )
3518
+ },
3519
+ async Open( _key, _nonce, _aad, _ct) {
3520
+ const nonce = ab(_nonce)
3521
+ const aad = ab(_aad)
3522
+ const key = ab(_key)
3523
+ const ct = ab(_ct)
3524
+ return new Uint8Array(
3525
+ await subtle(
3526
+ async () =>
3527
+ crypto.subtle.decrypt(
3528
+ { name: this.algorithm, iv: nonce, additionalData: aad },
3529
+ await crypto.subtle.importKey(this.keyFormat, key, this.algorithm, false, [
3530
+ 'decrypt',
3531
+ ]),
3532
+ ct,
3533
+ ),
3534
+ this.name,
3535
+ ),
3536
+ )
3537
+ },
3538
+ }
3539
+ }
3540
+
3541
+
3542
+
3543
+
3544
+
3545
+
3546
+
3547
+
3548
+
3549
+
3550
+
3551
+
3552
+
3553
+
3554
+
3555
+
3556
+
3557
+
3558
+
3559
+
3560
+
3561
+
3562
+ export const AEAD_AES_128_GCM = function () {
3563
+ return {
3564
+ id: 0x0001,
3565
+ type: 'AEAD',
3566
+ name: 'AES-128-GCM',
3567
+ Nk: 16,
3568
+ Nn: 12,
3569
+ Nt: 16,
3570
+ algorithm: 'AES-GCM',
3571
+ keyFormat: 'raw',
3572
+ ...AEAD_SHARED(),
3573
+ }
3574
+ }
3575
+
3576
+
3577
+
3578
+
3579
+
3580
+
3581
+
3582
+
3583
+
3584
+
3585
+
3586
+
3587
+
3588
+
3589
+
3590
+
3591
+
3592
+
3593
+ export const AEAD_AES_256_GCM = function () {
3594
+ return {
3595
+ id: 0x0002,
3596
+ type: 'AEAD',
3597
+ name: 'AES-256-GCM',
3598
+ Nk: 32,
3599
+ Nn: 12,
3600
+ Nt: 16,
3601
+ algorithm: 'AES-GCM',
3602
+ keyFormat: 'raw',
3603
+ ...AEAD_SHARED(),
3604
+ }
3605
+ }
3606
+
3607
+
3608
+
3609
+
3610
+
3611
+
3612
+
3613
+
3614
+
3615
+
3616
+
3617
+
3618
+
3619
+
3620
+
3621
+
3622
+
3623
+
3624
+ export const AEAD_ChaCha20Poly1305 = function AEAD_ChaCha20Poly1305() {
3625
+ return {
3626
+ id: 0x0003,
3627
+ type: 'AEAD',
3628
+ name: 'ChaCha20Poly1305',
3629
+ Nk: 32,
3630
+ Nn: 12,
3631
+ Nt: 16,
3632
+ algorithm: 'ChaCha20-Poly1305',
3633
+
3634
+ keyFormat: 'raw-secret',
3635
+ ...AEAD_SHARED(),
3636
+ }
3637
+ }
3638
+
3639
+
3640
+
3641
+
3642
+
3643
+
3644
+ const InvalidInvocation = (_ ) => {
3645
+ if (_ !== priv) {
3646
+ throw new Error('invalid invocation')
3647
+ }
3648
+ }
3649
+ const priv = Symbol()
3650
+ class HybridKey {
3651
+ #algorithm
3652
+ #type
3653
+ #extractable
3654
+ #t
3655
+ #pq
3656
+ #seed
3657
+ #publicKey
3658
+
3659
+ static #isValid(key ) {
3660
+ return key.#algorithm !== undefined
3661
+ }
3662
+
3663
+ static validate(key , extractable ) {
3664
+ try {
3665
+ if (!HybridKey.#isValid(key )) {
3666
+ throw new TypeError('unexpected key constructor')
3667
+ }
3668
+ } catch {
3669
+ throw new TypeError('unexpected key constructor')
3670
+ }
3671
+ if (extractable && !(key ).extractable) {
3672
+ throw new TypeError('key must be extractable')
3673
+ }
3674
+ }
3675
+
3676
+ constructor(
3677
+ _ ,
3678
+ algorithm ,
3679
+ type ,
3680
+ extractable ,
3681
+ pq ,
3682
+ t ,
3683
+ seed ,
3684
+ publicKey ,
3685
+ ) {
3686
+ InvalidInvocation(_)
3687
+ this.#algorithm = algorithm
3688
+ this.#type = type
3689
+ this.#extractable = extractable
3690
+ this.#pq = pq
3691
+ this.#t = t
3692
+ this.#seed = seed
3693
+ this.#publicKey = publicKey
3694
+ }
3695
+
3696
+ get algorithm() {
3697
+ return { name: this.#algorithm.name }
3698
+ }
3699
+
3700
+ get extractable() {
3701
+ return this.#extractable
3702
+ }
3703
+
3704
+ get type() {
3705
+ return this.#type
3706
+ }
3707
+
3708
+ getPublicKey(_ ) {
3709
+ InvalidInvocation(_)
3710
+ return this.#publicKey
3711
+ }
3712
+
3713
+ getSeed(_ ) {
3714
+ InvalidInvocation(_)
3715
+ return slice(this.#seed )
3716
+ }
3717
+
3718
+ getT(_ ) {
3719
+ InvalidInvocation(_)
3720
+ return this.#t
3721
+ }
3722
+
3723
+ getPq(_ ) {
3724
+ InvalidInvocation(_)
3725
+ return this.#pq
3726
+ }
3727
+ }
3728
+
3729
+ function split(N1 , N2 , x ) {
3730
+ if (x.byteLength !== N1 + N2) {
3731
+ throw new Error('x.byteLength !== N1 + N2')
3732
+ }
3733
+
3734
+ const x1 = slice(x, 0, N1)
3735
+ const x2 = slice(x, -N2)
3736
+
3737
+ return [x1, x2]
3738
+ }
3739
+
3740
+ function RandomScalarNist(t , seed ) {
3741
+ let sk_bigint = 0n
3742
+ let start = 0
3743
+ let end = t.Nscalar
3744
+ sk_bigint = OS2IP(slice(seed, start, end))
3745
+
3746
+ while (sk_bigint === 0n || sk_bigint >= t.order ) {
3747
+ start = end
3748
+ end = end + t.Nscalar
3749
+ if (end > seed.byteLength) {
3750
+ throw new DeriveKeyPairError('Rejection sampling failed')
3751
+ }
3752
+ sk_bigint = OS2IP(slice(seed, start, end))
3753
+ }
3754
+ return bigIntToUint8Array(sk_bigint, t.Nscalar )
3755
+ }
3756
+
3757
+ async function expandDecapsKeyG(PQTKEM , _seed ) {
3758
+ const Nout = PQTKEM.pq.Nseed + PQTKEM.t.Nseed
3759
+
3760
+ const algorithm = { name: 'cSHAKE256', length: Nout << 3 }
3761
+ const seed = ab(_seed)
3762
+ const seed_full = await subtle(() => crypto.subtle.digest(algorithm, seed), PQTKEM.name)
3763
+
3764
+ const [_seed_PQ, seed_T] = split(PQTKEM.pq.Nseed, PQTKEM.t.Nseed, new Uint8Array(seed_full))
3765
+ const seed_PQ = ab(_seed_PQ)
3766
+
3767
+
3768
+ const format = 'raw-seed'
3769
+
3770
+ const usages = ['decapsulateBits', 'encapsulateBits']
3771
+ const dk_PQ = await subtle(
3772
+ () => crypto.subtle.importKey(format, seed_PQ, PQTKEM.pq.algorithm, true, [usages[0]]),
3773
+ PQTKEM.name,
3774
+ )
3775
+ const ek_PQ = await getPublicKey(PQTKEM.name, dk_PQ, [usages[1]])
3776
+
3777
+ const sk = PQTKEM.t.RandomScalar?.(seed_T) ?? seed_T
3778
+ const { privateKey: dk_T, publicKey: ek_T } = await PQTKEM.t.GetKeyPair(sk)
3779
+
3780
+ return { ek_PQ, ek_T, dk_PQ, dk_T }
3781
+ }
3782
+
3783
+ async function C2PRICombiner(
3784
+ PQTKEM ,
3785
+ ss_PQ ,
3786
+ ss_T ,
3787
+ ct_T ,
3788
+ _ek_T ,
3789
+ label ,
3790
+ ) {
3791
+ const ek_T = new Uint8Array(
3792
+ await subtle(() => crypto.subtle.exportKey('raw', _ek_T), PQTKEM.name),
3793
+ )
3794
+ const data = ab(concat(ss_PQ, ss_T, ct_T, ek_T, label))
3795
+ return new Uint8Array(await subtle(() => crypto.subtle.digest('SHA3-256', data), PQTKEM.name))
3796
+ }
3797
+
3798
+ async function prepareEncapsG(
3799
+ PQTKEM ,
3800
+ ek_PQ ,
3801
+ ek_T ,
3802
+ ) {
3803
+ const res = (await subtle(
3804
+ () =>
3805
+
3806
+ crypto.subtle.encapsulateBits(PQTKEM.pq.algorithm, ek_PQ),
3807
+ PQTKEM.name,
3808
+ ))
3809
+ const ss_PQ = new Uint8Array(res.sharedKey)
3810
+ const ct_PQ = new Uint8Array(res.ciphertext)
3811
+
3812
+ const { privateKey: sk_E, publicKey } = (await subtle(
3813
+ () => crypto.subtle.generateKey(PQTKEM.t.algorithm, true, ['deriveBits']),
3814
+ PQTKEM.name,
3815
+ ))
3816
+ const ct_T = new Uint8Array(
3817
+ await subtle(() => crypto.subtle.exportKey('raw', publicKey), PQTKEM.name),
3818
+ )
3819
+
3820
+ const ss_T = new Uint8Array(
3821
+ await subtle(
3822
+ () =>
3823
+ crypto.subtle.deriveBits(
3824
+ { name: PQTKEM.t.algorithm.name, public: ek_T },
3825
+ sk_E,
3826
+ PQTKEM.t.Nss << 3,
3827
+ ),
3828
+ PQTKEM.name,
3829
+ ),
3830
+ )
3831
+ checkNotAllZeros(ss_T)
3832
+
3833
+ return [ss_PQ, ss_T, ct_PQ, ct_T]
3834
+ }
3835
+
3836
+ async function prepareDecapsG(
3837
+ PQTKEM ,
3838
+ dk_PQ ,
3839
+ dk_T ,
3840
+ ct_PQ ,
3841
+ _ct_T ,
3842
+ ) {
3843
+ const ss_PQ = new Uint8Array(
3844
+ await subtle(
3845
+ () =>
3846
+
3847
+ crypto.subtle.decapsulateBits(PQTKEM.pq.algorithm, dk_PQ, ct_PQ),
3848
+ PQTKEM.name,
3849
+ ),
3850
+ )
3851
+
3852
+ const ct_T = ab(_ct_T)
3853
+ const pub = await subtle(
3854
+ () => crypto.subtle.importKey('raw', ct_T, PQTKEM.t.algorithm, true, []),
3855
+ PQTKEM.name,
3856
+ )
3857
+
3858
+ const ss_T = new Uint8Array(
3859
+ await subtle(
3860
+ () =>
3861
+ crypto.subtle.deriveBits(
3862
+ { name: PQTKEM.t.algorithm.name, public: pub },
3863
+ dk_T,
3864
+ PQTKEM.t.Nss << 3,
3865
+ ),
3866
+ PQTKEM.name,
3867
+ ),
3868
+ )
3869
+ checkNotAllZeros(ss_T)
3870
+
3871
+ return [ss_PQ, ss_T]
3872
+ }
3873
+
3874
+
3875
+
3876
+
3877
+
3878
+
3879
+
3880
+
3881
+
3882
+
3883
+
3884
+
3885
+
3886
+
3887
+
3888
+
3889
+
3890
+
3891
+
3892
+
3893
+
3894
+
3895
+
3896
+
3897
+
3898
+
3899
+
3900
+
3901
+
3902
+ function PQTKEM_SHARED() {
3903
+ Object.freeze(HybridKey.prototype)
3904
+ return {
3905
+ async DeriveKeyPair( ikm , extractable) {
3906
+ const seed = await LabeledDerive(
3907
+ this.kdf,
3908
+ this.suite_id,
3909
+ ikm,
3910
+ encode('DeriveKeyPair'),
3911
+ new Uint8Array(),
3912
+ 32,
3913
+ )
3914
+
3915
+ const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, seed)
3916
+
3917
+ const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3918
+ const privateKey = new HybridKey(
3919
+ priv,
3920
+ this.algorithm,
3921
+ 'private',
3922
+ extractable,
3923
+ dk_PQ,
3924
+ dk_T,
3925
+ seed,
3926
+ publicKey,
3927
+ )
3928
+
3929
+ return { privateKey, publicKey }
3930
+ },
3931
+ async GenerateKeyPair( extractable) {
3932
+ return await this.DeriveKeyPair(crypto.getRandomValues(new Uint8Array(32)), extractable)
3933
+ },
3934
+ async SerializePublicKey( key) {
3935
+ assertKeyAlgorithm(key, this.algorithm)
3936
+ HybridKey.validate(key, true)
3937
+
3938
+ const format = 'raw-public'
3939
+ const ek_PQ = new Uint8Array(
3940
+ await subtle(() => crypto.subtle.exportKey(format, key.getPq(priv)), this.name),
3941
+ )
3942
+ const ek_T = new Uint8Array(
3943
+ await subtle(() => crypto.subtle.exportKey('raw', key.getT(priv)), this.name),
3944
+ )
3945
+
3946
+ return concat(ek_PQ, ek_T)
3947
+ },
3948
+ async DeserializePublicKey( key) {
3949
+
3950
+ const format = 'raw-public'
3951
+
3952
+ const usages = ['encapsulateBits']
3953
+ const pubPq = ab(key.subarray(0, this.pq.Npk))
3954
+ const pubT = ab(key.subarray(this.pq.Npk))
3955
+ const [ek_PQ, ek_T] = await Promise.all([
3956
+ subtle(
3957
+ () => crypto.subtle.importKey(format, pubPq, this.pq.algorithm, true, usages),
3958
+ this.name,
3959
+ ),
3960
+ subtle(() => crypto.subtle.importKey('raw', pubT, this.t.algorithm, true, []), this.name),
3961
+ ])
3962
+
3963
+ return new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3964
+ },
3965
+ async SerializePrivateKey( key) {
3966
+ assertKeyAlgorithm(key, this.algorithm)
3967
+ HybridKey.validate(key, true)
3968
+
3969
+ return key.getSeed(priv)
3970
+ },
3971
+ async DeserializePrivateKey( key, extractable) {
3972
+ const { ek_PQ, ek_T, dk_PQ, dk_T } = await expandDecapsKeyG(this, key)
3973
+ const publicKey = new HybridKey(priv, this.algorithm, 'public', true, ek_PQ, ek_T)
3974
+ const privateKey = new HybridKey(
3975
+ priv,
3976
+ this.algorithm,
3977
+ 'private',
3978
+ extractable,
3979
+ dk_PQ,
3980
+ dk_T,
3981
+ slice(key),
3982
+ publicKey,
3983
+ )
3984
+
3985
+ return privateKey
3986
+ },
3987
+ async Encap( pkR) {
3988
+ assertKeyAlgorithm(pkR, this.algorithm)
3989
+ HybridKey.validate(pkR)
3990
+
3991
+ const ek_PQ = pkR.getPq(priv)
3992
+ const ek_T = pkR.getT(priv)
3993
+ const [ss_PQ, ss_T, ct_PQ, ct_T] = await prepareEncapsG(this, ek_PQ, ek_T)
3994
+ const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)
3995
+ const ct_H = concat(ct_PQ, ct_T)
3996
+
3997
+ return { shared_secret: ss_H, enc: ct_H }
3998
+ },
3999
+ async Decap( enc, skR, pkR) {
4000
+ assertKeyAlgorithm(skR, this.algorithm)
4001
+ HybridKey.validate(skR)
4002
+
4003
+ if (pkR) {
4004
+ assertKeyAlgorithm(pkR, this.algorithm)
4005
+ HybridKey.validate(pkR)
4006
+ }
4007
+
4008
+ const [ct_PQ, ct_T] = split(this.pq.Nct, this.t.Nct, enc)
4009
+ const ek = pkR ?? skR.getPublicKey(priv)
4010
+ const ek_T = ek.getT(priv)
4011
+ const dk_PQ = skR.getPq(priv)
4012
+ const dk_T = skR.getT(priv)
4013
+ const [ss_PQ, ss_T] = await prepareDecapsG(this, dk_PQ, dk_T, ct_PQ, ct_T)
4014
+ const ss_H = await C2PRICombiner(this, ss_PQ, ss_T, ct_T, ek_T, this.label)
4015
+
4016
+ return ss_H
4017
+ },
4018
+ }
4019
+ }
4020
+
4021
+
4022
+
4023
+
4024
+
4025
+
4026
+
4027
+
4028
+
4029
+
4030
+
4031
+
4032
+
4033
+
4034
+
4035
+
4036
+
4037
+
4038
+
4039
+
4040
+
4041
+
4042
+
4043
+ export const KEM_MLKEM768_X25519 = function () {
4044
+ const id = 0x647a
4045
+ const name = 'MLKEM768-X25519'
4046
+ const kdf = KDF_SHAKE256()
4047
+ const pkcs8 = Uint8Array.of(0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x6e, 0x04, 0x22, 0x04, 0x20);
4048
+
4049
+ kdf.name = name
4050
+ return {
4051
+ id,
4052
+ kdf,
4053
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4054
+ type: 'KEM',
4055
+ name,
4056
+ Nsecret: 32,
4057
+ Nenc: 1120,
4058
+ Npk: 1216,
4059
+ Nsk: 32,
4060
+ algorithm: { name: 'MLKEM768-X25519' },
4061
+ pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },
4062
+ t: {
4063
+ algorithm: { name: 'X25519' },
4064
+ Nseed: 32,
4065
+ Npk: 32,
4066
+ Nss: 32,
4067
+ Nsk: 32,
4068
+ Nct: 32,
4069
+ async GetKeyPair(sk) {
4070
+ const privateKey = await CurveKeyFromD(name, this.Nsk, pkcs8, this.algorithm, sk, true)
4071
+ const publicKey = await getPublicKey(name, privateKey, [])
4072
+
4073
+ return { privateKey, publicKey }
4074
+ },
4075
+ },
4076
+ label: Uint8Array.of(0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c),
4077
+ ...PQTKEM_SHARED(),
4078
+ }
4079
+ }
4080
+
4081
+
4082
+
4083
+
4084
+
4085
+
4086
+
4087
+
4088
+
4089
+
4090
+
4091
+
4092
+
4093
+
4094
+
4095
+
4096
+
4097
+
4098
+
4099
+ export const KEM_MLKEM768_P256 = function () {
4100
+ const id = 0x0050
4101
+ const name = 'MLKEM768-P256'
4102
+ const kdf = KDF_SHAKE256()
4103
+
4104
+ kdf.name = name
4105
+ return {
4106
+ id,
4107
+ kdf,
4108
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4109
+ type: 'KEM',
4110
+ name,
4111
+ Nsecret: 32,
4112
+ Nenc: 1153,
4113
+ Npk: 1249,
4114
+ Nsk: 32,
4115
+ algorithm: { name: 'MLKEM768-P256' },
4116
+ pq: { algorithm: { name: 'ML-KEM-768' }, Nseed: 64, Npk: 1184, Nct: 1088 },
4117
+ t: {
4118
+ ...P256,
4119
+ Nseed: 128,
4120
+ Nss: 32,
4121
+ Nct: 65,
4122
+ Nscalar: 32,
4123
+ order: 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n,
4124
+ RandomScalar(seed) {
4125
+ return RandomScalarNist(this, seed)
4126
+ },
4127
+ GetKeyPair(sk) {
4128
+ return GetKeyPairNist(P256, sk, true, name)
4129
+ },
4130
+ },
4131
+ label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x37, 0x36, 0x38, 0x2d, 0x50, 0x32, 0x35, 0x36),
4132
+ ...PQTKEM_SHARED(),
4133
+ }
4134
+ }
4135
+
4136
+
4137
+
4138
+
4139
+
4140
+
4141
+
4142
+
4143
+
4144
+
4145
+
4146
+
4147
+
4148
+
4149
+
4150
+
4151
+
4152
+
4153
+
4154
+ export const KEM_MLKEM1024_P384 = function () {
4155
+ const id = 0x0051
4156
+ const name = 'MLKEM1024-P384'
4157
+ const kdf = KDF_SHAKE256()
4158
+
4159
+ kdf.name = name
4160
+ return {
4161
+ id,
4162
+ kdf,
4163
+ suite_id: concat(encode('KEM'), I2OSP(id, 2)),
4164
+ type: 'KEM',
4165
+ name,
4166
+ Nsecret: 32,
4167
+ Nenc: 1665,
4168
+ Npk: 1665,
4169
+ Nsk: 32,
4170
+ algorithm: { name: 'MLKEM1024-P384' },
4171
+ pq: { algorithm: { name: 'ML-KEM-1024' }, Nseed: 64, Npk: 1568, Nct: 1568 },
4172
+ t: {
4173
+ ...P384,
4174
+ Nseed: 48,
4175
+ Nss: 48,
4176
+ Nct: 97,
4177
+ Nscalar: 48,
4178
+ order:
4179
+ 0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973n,
4180
+ RandomScalar(seed) {
4181
+ return RandomScalarNist(this, seed)
4182
+ },
4183
+ GetKeyPair(sk) {
4184
+ return GetKeyPairNist(P384, sk, true, name)
4185
+ },
4186
+ },
4187
+ label: Uint8Array.of(0x4d, 0x4c, 0x4b, 0x45, 0x4d, 0x31, 0x30, 0x32, 0x34, 0x2d, 0x50, 0x33, 0x38, 0x34),
4188
+ ...PQTKEM_SHARED(),
4189
+ }
4190
+ }