Debian Codegraph @

third_party/rust/mls-rs-crypto-nss/src/kdf.rs

raw
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // Copyright by contributors to this project.
3 // SPDX-License-Identifier: (Apache-2.0 OR MIT)
4
5 use core::fmt::Debug;
6
7 use mls_rs_core::{crypto::CipherSuite, error::IntoAnyError};
8 use mls_rs_crypto_traits::{KdfId, KdfType};
9
10 use alloc::vec::Vec;
11
12 #[derive(Debug)]
13 #[cfg_attr(feature = "std", derive(thiserror::Error))]
14 pub enum KdfError {
15 // #[cfg_attr(feature = "std", error("invalid prk length"))]
16 // InvalidPrkLength,
17 // #[cfg_attr(feature = "std", error("invalid length"))]
18 // InvalidLength,
19 #[cfg_attr(
20 feature = "std",
21 error("the provided length of the key {0} is shorter than the minimum length {1}")
22 )]
23 TooShortKey(usize, usize),
24 #[cfg_attr(feature = "std", error("invalid input"))]
25 InvalidInput,
26 #[cfg_attr(feature = "std", error("internal error"))]
27 InternalError,
28 #[cfg_attr(feature = "std", error("unsupported cipher suite"))]
29 UnsupportedCipherSuite,
30 }
31
32 impl From<nss_gk_api::hkdf::HkdfError> for KdfError {
33 fn from(_value: nss_gk_api::hkdf::HkdfError) -> Self {
34 KdfError::InvalidInput
35 }
36 }
37
38 impl IntoAnyError for KdfError {
39 #[cfg(feature = "std")]
40 fn into_dyn_error(self) -> Result<Box<dyn std::error::Error + Send + Sync>, Self> {
41 Ok(self.into())
42 }
43 }
44
45 #[derive(Clone, Copy, Debug, Eq, PartialEq)]
46 pub struct Kdf(KdfId);
47
48 impl Kdf {
49 pub fn new(cipher_suite: CipherSuite) -> Option<Self> {
50 KdfId::new(cipher_suite).map(Self)
51 }
52 }
53
54 #[cfg_attr(not(mls_build_async), maybe_async::must_be_sync)]
55 #[cfg_attr(all(target_arch = "wasm32", mls_build_async), maybe_async::must_be_async(?Send))]
56 #[cfg_attr(
57 all(not(target_arch = "wasm32"), mls_build_async),
58 maybe_async::must_be_async
59 )]
60 impl KdfType for Kdf {
61 type Error = KdfError;
62
63 async fn expand(&self, prk: &[u8], info: &[u8], len: usize) -> Result<Vec<u8>, KdfError> {
64 if prk.len() < self.extract_size() {
65 return Err(KdfError::TooShortKey(prk.len(), self.extract_size()));
66 }
67
68 nss_gk_api::init();
69
70 let alg = match self.0 {
71 KdfId::HkdfSha256 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_256),
72 KdfId::HkdfSha384 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_384),
73 KdfId::HkdfSha512 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_512),
74 _ => Err(KdfError::UnsupportedCipherSuite),
75 }?;
76
77 let hkdf = nss_gk_api::hkdf::Hkdf::new(alg);
78 let prk_symkey = hkdf.import_secret(prk).unwrap();
79
80 // Expand
81 let r = hkdf
82 .expand_data(&prk_symkey, info, len)
83 .expect("HkdfError::InternalError");
84 Ok(r)
85 }
86
87 async fn extract(&self, salt: &[u8], ikm: &[u8]) -> Result<Vec<u8>, KdfError> {
88 if ikm.is_empty() {
89 return Err(KdfError::TooShortKey(0, 1));
90 }
91
92 nss_gk_api::init();
93
94 let alg = match self.0 {
95 KdfId::HkdfSha256 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_256),
96 KdfId::HkdfSha384 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_384),
97 KdfId::HkdfSha512 => Ok(nss_gk_api::hkdf::HkdfAlgorithm::HKDF_SHA2_512),
98 _ => Err(KdfError::UnsupportedCipherSuite),
99 }?;
100
101 let hkdf = nss_gk_api::hkdf::Hkdf::new(alg);
102 let ikm_symkey = hkdf.import_secret(ikm).unwrap();
103
104 // Extract
105 let prk = hkdf.extract(salt, &ikm_symkey).unwrap();
106 let prk_data = prk.key_data().unwrap();
107 Ok(prk_data.to_vec())
108 }
109
110 fn extract_size(&self) -> usize {
111 self.0.extract_size()
112 }
113
114 fn kdf_id(&self) -> u16 {
115 self.0 as u16
116 }
117 }
118
119 #[cfg(all(test, not(mls_build_async)))]
120 mod test {
121 use assert_matches::assert_matches;
122 use mls_rs_core::crypto::CipherSuite;
123 use mls_rs_crypto_traits::KdfType;
124
125 use crate::kdf::{Kdf, KdfError};
126
127 use alloc::vec;
128
129 #[test]
130 fn no_key() {
131 let kdf = Kdf::new(CipherSuite::CURVE25519_AES128).unwrap();
132 assert!(kdf.extract(b"key", &[]).is_err());
133 }
134
135 #[test]
136 fn no_salt() {
137 let kdf = Kdf::new(CipherSuite::CURVE25519_AES128).unwrap();
138 assert!(kdf.extract(&[], b"key").is_ok());
139 }
140
141 #[test]
142 fn no_info() {
143 let kdf = Kdf::new(CipherSuite::CURVE25519_AES128).unwrap();
144 let key = vec![0u8; kdf.extract_size()];
145 assert!(kdf.expand(&key, &[], 42).is_ok());
146 }
147
148 #[test]
149 fn test_short_key() {
150 let kdf = Kdf::new(CipherSuite::CURVE25519_AES128).unwrap();
151 let key = vec![0u8; kdf.extract_size() - 1];
152
153 assert_matches!(kdf.expand(&key, &[], 42), Err(KdfError::TooShortKey(_, _)));
154 }
155 }