script/dom/webcrypto/subtlecrypto/sha3_operation.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use sha3::digest::Digest;
6use sha3::{Sha3_256, Sha3_384, Sha3_512};
7
8use crate::dom::bindings::error::Error;
9use crate::dom::subtlecrypto::{CryptoAlgorithm, SubtleAlgorithm};
10
11/// <https://wicg.github.io/webcrypto-modern-algos/#sha3-operations-digest>
12pub(crate) fn digest(
13 normalized_algorithm: &SubtleAlgorithm,
14 message: &[u8],
15) -> Result<Vec<u8>, Error> {
16 // Step 1.
17 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-256":
18 // Let result be the result of performing the SHA3-256 hash function defined in Section 6.1
19 // of [FIPS-202] using message as the input message, M.
20 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-384":
21 // Let result be the result of performing the SHA3-384 hash function defined in Section 6.1
22 // of [FIPS-202] using message as the input message, M.
23 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-512":
24 // Let result be the result of performing the SHA3-512 hash function defined in Section 6.1
25 // of [FIPS-202] using message as the input message, M.
26 // Step 2. If performing the operation results in an error, then throw an OperationError.
27 let result = match normalized_algorithm.name {
28 CryptoAlgorithm::Sha3_256 => Sha3_256::new_with_prefix(message).finalize().to_vec(),
29 CryptoAlgorithm::Sha3_384 => Sha3_384::new_with_prefix(message).finalize().to_vec(),
30 CryptoAlgorithm::Sha3_512 => Sha3_512::new_with_prefix(message).finalize().to_vec(),
31 _ => return Err(Error::NotSupported(None)),
32 };
33
34 // Step 3. Return result.
35 Ok(result)
36}