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, Sha512};
6
7type HmacSha256 = Hmac<Sha256>;
8type HmacSha512 = Hmac<Sha512>;
9pub struct HMAC;
10pub struct HMACSha512;
11
12impl CASHMAC for HMAC {
13    /// Signs a message using HMAC with SHA-256.
14    /// Returns the signature as a vector of bytes.
15    fn sign(key: Vec<u8>, message: Vec<u8>) -> CasResult<Vec<u8>> {
16        let mut mac = HmacSha256::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
17        mac.update(&message);
18        Ok(mac.finalize().into_bytes().to_vec())
19    }
20
21
22
23    /// Verifies a signature using HMAC with SHA-256.
24    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if it is not, and
25    /// an error if the key could not be used.
26    fn verify(key: Vec<u8>, message: Vec<u8>, signature: Vec<u8>) -> CasResult<bool> {
27        let mut mac = HmacSha256::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
28        mac.update(&message);
29        Ok(mac.verify_slice(&signature).is_ok())
30    }
31
32
33}
34
35impl CASHMAC for HMACSha512 {
36    /// Signs a message using HMAC with SHA2-512.
37    /// Returns the signature as a vector of bytes.
38    fn sign(key: Vec<u8>, message: Vec<u8>) -> CasResult<Vec<u8>> {
39        let mut mac = HmacSha512::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
40        mac.update(&message);
41        Ok(mac.finalize().into_bytes().to_vec())
42    }
43
44    /// Verifies a signature using HMAC with SHA2-512.
45    /// Returns `Ok(true)` if the signature is valid, `Ok(false)` if it is not, and
46    /// an error if the key could not be used.
47    fn verify(key: Vec<u8>, message: Vec<u8>, signature: Vec<u8>) -> CasResult<bool> {
48        let mut mac = HmacSha512::new_from_slice(&key).map_err(|_| CasError::InvalidKey)?;
49        mac.update(&message);
50        Ok(mac.verify_slice(&signature).is_ok())
51    }
52}