Skip to main content

crypto_dispatch/
hash.rs

1// SPDX-FileCopyrightText: Copyright © 2026 ReallyMe LLC. All rights reserved
2//
3// SPDX-License-Identifier: Apache-2.0
4
5#[cfg(any(feature = "sha2", feature = "sha3"))]
6use crate::traits::HashDigestAlgorithm;
7use crate::AlgorithmError;
8use crypto_core::HashAlgorithm;
9
10/// Compute a digest using the selected hash algorithm.
11pub fn hash_digest(alg: HashAlgorithm, message: &[u8]) -> Result<Vec<u8>, AlgorithmError> {
12    #[cfg(not(any(feature = "sha2", feature = "sha3")))]
13    let _ = message;
14
15    match alg {
16        HashAlgorithm::Sha2_256 => {
17            #[cfg(feature = "sha2")]
18            {
19                crate::algorithms::sha2_256::Sha2_256Algo::digest(message)
20            }
21            #[cfg(not(feature = "sha2"))]
22            {
23                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
24            }
25        }
26        HashAlgorithm::Sha2_384 => {
27            #[cfg(feature = "sha2")]
28            {
29                crate::algorithms::sha2::Sha2_384Algo::digest(message)
30            }
31            #[cfg(not(feature = "sha2"))]
32            {
33                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
34            }
35        }
36        HashAlgorithm::Sha2_512 => {
37            #[cfg(feature = "sha2")]
38            {
39                crate::algorithms::sha2::Sha2_512Algo::digest(message)
40            }
41            #[cfg(not(feature = "sha2"))]
42            {
43                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
44            }
45        }
46        HashAlgorithm::Sha3_224 => {
47            #[cfg(feature = "sha3")]
48            {
49                crate::algorithms::sha3::Sha3_224Algo::digest(message)
50            }
51            #[cfg(not(feature = "sha3"))]
52            {
53                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
54            }
55        }
56        HashAlgorithm::Sha3_256 => {
57            #[cfg(feature = "sha3")]
58            {
59                crate::algorithms::sha3_256::Sha3_256Algo::digest(message)
60            }
61            #[cfg(not(feature = "sha3"))]
62            {
63                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
64            }
65        }
66        HashAlgorithm::Sha3_384 => {
67            #[cfg(feature = "sha3")]
68            {
69                crate::algorithms::sha3::Sha3_384Algo::digest(message)
70            }
71            #[cfg(not(feature = "sha3"))]
72            {
73                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
74            }
75        }
76        HashAlgorithm::Sha3_512 => {
77            #[cfg(feature = "sha3")]
78            {
79                crate::algorithms::sha3::Sha3_512Algo::digest(message)
80            }
81            #[cfg(not(feature = "sha3"))]
82            {
83                Err(AlgorithmError::UnsupportedHashAlgorithm(alg))
84            }
85        }
86    }
87}