Skip to main content

apple_cryptokit/authentication/
hmac.rs

1use crate::error::{CryptoKitError, Result};
2
3/// HMAC algorithm trait providing a unified interface for different HMAC algorithms
4pub trait HMAC {
5    /// HMAC output size (bytes)
6    const OUTPUT_SIZE: usize;
7
8    /// Calculate HMAC
9    fn authenticate(key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
10        let mut output = vec![0u8; Self::OUTPUT_SIZE];
11        Self::authenticate_to(key, data, &mut output)?;
12        Ok(output)
13    }
14
15    /// Calculate HMAC to the provided buffer (zero-allocation)
16    ///
17    /// # Parameters
18    /// - `output`: Must be at least `OUTPUT_SIZE` bytes
19    ///
20    /// # Returns
21    /// - `Ok(usize)`: Number of bytes written
22    /// - `Err`: Authentication failed
23    fn authenticate_to(key: &[u8], data: &[u8], output: &mut [u8]) -> Result<usize>;
24
25    /// Get output size (deprecated, use OUTPUT_SIZE constant instead)
26    fn output_size() -> usize {
27        Self::OUTPUT_SIZE
28    }
29}
30
31/// Message authentication code verification
32pub fn verify_hmac<T: AsRef<[u8]>>(expected: T, computed: T) -> bool {
33    let expected_bytes = expected.as_ref();
34    let computed_bytes = computed.as_ref();
35
36    if expected_bytes.len() != computed_bytes.len() {
37        return false;
38    }
39
40    // Use constant-time comparison to prevent timing attacks
41    constant_time_eq(expected_bytes, computed_bytes)
42}
43
44/// Constant-time byte comparison
45pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
46    if a.len() != b.len() {
47        return false;
48    }
49
50    let mut result = 0u8;
51    for (x, y) in a.iter().zip(b.iter()) {
52        result |= x ^ y;
53    }
54    result == 0
55}
56
57/// HMAC algorithm enumeration
58#[derive(Debug, Clone, Copy, PartialEq)]
59pub enum HmacAlgorithm {
60    /// SHA-1 (insecure, for compatibility only)
61    Sha1,
62    /// SHA-256
63    Sha256,
64    /// SHA-384
65    Sha384,
66    /// SHA-512
67    Sha512,
68}
69
70impl HmacAlgorithm {
71    /// Get output length
72    pub fn output_size(&self) -> usize {
73        match self {
74            HmacAlgorithm::Sha1 => 20,
75            HmacAlgorithm::Sha256 => 32,
76            HmacAlgorithm::Sha384 => 48,
77            HmacAlgorithm::Sha512 => 64,
78        }
79    }
80
81    /// Calculate HMAC
82    pub fn compute(&self, key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
83        let mut output = vec![0u8; self.output_size()];
84        self.compute_to(key, data, &mut output)?;
85        Ok(output)
86    }
87
88    /// Calculate HMAC to the provided buffer (zero-allocation)
89    ///
90    /// # Parameters
91    /// - `output`: Must be at least `output_size()` bytes
92    ///
93    /// # Returns
94    /// Number of bytes written to output
95    pub fn compute_to(&self, key: &[u8], data: &[u8], output: &mut [u8]) -> Result<usize> {
96        assert!(
97            output.len() >= self.output_size(),
98            "Output buffer too small: {} < {}",
99            output.len(),
100            self.output_size()
101        );
102        match self {
103            HmacAlgorithm::Sha1 => {
104                use crate::authentication::sha1::hmac_sha1_to;
105                hmac_sha1_to(key, data, output)
106            }
107            HmacAlgorithm::Sha256 => {
108                use crate::authentication::sha256::hmac_sha256_to;
109                hmac_sha256_to(key, data, output)
110            }
111            HmacAlgorithm::Sha384 => {
112                use crate::authentication::sha384::hmac_sha384_to;
113                hmac_sha384_to(key, data, output)
114            }
115            HmacAlgorithm::Sha512 => {
116                use crate::authentication::sha512::hmac_sha512_to;
117                hmac_sha512_to(key, data, output)
118            }
119        }
120    }
121
122    /// Verify HMAC
123    pub fn verify(&self, key: &[u8], data: &[u8], expected_hmac: &[u8]) -> Result<bool> {
124        let computed = self.compute(key, data)?;
125        Ok(constant_time_eq(&computed, expected_hmac))
126    }
127}
128
129/// HMAC builder
130pub struct HmacBuilder {
131    algorithm: HmacAlgorithm,
132    key: Vec<u8>,
133}
134
135impl HmacBuilder {
136    /// Create a new HMAC builder
137    pub fn new(algorithm: HmacAlgorithm) -> Self {
138        Self {
139            algorithm,
140            key: Vec::new(),
141        }
142    }
143
144    /// Set the key
145    pub fn key(mut self, key: &[u8]) -> Self {
146        self.key = key.to_vec();
147        self
148    }
149
150    /// Calculate HMAC
151    pub fn compute(&self, data: &[u8]) -> Result<Vec<u8>> {
152        if self.key.is_empty() {
153            return Err(CryptoKitError::InvalidKey);
154        }
155        self.algorithm.compute(&self.key, data)
156    }
157
158    /// Calculate HMAC to the provided buffer (zero-allocation)
159    ///
160    /// # Returns
161    /// Number of bytes written to output
162    pub fn compute_to(&self, data: &[u8], output: &mut [u8]) -> Result<usize> {
163        if self.key.is_empty() {
164            return Err(CryptoKitError::InvalidKey);
165        }
166        self.algorithm.compute_to(&self.key, data, output)
167    }
168
169    /// Verify HMAC
170    pub fn verify(&self, data: &[u8], expected_hmac: &[u8]) -> Result<bool> {
171        let computed = self.compute(data)?;
172        Ok(constant_time_eq(&computed, expected_hmac))
173    }
174
175    /// Get output size
176    pub fn output_size(&self) -> usize {
177        self.algorithm.output_size()
178    }
179}