owned.rs (3135B)
1 // Copyright 2023 Cryspen Sarl 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 9 //! This module contains the trait and related errors for a KEM that takes array references as 10 //! arguments and returns values as arrays. 11 //! 12 use super::arrayref; 13 14 pub use arrayref::{DecapsError, EncapsError, KeyGenError}; 15 16 /// A Key Encapsulation Mechanismd (KEM) that returns values insteaf of writing the results to 17 /// `&mut` arguments. 18 pub trait Kem< 19 const EK_LEN: usize, 20 const DK_LEN: usize, 21 const CT_LEN: usize, 22 const SS_LEN: usize, 23 const RAND_KEYGEN_LEN: usize, 24 const RAND_ENCAPS_LEN: usize, 25 > 26 { 27 /// Generate a pair of encapsulation and decapsulation keys. 28 /// It is the responsibility of the caller to ensure that the `rand` argument is actually 29 /// random. 30 fn keygen(rand: &[u8; RAND_KEYGEN_LEN]) -> Result<([u8; DK_LEN], [u8; EK_LEN]), KeyGenError>; 31 32 /// Encapsulate a shared secret towards a given encapsulation key. 33 /// It is the responsibility of the caller to ensure that the `rand` argument is actually 34 /// random. 35 fn encaps( 36 ek: &[u8; EK_LEN], 37 rand: &[u8; RAND_ENCAPS_LEN], 38 ) -> Result<([u8; SS_LEN], [u8; CT_LEN]), EncapsError>; 39 40 /// Decapsulate a shared secret. 41 fn decaps(ct: &[u8; CT_LEN], dk: &[u8; DK_LEN]) -> Result<[u8; SS_LEN], DecapsError>; 42 } 43 44 impl< 45 const EK_LEN: usize, 46 const DK_LEN: usize, 47 const CT_LEN: usize, 48 const SS_LEN: usize, 49 const RAND_KEYGEN_LEN: usize, 50 const RAND_ENCAPS_LEN: usize, 51 T: arrayref::Kem<EK_LEN, DK_LEN, CT_LEN, SS_LEN, RAND_KEYGEN_LEN, RAND_ENCAPS_LEN>, 52 > Kem<EK_LEN, DK_LEN, CT_LEN, SS_LEN, RAND_KEYGEN_LEN, RAND_ENCAPS_LEN> for T 53 { 54 fn keygen(rand: &[u8; RAND_KEYGEN_LEN]) -> Result<([u8; DK_LEN], [u8; EK_LEN]), KeyGenError> { 55 let mut dk = [0u8; DK_LEN]; 56 let mut ek = [0u8; EK_LEN]; 57 58 <Self as arrayref::Kem< 59 EK_LEN, 60 DK_LEN, 61 CT_LEN, 62 SS_LEN, 63 RAND_KEYGEN_LEN, 64 RAND_ENCAPS_LEN, 65 >>::keygen(&mut ek, &mut dk, rand)?; 66 67 Ok((dk, ek)) 68 } 69 70 fn encaps( 71 ek: &[u8; EK_LEN], 72 rand: &[u8; RAND_ENCAPS_LEN], 73 ) -> Result<([u8; SS_LEN], [u8; CT_LEN]), EncapsError> { 74 let mut ss = [0u8; SS_LEN]; 75 let mut ct = [0u8; CT_LEN]; 76 77 <Self as arrayref::Kem< 78 EK_LEN, 79 DK_LEN, 80 CT_LEN, 81 SS_LEN, 82 RAND_KEYGEN_LEN, 83 RAND_ENCAPS_LEN, 84 >>::encaps(&mut ct, &mut ss, ek, rand)?; 85 86 Ok((ss, ct)) 87 } 88 89 fn decaps(ct: &[u8; CT_LEN], dk: &[u8; DK_LEN]) -> Result<[u8; SS_LEN], DecapsError> { 90 let mut ss = [0u8; SS_LEN]; 91 92 <Self as arrayref::Kem< 93 EK_LEN, 94 DK_LEN, 95 CT_LEN, 96 SS_LEN, 97 RAND_KEYGEN_LEN, 98 RAND_ENCAPS_LEN, 99 >>::decaps(&mut ss, ct, dk)?; 100 101 Ok(ss) 102 } 103 }