use hmac::{Hmac, Mac};
use sha2::Sha256;
type HmacSha256 = Hmac<Sha256>;
pub fn hmac_sign(key: &[u8], message: &[u8]) -> [u8; 32] {
#[allow(clippy::expect_used)]
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
mac.update(message);
let result = mac.finalize();
let mut tag = [0u8; 32];
tag.copy_from_slice(&result.into_bytes());
tag
}
pub fn hmac_verify(key: &[u8], message: &[u8], tag: &[u8; 32]) -> bool {
#[allow(clippy::expect_used)]
let mut mac = HmacSha256::new_from_slice(key).expect("HMAC accepts any key length");
mac.update(message);
mac.verify_slice(tag).is_ok()
}
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
use subtle::ConstantTimeEq;
if a.len() != b.len() {
return false;
}
a.ct_eq(b).into()
}
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic
)]
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sign_and_verify() {
let tag = hmac_sign(b"key", b"hello");
assert!(hmac_verify(b"key", b"hello", &tag));
}
#[test]
fn wrong_key_fails() {
let tag = hmac_sign(b"key", b"hello");
assert!(!hmac_verify(b"wrong", b"hello", &tag));
}
#[test]
fn wrong_message_fails() {
let tag = hmac_sign(b"key", b"hello");
assert!(!hmac_verify(b"key", b"world", &tag));
}
#[test]
fn constant_time_eq_works() {
assert!(constant_time_eq(b"abc", b"abc"));
assert!(!constant_time_eq(b"abc", b"abd"));
assert!(!constant_time_eq(b"abc", b"ab"));
assert!(!constant_time_eq(b"ab", b"abc"));
assert!(constant_time_eq(b"", b""));
assert!(!constant_time_eq(b"", b"a"));
}
#[test]
fn hmac_verify_rejects_wrong_length_and_zero_tags() {
let tag = hmac_sign(b"key", b"hello");
assert!(!hmac_verify(b"key", b"hello", &[0u8; 32]));
assert!(!hmac_verify(b"key", b"hello", &[0xFF; 32]));
let mut flipped = tag;
for b in flipped.iter_mut() {
*b ^= 0xFF;
}
assert!(!hmac_verify(b"key", b"hello", &flipped));
assert!(hmac_verify(b"key", b"hello", &tag));
}
#[test]
fn deterministic() {
let tag1 = hmac_sign(b"k", b"m");
let tag2 = hmac_sign(b"k", b"m");
assert_eq!(tag1, tag2);
}
}