Alice Wang | f1a83b0 | 2023-09-26 12:39:17 +0000 | [diff] [blame] | 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}; |
Maurice Lam | 0322b8c | 2023-12-18 22:13:48 +0000 | [diff] [blame] | 20 | use bssl_sys::HKDF; |
Alice Wang | ccc52e5 | 2023-10-03 13:14:09 +0000 | [diff] [blame] | 21 | use zeroize::Zeroizing; |
Alice Wang | f1a83b0 | 2023-09-26 12:39:17 +0000 | [diff] [blame] | 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 |
| 27 | pub fn hkdf<const N: usize>( |
| 28 | secret: &[u8], |
| 29 | salt: &[u8], |
| 30 | info: &[u8], |
| 31 | digester: Digester, |
Alice Wang | ccc52e5 | 2023-10-03 13:14:09 +0000 | [diff] [blame] | 32 | ) -> Result<Zeroizing<[u8; N]>> { |
| 33 | let mut key = Zeroizing::new([0u8; N]); |
Alice Wang | f1a83b0 | 2023-09-26 12:39:17 +0000 | [diff] [blame] | 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 | } |