Skip to main content

crypto_dispatch/
mac.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#[cfg(feature = "hmac")]
6use crate::traits::MacAlgorithmAdapter;
7use crate::traits::MacParams;
8use crate::AlgorithmError;
9use crypto_core::MacAlgorithm;
10
11/// Computes a MAC tag using the selected MAC algorithm.
12pub fn mac_authenticate(
13    alg: MacAlgorithm,
14    params: &MacParams<'_>,
15    message: &[u8],
16) -> Result<Vec<u8>, AlgorithmError> {
17    #[cfg(not(feature = "hmac"))]
18    let _ = (params, message);
19
20    match alg {
21        MacAlgorithm::HmacSha256 => {
22            #[cfg(feature = "hmac")]
23            {
24                crate::algorithms::hmac::HmacSha256Algo::authenticate(params, message)
25            }
26            #[cfg(not(feature = "hmac"))]
27            {
28                Err(AlgorithmError::UnsupportedMacAlgorithm(alg))
29            }
30        }
31        MacAlgorithm::HmacSha512 => {
32            #[cfg(feature = "hmac")]
33            {
34                crate::algorithms::hmac::HmacSha512Algo::authenticate(params, message)
35            }
36            #[cfg(not(feature = "hmac"))]
37            {
38                Err(AlgorithmError::UnsupportedMacAlgorithm(alg))
39            }
40        }
41    }
42}
43
44/// Verifies a MAC tag using the selected MAC algorithm.
45pub fn mac_verify(
46    alg: MacAlgorithm,
47    params: &MacParams<'_>,
48    message: &[u8],
49    tag: &[u8],
50) -> Result<(), AlgorithmError> {
51    #[cfg(not(feature = "hmac"))]
52    let _ = (params, message, tag);
53
54    match alg {
55        MacAlgorithm::HmacSha256 => {
56            #[cfg(feature = "hmac")]
57            {
58                crate::algorithms::hmac::HmacSha256Algo::verify(params, message, tag)
59            }
60            #[cfg(not(feature = "hmac"))]
61            {
62                Err(AlgorithmError::UnsupportedMacAlgorithm(alg))
63            }
64        }
65        MacAlgorithm::HmacSha512 => {
66            #[cfg(feature = "hmac")]
67            {
68                crate::algorithms::hmac::HmacSha512Algo::verify(params, message, tag)
69            }
70            #[cfg(not(feature = "hmac"))]
71            {
72                Err(AlgorithmError::UnsupportedMacAlgorithm(alg))
73            }
74        }
75    }
76}