61 lines
1.7 KiB
Rust
61 lines
1.7 KiB
Rust
//! Hash functions from `aws_lc_rs::digest`: SHA-2 and SHA-3.
|
|
//!
|
|
//! BLAKE2b-512 is not in AWS-LC and returns
|
|
//! [`CryptoError::FeatureNotCompiled`].
|
|
|
|
use aws_lc_rs::digest::{self, SHA256, SHA384, SHA3_256, SHA3_512, SHA512};
|
|
|
|
use ccc_crypto_core::{algorithms::HashAlgorithm, error::CryptoError};
|
|
|
|
/// Compute the digest of `data`.
|
|
pub fn hash(algo: HashAlgorithm, data: &[u8]) -> Result<Vec<u8>, CryptoError> {
|
|
let alg = match algo {
|
|
HashAlgorithm::Sha256 => &SHA256,
|
|
HashAlgorithm::Sha384 => &SHA384,
|
|
HashAlgorithm::Sha512 => &SHA512,
|
|
HashAlgorithm::Sha3_256 => &SHA3_256,
|
|
HashAlgorithm::Sha3_512 => &SHA3_512,
|
|
HashAlgorithm::Blake2b512 => {
|
|
return Err(CryptoError::FeatureNotCompiled(format!(
|
|
"{} is not offered by the awslc provider",
|
|
algo.name()
|
|
)))
|
|
}
|
|
};
|
|
Ok(digest::digest(alg, data).as_ref().to_vec())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn digest_lengths_match_registry() {
|
|
for algo in [
|
|
HashAlgorithm::Sha256,
|
|
HashAlgorithm::Sha384,
|
|
HashAlgorithm::Sha512,
|
|
HashAlgorithm::Sha3_256,
|
|
HashAlgorithm::Sha3_512,
|
|
] {
|
|
assert_eq!(hash(algo, b"abc").unwrap().len(), algo.digest_len());
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn sha256_abc() {
|
|
assert_eq!(
|
|
hex::encode(hash(HashAlgorithm::Sha256, b"abc").unwrap()),
|
|
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn blake2b_is_not_compiled() {
|
|
assert!(matches!(
|
|
hash(HashAlgorithm::Blake2b512, b"abc"),
|
|
Err(CryptoError::FeatureNotCompiled(_))
|
|
));
|
|
}
|
|
}
|