1 // Copyright 2022, 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 //! Functionality related to HMAC signing/verification.
16
17 use crate::{km_err, try_to_vec, Error};
18 use alloc::vec::Vec;
19 use kmr_wire::KeySizeInBits;
20 use zeroize::ZeroizeOnDrop;
21
22 /// Minimum size of an HMAC key in bits.
23 pub const MIN_KEY_SIZE_BITS: usize = 64;
24
25 /// Maximum size of a StrongBox HMAC key in bits.
26 pub const MAX_STRONGBOX_KEY_SIZE_BITS: usize = 512;
27
28 /// Maximum size of a HMAC key in bits.
29 pub const MAX_KEY_SIZE_BITS: usize = 1024;
30
31 /// An HMAC key.
32 #[derive(Clone, PartialEq, Eq, ZeroizeOnDrop)]
33 pub struct Key(pub Vec<u8>);
34
valid_size(key_size: KeySizeInBits, max_size_bits: usize) -> Result<(), Error>35 fn valid_size(key_size: KeySizeInBits, max_size_bits: usize) -> Result<(), Error> {
36 if key_size.0 % 8 != 0 {
37 Err(km_err!(UnsupportedKeySize, "key size {} bits not a multiple of 8", key_size.0))
38 } else if !(MIN_KEY_SIZE_BITS..=max_size_bits).contains(&(key_size.0 as usize)) {
39 Err(km_err!(UnsupportedKeySize, "unsupported KEY_SIZE {} bits for HMAC", key_size.0))
40 } else {
41 Ok(())
42 }
43 }
44
45 /// Check that the size of an HMAC key is within the allowed size for the KeyMint HAL.
valid_hal_size(key_size: KeySizeInBits) -> Result<(), Error>46 pub fn valid_hal_size(key_size: KeySizeInBits) -> Result<(), Error> {
47 valid_size(key_size, MAX_KEY_SIZE_BITS)
48 }
49
50 /// Check that the size of an HMAC key is within the allowed size for a StrongBox implementation.
valid_strongbox_hal_size(key_size: KeySizeInBits) -> Result<(), Error>51 pub fn valid_strongbox_hal_size(key_size: KeySizeInBits) -> Result<(), Error> {
52 valid_size(key_size, MAX_STRONGBOX_KEY_SIZE_BITS)
53 }
54
55 impl Key {
56 /// Create a new HMAC key from data.
new(data: Vec<u8>) -> Key57 pub fn new(data: Vec<u8>) -> Key {
58 Key(data)
59 }
60
61 /// Create a new HMAC key from data.
new_from(data: &[u8]) -> Result<Key, Error>62 pub fn new_from(data: &[u8]) -> Result<Key, Error> {
63 Ok(Key::new(try_to_vec(data)?))
64 }
65
66 /// Indicate the size of the key in bits.
size(&self) -> KeySizeInBits67 pub fn size(&self) -> KeySizeInBits {
68 KeySizeInBits((self.0.len() * 8) as u32)
69 }
70 }
71