• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 Google LLC
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 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 /// Trait which defines hkdf operations
16 pub trait Hkdf {
17     /// Creates a new instance of an hkdf from a salt and key material
new(salt: Option<&[u8]>, ikm: &[u8]) -> Self18     fn new(salt: Option<&[u8]>, ikm: &[u8]) -> Self;
19 
20     /// The RFC5869 HKDF-Expand operation. The info argument for the expand is set to
21     /// the concatenation of all the elements of info_components
expand_multi_info( &self, info_components: &[&[u8]], okm: &mut [u8], ) -> Result<(), InvalidLength>22     fn expand_multi_info(
23         &self,
24         info_components: &[&[u8]],
25         okm: &mut [u8],
26     ) -> Result<(), InvalidLength>;
27 
28     /// The RFC5869 HKDF-Expand operation.
expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength>29     fn expand(&self, info: &[u8], okm: &mut [u8]) -> Result<(), InvalidLength>;
30 }
31 
32 /// Error type returned from the hkdf expand operations when the output key material has
33 /// an invalid length
34 #[derive(Debug)]
35 pub struct InvalidLength;
36 
37 /// Test cases exported for testing specific hkdf implementations
38 #[cfg(feature = "testing")]
39 pub mod testing {
40     extern crate alloc;
41     use crate::hkdf::Hkdf;
42     pub use crate::testing::prelude::*;
43     use crate::CryptoProvider;
44     use alloc::vec;
45     use alloc::vec::Vec;
46     use core::iter;
47     use core::marker::PhantomData;
48     use hex_literal::hex;
49     use rstest_reuse::template;
50 
51     /// Generates the test cases to validate the hkdf implementation.
52     /// For example, to test `MyCryptoProvider`:
53     ///
54     /// ```
55     /// mod tests {
56     ///     use std::marker::PhantomData;
57     ///     use crypto_provider::testing::CryptoProviderTestCase;
58     ///     #[apply(hkdf_test_cases)]
59     ///     fn hkdf_tests(testcase: CryptoProviderTestCase<MyCryptoProvider>){
60     ///         testcase(PhantomData::<MyCryptoProvider>);
61     ///     }
62     /// }
63     /// ```
64     #[template]
65     #[export]
66     #[rstest]
67     #[case::basic_test_hkdf(basic_test_hkdf)]
68     #[case::test_rfc5869_sha256(test_rfc5869_sha256)]
69     #[case::test_lengths(test_lengths)]
70     #[case::test_max_length(test_max_length)]
71     #[case::test_max_length_exceeded(test_max_length_exceeded)]
72     #[case::test_unsupported_length(test_unsupported_length)]
73     #[case::test_expand_multi_info(test_expand_multi_info)]
74     #[case::run_hkdf_sha256_vectors(run_hkdf_sha256_vectors)]
75     #[case::run_hkdf_sha512_vectors(run_hkdf_sha512_vectors)]
hkdf_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>)76     fn hkdf_test_cases<C: CryptoProvider>(#[case] testcase: CryptoProviderTestCase<C>) {}
77 
78     const MAX_SHA256_LENGTH: usize = 255 * (256 / 8); // =8160
79 
80     ///
81     pub struct Test<'a> {
82         ikm: &'a [u8],
83         salt: &'a [u8],
84         info: &'a [u8],
85         okm: &'a [u8],
86     }
87 
88     /// data taken from sample code in Readme of crates.io page
basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>)89     pub fn basic_test_hkdf<C: CryptoProvider>(_: PhantomData<C>) {
90         let ikm = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
91         let salt = hex!("000102030405060708090a0b0c");
92         let info = hex!("f0f1f2f3f4f5f6f7f8f9");
93 
94         let hk = C::HkdfSha256::new(Some(&salt[..]), &ikm);
95         let mut okm = [0u8; 42];
96         hk.expand(&info, &mut okm)
97             .expect("42 is a valid length for Sha256 to output");
98 
99         let expected = hex!(
100             "
101         3cb25f25faacd57a90434f64d0362f2a
102         2d2d0a90cf1a5a4c5db02d56ecc4c5bf
103         34007208d5b887185865
104         "
105         );
106         assert_eq!(okm, expected);
107     }
108 
109     // Test Vectors from https://tools.ietf.org/html/rfc5869.
110     #[rustfmt::skip]
111     ///
test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>)112     pub fn test_rfc5869_sha256<C: CryptoProvider>(_: PhantomData<C>) {
113         let tests = [
114             Test {
115                 // Test Case 1
116                 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
117                 salt: &hex!("000102030405060708090a0b0c"),
118                 info: &hex!("f0f1f2f3f4f5f6f7f8f9"),
119                 okm: &hex!("
120                     3cb25f25faacd57a90434f64d0362f2a
121                     2d2d0a90cf1a5a4c5db02d56ecc4c5bf
122                     34007208d5b887185865
123                 "),
124             },
125             Test {
126                 // Test Case 2
127                 ikm: &hex!("
128                     000102030405060708090a0b0c0d0e0f
129                     101112131415161718191a1b1c1d1e1f
130                     202122232425262728292a2b2c2d2e2f
131                     303132333435363738393a3b3c3d3e3f
132                     404142434445464748494a4b4c4d4e4f
133                 "),
134                 salt: &hex!("
135                     606162636465666768696a6b6c6d6e6f
136                     707172737475767778797a7b7c7d7e7f
137                     808182838485868788898a8b8c8d8e8f
138                     909192939495969798999a9b9c9d9e9f
139                     a0a1a2a3a4a5a6a7a8a9aaabacadaeaf
140                 "),
141                 info: &hex!("
142                     b0b1b2b3b4b5b6b7b8b9babbbcbdbebf
143                     c0c1c2c3c4c5c6c7c8c9cacbcccdcecf
144                     d0d1d2d3d4d5d6d7d8d9dadbdcdddedf
145                     e0e1e2e3e4e5e6e7e8e9eaebecedeeef
146                     f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff
147                 "),
148                 okm: &hex!("
149                     b11e398dc80327a1c8e7f78c596a4934
150                     4f012eda2d4efad8a050cc4c19afa97c
151                     59045a99cac7827271cb41c65e590e09
152                     da3275600c2f09b8367793a9aca3db71
153                     cc30c58179ec3e87c14c01d5c1f3434f
154                     1d87
155                 "),
156             },
157             Test {
158                 // Test Case 3
159                 ikm: &hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"),
160                 salt: &hex!(""),
161                 info: &hex!(""),
162                 okm: &hex!("
163                     8da4e775a563c18f715f802a063c5a31
164                     b8a11f5c5ee1879ec3454e5f3c738d2d
165                     9d201395faa4b61a96c8
166                 "),
167             },
168         ];
169         for Test { ikm, salt, info, okm } in tests.iter() {
170             let salt = if salt.is_empty() {
171                 None
172             } else {
173                 Some(&salt[..])
174             };
175             let hkdf = C::HkdfSha256::new(salt, ikm);
176             let mut okm2 = vec![0u8; okm.len()];
177             assert!(hkdf.expand(&info[..], &mut okm2).is_ok());
178             assert_eq!(okm2[..], okm[..]);
179         }
180     }
181 
182     ///
test_lengths<C: CryptoProvider>(_: PhantomData<C>)183     pub fn test_lengths<C: CryptoProvider>(_: PhantomData<C>) {
184         let hkdf = C::HkdfSha256::new(None, &[]);
185         let mut longest = vec![0u8; MAX_SHA256_LENGTH];
186         assert!(hkdf.expand(&[], &mut longest).is_ok());
187         // Runtime is O(length), so exhaustively testing all legal lengths
188         // would take too long (at least without --release). Only test a
189         // subset: the first 500, the last 10, and every 100th in between.
190         // 0 is an invalid key length for openssl, so start at 1
191         let lengths = (1..MAX_SHA256_LENGTH + 1)
192             .filter(|&len| !(500..=MAX_SHA256_LENGTH - 10).contains(&len) || len % 100 == 0);
193 
194         for length in lengths {
195             let mut okm = vec![0u8; length];
196 
197             assert!(hkdf.expand(&[], &mut okm).is_ok());
198             assert_eq!(okm.len(), length);
199             assert_eq!(okm[..], longest[..length]);
200         }
201     }
202 
203     ///
test_max_length<C: CryptoProvider>(_: PhantomData<C>)204     pub fn test_max_length<C: CryptoProvider>(_: PhantomData<C>) {
205         let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
206         let mut okm = vec![0u8; MAX_SHA256_LENGTH];
207         assert!(hkdf.expand(&[], &mut okm).is_ok());
208     }
209 
210     ///
test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>)211     pub fn test_max_length_exceeded<C: CryptoProvider>(_: PhantomData<C>) {
212         let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
213         let mut okm = vec![0u8; MAX_SHA256_LENGTH + 1];
214         assert!(hkdf.expand(&[], &mut okm).is_err());
215     }
216 
217     ///
test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>)218     pub fn test_unsupported_length<C: CryptoProvider>(_: PhantomData<C>) {
219         let hkdf = C::HkdfSha256::new(Some(&[]), &[]);
220         let mut okm = vec![0u8; 90000];
221         assert!(hkdf.expand(&[], &mut okm).is_err());
222     }
223 
224     ///
test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>)225     pub fn test_expand_multi_info<C: CryptoProvider>(_: PhantomData<C>) {
226         let info_components = &[
227             &b"09090909090909090909090909090909090909090909"[..],
228             &b"8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a8a"[..],
229             &b"0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0"[..],
230             &b"4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4"[..],
231             &b"1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d1d"[..],
232         ];
233 
234         let hkdf = C::HkdfSha256::new(None, b"some ikm here");
235 
236         // Compute HKDF-Expand on the concatenation of all the info components
237         let mut oneshot_res = [0u8; 16];
238         hkdf.expand(&info_components.concat(), &mut oneshot_res)
239             .unwrap();
240 
241         // Now iteratively join the components of info_components until it's all 1 component. The value
242         // of HKDF-Expand should be the same throughout
243         let mut num_concatted = 0;
244         let mut info_head = Vec::new();
245 
246         while num_concatted < info_components.len() {
247             info_head.extend(info_components[num_concatted]);
248 
249             // Build the new input to be the info head followed by the remaining components
250             let input: Vec<&[u8]> = iter::once(info_head.as_slice())
251                 .chain(info_components.iter().cloned().skip(num_concatted + 1))
252                 .collect();
253 
254             // Compute and compare to the one-shot answer
255             let mut multipart_res = [0u8; 16];
256             hkdf.expand_multi_info(&input, &mut multipart_res).unwrap();
257             assert_eq!(multipart_res, oneshot_res);
258             num_concatted += 1;
259         }
260     }
261 
262     ///
run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>)263     pub fn run_hkdf_sha256_vectors<C: CryptoProvider>(_: PhantomData<C>) {
264         run_hkdf_test_vectors::<C::HkdfSha256>(HashAlg::Sha256)
265     }
266 
267     ///
run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>)268     pub fn run_hkdf_sha512_vectors<C: CryptoProvider>(_: PhantomData<C>) {
269         run_hkdf_test_vectors::<C::HkdfSha512>(HashAlg::Sha512)
270     }
271 
272     enum HashAlg {
273         Sha256,
274         Sha512,
275     }
276 
277     ///
run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg)278     fn run_hkdf_test_vectors<K: Hkdf>(hash: HashAlg) {
279         let test_name = match hash {
280             HashAlg::Sha256 => wycheproof::hkdf::TestName::HkdfSha256,
281             HashAlg::Sha512 => wycheproof::hkdf::TestName::HkdfSha512,
282         };
283 
284         let test_set =
285             wycheproof::hkdf::TestSet::load(test_name).expect("should be able to load test set");
286         for test_group in test_set.test_groups {
287             for test in test_group.tests {
288                 let ikm = test.ikm;
289                 let salt = test.salt;
290                 let info = test.info;
291                 let okm = test.okm;
292                 let tc_id = test.tc_id;
293                 if let Some(desc) = run_test::<K>(
294                     ikm.as_slice(),
295                     salt.as_slice(),
296                     info.as_slice(),
297                     okm.as_slice(),
298                 ) {
299                     panic!(
300                         "\n\
301                          Failed test {tc_id}: {desc}\n\
302                          ikm:\t{ikm:?}\n\
303                          salt:\t{salt:?}\n\
304                          info:\t{info:?}\n\
305                          okm:\t{okm:?}\n"
306                     );
307                 }
308             }
309         }
310     }
311 
run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str>312     fn run_test<K: Hkdf>(ikm: &[u8], salt: &[u8], info: &[u8], okm: &[u8]) -> Option<&'static str> {
313         let prk = K::new(Some(salt), ikm);
314         let mut got_okm = vec![0; okm.len()];
315 
316         if prk.expand(info, &mut got_okm).is_err() {
317             return Some("prk expand");
318         }
319         if got_okm != okm {
320             return Some("mismatch in okm");
321         }
322         None
323     }
324 }
325