| 1 | //! This crate provides trait for Message Authentication Code (MAC) algorithms. |
| 2 | |
| 3 | #![no_std] |
| 4 | #![cfg_attr(docsrs, feature(doc_cfg))] |
| 5 | #![doc( |
| 6 | html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg", |
| 7 | html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg" |
| 8 | )] |
| 9 | #![forbid(unsafe_code)] |
| 10 | #![warn(missing_docs, rust_2018_idioms)] |
| 11 | |
| 12 | #[cfg(feature = "std")] |
| 13 | extern crate std; |
| 14 | |
| 15 | #[cfg(feature = "cipher")] |
| 16 | pub use cipher; |
| 17 | #[cfg(feature = "cipher")] |
| 18 | use cipher::{BlockCipher, NewBlockCipher}; |
| 19 | |
| 20 | #[cfg(feature = "dev")] |
| 21 | #[cfg_attr(docsrs, doc(cfg(feature = "dev")))] |
| 22 | pub mod dev; |
| 23 | |
| 24 | mod errors; |
| 25 | |
| 26 | pub use crate::errors::{InvalidKeyLength, MacError}; |
| 27 | pub use generic_array::{self, typenum::consts}; |
| 28 | |
| 29 | use generic_array::typenum::Unsigned; |
| 30 | use generic_array::{ArrayLength, GenericArray}; |
| 31 | use subtle::{Choice, ConstantTimeEq}; |
| 32 | |
| 33 | /// Key for an algorithm that implements [`NewMac`]. |
| 34 | pub type Key<M> = GenericArray<u8, <M as NewMac>::KeySize>; |
| 35 | |
| 36 | /// Instantiate a [`Mac`] algorithm. |
| 37 | pub trait NewMac: Sized { |
| 38 | /// Key size in bytes with which cipher guaranteed to be initialized. |
| 39 | type KeySize: ArrayLength<u8>; |
| 40 | |
| 41 | /// Initialize new MAC instance from key with fixed size. |
| 42 | fn new(key: &Key<Self>) -> Self; |
| 43 | |
| 44 | /// Initialize new MAC instance from key with variable size. |
| 45 | /// |
| 46 | /// Default implementation will accept only keys with length equal to |
| 47 | /// `KeySize`, but some MACs can accept range of key lengths. |
| 48 | fn new_varkey(key: &[u8]) -> Result<Self, InvalidKeyLength> { |
| 49 | if key.len() != Self::KeySize::to_usize() { |
| 50 | Err(InvalidKeyLength) |
| 51 | } else { |
| 52 | Ok(Self::new(GenericArray::from_slice(key))) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /// The [`Mac`] trait defines methods for a Message Authentication algorithm. |
| 58 | pub trait Mac: Clone { |
| 59 | /// Output size of the [[`Mac`]] |
| 60 | type OutputSize: ArrayLength<u8>; |
| 61 | |
| 62 | /// Update MAC state with the given data. |
| 63 | fn update(&mut self, data: &[u8]); |
| 64 | |
| 65 | /// Reset [`Mac`] instance. |
| 66 | fn reset(&mut self); |
| 67 | |
| 68 | /// Obtain the result of a [`Mac`] computation as a [`Output`] and consume |
| 69 | /// [`Mac`] instance. |
| 70 | fn finalize(self) -> Output<Self>; |
| 71 | |
| 72 | /// Obtain the result of a [`Mac`] computation as a [`Output`] and reset |
| 73 | /// [`Mac`] instance. |
| 74 | fn finalize_reset(&mut self) -> Output<Self> { |
| 75 | let res = self.clone().finalize(); |
| 76 | self.reset(); |
| 77 | res |
| 78 | } |
| 79 | |
| 80 | /// Check if tag/code value is correct for the processed input. |
| 81 | fn verify(self, tag: &[u8]) -> Result<(), MacError> { |
| 82 | let choice = self.finalize().bytes.ct_eq(tag); |
| 83 | |
| 84 | if choice.unwrap_u8() == 1 { |
| 85 | Ok(()) |
| 86 | } else { |
| 87 | Err(MacError) |
| 88 | } |
| 89 | } |
| 90 | } |
| 91 | |
| 92 | /// [`Output`] is a thin wrapper around bytes array which provides a safe `Eq` |
| 93 | /// implementation that runs in a fixed time. |
| 94 | #[derive(Clone)] |
| 95 | pub struct Output<M: Mac> { |
| 96 | bytes: GenericArray<u8, M::OutputSize>, |
| 97 | } |
| 98 | |
| 99 | impl<M: Mac> Output<M> { |
| 100 | /// Create a new MAC [`Output`]. |
| 101 | pub fn new(bytes: GenericArray<u8, M::OutputSize>) -> Output<M> { |
| 102 | Output { bytes } |
| 103 | } |
| 104 | |
| 105 | /// Get the MAC tag/code value as a byte array. |
| 106 | /// |
| 107 | /// Be very careful using this method, since incorrect use of the tag value |
| 108 | /// may permit timing attacks which defeat the security provided by the |
| 109 | /// [`Mac`] trait. |
| 110 | pub fn into_bytes(self) -> GenericArray<u8, M::OutputSize> { |
| 111 | self.bytes |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl<M: Mac> ConstantTimeEq for Output<M> { |
| 116 | fn ct_eq(&self, other: &Self) -> Choice { |
| 117 | self.bytes.ct_eq(&other.bytes) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | impl<M: Mac> PartialEq for Output<M> { |
| 122 | fn eq(&self, x: &Output<M>) -> bool { |
| 123 | self.ct_eq(x).unwrap_u8() == 1 |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | impl<M: Mac> Eq for Output<M> {} |
| 128 | |
| 129 | #[cfg(feature = "cipher")] |
| 130 | #[cfg_attr(docsrs, doc(cfg(feature = "cipher")))] |
| 131 | /// Trait for MAC functions which can be created from block cipher. |
| 132 | pub trait FromBlockCipher { |
| 133 | /// Block cipher type |
| 134 | type Cipher: BlockCipher; |
| 135 | |
| 136 | /// Create new MAC isntance from provided block cipher. |
| 137 | fn from_cipher(cipher: Self::Cipher) -> Self; |
| 138 | } |
| 139 | |
| 140 | #[cfg(feature = "cipher")] |
| 141 | #[cfg_attr(docsrs, doc(cfg(feature = "cipher")))] |
| 142 | impl<T> NewMac for T |
| 143 | where |
| 144 | T: FromBlockCipher, |
| 145 | T::Cipher: NewBlockCipher, |
| 146 | { |
| 147 | type KeySize = <<Self as FromBlockCipher>::Cipher as NewBlockCipher>::KeySize; |
| 148 | |
| 149 | fn new(key: &Key<Self>) -> Self { |
| 150 | let cipher = <Self as FromBlockCipher>::Cipher::new(key); |
| 151 | Self::from_cipher(cipher) |
| 152 | } |
| 153 | |
| 154 | fn new_varkey(key: &[u8]) -> Result<Self, InvalidKeyLength> { |
| 155 | <Self as FromBlockCipher>::Cipher::new_varkey(key) |
| 156 | .map_err(|_| InvalidKeyLength) |
| 157 | .map(Self::from_cipher) |
| 158 | } |
| 159 | } |