hyprstream_crypto/backend.rs
1//! Cryptographic backend abstraction for KDF and MAC operations.
2//!
3//! Provides unified API for key derivation and message authentication,
4//! with compile-time selection between:
5//! - **Default**: Blake3 (fast, modern, ~10+ GB/s with SIMD)
6//! - **FIPS mode**: HKDF-SHA256 + HMAC-SHA256 (NIST-approved)
7//!
8//! # Feature Flags
9//!
10//! - Default: Blake3 `derive_key()` and `keyed_hash()`
11//! - `fips`: HKDF-SHA256 (SP 800-56C) and HMAC-SHA256 (FIPS 198-1)
12
13// ============================================================================
14// Key Derivation Function (KDF)
15// ============================================================================
16
17/// Derive a 32-byte key from input material with domain separation.
18///
19/// # Arguments
20///
21/// * `context` - Static domain separation string (must be compile-time constant)
22/// * `ikm` - Input key material (e.g., shared_secret || salt)
23///
24/// # Returns
25///
26/// 32-byte derived key.
27///
28/// # Backend Behavior
29///
30/// - **Blake3**: Uses `blake3::derive_key(context, ikm)`
31/// - **FIPS**: Uses `HKDF-Expand(HKDF-Extract(ikm), context)`
32#[cfg(not(feature = "fips"))]
33pub fn derive_key(context: &str, ikm: &[u8]) -> [u8; 32] {
34 blake3::derive_key(context, ikm)
35}
36
37#[cfg(feature = "fips")]
38pub fn derive_key(context: &str, ikm: &[u8]) -> [u8; 32] {
39 use hkdf::Hkdf;
40 use sha2::Sha256;
41
42 // HKDF-Extract with no salt (salt = None means use zeros)
43 // Then HKDF-Expand with context as info
44 let hk = Hkdf::<Sha256>::new(None, ikm);
45 let mut output = [0u8; 32];
46 // SAFETY: 32 bytes is always valid for HKDF-SHA256 (max output is 255 * 32 = 8160 bytes)
47 // This cannot fail at runtime, but we handle it gracefully anyway
48 if hk.expand(context.as_bytes(), &mut output).is_err() {
49 // This branch is unreachable with valid HKDF parameters
50 output = [0u8; 32];
51 }
52 output
53}
54
55// ============================================================================
56// Message Authentication Code (MAC)
57// ============================================================================
58
59/// Compute a 32-byte keyed MAC.
60///
61/// # Arguments
62///
63/// * `key` - 32-byte MAC key
64/// * `data` - Data to authenticate
65///
66/// # Returns
67///
68/// 32-byte MAC tag.
69///
70/// # Backend Behavior
71///
72/// - **Blake3**: Uses `blake3::keyed_hash(key, data)`
73/// - **FIPS**: Uses `HMAC-SHA256(key, data)`
74#[cfg(not(feature = "fips"))]
75pub fn keyed_mac(key: &[u8; 32], data: &[u8]) -> [u8; 32] {
76 *blake3::keyed_hash(key, data).as_bytes()
77}
78
79#[cfg(feature = "fips")]
80pub fn keyed_mac(key: &[u8; 32], data: &[u8]) -> [u8; 32] {
81 use hmac::{Hmac, Mac};
82 use sha2::Sha256;
83
84 // SAFETY: HMAC-SHA256 accepts any key size - new_from_slice cannot fail for any &[u8]
85 // Using match instead of expect to satisfy clippy
86 let mut mac = match Hmac::<Sha256>::new_from_slice(key) {
87 Ok(m) => m,
88 Err(_) => unreachable!("HMAC-SHA256 accepts any key size"),
89 };
90 mac.update(data);
91 let result = mac.finalize();
92 let mut output = [0u8; 32];
93 output.copy_from_slice(&result.into_bytes());
94 output
95}
96
97/// Compute a 16-byte truncated keyed MAC (for wire format).
98///
99/// Used by streaming protocol (`StreamHmacState`) where 16-byte MACs reduce
100/// overhead while still providing 128-bit authentication strength.
101///
102/// # Wire format dependency
103///
104/// The 16-byte truncation is part of the on-wire stream block format. **Do not**
105/// widen this to 32 bytes without coordinating a protocol version bump on both
106/// server and client — the receiver expects exactly 16 bytes per block trailer.
107///
108/// # Cryptographic properties
109///
110/// 128-bit MAC tags are the standard floor for authentication (GCM, Poly1305,
111/// SIV, CMAC all operate at 128 bits). Both Blake3 and HMAC-SHA256 are PRFs;
112/// truncating to any prefix preserves PRF security. Online forgery probability
113/// per attempt is 2^-128. The 2^64 collision bound does NOT threaten
114/// authentication; it would only matter if you relied on collision-resistance.
115///
116/// First-N-bytes truncation is the standard safe pattern (NIST SP 800-107,
117/// FIPS 198-1). The myth that you need middle/folded truncation came from
118/// ad-hoc constructions on MD5/SHA-1 and does not apply here.
119///
120/// # Arguments
121///
122/// * `key` - 32-byte MAC key
123/// * `data` - Data to authenticate
124///
125/// # Returns
126///
127/// 16-byte truncated MAC tag (first 16 bytes of full output).
128pub fn keyed_mac_truncated(key: &[u8; 32], data: &[u8]) -> [u8; 16] {
129 let full = keyed_mac(key, data);
130 let mut output = [0u8; 16];
131 output.copy_from_slice(&full[..16]);
132 output
133}
134
135/// Multi-part variant of [`keyed_mac_truncated`] — authenticates the
136/// concatenation of `parts` **without allocating a joined buffer**.
137///
138/// `keyed_mac_truncated_parts(k, &[a, b])` is byte-for-byte identical to
139/// `keyed_mac_truncated(k, &[a, b].concat())` (both Blake3's keyed hasher and
140/// HMAC are defined over the streamed input), so this is a zero-copy drop-in on
141/// the wire — used by the stream verifier to MAC `prev_mac ‖ block` over a
142/// borrowed payload slice instead of copying the block into a scratch `Vec`.
143#[cfg(not(feature = "fips"))]
144pub fn keyed_mac_truncated_parts(key: &[u8; 32], parts: &[&[u8]]) -> [u8; 16] {
145 let mut hasher = blake3::Hasher::new_keyed(key);
146 for p in parts {
147 hasher.update(p);
148 }
149 let full = hasher.finalize();
150 let mut output = [0u8; 16];
151 output.copy_from_slice(&full.as_bytes()[..16]);
152 output
153}
154
155#[cfg(feature = "fips")]
156pub fn keyed_mac_truncated_parts(key: &[u8; 32], parts: &[&[u8]]) -> [u8; 16] {
157 use hmac::{Hmac, Mac};
158 use sha2::Sha256;
159
160 let mut mac = match Hmac::<Sha256>::new_from_slice(key) {
161 Ok(m) => m,
162 Err(_) => unreachable!("HMAC-SHA256 accepts any key size"),
163 };
164 for p in parts {
165 mac.update(p);
166 }
167 let result = mac.finalize();
168 let mut output = [0u8; 16];
169 output.copy_from_slice(&result.into_bytes()[..16]);
170 output
171}
172
173// ============================================================================
174// Tests
175// ============================================================================
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 #[test]
182 fn test_keyed_mac_truncated_parts_equals_concat() {
183 // The multi-part MAC must be byte-identical to MAC-of-concatenation, so
184 // the zero-copy stream verifier produces the same wire MAC as before.
185 let key = [0x5au8; 32];
186 let prev = [0x11u8; 16];
187 let block = b"a stream block payload of arbitrary length".as_slice();
188
189 let mut joined = Vec::new();
190 joined.extend_from_slice(&prev);
191 joined.extend_from_slice(block);
192
193 assert_eq!(
194 keyed_mac_truncated_parts(&key, &[&prev, block]),
195 keyed_mac_truncated(&key, &joined),
196 );
197 // Empty-parts and single-part degenerate cases.
198 assert_eq!(
199 keyed_mac_truncated_parts(&key, &[block]),
200 keyed_mac_truncated(&key, block),
201 );
202 }
203
204 #[test]
205 fn test_derive_key_deterministic() {
206 let ikm = [0x42u8; 32];
207 let key1 = derive_key("test context", &ikm);
208 let key2 = derive_key("test context", &ikm);
209 assert_eq!(key1, key2);
210 }
211
212 #[test]
213 fn test_derive_key_different_contexts() {
214 let ikm = [0x42u8; 32];
215 let key1 = derive_key("context a", &ikm);
216 let key2 = derive_key("context b", &ikm);
217 assert_ne!(key1, key2);
218 }
219
220 #[test]
221 fn test_derive_key_different_ikm() {
222 let key1 = derive_key("test context", &[0x01u8; 32]);
223 let key2 = derive_key("test context", &[0x02u8; 32]);
224 assert_ne!(key1, key2);
225 }
226
227 #[test]
228 fn test_keyed_mac_deterministic() {
229 let key = [0x42u8; 32];
230 let data = b"test data";
231 let mac1 = keyed_mac(&key, data);
232 let mac2 = keyed_mac(&key, data);
233 assert_eq!(mac1, mac2);
234 }
235
236 #[test]
237 fn test_keyed_mac_different_keys() {
238 let data = b"test data";
239 let mac1 = keyed_mac(&[0x01u8; 32], data);
240 let mac2 = keyed_mac(&[0x02u8; 32], data);
241 assert_ne!(mac1, mac2);
242 }
243
244 #[test]
245 fn test_keyed_mac_different_data() {
246 let key = [0x42u8; 32];
247 let mac1 = keyed_mac(&key, b"data a");
248 let mac2 = keyed_mac(&key, b"data b");
249 assert_ne!(mac1, mac2);
250 }
251
252 #[test]
253 fn test_keyed_mac_truncated() {
254 let key = [0x42u8; 32];
255 let data = b"test data";
256 let full = keyed_mac(&key, data);
257 let truncated = keyed_mac_truncated(&key, data);
258 assert_eq!(&full[..16], &truncated[..]);
259 }
260}