latticearc 0.5.1

Production-ready post-quantum cryptography. Hybrid ML-KEM+X25519 by default, all 4 NIST standards (FIPS 203–206), post-quantum TLS, and FIPS 140-3 backend — one crate, zero unsafe.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#![deny(unsafe_code)]
#![deny(missing_docs)]
#![deny(clippy::unwrap_used)]
#![deny(clippy::panic)]

//! HMAC (Hash-based Message Authentication Code)
//!
//! HMAC-SHA256 backed by FIPS 140-3 validated `aws-lc-rs`.
//!
//! Standards:
//! - RFC 2104: HMAC: Keyed-Hashing for Message Authentication
//! - FIPS 198-1: The Keyed-Hash Message Authentication Code (HMAC)
//! - NIST SP 800-107: Recommendation for Applications Using Approved Hash Algorithms
//!
//! The HMAC formula is:
//! `H((K ⊕ opad) || H((K ⊕ ipad) || text))`
//!
//! All HMAC operations in the crate share a single backend (aws-lc-rs). Key
//! padding, constant-time tag verification, and FIPS compliance are handled
//! by the underlying library.

use crate::prelude::error::{LatticeArcError, Result};
use aws_lc_rs::hmac::{self, HMAC_SHA256};

/// Compute HMAC-SHA256 for given key and data
///
/// This function computes the HMAC-SHA256 hash using the formula:
/// H((K ⊕ opad) || H((K ⊕ ipad) || text))
///
/// # Arguments
/// * `key` - The secret key (any size, will be padded or hashed to block size)
/// * `data` - The message to authenticate
///
/// # Returns
/// A 32-byte HMAC-SHA256 tag
///
/// # Security Requirements
/// - The key must be cryptographically secure and randomly generated
/// - Use fresh keys for each context (never reuse keys across applications)
/// - The key must be kept secret
/// - Minimum key length: 1 byte (recommended: 32 bytes or more)
/// - Maximum key length: no limit (will be hashed if longer than block size)
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::primitives::mac::hmac::hmac_sha256;
///
/// let key = b"my secret key";
/// let data = b"message to authenticate";
///
/// let tag = hmac_sha256(key, data)?;
/// assert_eq!(tag.len(), 32);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
/// Returns an error if the key is empty or has an invalid length for HMAC.
///
/// # NIST SP 800-107 Compliance
/// - Uses standard HMAC formula as specified
/// - Key padding handled by audited hmac crate
/// - Supports keys of any length (properly hashed if > block size)
pub fn hmac_sha256(key: &[u8], data: &[u8]) -> Result<[u8; 32]> {
    // Validate key length (must be at least 1 byte). aws-lc-rs accepts any
    // nonzero key length and handles padding/hashing per RFC 2104.
    if key.is_empty() {
        return Err(LatticeArcError::InvalidInput("HMAC key cannot be empty".to_string()));
    }

    let hk = hmac::Key::new(HMAC_SHA256, key);
    let tag = hmac::sign(&hk, data);

    // HMAC-SHA256 always produces exactly 32 bytes (RFC 2104).
    // Returning all-zeros on shorter output would be a dangerous silent failure.
    let src = tag.as_ref().get(..32).ok_or_else(|| LatticeArcError::ValidationError {
        message: format!("HMAC-SHA256 output is {} bytes, expected 32", tag.as_ref().len()),
    })?;
    let mut bytes = [0u8; 32];
    bytes.copy_from_slice(src);
    Ok(bytes)
}

/// Verify HMAC-SHA256 tag using constant-time comparison
///
/// This function computes the HMAC-SHA256 tag for the given data and compares it
/// with the provided tag in constant-time to prevent timing attacks.
///
/// # Security Notice
/// Always use constant-time comparison for tag verification to prevent timing attacks.
/// Using standard equality comparison (==) on HMAC tags is vulnerable to timing attacks.
///
/// # Arguments
/// * `key` - The secret key
/// * `data` - The message to verify
/// * `tag` - The HMAC tag to verify against (must be 32 bytes)
///
/// # Returns
/// `true` if the tag is valid, `false` otherwise
///
/// # Example
/// ```no_run
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use latticearc::primitives::mac::hmac::{hmac_sha256, verify_hmac_sha256};
///
/// let key = b"my secret key";
/// let data = b"message to authenticate";
///
/// let tag = hmac_sha256(key, data)?;
/// let is_valid = verify_hmac_sha256(key, data, &tag);
/// assert!(is_valid);
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn verify_hmac_sha256(key: &[u8], data: &[u8], tag: &[u8]) -> bool {
    use subtle::{Choice, ConstantTimeEq};

    // Always compute MAC to prevent timing side-channels.
    let key_valid = Choice::from(u8::from(!key.is_empty()));
    let tag_len_valid = tag.len().ct_eq(&32);

    let mac_matches = match hmac_sha256(key, data) {
        Ok(computed_tag) => computed_tag.ct_eq(tag),
        Err(_) => Choice::from(0u8),
    };

    // Bitwise AND on subtle::Choice: no short-circuit, constant-time combine.
    bool::from(key_valid & tag_len_valid & mac_matches)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Tests use unwrap for simplicity
mod tests {
    use super::*;
    use hex_literal::hex;

    /// Basic HMAC-SHA256 test
    #[test]
    fn test_hmac_sha256_basic_returns_32_byte_tag_succeeds() {
        let key = b"secret_key";
        let data = b"message";
        let result = hmac_sha256(key, data).unwrap();
        assert_eq!(result.len(), 32);
    }

    /// Test that empty data produces valid HMAC
    #[test]
    fn test_hmac_sha256_empty_data_returns_32_byte_tag_succeeds() {
        let key = b"secret_key";
        let data = b"";
        let result = hmac_sha256(key, data).unwrap();
        assert_eq!(result.len(), 32);
    }

    /// Test that different keys produce different tags
    #[test]
    fn test_hmac_sha256_different_keys_produce_distinct_tags_are_unique() {
        let key1 = b"key1";
        let key2 = b"key2";
        let data = b"message";

        let tag1 = hmac_sha256(key1, data);
        let tag2 = hmac_sha256(key2, data);

        assert_ne!(tag1, tag2, "Different keys should produce different tags");
    }

    /// Test that different data produces different tags
    #[test]
    fn test_hmac_sha256_different_data_produce_distinct_tags_are_unique() {
        let key = b"secret_key";
        let data1 = b"message1";
        let data2 = b"message2";

        let tag1 = hmac_sha256(key, data1);
        let tag2 = hmac_sha256(key, data2);

        assert_ne!(tag1, tag2, "Different data should produce different tags");
    }

    /// Test HMAC with long keys (longer than block size)
    ///
    /// When key is longer than block size (64 bytes for SHA-256),
    /// the key is hashed first to produce the actual HMAC key.
    #[test]
    fn test_hmac_sha256_long_key_returns_32_byte_tag_succeeds() {
        let key = [0u8; 100]; // 100 bytes, longer than SHA-256 block size (64 bytes)
        let data = b"message";
        let result = hmac_sha256(&key, data).unwrap();
        assert_eq!(result.len(), 32);
    }

    /// Test HMAC with key exactly equal to block size (64 bytes)
    #[test]
    fn test_hmac_sha256_block_size_key_returns_32_byte_tag_has_correct_size() {
        let key = [0u8; 64]; // Exactly SHA-256 block size
        let data = b"message";
        let result = hmac_sha256(&key, data).unwrap();
        assert_eq!(result.len(), 32);
    }

    /// Test constant-time verification with valid tag
    #[test]
    fn test_verify_hmac_sha256_valid_tag_returns_true_succeeds() {
        let key = b"secret_key";
        let data = b"message";

        let tag = hmac_sha256(key, data).unwrap();
        assert!(verify_hmac_sha256(key, data, &tag));
    }

    /// Test constant-time verification with invalid tag
    #[test]
    fn test_verify_hmac_sha256_invalid_returns_false_fails() {
        let key = b"secret_key";
        let data = b"message";

        let tag = hmac_sha256(key, data).unwrap();
        let mut invalid_tag = tag;
        invalid_tag[0] ^= 0xFF; // Corrupt the tag

        assert!(!verify_hmac_sha256(key, data, &invalid_tag));
    }

    /// Test verification with wrong data
    #[test]
    fn test_verify_hmac_sha256_wrong_data_returns_false_fails() {
        let key = b"secret_key";
        let data1 = b"message1";
        let data2 = b"message2";

        let tag = hmac_sha256(key, data1).unwrap();
        assert!(!verify_hmac_sha256(key, data2, &tag));
    }

    /// Test verification with wrong key
    #[test]
    fn test_verify_hmac_sha256_wrong_key_returns_false_fails() {
        let key1 = b"key1";
        let key2 = b"key2";
        let data = b"message";

        let tag = hmac_sha256(key1, data).unwrap();
        assert!(!verify_hmac_sha256(key2, data, &tag));
    }

    /// Test verification with invalid tag length
    #[test]
    fn test_verify_hmac_sha256_invalid_tag_length_returns_false_fails() {
        let key = b"secret_key";
        let data = b"message";
        let short_tag = [0u8; 16]; // Wrong length

        assert!(!verify_hmac_sha256(key, data, &short_tag));
    }

    // FIPS 198-1 Test Vectors for HMAC-SHA-256
    // From: https://csrc.nist.gov/Projects/Cryptographic-Standards-and-Guidelines/example-values

    /// RFC 4231 Test Case 1: Key = 20 bytes of 0x0b, Data = "Hi There"
    #[test]
    fn test_hmac_sha256_rfc4231_test_case_1_matches_expected() {
        let key = hex!("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");

        let data = b"Hi There";

        let expected = hex!("b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7");

        let result = hmac_sha256(&key, data).unwrap();
        assert_eq!(result, expected, "RFC 4231 test case 1 failed");
        assert!(verify_hmac_sha256(&key, data, &expected));
    }

    /// RFC 4231 Test Case 2: Key = "Jefe", Data = "what do ya want for nothing?"
    #[test]
    fn test_hmac_sha256_rfc4231_test_case_2_matches_expected() {
        let key = b"Jefe";

        let data = b"what do ya want for nothing?";

        let expected = hex!("5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");

        let result = hmac_sha256(key, data).unwrap();
        assert_eq!(result, expected, "RFC 4231 test case 2 failed");
        assert!(verify_hmac_sha256(key, data, &expected));
    }

    /// Test case 3: Key size = block size (20 bytes), data size = 50 bytes
    #[test]
    fn test_hmac_sha256_fips_test_case_3_matches_expected() {
        // Key = 0xaa repeated 20 times
        let key = [0xaa_u8; 20];

        // Data = 0xdd repeated 50 times
        let data = [0xdd_u8; 50];

        // Expected MAC = 0x773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe
        let expected = hex!("773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe");

        let result = hmac_sha256(&key, &data).unwrap();
        assert_eq!(result, expected, "FIPS 198-1 test case 3 failed");
        assert!(verify_hmac_sha256(&key, &data, &expected));
    }

    /// Test case 4: Key size = 25 bytes, data size = 50 bytes
    #[test]
    fn test_hmac_sha256_fips_test_case_4_matches_expected() {
        // Key = 0x0102030405060708090a0b0c0d0e0f10111213141516171819
        let key = hex!("0102030405060708090a0b0c0d0e0f10111213141516171819");

        // Data = 0xcd repeated 50 times
        let data = [0xcd_u8; 50];

        // Expected MAC = 0x82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b
        let expected = hex!("82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b");

        let result = hmac_sha256(&key, &data).unwrap();
        assert_eq!(result, expected, "FIPS 198-1 test case 4 failed");
        assert!(verify_hmac_sha256(&key, &data, &expected));
    }

    /// RFC 4231 Test Case 6: Key = 131 bytes of 0xaa, large key (hashed first)
    #[test]
    fn test_hmac_sha256_rfc4231_test_case_6_matches_expected() {
        let key = [0xaa_u8; 131];

        let data = b"Test Using Larger Than Block-Size Key - Hash Key First";

        let expected = hex!("60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54");

        let result = hmac_sha256(&key, data).unwrap();
        assert_eq!(result, expected, "RFC 4231 test case 6 failed");
        assert!(verify_hmac_sha256(&key, data, &expected));
    }

    /// RFC 4231 Test Case 7: Key = 131 bytes of 0xaa, large key + large data
    #[test]
    fn test_hmac_sha256_rfc4231_test_case_7_matches_expected() {
        let key = [0xaa_u8; 131];

        let data = b"This is a test using a larger than block-size key and a larger than block-size data. The key needs to be hashed before being used by the HMAC algorithm.";

        let expected = hex!("9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2");

        let result = hmac_sha256(&key, data).unwrap();
        assert_eq!(result, expected, "RFC 4231 test case 7 failed");
        assert!(verify_hmac_sha256(&key, data, &expected));
    }

    /// Additional test: Verify deterministic behavior
    #[test]
    fn test_hmac_sha256_deterministic_returns_same_tag_is_deterministic() {
        let key = b"test_key_12345";
        let data = b"test_data_67890";

        let tag1 = hmac_sha256(key, data);
        let tag2 = hmac_sha256(key, data);

        assert_eq!(tag1, tag2, "HMAC should be deterministic");
    }

    /// Additional test: Verify key sensitivity
    #[test]
    fn test_hmac_sha256_key_sensitivity_produces_avalanche_effect_succeeds() {
        let key1 = b"key123";
        let key2 = b"key124"; // Only one bit different
        let data = b"message";

        let tag1 = hmac_sha256(key1, data);
        let tag2 = hmac_sha256(key2, data);

        // Small key change should produce completely different tag
        let mut same_bytes = 0;
        for (a, b) in tag1.iter().zip(tag2.iter()) {
            if a == b {
                same_bytes += 1;
            }
        }
        assert!(same_bytes < 8, "Key change should produce avalanche effect");
    }

    /// Additional test: Verify data sensitivity
    #[test]
    fn test_hmac_sha256_data_sensitivity_produces_avalanche_effect_succeeds() {
        let key = b"secret_key";
        let data1 = b"message1";
        let data2 = b"message2"; // Only one character different

        let tag1 = hmac_sha256(key, data1);
        let tag2 = hmac_sha256(key, data2);

        // Small data change should produce completely different tag
        let mut same_bytes = 0;
        for (a, b) in tag1.iter().zip(tag2.iter()) {
            if a == b {
                same_bytes += 1;
            }
        }
        assert!(same_bytes < 8, "Data change should produce avalanche effect");
    }

    /// Additional test: Large data
    #[test]
    fn test_hmac_sha256_large_data_succeeds() {
        let key = b"secret_key";
        let data = vec![0u8; 1000000]; // 1 MB of data

        let result = hmac_sha256(key, &data).unwrap();
        assert_eq!(result.len(), 32);
        assert!(verify_hmac_sha256(key, &data, &result));
    }
}