-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.ts
More file actions
4283 lines (3969 loc) · 134 KB
/
index.ts
File metadata and controls
4283 lines (3969 loc) · 134 KB
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
/**
* Hybrid Public Key Encryption (HPKE) implementation for JavaScript runtimes.
*
* Implements an authenticated encryption encapsulation format that combines a semi-static
* asymmetric key exchange with a symmetric cipher. This was originally defined in an Informational
* document on the IRTF stream as [RFC 9180](https://www.rfc-editor.org/rfc/rfc9180.html) and is now
* being republished as a Standards Track document of the IETF as
* [draft-ietf-hpke-hpke](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03).
*
* HPKE provides a variant of public key encryption for arbitrary-sized plaintexts using a recipient
* public key.
*
* @module hpke
* @example
*
* Getting started with {@link CipherSuite}
*
* ```ts
* import * as HPKE from 'hpke'
*
* // 1. Choose a cipher suite
* const suite = new HPKE.CipherSuite(
* HPKE.KEM_DHKEM_P256_HKDF_SHA256,
* HPKE.KDF_HKDF_SHA256,
* HPKE.AEAD_AES_128_GCM,
* )
*
* // 2. Generate recipient key pair
* const recipient = await suite.GenerateKeyPair()
*
* // 3. Encrypt a message
* const plaintext = new TextEncoder().encode('Hello, World!')
* const { encapsulatedSecret, ciphertext } = await suite.Seal(recipient.publicKey, plaintext)
*
* // 4. Decrypt the message
* const decrypted = await suite.Open(recipient.privateKey, encapsulatedSecret, ciphertext)
* console.log(new TextDecoder().decode(decrypted)) // "Hello, World!"
* ```
*/
// ============================================================================
// HPKE Context Classes - Sender and Recipient Contexts
// ============================================================================
/** @see [ComputeNonce](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2) */
function ComputeNonce(base_nonce: Uint8Array, seq: number, Nn: number): Uint8Array {
const seq_bytes = I2OSP(seq, Nn)
return xor(base_nonce, seq_bytes)
}
/** @see [Context.IncrementSeq](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2) */
function IncrementSeq(seq: number): number {
// seq is guaranteed to be a safe integer due to:
// 1. Initial value is 0
// 2. This function throws at MAX_SAFE_INTEGER
if (seq >= Number.MAX_SAFE_INTEGER) {
throw new MessageLimitReachedError('Sequence number overflow')
}
return ++seq
}
/** @see [Context.Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.3) */
async function ContextExport(
suite: Triple,
exporterSecret: Uint8Array,
exporterContext: Uint8Array,
L: number,
) {
checkUint8Array(exporterContext, 'exporterContext')
const stages = KDFStages(suite.KDF)
if (!Number.isInteger(L) || L <= 0 || L > 0xffff) {
throw new TypeError('"L" must be a positive integer not exceeding 65535')
}
const Export = stages === 1 ? Export_OneStage : Export_TwoStage
return await Export(suite.KDF, suite.id, exporterSecret, exporterContext, L)
}
class Mutex {
#locked: Promise<void> = Promise.resolve()
async lock(): Promise<() => void> {
let releaseLock!: () => void
const nextLock = new Promise<void>((resolve) => {
releaseLock = resolve
})
const previousLock = this.#locked
this.#locked = nextLock
await previousLock
return releaseLock
}
}
/**
* Context for encrypting multiple messages and exporting secrets on the sender side.
*
* `SenderContext` instance is obtained from {@link CipherSuite.SetupSender}.
*
* This context maintains an internal sequence number that increments with each {@link Seal}
* operation, ensuring nonce uniqueness for the underlying AEAD algorithm.
*
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let publicKey!: HPKE.Key // recipient's public key
*
* const { encapsulatedSecret, ctx } = await suite.SetupSender(publicKey)
* ```
*
* @group Core
*/
class SenderContext {
#suite: Triple
#key: Uint8Array
#base_nonce: Uint8Array
#exporter_secret: Uint8Array
#mode: typeof MODE_BASE | typeof MODE_PSK
#seq: number = 0
#mutex?: Mutex
constructor(
suite: Triple,
mode: typeof MODE_BASE | typeof MODE_PSK,
key: Uint8Array,
base_nonce: Uint8Array,
exporter_secret: Uint8Array,
) {
this.#suite = suite
this.#mode = mode
this.#key = key
this.#base_nonce = base_nonce
this.#exporter_secret = exporter_secret
}
/**
* @returns The mode (0x00 = Base, 0x01 = PSK) for this context.
* @see {@link MODE_BASE}
* @see {@link MODE_PSK}
*/
get mode(): number {
return this.#mode
}
/**
* @returns The sequence number for this context's next {@link Seal}, initially zero, increments
* automatically with each successful {@link Seal}. The sequence number provides AEAD nonce
* uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
*/
get seq(): number {
return this.#seq
}
/**
* Encrypts plaintext with additional authenticated data. Each successful call automatically
* increments the sequence number to ensure nonce uniqueness.
*
* @example
*
* ```ts
* let ctx!: HPKE.SenderContext
*
* // Encrypt multiple messages with the same context
* const aad1: Uint8Array = new TextEncoder().encode('message 1 aad')
* const pt1: Uint8Array = new TextEncoder().encode('First message')
* const ct1: Uint8Array = await ctx.Seal(pt1, aad1)
*
* const aad2: Uint8Array = new TextEncoder().encode('message 2 aad')
* const pt2: Uint8Array = new TextEncoder().encode('Second message')
* const ct2: Uint8Array = await ctx.Seal(pt2, aad2)
* ```
*
* @param plaintext - Plaintext to encrypt
* @param aad - Additional authenticated data
*
* @returns A Promise that resolves to the ciphertext. The ciphertext is {@link Nt} bytes longer
* than the plaintext.
* @see [Context.Seal](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2)
*/
async Seal(plaintext: Uint8Array, aad?: Uint8Array): Promise<Uint8Array> {
checkUint8Array(plaintext, 'plaintext')
aad ??= new Uint8Array()
checkUint8Array(aad, 'aad')
if (this.#suite.AEAD.id === EXPORT_ONLY) {
throw new TypeError('Export-only AEAD cannot be used with Seal')
}
this.#mutex ??= new Mutex()
const release = await this.#mutex.lock()
let ct: Uint8Array
try {
ct = await this.#suite.AEAD.Seal(
this.#key,
ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
aad,
plaintext,
)
this.#seq = IncrementSeq(this.#seq)
return ct
} finally {
release()
}
}
/**
* Exports a secret using a variable-length pseudorandom function (PRF).
*
* The exported secret is indistinguishable from a uniformly random bitstring of equal length.
*
* @example
*
* ```ts
* let ctx!: HPKE.SenderContext
*
* // Export a 32-byte secret
* const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
* const exportedSecret: Uint8Array = await ctx.Export(exporterContext, 32)
*
* // The recipient can derive the same secret using the same exporterContext
* ```
*
* @param exporterContext - Context for domain separation
* @param length - Desired length of exported secret in bytes
*
* @returns A Promise that resolves to the exported secret.
* @see [Context.Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.3)
*/
async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
}
/**
* @returns The length in bytes of an authentication tag for the AEAD algorithm used by this
* context.
*/
get Nt(): number {
return this.#suite.AEAD.Nt
}
}
export type { SenderContext }
/**
* Context for decrypting multiple messages and exporting secrets on the recipient side.
*
* `RecipientContext` instance is obtained from {@link CipherSuite.SetupRecipient}.
*
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let privateKey!: HPKE.Key | HPKE.KeyPair
*
* // ... receive encapsulatedSecret from sender
* let encapsulatedSecret!: Uint8Array
*
* const ctx: HPKE.RecipientContext = await suite.SetupRecipient(privateKey, encapsulatedSecret)
* ```
*
* @group Core
*/
class RecipientContext {
#suite: Triple
#key: Uint8Array
#base_nonce: Uint8Array
#exporter_secret: Uint8Array
#mode: typeof MODE_BASE | typeof MODE_PSK
#seq: number = 0
#mutex?: Mutex
constructor(
suite: Triple,
mode: typeof MODE_BASE | typeof MODE_PSK,
key: Uint8Array,
base_nonce: Uint8Array,
exporter_secret: Uint8Array,
) {
this.#suite = suite
this.#mode = mode
this.#key = key
this.#base_nonce = base_nonce
this.#exporter_secret = exporter_secret
}
/**
* @returns The mode (0x00 = Base, 0x01 = PSK) for this context.
* @see {@link MODE_BASE}
* @see {@link MODE_PSK}
*/
get mode(): number {
return this.#mode
}
/**
* @returns The sequence number for this context's next {@link Open}, initially zero, increments
* automatically with each successful {@link Open}. The sequence number provides AEAD nonce
* uniqueness. The maximum supported sequence number in this implementation is `2^53-1`.
*/
get seq(): number {
return this.#seq
}
/**
* Decrypts ciphertext with additional authenticated data.
*
* Applications must ensure that ciphertexts are presented to `Open` in the exact order they were
* produced by the sender.
*
* @example
*
* ```ts
* let ctx!: HPKE.RecipientContext
*
* // Decrypt multiple messages with the same context
* let aad1!: Uint8Array | undefined
* let ct1!: Uint8Array
* const pt1: Uint8Array = await ctx.Open(ct1, aad1)
*
* let aad2!: Uint8Array | undefined
* let ct2!: Uint8Array
* const pt2: Uint8Array = await ctx.Open(ct2, aad2)
* ```
*
* @param ciphertext - Ciphertext to decrypt
* @param aad - Additional authenticated data
*
* @returns A Promise that resolves to the decrypted plaintext.
* @see [Context.Open](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.2)
*/
async Open(ciphertext: Uint8Array, aad?: Uint8Array): Promise<Uint8Array> {
checkUint8Array(ciphertext, 'ciphertext')
aad ??= new Uint8Array()
checkUint8Array(aad, 'aad')
if (this.#suite.AEAD.id === EXPORT_ONLY) {
throw new TypeError('Export-only AEAD cannot be used with Open')
}
this.#mutex ??= new Mutex()
const release = await this.#mutex.lock()
try {
let pt: Uint8Array
try {
pt = await this.#suite.AEAD.Open(
this.#key,
ComputeNonce(this.#base_nonce, this.#seq, this.#suite.AEAD.Nn),
aad,
ciphertext,
)
} catch (cause) {
if (cause instanceof MessageLimitReachedError || cause instanceof NotSupportedError) {
throw cause
}
throw new OpenError('AEAD decryption failed', { cause })
}
this.#seq = IncrementSeq(this.#seq)
return pt
} finally {
release()
}
}
/**
* Exports a secret using a variable-length pseudorandom function (PRF).
*
* The exported secret is indistinguishable from a uniformly random bitstring of equal length.
*
* @example
*
* ```ts
* let ctx!: HPKE.RecipientContext
*
* // Export a 32-byte secret
* const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
* const exported: Uint8Array = await ctx.Export(exporterContext, 32)
*
* // The sender can derive the same secret using the same exporterContext
* ```
*
* @param exporterContext - Context for domain separation
* @param length - Desired length of exported secret in bytes
*
* @returns A Promise that resolves to the exported secret.
* @see [Context.Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-5.3)
*/
async Export(exporterContext: Uint8Array, length: number): Promise<Uint8Array> {
return await ContextExport(this.#suite, this.#exporter_secret, exporterContext, length)
}
}
export type { RecipientContext }
// ============================================================================
// Main CipherSuite Class
// ============================================================================
const validate = <T extends { type: string }>(factory: () => T, type: string): T => {
try {
const result = factory()
if (result.type !== type) {
throw new Error(`Invalid "${type}" return discriminator`)
}
return result
} catch (cause) {
throw new TypeError(`Invalid "${type}"`, { cause })
}
}
/**
* Hybrid Public Key Encryption (HPKE) suite combining a KEM, KDF, and AEAD.
*
* Implements an authenticated encryption encapsulation format that combines a semi-static
* asymmetric key exchange with a symmetric cipher. This was originally defined in an Informational
* document on the IRTF stream as [RFC 9180](https://www.rfc-editor.org/rfc/rfc9180.html) and is now
* being republished as a Standards Track document of the IETF as
* [draft-ietf-hpke-hpke](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03).
*
* HPKE provides a variant of public key encryption for arbitrary-sized plaintexts using a recipient
* public key. It supports two modes:
*
* - Base mode: Encryption to a public key without sender authentication
* - PSK mode: Encryption with pre-shared key authentication
*
* The cipher suite consists of:
*
* - KEM: Key Encapsulation Mechanism for establishing shared secrets
* - KDF: Key Derivation Function for deriving symmetric keys
* - AEAD: Authenticated Encryption with Additional Data for encryption
*
* @group Core
*/
export class CipherSuite {
#suite: Triple
/**
* Creates a new HPKE cipher suite by combining a Key Encapsulation Mechanism (KEM), Key
* Derivation Function (KDF), and an Authenticated Encryption with Associated Data (AEAD)
* algorithm.
*
* A cipher suite defines the complete cryptographic configuration for HPKE operations. The choice
* of algorithms affects security properties, performance, and compatibility across different
* platforms and runtimes.
*
* @example
*
* Traditional algorithms
*
* ```ts
* import * as HPKE from 'hpke'
*
* const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
* HPKE.KEM_DHKEM_P256_HKDF_SHA256,
* HPKE.KDF_HKDF_SHA256,
* HPKE.AEAD_AES_128_GCM,
* )
* ```
*
* @example
*
* Hybrid post-quantum/traditional (PQ/T) KEM
*
* ```ts
* import * as HPKE from 'hpke'
*
* const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
* HPKE.KEM_MLKEM768_X25519,
* HPKE.KDF_SHAKE256,
* HPKE.AEAD_ChaCha20Poly1305,
* )
* ```
*
* @example
*
* Post-quantum (PQ) KEM
*
* ```ts
* import * as HPKE from 'hpke'
*
* const suite: HPKE.CipherSuite = new HPKE.CipherSuite(
* HPKE.KEM_ML_KEM_768,
* HPKE.KDF_SHAKE256,
* HPKE.AEAD_ChaCha20Poly1305,
* )
* ```
*
* @param KEM - KEM implementation factory. Must return an object conforming to the {@link KEM}
* interface.
* @param KDF - KDF implementation factory. Must return an object conforming to the {@link KDF}
* interface.
* @param AEAD - AEAD implementation factory. Must return an object conforming to the {@link AEAD}
* interface.
* @see {@link KEMFactory Available KEMs}
* @see {@link KDFFactory Available KDFs}
* @see {@link AEADFactory Available AEADs}
*/
constructor(KEM: KEMFactory, KDF: KDFFactory, AEAD: AEADFactory) {
const kem = validate(KEM, 'KEM')
const kdf = validate(KDF, 'KDF')
const aead = validate(AEAD, 'AEAD')
this.#suite = {
KEM: kem,
KDF: kdf,
AEAD: aead,
id: concat(encode('HPKE'), I2OSP(kem.id, 2), I2OSP(kdf.id, 2), I2OSP(aead.id, 2)),
}
}
/**
* Provides read-only access to this suite's KEM identifier, name, and other attributes.
*
* @returns An object with this suite's Key Encapsulation Mechanism (KEM) properties.
*/
get KEM(): {
/** The identifier of this suite's KEM */
id: number
/** The name of this suite's KEM */
name: string
/** The length in bytes of this suite's KEM produced shared secret */
Nsecret: number
/** The length in bytes of this suite's KEM produced encapsulated secret */
Nenc: number
/** The length in bytes of this suite's KEM public key */
Npk: number
/** The length in bytes of this suite's KEM private key */
Nsk: number
} {
return {
id: this.#suite.KEM.id,
name: this.#suite.KEM.name,
Nsecret: this.#suite.KEM.Nsecret,
Nenc: this.#suite.KEM.Nenc,
Npk: this.#suite.KEM.Npk,
Nsk: this.#suite.KEM.Nsk,
}
}
/**
* Provides read-only access to this suite's KDF identifier, name, and other attributes.
*
* @returns An object with this suite's Key Derivation Function (KDF) properties.
*/
get KDF(): {
/** The identifier of this suite's KDF */
id: number
/** The name of this suite's KDF */
name: string
/**
* When 1, this suite's KDF is a one-stage (Derive) KDF.
*
* When 2, this suite's KDF is a two-stage (Extract and Expand) KDF.
*/
stages: 1 | 2
/**
* For one-stage KDF: The security strength of this suite's KDF, in bytes.
*
* For two-stage KDF: The output size of this suite's KDF Extract() function in bytes.
*/
Nh: number
} {
return {
id: this.#suite.KDF.id,
name: this.#suite.KDF.name,
stages: this.#suite.KDF.stages,
Nh: this.#suite.KDF.Nh,
}
}
/**
* Provides read-only access to this suite's AEAD identifier, name, and other attributes.
*
* @returns An object with this suite's Authenticated Encryption with Associated Data (AEAD)
* cipher properties.
*/
get AEAD(): {
/** The identifier of this suite's AEAD */
id: number
/** The name of this suite's AEAD */
name: string
/** The length in bytes of a key for this suite's AEAD */
Nk: number
/** The length in bytes of a nonce for this suite's AEAD */
Nn: number
/** The length in bytes of an authentication tag for this suite's AEAD */
Nt: number
} {
return {
id: this.#suite.AEAD.id,
name: this.#suite.AEAD.name,
Nk: this.#suite.AEAD.Nk,
Nn: this.#suite.AEAD.Nn,
Nt: this.#suite.AEAD.Nt,
}
}
/**
* Generates a random key pair for this CipherSuite. By default, private keys are generated as
* non-extractable (their value cannot be exported).
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* const keyPair: HPKE.KeyPair = await suite.GenerateKeyPair()
* ```
*
* @param extractable - Whether the generated key pair's private key should be extractable (e.g.
* by {@link SerializePrivateKey}) (default: false)
*
* @returns A Promise that resolves to a generated key pair.
*/
async GenerateKeyPair(extractable?: boolean): Promise<KeyPair> {
extractable ??= false
checkExtractable(extractable)
return await this.#suite.KEM.GenerateKeyPair(extractable)
}
/**
* Deterministically derives a key pair for this CipherSuite's KEM from input keying material. By
* default, private keys are derived as non-extractable (their value cannot be exported).
*
* > [!CAUTION]\
* > Input keying material must not be reused elsewhere, particularly not with `DeriveKeyPair()` of
* > a different KEM. Re-use across different KEMs could leak information about the private key.
*
* > [!CAUTION]\
* > Input keying material should be generated from a cryptographically secure random source or
* > derived from high-entropy secret material.
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let ikm!: Uint8Array // ... previously serialized ikm of at least suite.KEM.Nsk length
* const keyPair: HPKE.KeyPair = await suite.DeriveKeyPair(ikm)
* ```
*
* @param ikm - Input keying material (must be at least {@link CipherSuite.KEM Nsk} bytes)
* @param extractable - Whether the derived key pair's private key should be extractable (e.g. by
* {@link SerializePrivateKey}) (default: false)
*
* @returns A Promise that resolves to the derived key pair.
*/
async DeriveKeyPair(ikm: Uint8Array, extractable?: boolean): Promise<KeyPair> {
extractable ??= false
checkExtractable(extractable)
checkUint8Array(ikm, 'ikm')
if (ikm.byteLength < this.#suite.KEM.Nsk) {
throw new DeriveKeyPairError('Insufficient "ikm" length')
}
try {
return await this.#suite.KEM.DeriveKeyPair(ikm, extractable)
} catch (cause) {
if (cause instanceof NotSupportedError) {
throw cause
}
throw new DeriveKeyPairError('Key derivation failed', { cause })
}
}
/**
* Serializes an extractable private key to bytes.
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let privateKey!: HPKE.Key
* const serialized: Uint8Array = await suite.SerializePrivateKey(privateKey)
* ```
*
* @param privateKey - Private key to serialize
*
* @returns A Promise that resolves to the serialized private key.
*/
async SerializePrivateKey(privateKey: Key): Promise<Uint8Array> {
isKey(privateKey, 'private', true)
return await this.#suite.KEM.SerializePrivateKey(privateKey)
}
/**
* Serializes a public key to bytes.
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let publicKey!: HPKE.Key
* const serialized: Uint8Array = await suite.SerializePublicKey(publicKey)
* ```
*
* @param publicKey - Public key to serialize
*
* @returns A Promise that resolves to the serialized public key.
*/
async SerializePublicKey(publicKey: Key): Promise<Uint8Array> {
isKey(publicKey, 'public', true)
return await this.#suite.KEM.SerializePublicKey(publicKey)
}
/**
* Deserializes a private key from bytes. By default, private keys are deserialized as
* non-extractable (their value cannot be exported).
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let serialized!: Uint8Array // ... previously serialized key of suite.KEM.Nsk length
* const privateKey: HPKE.Key = await suite.DeserializePrivateKey(serialized)
* ```
*
* @param privateKey - Serialized private key (must be exactly {@link CipherSuite.KEM Nsk} bytes)
* @param extractable - Whether the deserialized private key should be extractable (e.g. by
* {@link SerializePrivateKey}) (default: false)
*
* @returns A Promise that resolves to the deserialized private key.
*/
async DeserializePrivateKey(privateKey: Uint8Array, extractable?: boolean): Promise<Key> {
extractable ??= false
checkExtractable(extractable)
checkUint8Array(privateKey, 'privateKey')
try {
if (privateKey.byteLength !== this.#suite.KEM.Nsk) {
throw new Error('Invalid "privateKey" length')
}
return await this.#suite.KEM.DeserializePrivateKey(privateKey, extractable)
} catch (cause) {
if (cause instanceof NotSupportedError) {
throw cause
}
throw new DeserializeError('Private key deserialization failed', { cause })
}
}
/**
* Deserializes a public key from bytes. Public keys are always deserialized as extractable (their
* value can be exported, e.g. by {@link SerializePublicKey}).
*
* @category Key Management
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let serialized!: Uint8Array // ... previously serialized key of suite.KEM.Npk length
* const publicKey: HPKE.Key = await suite.DeserializePublicKey(serialized)
* ```
*
* @param publicKey - Serialized public key (must be exactly {@link CipherSuite.KEM Npk} bytes)
*
* @returns A Promise that resolves to the deserialized public key.
*/
async DeserializePublicKey(publicKey: Uint8Array): Promise<Key> {
checkUint8Array(publicKey, 'publicKey')
try {
if (publicKey.byteLength !== this.#suite.KEM.Npk) {
throw new Error('Invalid "publicKey" length')
}
return await this.#suite.KEM.DeserializePublicKey(publicKey)
} catch (cause) {
if (cause instanceof NotSupportedError) {
throw cause
}
throw new DeserializeError('Public key deserialization failed', { cause })
}
}
/**
* Single-shot API for encrypting a single message. It combines context setup and encryption in
* one call.
*
* Mode selection:
*
* - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
* - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
*
* @category Single-Shot APIs
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let publicKey!: HPKE.Key // recipient's public key
*
* const plaintext: Uint8Array = new TextEncoder().encode('Hello, World!')
*
* const { encapsulatedSecret, ciphertext } = await suite.Seal(publicKey, plaintext)
* ```
*
* @param publicKey - Recipient's public key
* @param plaintext - Plaintext to encrypt
* @param options - Options
* @param options.aad - Additional authenticated data passed to the AEAD
* @param options.info - Application-supplied information
* @param options.psk - Pre-shared key (for PSK modes)
* @param options.pskId - Pre-shared key identifier (for PSK modes)
*
* @returns A Promise that resolves to an object containing the encapsulated secret and
* ciphertext. The ciphertext is {@link CipherSuite.AEAD Nt} bytes longer than the plaintext. The
* encapsulated secret is {@link CipherSuite.KEM Nenc} bytes.
* @see [Single-Shot Encryption](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-6.1)
*/
async Seal(
publicKey: Key,
plaintext: Uint8Array,
options?: { aad?: Uint8Array; info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
): Promise<{ encapsulatedSecret: Uint8Array; ciphertext: Uint8Array }> {
if (this.#suite.AEAD.id === EXPORT_ONLY) {
throw new TypeError('Export-only AEAD cannot be used with Seal')
}
const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
const ciphertext = await ctx.Seal(plaintext, options?.aad)
return { encapsulatedSecret, ciphertext }
}
/**
* Single-shot API for decrypting a single message.
*
* It combines context setup and decryption in one call.
*
* Mode selection:
*
* - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
* - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
*
* @category Single-Shot APIs
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let privateKey!: HPKE.Key | HPKE.KeyPair
*
* // ... receive encapsulatedSecret, ciphertext from sender
* let encapsulatedSecret!: Uint8Array
* let ciphertext!: Uint8Array
*
* const plaintext: Uint8Array = await suite.Open(privateKey, encapsulatedSecret, ciphertext)
* ```
*
* @param privateKey - Recipient's private key or key pair
* @param encapsulatedSecret - Encapsulated secret from the sender
* @param ciphertext - Ciphertext to decrypt
* @param options - Options
* @param options.aad - Additional authenticated data
* @param options.info - Application-supplied information
* @param options.psk - Pre-shared key (for PSK mode)
* @param options.pskId - Pre-shared key identifier (for PSK mode)
*
* @returns A Promise that resolves to the decrypted plaintext.
* @see [Single-Shot Decryption](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-6.1)
*/
async Open(
privateKey: Key | KeyPair,
encapsulatedSecret: Uint8Array,
ciphertext: Uint8Array,
options?: { aad?: Uint8Array; info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
): Promise<Uint8Array> {
if (this.#suite.AEAD.id === EXPORT_ONLY) {
throw new TypeError('Export-only AEAD cannot be used with Open')
}
const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
return await ctx.Open(ciphertext, options?.aad)
}
/**
* Single-shot API for deriving a secret known only to sender and recipient.
*
* It combines context setup and secret export in one call.
*
* The exported secret is indistinguishable from a uniformly random bitstring of equal length.
*
* @category Single-Shot APIs
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let publicKey!: HPKE.Key // recipient's public key
*
* const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
*
* const { encapsulatedSecret, exportedSecret } = await suite.SendExport(
* publicKey,
* exporterContext,
* 32,
* )
* ```
*
* @param publicKey - Recipient's public key
* @param exporterContext - Context of the export operation
* @param length - Desired length of exported secret in bytes
* @param options - Options
* @param options.info - Application-supplied information
* @param options.psk - Pre-shared key (for PSK modes)
* @param options.pskId - Pre-shared key identifier (for PSK modes)
*
* @returns A Promise that resolves to an object containing the encapsulated secret and the
* exported secret.
* @see [Single-Shot Secret Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-6.2)
*/
async SendExport(
publicKey: Key,
exporterContext: Uint8Array,
length: number,
options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
): Promise<{ encapsulatedSecret: Uint8Array; exportedSecret: Uint8Array }> {
const { encapsulatedSecret, ctx } = await this.SetupSender(publicKey, options)
const exportedSecret = await ctx.Export(exporterContext, length)
return { encapsulatedSecret, exportedSecret }
}
/**
* Single-shot API for receiving an exported secret.
*
* It combines context setup and secret export in one call.
*
* @category Single-Shot APIs
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let privateKey!: HPKE.Key | HPKE.KeyPair
*
* const exporterContext: Uint8Array = new TextEncoder().encode('exporter context')
*
* // ... receive encapsulatedSecret from sender
* let encapsulatedSecret!: Uint8Array
*
* const exported: Uint8Array = await suite.ReceiveExport(
* privateKey,
* encapsulatedSecret,
* exporterContext,
* 32,
* )
* ```
*
* @param privateKey - Recipient's private key or key pair
* @param encapsulatedSecret - Encapsulated secret from the sender
* @param exporterContext - Context of the export operation
* @param length - Desired length of exported secret in bytes
* @param options - Options
* @param options.info - Application-supplied information
* @param options.psk - Pre-shared key (for PSK mode)
* @param options.pskId - Pre-shared key identifier (for PSK mode)
*
* @returns A Promise that resolves to the exported secret.
* @see [Single-Shot Secret Export](https://datatracker.ietf.org/doc/html/draft-ietf-hpke-hpke-03.html#section-6.2)
*/
async ReceiveExport(
privateKey: Key | KeyPair,
encapsulatedSecret: Uint8Array,
exporterContext: Uint8Array,
length: number,
options?: { info?: Uint8Array; psk?: Uint8Array; pskId?: Uint8Array },
): Promise<Uint8Array> {
const ctx = await this.SetupRecipient(privateKey, encapsulatedSecret, options)
return await ctx.Export(exporterContext, length)
}
/**
* Establishes a sender encryption context.
*
* Creates a context that can be used to encrypt multiple messages to the same recipient,
* amortizing the cost of the public key operations.
*
* Mode selection:
*
* - If the options `psk` and `pskId` are omitted: Base mode (unauthenticated)
* - If the options `psk` and `pskId` are provided: PSK mode (authenticated with pre-shared key)
*
* The returned context maintains a sequence number that increments with each encryption, ensuring
* nonce uniqueness.
*
* @category Encryption Context
* @example
*
* ```ts
* let suite!: HPKE.CipherSuite
* let publicKey!: HPKE.Key // recipient's public key
*
* const { encapsulatedSecret, ctx } = await suite.SetupSender(publicKey)
*
* // Encrypt multiple messages with the same context
* const aad1: Uint8Array = new TextEncoder().encode('message 1 aad')
* const pt1: Uint8Array = new TextEncoder().encode('First message')
* const ct1: Uint8Array = await ctx.Seal(pt1, aad1)
*
* const aad2: Uint8Array = new TextEncoder().encode('message 2 aad')
* const pt2: Uint8Array = new TextEncoder().encode('Second message')
* const ct2: Uint8Array = await ctx.Seal(pt2, aad2)
* ```
*
* @param publicKey - Recipient's public key
* @param options - Options
* @param options.info - Application-supplied information