Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_crypto/src/mac.rs

10.6 KiB, 17 runs

created by r1870400018:75652, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! HMAC-SHA256 (RFC 2104), HKDF-SHA256 (RFC 5869) and PBKDF2-HMAC-SHA256 (RFC 8018), in pure
2//! Rust.
3//!
4//! All rest on [`oxedyne_fe2o3_hash::sha256`], so nothing here asks for a C toolchain or the
5//! operating system and the module compiles to wasm32 with the rest of the pure-Rust subset.
6//! That is the reason it exists beside `fe2o3_net::hmac`, which wraps `ring` and is native only:
7//! a key derived in a browser by WebCrypto's HKDF and the same key derived by a native process
8//! must be the same bytes, and only a derivation both sides can run gives that.
9//!
10//! The tag comparison in [`verify_hmac_sha256`] runs over every byte whatever it finds, so the
11//! time it takes says nothing about how much of a forged tag was right.
12//!
13//! [Written with AI entirely](https://need2know.ai/entirely-ai/code)\
14//! Anthropic Claude
15
16use oxedyne_fe2o3_core::prelude::*;
17use oxedyne_fe2o3_hash::sha256::{
18 self,
19 Sha256,
20};
21
22/// The SHA-256 block, which is the width a key is padded or hashed to.
23const BLOCK: usize = 64;
24
25/// The width of every tag and of every pseudorandom key here.
26pub const HMAC_SHA256_LEN: usize = sha256::DIGEST_LEN;
27
28/// The most HKDF-SHA256 can expand to: 255 blocks of output (RFC 5869 §2.3).
29pub const HKDF_SHA256_MAX: usize = 255 * HMAC_SHA256_LEN;
30
31/// HMAC-SHA256 of `msg` under `key`. A key of any length is legal: one longer than a block is
32/// hashed first, as RFC 2104 says.
33pub fn hmac_sha256(key: &[u8], msg: &[u8]) -> [u8; HMAC_SHA256_LEN] {
34 hmac_sha256_parts(key, &[msg])
35}
36
37/// HMAC-SHA256 over the concatenation of `parts`, without making the concatenation.
38pub fn hmac_sha256_parts(key: &[u8], parts: &[&[u8]]) -> [u8; HMAC_SHA256_LEN] {
39 Keyed::new(key).tag(parts)
40}
41
42/// The inner and outer hashers with the padded key already absorbed, so that a caller tagging
43/// many messages under one key, as PBKDF2 does, hashes the key's two blocks once.
44struct Keyed {
45 inner: Sha256,
46 outer: Sha256,
47}
48
49impl Keyed {
50
51 fn new(key: &[u8]) -> Self {
52 let mut k = [0u8; BLOCK];
53 if key.len() > BLOCK {
54 let d = sha256::digest(key);
55 k[..d.len()].copy_from_slice(&d);
56 } else {
57 k[..key.len()].copy_from_slice(key);
58 }
59 let mut ipad = [0x36u8; BLOCK];
60 let mut opad = [0x5cu8; BLOCK];
61 for i in 0..BLOCK {
62 ipad[i] ^= k[i];
63 opad[i] ^= k[i];
64 }
65 let mut inner = Sha256::new();
66 inner.update(&ipad);
67 let mut outer = Sha256::new();
68 outer.update(&opad);
69 // The padded key is the key: it is not left lying in a stack slot for the next caller.
70 for b in k.iter_mut().chain(ipad.iter_mut()).chain(opad.iter_mut()) {
71 *b = 0;
72 }
73 Self { inner, outer }
74 }
75
76 fn tag(&self, parts: &[&[u8]]) -> [u8; HMAC_SHA256_LEN] {
77 let mut inner = self.inner.clone();
78 for p in parts {
79 inner.update(p);
80 }
81 let ih = inner.finish();
82 let mut outer = self.outer.clone();
83 outer.update(&ih);
84 outer.finish()
85 }
86}
87
88/// Whether `tag` is the HMAC-SHA256 of `msg` under `key`, compared in constant time.
89pub fn verify_hmac_sha256(key: &[u8], msg: &[u8], tag: &[u8]) -> bool {
90 let want = hmac_sha256(key, msg);
91 if tag.len() != want.len() {
92 return false;
93 }
94 let mut diff = 0u8;
95 for i in 0..want.len() {
96 diff |= want[i] ^ tag[i];
97 }
98 diff == 0
99}
100
101/// HKDF-Extract: the pseudorandom key from input keying material and a salt. An empty salt is
102/// a block of zeros, as RFC 5869 §2.2 says, which HMAC's padding makes the same thing.
103pub fn hkdf_sha256_extract(salt: &[u8], ikm: &[u8]) -> [u8; HMAC_SHA256_LEN] {
104 hmac_sha256(salt, ikm)
105}
106
107/// HKDF-Expand: `out.len()` bytes of output keying material from a pseudorandom key and an
108/// `info` string. Refuses more than [`HKDF_SHA256_MAX`] bytes, which the counter cannot name.
109pub fn hkdf_sha256_expand(prk: &[u8], info: &[u8], out: &mut [u8]) -> Outcome<()> {
110 if out.len() > HKDF_SHA256_MAX {
111 return Err(err!(
112 "HKDF-SHA256 was asked for {} bytes, more than the {} its one-byte counter can name.",
113 out.len(), HKDF_SHA256_MAX;
114 Invalid, Input, TooBig));
115 }
116 let mut prev: [u8; HMAC_SHA256_LEN] = [0u8; HMAC_SHA256_LEN];
117 let mut have_prev = false;
118 let mut at = 0usize;
119 let mut counter = 1u8;
120 while at < out.len() {
121 let t = if have_prev {
122 hmac_sha256_parts(prk, &[&prev[..], info, &[counter]])
123 } else {
124 hmac_sha256_parts(prk, &[info, &[counter]])
125 };
126 let take = std::cmp::min(HMAC_SHA256_LEN, out.len() - at);
127 out[at..at + take].copy_from_slice(&t[..take]);
128 at += take;
129 prev = t;
130 have_prev = true;
131 counter = counter.wrapping_add(1);
132 }
133 for b in prev.iter_mut() {
134 *b = 0;
135 }
136 Ok(())
137}
138
139/// HKDF-SHA256, extract then expand, into `out`. This is what WebCrypto's
140/// `deriveKey({ name: 'HKDF', hash: 'SHA-256', salt, info }, ..)` computes for a key of
141/// `out.len()` bytes.
142pub fn hkdf_sha256(ikm: &[u8], salt: &[u8], info: &[u8], out: &mut [u8]) -> Outcome<()> {
143 let mut prk = hkdf_sha256_extract(salt, ikm);
144 let result = hkdf_sha256_expand(&prk, info, out);
145 for b in prk.iter_mut() {
146 *b = 0;
147 }
148 result
149}
150
151/// PBKDF2-HMAC-SHA256 (RFC 8018 §5.2): `out.len()` bytes derived from `pass` and `salt` over
152/// `rounds` iterations. This is what WebCrypto's
153/// `deriveBits({ name: 'PBKDF2', hash: 'SHA-256', salt, iterations }, ..)` computes for
154/// `8 * out.len()` bits. Refuses no rounds at all, and more output than the block counter can
155/// name.
156pub fn pbkdf2_hmac_sha256(pass: &[u8], salt: &[u8], rounds: u32, out: &mut [u8]) -> Outcome<()> {
157 if rounds == 0 {
158 return Err(err!(
159 "PBKDF2-HMAC-SHA256 was asked for zero rounds; at least one is required.";
160 Invalid, Input));
161 }
162 res!(pbkdf2_blocks(out.len()));
163 let prf = Keyed::new(pass);
164 for (i, chunk) in out.chunks_mut(HMAC_SHA256_LEN).enumerate() {
165 // F(P, S, c, i) = U1 ^ U2 ^ ... ^ Uc, with U1 = PRF(P, S || INT(i)), i from 1.
166 let index = (i as u32 + 1).to_be_bytes();
167 let mut u = prf.tag(&[salt, &index]);
168 let mut t = u;
169 for _ in 1..rounds {
170 u = prf.tag(&[&u]);
171 for j in 0..HMAC_SHA256_LEN {
172 t[j] ^= u[j];
173 }
174 }
175 chunk.copy_from_slice(&t[..chunk.len()]);
176 for b in u.iter_mut().chain(t.iter_mut()) {
177 *b = 0;
178 }
179 }
180 Ok(())
181}
182
183/// How many blocks PBKDF2 derives `len` bytes in, refusing more than its 32-bit block counter
184/// can name (RFC 8018 §5.2 step 1). Apart, so the refusal is tested without such a buffer.
185fn pbkdf2_blocks(len: usize) -> Outcome<usize> {
186 let blocks = len.div_ceil(HMAC_SHA256_LEN);
187 if blocks as u64 > u32::MAX as u64 {
188 return Err(err!(
189 "PBKDF2-HMAC-SHA256 was asked for {} bytes, more than its 32-bit block counter can \
190 name.", len;
191 Invalid, Input, TooBig));
192 }
193 Ok(blocks)
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199
200 fn unhex(s: &str) -> Vec<u8> {
201 let b = s.as_bytes();
202 let mut out = Vec::with_capacity(b.len() / 2);
203 let mut i = 0;
204 while i + 1 < b.len() {
205 let hi = (b[i] as char).to_digit(16).unwrap_or(0) as u8;
206 let lo = (b[i + 1] as char).to_digit(16).unwrap_or(0) as u8;
207 out.push((hi << 4) | lo);
208 i += 2;
209 }
210 out
211 }
212
213 // RFC 4231 test cases 1, 2, 6 (a key longer than a block) and 7.
214 // The largest output the counter can name, and one byte more.
215 #[test]
216 fn test_pbkdf2_blocks_refuses_past_the_counter() -> Outcome<()> {
217 let max = u32::MAX as usize * HMAC_SHA256_LEN;
218 req!(res!(pbkdf2_blocks(0)), 0);
219 req!(res!(pbkdf2_blocks(33)), 2);
220 req!(res!(pbkdf2_blocks(max)), u32::MAX as usize);
221 req!(pbkdf2_blocks(max + 1).is_err(), true);
222 Ok(())
223 }
224
225 #[test]
226 fn test_hmac_sha256_rfc4231() -> Outcome<()> {
227 let cases: [(&str, &[u8], &str); 4] = [
228 ("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b", b"Hi There",
229 "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7"),
230 ("4a656665", b"what do ya want for nothing?",
231 "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843"),
232 (&"aa".repeat(131), b"Test Using Larger Than Block-Size Key - Hash Key First",
233 "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54"),
234 (&"aa".repeat(131),
235 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.",
236 "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2"),
237 ];
238 for (k, m, t) in cases.iter() {
239 let tag = hmac_sha256(&unhex(k), m);
240 req!(tag.to_vec(), unhex(t));
241 req!(verify_hmac_sha256(&unhex(k), m, &unhex(t)), true);
242 let mut bad = unhex(t);
243 bad[31] ^= 1;
244 req!(verify_hmac_sha256(&unhex(k), m, &bad), false);
245 }
246 Ok(())
247 }
248
249 // RFC 5869 test cases 1, 2 and 3 (empty salt and info).
250 #[test]
251 fn test_hkdf_sha256_rfc5869() -> Outcome<()> {
252 let ikm1 = unhex("0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b");
253 let mut okm = [0u8; 42];
254 res!(hkdf_sha256(&ikm1, &unhex("000102030405060708090a0b0c"),
255 &unhex("f0f1f2f3f4f5f6f7f8f9"), &mut okm));
256 req!(okm.to_vec(), unhex("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"));
257
258 let ikm2: Vec<u8> = (0x00u8..=0x4f).collect();
259 let salt2: Vec<u8> = (0x60u8..=0xaf).collect();
260 let info2: Vec<u8> = (0xb0u8..=0xff).collect();
261 let mut okm2 = [0u8; 82];
262 res!(hkdf_sha256(&ikm2, &salt2, &info2, &mut okm2));
263 req!(okm2.to_vec(), unhex(concat!(
264 "b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c",
265 "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71",
266 "cc30c58179ec3e87c14c01d5c1f3434f1d87")));
267
268 let mut okm3 = [0u8; 42];
269 res!(hkdf_sha256(&ikm1, &[], &[], &mut okm3));
270 req!(okm3.to_vec(), unhex("8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"));
271 Ok(())
272 }
273
274 #[test]
275 fn test_hkdf_sha256_refuses_too_long() -> Outcome<()> {
276 let mut big = vec![0u8; HKDF_SHA256_MAX + 1];
277 req!(hkdf_sha256(b"k", b"s", b"i", &mut big).is_err(), true);
278 let mut max = vec![0u8; HKDF_SHA256_MAX];
279 res!(hkdf_sha256(b"k", b"s", b"i", &mut max));
280 Ok(())
281 }
282}