1use crate::aws_lc::{
49 EVP_PKEY_CTX_kem_set_params, EVP_PKEY_decapsulate, EVP_PKEY_encapsulate,
50 EVP_PKEY_kem_new_raw_public_key, EVP_PKEY, EVP_PKEY_KEM,
51};
52use crate::buffer::Buffer;
53use crate::encoding::generated_encodings;
54use crate::error::{KeyRejected, Unspecified};
55use crate::ptr::LcPtr;
56use alloc::borrow::Cow;
57use core::cmp::Ordering;
58use zeroize::Zeroize;
59
60const ML_KEM_512_SHARED_SECRET_LENGTH: usize = 32;
61const ML_KEM_512_PUBLIC_KEY_LENGTH: usize = 800;
62const ML_KEM_512_SECRET_KEY_LENGTH: usize = 1632;
63const ML_KEM_512_CIPHERTEXT_LENGTH: usize = 768;
64
65const ML_KEM_768_SHARED_SECRET_LENGTH: usize = 32;
66const ML_KEM_768_PUBLIC_KEY_LENGTH: usize = 1184;
67const ML_KEM_768_SECRET_KEY_LENGTH: usize = 2400;
68const ML_KEM_768_CIPHERTEXT_LENGTH: usize = 1088;
69
70const ML_KEM_1024_SHARED_SECRET_LENGTH: usize = 32;
71const ML_KEM_1024_PUBLIC_KEY_LENGTH: usize = 1568;
72const ML_KEM_1024_SECRET_KEY_LENGTH: usize = 3168;
73const ML_KEM_1024_CIPHERTEXT_LENGTH: usize = 1568;
74
75pub const ML_KEM_512: Algorithm<AlgorithmId> = Algorithm {
77 id: AlgorithmId::MlKem512,
78 decapsulate_key_size: ML_KEM_512_SECRET_KEY_LENGTH,
79 encapsulate_key_size: ML_KEM_512_PUBLIC_KEY_LENGTH,
80 ciphertext_size: ML_KEM_512_CIPHERTEXT_LENGTH,
81 shared_secret_size: ML_KEM_512_SHARED_SECRET_LENGTH,
82};
83
84pub const ML_KEM_768: Algorithm<AlgorithmId> = Algorithm {
86 id: AlgorithmId::MlKem768,
87 decapsulate_key_size: ML_KEM_768_SECRET_KEY_LENGTH,
88 encapsulate_key_size: ML_KEM_768_PUBLIC_KEY_LENGTH,
89 ciphertext_size: ML_KEM_768_CIPHERTEXT_LENGTH,
90 shared_secret_size: ML_KEM_768_SHARED_SECRET_LENGTH,
91};
92
93pub const ML_KEM_1024: Algorithm<AlgorithmId> = Algorithm {
95 id: AlgorithmId::MlKem1024,
96 decapsulate_key_size: ML_KEM_1024_SECRET_KEY_LENGTH,
97 encapsulate_key_size: ML_KEM_1024_PUBLIC_KEY_LENGTH,
98 ciphertext_size: ML_KEM_1024_CIPHERTEXT_LENGTH,
99 shared_secret_size: ML_KEM_1024_SHARED_SECRET_LENGTH,
100};
101
102use crate::aws_lc::{NID_MLKEM1024, NID_MLKEM512, NID_MLKEM768};
103
104pub trait AlgorithmIdentifier:
106 Copy + Clone + Debug + PartialEq + crate::sealed::Sealed + 'static
107{
108 fn nid(self) -> i32;
110}
111
112#[derive(PartialEq)]
114pub struct Algorithm<Id = AlgorithmId>
115where
116 Id: AlgorithmIdentifier,
117{
118 pub(crate) id: Id,
119 pub(crate) decapsulate_key_size: usize,
120 pub(crate) encapsulate_key_size: usize,
121 pub(crate) ciphertext_size: usize,
122 pub(crate) shared_secret_size: usize,
123}
124
125impl<Id> Algorithm<Id>
126where
127 Id: AlgorithmIdentifier,
128{
129 #[must_use]
131 pub fn id(&self) -> Id {
132 self.id
133 }
134
135 #[inline]
136 #[allow(dead_code)]
137 pub(crate) fn decapsulate_key_size(&self) -> usize {
138 self.decapsulate_key_size
139 }
140
141 #[inline]
142 pub(crate) fn encapsulate_key_size(&self) -> usize {
143 self.encapsulate_key_size
144 }
145
146 #[inline]
147 pub(crate) fn ciphertext_size(&self) -> usize {
148 self.ciphertext_size
149 }
150
151 #[inline]
152 pub(crate) fn shared_secret_size(&self) -> usize {
153 self.shared_secret_size
154 }
155}
156
157impl<Id> Debug for Algorithm<Id>
158where
159 Id: AlgorithmIdentifier,
160{
161 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
162 Debug::fmt(&self.id, f)
163 }
164}
165
166pub struct DecapsulationKey<Id = AlgorithmId>
168where
169 Id: AlgorithmIdentifier,
170{
171 algorithm: &'static Algorithm<Id>,
172 evp_pkey: LcPtr<EVP_PKEY>,
173}
174
175#[non_exhaustive]
177#[derive(Clone, Copy, Debug, PartialEq)]
178pub enum AlgorithmId {
179 MlKem512,
181
182 MlKem768,
184
185 MlKem1024,
187}
188
189impl AlgorithmIdentifier for AlgorithmId {
190 fn nid(self) -> i32 {
191 match self {
192 AlgorithmId::MlKem512 => NID_MLKEM512,
193 AlgorithmId::MlKem768 => NID_MLKEM768,
194 AlgorithmId::MlKem1024 => NID_MLKEM1024,
195 }
196 }
197}
198
199impl crate::sealed::Sealed for AlgorithmId {}
200
201impl<Id> DecapsulationKey<Id>
202where
203 Id: AlgorithmIdentifier,
204{
205 pub fn generate(alg: &'static Algorithm<Id>) -> Result<Self, Unspecified> {
210 let kyber_key = kem_key_generate(alg.id.nid())?;
211 Ok(DecapsulationKey {
212 algorithm: alg,
213 evp_pkey: kyber_key,
214 })
215 }
216
217 #[must_use]
219 pub fn algorithm(&self) -> &'static Algorithm<Id> {
220 self.algorithm
221 }
222
223 #[allow(clippy::missing_panics_doc)]
228 pub fn encapsulation_key(&self) -> Result<EncapsulationKey<Id>, Unspecified> {
229 let evp_pkey = self.evp_pkey.clone();
230
231 Ok(EncapsulationKey {
232 algorithm: self.algorithm,
233 evp_pkey,
234 })
235 }
236
237 #[allow(clippy::needless_pass_by_value)]
245 pub fn decapsulate(&self, ciphertext: Ciphertext<'_>) -> Result<SharedSecret, Unspecified> {
246 let mut shared_secret_len = self.algorithm.shared_secret_size();
247 let mut shared_secret: Vec<u8> = vec![0u8; shared_secret_len];
248
249 let mut ctx = self.evp_pkey.create_EVP_PKEY_CTX()?;
250
251 let ciphertext = ciphertext.as_ref();
252
253 if 1 != unsafe {
254 EVP_PKEY_decapsulate(
255 *ctx.as_mut(),
256 shared_secret.as_mut_ptr(),
257 &mut shared_secret_len,
258 ciphertext.as_ptr() as *mut u8,
260 ciphertext.len(),
261 )
262 } {
263 return Err(Unspecified);
264 }
265
266 debug_assert_eq!(shared_secret_len, shared_secret.len());
271 shared_secret.truncate(shared_secret_len);
272
273 Ok(SharedSecret(shared_secret.into_boxed_slice()))
274 }
275}
276
277unsafe impl<Id> Send for DecapsulationKey<Id> where Id: AlgorithmIdentifier {}
278
279unsafe impl<Id> Sync for DecapsulationKey<Id> where Id: AlgorithmIdentifier {}
280
281impl<Id> Debug for DecapsulationKey<Id>
282where
283 Id: AlgorithmIdentifier,
284{
285 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
286 f.debug_struct("DecapsulationKey")
287 .field("algorithm", &self.algorithm)
288 .finish_non_exhaustive()
289 }
290}
291
292generated_encodings!((EncapsulationKeyBytes, EncapsulationKeyBytesType));
293
294pub struct EncapsulationKey<Id = AlgorithmId>
297where
298 Id: AlgorithmIdentifier,
299{
300 algorithm: &'static Algorithm<Id>,
301 evp_pkey: LcPtr<EVP_PKEY>,
302}
303
304impl<Id> EncapsulationKey<Id>
305where
306 Id: AlgorithmIdentifier,
307{
308 #[must_use]
310 pub fn algorithm(&self) -> &'static Algorithm<Id> {
311 self.algorithm
312 }
313
314 pub fn encapsulate(&self) -> Result<(Ciphertext<'static>, SharedSecret), Unspecified> {
320 let mut ciphertext_len = self.algorithm.ciphertext_size();
321 let mut shared_secret_len = self.algorithm.shared_secret_size();
322 let mut ciphertext: Vec<u8> = vec![0u8; ciphertext_len];
323 let mut shared_secret: Vec<u8> = vec![0u8; shared_secret_len];
324
325 let mut ctx = self.evp_pkey.create_EVP_PKEY_CTX()?;
326
327 if 1 != unsafe {
328 EVP_PKEY_encapsulate(
329 *ctx.as_mut(),
330 ciphertext.as_mut_ptr(),
331 &mut ciphertext_len,
332 shared_secret.as_mut_ptr(),
333 &mut shared_secret_len,
334 )
335 } {
336 return Err(Unspecified);
337 }
338
339 debug_assert_eq!(ciphertext_len, ciphertext.len());
345 ciphertext.truncate(ciphertext_len);
346 debug_assert_eq!(shared_secret_len, shared_secret.len());
347 shared_secret.truncate(shared_secret_len);
348
349 Ok((
350 Ciphertext::new(ciphertext),
351 SharedSecret::new(shared_secret.into_boxed_slice()),
352 ))
353 }
354
355 pub fn key_bytes(&self) -> Result<EncapsulationKeyBytes<'static>, Unspecified> {
360 let mut encapsulate_bytes = vec![0u8; self.algorithm.encapsulate_key_size()];
361 let encapsulate_key_size = self
362 .evp_pkey
363 .marshal_raw_public_to_buffer(&mut encapsulate_bytes)?;
364
365 debug_assert_eq!(encapsulate_key_size, encapsulate_bytes.len());
366 encapsulate_bytes.truncate(encapsulate_key_size);
367
368 Ok(EncapsulationKeyBytes::new(encapsulate_bytes))
369 }
370
371 pub fn new(alg: &'static Algorithm<Id>, bytes: &[u8]) -> Result<Self, KeyRejected> {
382 match bytes.len().cmp(&alg.encapsulate_key_size()) {
383 Ordering::Less => Err(KeyRejected::too_small()),
384 Ordering::Greater => Err(KeyRejected::too_large()),
385 Ordering::Equal => Ok(()),
386 }?;
387 let pubkey = LcPtr::new(unsafe {
388 EVP_PKEY_kem_new_raw_public_key(alg.id.nid(), bytes.as_ptr(), bytes.len())
389 })?;
390 Ok(EncapsulationKey {
391 algorithm: alg,
392 evp_pkey: pubkey,
393 })
394 }
395}
396
397unsafe impl<Id> Send for EncapsulationKey<Id> where Id: AlgorithmIdentifier {}
398
399unsafe impl<Id> Sync for EncapsulationKey<Id> where Id: AlgorithmIdentifier {}
400
401impl<Id> Debug for EncapsulationKey<Id>
402where
403 Id: AlgorithmIdentifier,
404{
405 fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
406 f.debug_struct("EncapsulationKey")
407 .field("algorithm", &self.algorithm)
408 .finish_non_exhaustive()
409 }
410}
411
412pub struct Ciphertext<'a>(Cow<'a, [u8]>);
415
416impl<'a> Ciphertext<'a> {
417 fn new(value: Vec<u8>) -> Ciphertext<'a> {
418 Self(Cow::Owned(value))
419 }
420}
421
422impl Drop for Ciphertext<'_> {
423 fn drop(&mut self) {
424 if let Cow::Owned(ref mut v) = self.0 {
425 v.zeroize();
426 }
427 }
428}
429
430impl AsRef<[u8]> for Ciphertext<'_> {
431 fn as_ref(&self) -> &[u8] {
432 match self.0 {
433 Cow::Borrowed(v) => v,
434 Cow::Owned(ref v) => v.as_ref(),
435 }
436 }
437}
438
439impl<'a> From<&'a [u8]> for Ciphertext<'a> {
440 fn from(value: &'a [u8]) -> Self {
441 Self(Cow::Borrowed(value))
442 }
443}
444
445pub struct SharedSecret(Box<[u8]>);
447
448impl SharedSecret {
449 fn new(value: Box<[u8]>) -> Self {
450 Self(value)
451 }
452}
453
454impl Drop for SharedSecret {
455 fn drop(&mut self) {
456 self.0.zeroize();
457 }
458}
459
460impl AsRef<[u8]> for SharedSecret {
461 fn as_ref(&self) -> &[u8] {
462 self.0.as_ref()
463 }
464}
465
466#[inline]
468fn kem_key_generate(nid: i32) -> Result<LcPtr<EVP_PKEY>, Unspecified> {
469 let params_fn = |ctx| {
470 if 1 == unsafe { EVP_PKEY_CTX_kem_set_params(ctx, nid) } {
471 Ok(())
472 } else {
473 Err(())
474 }
475 };
476
477 LcPtr::<EVP_PKEY>::generate(EVP_PKEY_KEM, Some(params_fn))
478}
479
480#[cfg(test)]
481mod tests {
482 use super::{Ciphertext, DecapsulationKey, EncapsulationKey, SharedSecret};
483 use crate::error::KeyRejected;
484
485 use crate::kem::{ML_KEM_1024, ML_KEM_512, ML_KEM_768};
486
487 #[test]
488 fn ciphertext() {
489 let ciphertext_bytes = vec![42u8; 4];
490 let ciphertext = Ciphertext::from(ciphertext_bytes.as_ref());
491 assert_eq!(ciphertext.as_ref(), &[42, 42, 42, 42]);
492 drop(ciphertext);
493
494 let ciphertext_bytes = vec![42u8; 4];
495 let ciphertext = Ciphertext::<'static>::new(ciphertext_bytes);
496 assert_eq!(ciphertext.as_ref(), &[42, 42, 42, 42]);
497 }
498
499 #[test]
500 fn shared_secret() {
501 let secret_bytes = vec![42u8; 4];
502 let shared_secret = SharedSecret::new(secret_bytes.into_boxed_slice());
503 assert_eq!(shared_secret.as_ref(), &[42, 42, 42, 42]);
504 }
505
506 #[test]
507 fn test_kem_serialize() {
508 for algorithm in [&ML_KEM_512, &ML_KEM_768, &ML_KEM_1024] {
509 let priv_key = DecapsulationKey::generate(algorithm).unwrap();
510 assert_eq!(priv_key.algorithm(), algorithm);
511
512 let pub_key = priv_key.encapsulation_key().unwrap();
513 let pubkey_raw_bytes = pub_key.key_bytes().unwrap();
514 let pub_key_from_bytes =
515 EncapsulationKey::new(algorithm, pubkey_raw_bytes.as_ref()).unwrap();
516
517 assert_eq!(
518 pub_key.key_bytes().unwrap().as_ref(),
519 pub_key_from_bytes.key_bytes().unwrap().as_ref()
520 );
521 assert_eq!(pub_key.algorithm(), pub_key_from_bytes.algorithm());
522 }
523 }
524
525 #[test]
526 fn test_kem_wrong_sizes() {
527 for algorithm in [&ML_KEM_512, &ML_KEM_768, &ML_KEM_1024] {
528 let too_long_bytes = vec![0u8; algorithm.encapsulate_key_size() + 1];
529 let long_pub_key_from_bytes = EncapsulationKey::new(algorithm, &too_long_bytes);
530 assert_eq!(
531 long_pub_key_from_bytes.err(),
532 Some(KeyRejected::too_large())
533 );
534
535 let too_short_bytes = vec![0u8; algorithm.encapsulate_key_size() - 1];
536 let short_pub_key_from_bytes = EncapsulationKey::new(algorithm, &too_short_bytes);
537 assert_eq!(
538 short_pub_key_from_bytes.err(),
539 Some(KeyRejected::too_small())
540 );
541 }
542 }
543
544 #[test]
545 fn test_kem_e2e() {
546 for algorithm in [&ML_KEM_512, &ML_KEM_768, &ML_KEM_1024] {
547 let priv_key = DecapsulationKey::generate(algorithm).unwrap();
548 assert_eq!(priv_key.algorithm(), algorithm);
549
550 let pub_key = priv_key.encapsulation_key().unwrap();
551
552 let (alice_ciphertext, alice_secret) =
553 pub_key.encapsulate().expect("encapsulate successful");
554
555 let bob_secret = priv_key
556 .decapsulate(alice_ciphertext)
557 .expect("decapsulate successful");
558
559 assert_eq!(alice_secret.as_ref(), bob_secret.as_ref());
560 }
561 }
562
563 #[test]
564 fn test_serialized_kem_e2e() {
565 for algorithm in [&ML_KEM_512, &ML_KEM_768, &ML_KEM_1024] {
566 let priv_key = DecapsulationKey::generate(algorithm).unwrap();
567 assert_eq!(priv_key.algorithm(), algorithm);
568
569 let pub_key = priv_key.encapsulation_key().unwrap();
570
571 let pub_key_bytes = pub_key.key_bytes().unwrap();
573
574 drop(pub_key);
576
577 let retrieved_pub_key =
578 EncapsulationKey::new(algorithm, pub_key_bytes.as_ref()).unwrap();
579 let (ciphertext, bob_secret) = retrieved_pub_key
580 .encapsulate()
581 .expect("encapsulate successful");
582
583 let alice_secret = priv_key
584 .decapsulate(ciphertext)
585 .expect("decapsulate successful");
586
587 assert_eq!(alice_secret.as_ref(), bob_secret.as_ref());
588 }
589 }
590
591 #[test]
592 fn test_debug_fmt() {
593 let private = DecapsulationKey::generate(&ML_KEM_512).expect("successful generation");
594 assert_eq!(
595 format!("{private:?}"),
596 "DecapsulationKey { algorithm: MlKem512, .. }"
597 );
598 assert_eq!(
599 format!(
600 "{:?}",
601 private.encapsulation_key().expect("public key retrievable")
602 ),
603 "EncapsulationKey { algorithm: MlKem512, .. }"
604 );
605 }
606}