crypto_dispatch/algorithms/
hmac.rs1use crate::traits::{MacAlgorithmAdapter, MacParams};
6use crate::AlgorithmError;
7use crypto_core::MacAlgorithm;
8
9pub struct HmacSha256Algo;
11
12pub struct HmacSha512Algo;
14
15impl MacAlgorithmAdapter for HmacSha256Algo {
16 const ALG: MacAlgorithm = MacAlgorithm::HmacSha256;
17
18 fn authenticate(params: &MacParams<'_>, message: &[u8]) -> Result<Vec<u8>, AlgorithmError> {
19 authenticate(Self::ALG, params, message)
20 }
21
22 fn verify(params: &MacParams<'_>, message: &[u8], tag: &[u8]) -> Result<(), AlgorithmError> {
23 verify(Self::ALG, params, message, tag)
24 }
25}
26
27impl MacAlgorithmAdapter for HmacSha512Algo {
28 const ALG: MacAlgorithm = MacAlgorithm::HmacSha512;
29
30 fn authenticate(params: &MacParams<'_>, message: &[u8]) -> Result<Vec<u8>, AlgorithmError> {
31 authenticate(Self::ALG, params, message)
32 }
33
34 fn verify(params: &MacParams<'_>, message: &[u8], tag: &[u8]) -> Result<(), AlgorithmError> {
35 verify(Self::ALG, params, message, tag)
36 }
37}
38
39fn authenticate(
40 algorithm: MacAlgorithm,
41 params: &MacParams<'_>,
42 message: &[u8],
43) -> Result<Vec<u8>, AlgorithmError> {
44 #[cfg(any(feature = "native", all(feature = "wasm", target_arch = "wasm32")))]
45 {
46 let key = crypto_hmac::HmacKey::from_slice(params.key)?;
47 let tag = crypto_hmac::authenticate(algorithm, &key, message)?;
48 Ok(tag.into_vec())
49 }
50
51 #[cfg(not(any(feature = "native", all(feature = "wasm", target_arch = "wasm32"))))]
52 {
53 let _ = (params, message);
54 Err(AlgorithmError::UnsupportedMacAlgorithm(algorithm))
55 }
56}
57
58fn verify(
59 algorithm: MacAlgorithm,
60 params: &MacParams<'_>,
61 message: &[u8],
62 tag: &[u8],
63) -> Result<(), AlgorithmError> {
64 #[cfg(any(feature = "native", all(feature = "wasm", target_arch = "wasm32")))]
65 {
66 let key = crypto_hmac::HmacKey::from_slice(params.key)?;
67 crypto_hmac::verify(algorithm, &key, message, tag)?;
68 Ok(())
69 }
70
71 #[cfg(not(any(feature = "native", all(feature = "wasm", target_arch = "wasm32"))))]
72 {
73 let _ = (params, message, tag);
74 Err(AlgorithmError::UnsupportedMacAlgorithm(algorithm))
75 }
76}