script/dom/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, Sha3_256, Sha3_384, Sha3_512};
6
7use crate::dom::bindings::error::Error;
8use crate::dom::subtlecrypto::{ALG_SHA3_256, ALG_SHA3_384, ALG_SHA3_512, SubtleAlgorithm};
9
10/// <https://wicg.github.io/webcrypto-modern-algos/#sha3-operations-digest>
11pub(crate) fn digest(
12 normalized_algorithm: &SubtleAlgorithm,
13 message: &[u8],
14) -> Result<Vec<u8>, Error> {
15 // Step 1.
16 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-256":
17 // Let result be the result of performing the SHA3-256 hash function defined in Section 6.1
18 // of [FIPS-202] using message as the input message, M.
19 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-384":
20 // Let result be the result of performing the SHA3-384 hash function defined in Section 6.1
21 // of [FIPS-202] using message as the input message, M.
22 // If the name member of normalizedAlgorithm is a case-sensitive string match for "SHA3-512":
23 // Let result be the result of performing the SHA3-512 hash function defined in Section 6.1
24 // of [FIPS-202] using message as the input message, M.
25 // Step 2. If performing the operation results in an error, then throw an OperationError.
26 let result = match normalized_algorithm.name.as_str() {
27 ALG_SHA3_256 => Sha3_256::new_with_prefix(message).finalize().to_vec(),
28 ALG_SHA3_384 => Sha3_384::new_with_prefix(message).finalize().to_vec(),
29 ALG_SHA3_512 => Sha3_512::new_with_prefix(message).finalize().to_vec(),
30 _ => return Err(Error::NotSupported(None)),
31 };
32
33 // Step 3. Return result.
34 Ok(result)
35}