Skip to main content

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