Skip to content

Commit ba2b43b

Browse files
committed
ml-kem: add test hash check to decapsulate
1 parent 298fffb commit ba2b43b

1 file changed

Lines changed: 10 additions & 3 deletions

File tree

src/ml-kem.ts

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -305,10 +305,17 @@ function createKyber(opts: KyberOpts) {
305305
cleanBytes(kr.subarray(32));
306306
return { cipherText, sharedSecret: kr.subarray(0, 32) };
307307
},
308-
decapsulate: (cipherText: Uint8Array, secretKey: Uint8Array) => {
309-
ensureBytes(secretKey, secretCoder.bytesLen); // 768*k + 96
308+
decapsulate: (cipherText: Uint8Array, dk: Uint8Array) => {
309+
ensureBytes(dk, secretCoder.bytesLen); // 768*k + 96
310310
ensureBytes(cipherText, lengths.cipherText); // 32(du*k + dv)
311-
const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(secretKey);
311+
// test ← H(dk[384𝑘 ∶ 768𝑘 + 32])) .
312+
// If test ≠ dk[768𝑘 + 32 ∶ 768𝑘 + 64], then input checking has failed.
313+
const _768k = secretCoder.bytesLen - 96;
314+
const _start = _768k + 32;
315+
const test = HASH256(dk.subarray(_768k / 2, _start));
316+
if (!equalBytes(test, dk.subarray(_start, _start + 32)))
317+
throw new Error('invalid secretKey: hash check failed');
318+
const [sk, publicKey, publicKeyHash, z] = secretCoder.decode(dk);
312319
const msg = KPKE.decrypt(cipherText, sk);
313320
const kr = HASH512.create().update(msg).update(publicKeyHash).digest(); // derive randomness, Khat, rHat = G(mHat || h)
314321
const Khat = kr.subarray(0, 32);

0 commit comments

Comments
 (0)