Skip to content

Commit 4ef27cd

Browse files
committed
ml-kem: validate encryption/encapsulation keys
Adds a check that decoded `EncryptionKey`s successfully round-trip encode back to the bytes they were decoded from, in order to detect malformed keys. Closes #172
1 parent cae07ad commit 4ef27cd

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

ml-kem/src/pke.rs

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -156,15 +156,20 @@ where
156156
}
157157

158158
/// Parse an encryption key from a byte array `(t_hat || rho)`
159-
// TODO(tarcieri): validate decoded keys
160-
#[allow(clippy::unnecessary_wraps)]
161159
pub fn from_bytes(enc: &EncodedEncryptionKey<P>) -> Result<Self, Error> {
162160
let (t_hat, rho) = P::split_ek(enc);
163161
let t_hat = P::decode_u12(t_hat);
164-
Ok(Self {
162+
let ret = Self {
165163
t_hat,
166164
rho: rho.clone(),
167-
})
165+
};
166+
167+
// Ensure key round-trips successfully
168+
if &ret.as_bytes() == enc {
169+
Ok(ret)
170+
} else {
171+
Err(Error)
172+
}
168173
}
169174
}
170175

@@ -221,4 +226,12 @@ mod test {
221226
codec_test::<MlKem768Params>();
222227
codec_test::<MlKem1024Params>();
223228
}
229+
230+
#[test]
231+
fn reject_invalid_encryption_keys() {
232+
// Create an invalid key: all bytes set to 0xFF
233+
// When decoded as 12-bit coefficients, this produces values of 0xFFF = 4095 > 3329
234+
let invalid_key = EncodedEncryptionKey::<MlKem768Params>::from_fn(|_| 0xFF);
235+
assert!(EncryptionKey::<MlKem768Params>::from_bytes(&invalid_key).is_err());
236+
}
224237
}

0 commit comments

Comments
 (0)