tink_core/
mac.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//! Message Authentication Codes.
18
19/// `Mac` is the interface for MACs (Message Authentication Codes).
20///
21/// This interface should be used for authentication only, and not for other purposes
22/// (for example, it should not be used to generate pseudorandom bytes).
23pub trait Mac: MacBoxClone {
24    /// Compute message authentication code (MAC) for code data.
25    fn compute_mac(&self, data: &[u8]) -> Result<Vec<u8>, crate::TinkError>;
26
27    /// Returns `()` if `mac` is a correct authentication code (MAC) for `data`,
28    /// otherwise it returns an error.
29    fn verify_mac(&self, mac: &[u8], data: &[u8]) -> Result<(), crate::TinkError> {
30        let computed = self.compute_mac(data)?;
31        if crate::subtle::constant_time_compare(mac, &computed) {
32            Ok(())
33        } else {
34            Err("Invalid MAC".into())
35        }
36    }
37}
38
39/// Trait bound to indicate that primitive trait objects should support cloning
40/// themselves as trait objects.
41pub trait MacBoxClone {
42    fn box_clone(&self) -> Box<dyn Mac>;
43}
44
45/// Default implementation of the box-clone trait bound for any underlying
46/// concrete type that implements [`Clone`].
47impl<T> MacBoxClone for T
48where
49    T: 'static + Mac + Clone,
50{
51    fn box_clone(&self) -> Box<dyn Mac> {
52        Box::new(self.clone())
53    }
54}