-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path02-psk-mode.ts
More file actions
55 lines (41 loc) · 1.89 KB
/
02-psk-mode.ts
File metadata and controls
55 lines (41 loc) · 1.89 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
import * as HPKE from '../index.ts'
const encoder = new TextEncoder()
const decoder = new TextDecoder()
// Cipher suite components (agreed upon by both sender and recipient upfront)
const suite = new HPKE.CipherSuite(
HPKE.KEM_DHKEM_P256_HKDF_SHA256,
HPKE.KDF_HKDF_SHA256,
HPKE.AEAD_AES_128_GCM,
)
// Pre-shared key and identifier (agreed upon by both sender and recipient upfront)
const psk = crypto.getRandomValues(new Uint8Array(32))
const pskId = encoder.encode('shared-key-id-2024')
// Recipient: Generate a key pair
const recipientKeyPair = await suite.GenerateKeyPair()
// Recipient: Serialize public key for sending
const recipientPublicKeySerialized = await suite.SerializePublicKey(recipientKeyPair.publicKey)
// Recipient → Sender: Send serialized public key
// Sender: Deserialize recipient's public key
const recipientPublicKey = await suite.DeserializePublicKey(recipientPublicKeySerialized)
// Sender: Setup sender context with PSK mode
const { encapsulatedSecret, ctx: senderCtx } = await suite.SetupSender(recipientPublicKey, {
psk,
pskId,
})
// Sender → Recipient: Send encapsulated secret (enc)
// Recipient: Setup recipient context with PSK mode
const recipientCtx = await suite.SetupRecipient(recipientKeyPair, encapsulatedSecret, {
psk,
pskId,
})
// Sender: Encrypt message with AAD
const aad = encoder.encode('authenticated-data')
const plaintext = encoder.encode('Authenticated message using PSK mode')
const ciphertext = await senderCtx.Seal(plaintext, aad)
// Sender → Recipient: Send ciphertext and aad
// Recipient: Decrypt message
const decrypted = await recipientCtx.Open(ciphertext, aad)
console.log(decoder.decode(decrypted)) // "Authenticated message using PSK mode"
// Verify we're in PSK mode
console.log('Mode:', senderCtx.mode === HPKE.MODE_PSK ? 'PSK' : 'Base') // "Mode: PSK"
console.log('Mode:', recipientCtx.mode === HPKE.MODE_PSK ? 'PSK' : 'Base') // "Mode: PSK"