| 1 | use hmac::{Hmac, KeyInit, Mac}; |
| 2 | use sha2::Sha256; |
| 3 | use subtle::ConstantTimeEq; |
| 4 | |
| 5 | type HmacSha256 = Hmac<Sha256>; |
| 6 | |
| 7 | pub const MAC_LEN: usize = 32; |
| 8 | |
| 9 | pub fn mac(key: &[u8; 32], parts: &[&[u8]]) -> Vec<u8> { |
| 10 | let mut mac = |
| 11 | <HmacSha256 as KeyInit>::new_from_slice(key).expect("HMAC accepts any key length"); |
| 12 | for part in parts { |
| 13 | mac.update(part); |
| 14 | } |
| 15 | mac.finalize().into_bytes().to_vec() |
| 16 | } |
| 17 | |
| 18 | pub fn verify(key: &[u8; 32], parts: &[&[u8]], tag: &[u8]) -> bool { |
| 19 | tag.len() == MAC_LEN && bool::from(mac(key, parts).as_slice().ct_eq(tag)) |
| 20 | } |
| 21 | |
| 22 | pub fn parse_expiry(text: &str) -> Option<i64> { |
| 23 | let value: i64 = text.parse().ok()?; |
| 24 | (value.to_string() == text).then_some(value) |
| 25 | } |