tink_mac/
hmac_key_manager.rs

1// Copyright 2020 The Tink-Rust Authors
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////////////////////////////////////////////////////////////////////////////////
16
17//! Key manager for AES-CMAC keys for HMAC.
18
19use std::convert::TryFrom;
20use tink_core::{utils::wrap_err, TinkError};
21use tink_proto::{prost::Message, HashType};
22
23/// Maximal version of HMAC keys.
24pub const HMAC_KEY_VERSION: u32 = 0;
25/// Type URL of HMAC keys that Tink supports.
26pub const HMAC_TYPE_URL: &str = "type.googleapis.com/google.crypto.tink.HmacKey";
27
28/// Generates new HMAC keys and produces new instances of HMAC.
29#[derive(Default)]
30pub(crate) struct HmacKeyManager;
31
32impl tink_core::registry::KeyManager for HmacKeyManager {
33    /// Create an HMAC instance for the given serialized [`HmacKey`](tink_proto::HmacKey) proto.
34    fn primitive(&self, serialized_key: &[u8]) -> Result<tink_core::Primitive, TinkError> {
35        if serialized_key.is_empty() {
36            return Err("HmacKeyManager: invalid key".into());
37        }
38
39        let key = tink_proto::HmacKey::decode(serialized_key)
40            .map_err(|e| wrap_err("HmacKeyManager: decode failed", e))?;
41        validate_key(&key)?;
42
43        let params = match &key.params {
44            None => return Err("HmacKeyManager: no key params".into()),
45            Some(p) => p,
46        };
47        let hash = HashType::try_from(params.hash).unwrap_or(HashType::UnknownHash);
48        match crate::subtle::Hmac::new(hash, &key.key_value, params.tag_size as usize) {
49            Ok(p) => Ok(tink_core::Primitive::Mac(Box::new(p))),
50            Err(e) => Err(wrap_err("HmacKeyManager: cannot create new primitive", e)),
51        }
52    }
53
54    /// Generate a new serialized [`HmacKey`](tink_proto::HmacKey) according to specification in
55    /// the given [`HmacKeyFormat`](tink_proto::HmacKeyFormat).
56    fn new_key(&self, serialized_key_format: &[u8]) -> Result<Vec<u8>, TinkError> {
57        if serialized_key_format.is_empty() {
58            return Err("HmacKeyManager: invalid key format".into());
59        }
60        let key_format = tink_proto::HmacKeyFormat::decode(serialized_key_format)
61            .map_err(|_| "HmacKeyManager: invalid key format")?;
62        validate_key_format(&key_format)
63            .map_err(|e| wrap_err("HmacKeyManager: invalid key format", e))?;
64        let key_value = tink_core::subtle::random::get_random_bytes(key_format.key_size as usize);
65        let mut sk = Vec::new();
66        tink_proto::HmacKey {
67            version: HMAC_KEY_VERSION,
68            params: key_format.params,
69            key_value,
70        }
71        .encode(&mut sk)
72        .map_err(|e| wrap_err("HmacKeyManager: failed to encode new key", e))?;
73        Ok(sk)
74    }
75
76    fn type_url(&self) -> &'static str {
77        HMAC_TYPE_URL
78    }
79
80    fn key_material_type(&self) -> tink_proto::key_data::KeyMaterialType {
81        tink_proto::key_data::KeyMaterialType::Symmetric
82    }
83}
84
85/// Validate the given [`HmacKey`](tink_proto::HmacKey). It only validates the version of the
86/// key because other parameters will be validated in primitive construction.
87fn validate_key(key: &tink_proto::HmacKey) -> Result<(), TinkError> {
88    tink_core::keyset::validate_key_version(key.version, HMAC_KEY_VERSION)
89        .map_err(|e| wrap_err("HmacKeyManager: invalid version", e))?;
90    let key_size = key.key_value.len();
91    match &key.params {
92        None => Err("HmacKeyManager: missing HMAC params".into()),
93        Some(params) => {
94            let hash = HashType::try_from(params.hash).unwrap_or(HashType::UnknownHash);
95            crate::subtle::validate_hmac_params(hash, key_size, params.tag_size as usize)
96        }
97    }
98}
99
100/// Validate the given [`HmacKeyFormat`](tink_proto::HmacKeyFormat).
101fn validate_key_format(format: &tink_proto::HmacKeyFormat) -> Result<(), TinkError> {
102    match &format.params {
103        None => Err("missing HMAC params".into()),
104        Some(params) => {
105            let hash = HashType::try_from(params.hash).unwrap_or(HashType::UnknownHash);
106            crate::subtle::validate_hmac_params(
107                hash,
108                format.key_size as usize,
109                params.tag_size as usize,
110            )
111        }
112    }
113}