common_access_token/
utils.rs

1//! Utility functions for Common Access Token
2
3use crate::error::Error;
4use hmac::{Hmac, Mac};
5use sha2::Sha256;
6
7/// Type alias for HMAC-SHA256
8type HmacSha256 = Hmac<Sha256>;
9
10/// Compute HMAC-SHA256 signature
11pub fn compute_hmac_sha256(key: &[u8], data: &[u8]) -> Vec<u8> {
12    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
13    mac.update(data);
14    mac.finalize().into_bytes().to_vec()
15}
16
17/// Verify HMAC-SHA256 signature
18pub fn verify_hmac_sha256(key: &[u8], data: &[u8], signature: &[u8]) -> Result<(), Error> {
19    let mut mac = HmacSha256::new_from_slice(key).expect("HMAC can take key of any size");
20    mac.update(data);
21    mac.verify_slice(signature)
22        .map_err(|_| Error::SignatureVerification)
23}
24
25/// Get current timestamp in seconds since Unix epoch
26pub fn current_timestamp() -> u64 {
27    use std::time::{SystemTime, UNIX_EPOCH};
28    SystemTime::now()
29        .duration_since(UNIX_EPOCH)
30        .expect("Time went backwards")
31        .as_secs()
32}