Alice Wang | 24954b4 | 2023-02-06 10:03:45 +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 | //! This module mirrors the content in open-dice/include/dice/ops.h |
| 16 | //! It contains the set of functions that implement various operations that the |
| 17 | //! main DICE functions depend on. |
| 18 | |
| 19 | use crate::dice::{Hash, HASH_SIZE}; |
| 20 | use crate::error::{check_result, Result}; |
Alice Wang | 6ef44bc | 2023-02-08 12:08:32 +0000 | [diff] [blame] | 21 | use open_dice_cbor_bindgen::{DiceHash, DiceKdf}; |
Alice Wang | 24954b4 | 2023-02-06 10:03:45 +0000 | [diff] [blame] | 22 | use std::ptr; |
| 23 | |
| 24 | /// Hashes the provided input using DICE's hash function `DiceHash`. |
| 25 | pub fn hash(input: &[u8]) -> Result<Hash> { |
| 26 | let mut output: Hash = [0; HASH_SIZE]; |
| 27 | // SAFETY: DiceHash takes a sized input buffer and writes to a constant-sized output buffer. |
| 28 | // The first argument context is not used in this function. |
| 29 | check_result(unsafe { |
| 30 | DiceHash( |
| 31 | ptr::null_mut(), // context |
| 32 | input.as_ptr(), |
| 33 | input.len(), |
| 34 | output.as_mut_ptr(), |
| 35 | ) |
| 36 | })?; |
| 37 | Ok(output) |
| 38 | } |
Alice Wang | 6ef44bc | 2023-02-08 12:08:32 +0000 | [diff] [blame] | 39 | |
| 40 | /// An implementation of HKDF-SHA512. Derives a key of `derived_key.len()` bytes from `ikm`, `salt`, |
| 41 | /// and `info`. The derived key is written to the `derived_key`. |
| 42 | pub fn kdf(ikm: &[u8], salt: &[u8], info: &[u8], derived_key: &mut [u8]) -> Result<()> { |
| 43 | // SAFETY: The function writes to the `derived_key`, within the given bounds, and only reads the |
| 44 | // input values. The first argument context is not used in this function. |
| 45 | check_result(unsafe { |
| 46 | DiceKdf( |
| 47 | ptr::null_mut(), // context |
| 48 | derived_key.len(), |
| 49 | ikm.as_ptr(), |
| 50 | ikm.len(), |
| 51 | salt.as_ptr(), |
| 52 | salt.len(), |
| 53 | info.as_ptr(), |
| 54 | info.len(), |
| 55 | derived_key.as_mut_ptr(), |
| 56 | ) |
| 57 | }) |
| 58 | } |