1 // Copyright 2023, The Android Open Source Project
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 //! Wrappers of the HKDF functions in BoringSSL hkdf.h.
16 
17 use crate::digest::Digester;
18 use crate::util::check_int_result;
19 use bssl_avf_error::{ApiName, Result};
20 use bssl_sys::HKDF;
21 use zeroize::Zeroizing;
22 
23 /// Computes HKDF (as specified by [RFC 5869]) of initial keying material `secret` with
24 /// `salt` and `info` using the given `digester`.
25 ///
26 /// [RFC 5869]: https://www.rfc-editor.org/rfc/rfc5869.html
hkdf<const N: usize>( secret: &[u8], salt: &[u8], info: &[u8], digester: Digester, ) -> Result<Zeroizing<[u8; N]>>27 pub fn hkdf<const N: usize>(
28     secret: &[u8],
29     salt: &[u8],
30     info: &[u8],
31     digester: Digester,
32 ) -> Result<Zeroizing<[u8; N]>> {
33     let mut key = Zeroizing::new([0u8; N]);
34     // SAFETY: Only reads from/writes to the provided slices and the digester was non-null.
35     let ret = unsafe {
36         HKDF(
37             key.as_mut_ptr(),
38             key.len(),
39             digester.0,
40             secret.as_ptr(),
41             secret.len(),
42             salt.as_ptr(),
43             salt.len(),
44             info.as_ptr(),
45             info.len(),
46         )
47     };
48     check_int_result(ret, ApiName::HKDF)?;
49     Ok(key)
50 }
51