Skip to main content

cas_lib/message/
hmac.rs

1
2use crate::error::{CasError, CasResult};
3use super::cas_hmac::CASHMAC;
4use hmac::{Hmac, Mac};
5use sha2::Sha256;
6
7type HmacSha256 = Hmac<Sha256>;
8pub struct HMAC;
9
10impl CASHMAC for HMAC {
11    /// Signs a message using HMAC with SHA-256.
12    /// Returns the signature as a vector of bytes.
13    fn sign(key: Vec<u8>, message: Vec<u8>) -> CasResult<Vec<u8>> {
14        let mut mac = HmacSha256::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
15        mac.update(&message);
16        Ok(mac.finalize().into_bytes().to_vec())
17    }
18
19
20
21    /// Verifies a signature using HMAC with SHA-256.
22    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if it is not, and
23    /// an error if the key could not be used.
24    fn verify(key: Vec<u8>, message: Vec<u8>, signature: Vec<u8>) -> CasResult<bool> {
25        let mut mac = HmacSha256::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
26        mac.update(&message);
27        Ok(mac.verify_slice(&signature).is_ok())
28    }
29
30
31}