blob: d5aeb76e4fe31865f6f92aaea2ea00300ef720ab [file] [log] [blame]
Alice Wangf1a83b02023-09-26 12:39:17 +00001// 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
17use crate::digest::Digester;
18use crate::util::check_int_result;
19use bssl_avf_error::{ApiName, Result};
Maurice Lam0322b8c2023-12-18 22:13:48 +000020use bssl_sys::HKDF;
Alice Wangccc52e52023-10-03 13:14:09 +000021use zeroize::Zeroizing;
Alice Wangf1a83b02023-09-26 12:39:17 +000022
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
27pub fn hkdf<const N: usize>(
28 secret: &[u8],
29 salt: &[u8],
30 info: &[u8],
31 digester: Digester,
Alice Wangccc52e52023-10-03 13:14:09 +000032) -> Result<Zeroizing<[u8; N]>> {
33 let mut key = Zeroizing::new([0u8; N]);
Alice Wangf1a83b02023-09-26 12:39:17 +000034 // 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}