script/dom/subtlecrypto/
sha_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 aws_lc_rs::digest;
6
7use crate::dom::bindings::error::Error;
8use crate::dom::subtlecrypto::{ALG_SHA1, ALG_SHA256, ALG_SHA384, ALG_SHA512, SubtleAlgorithm};
9
10/// <https://w3c.github.io/webcrypto/#sha-operations-digest>
11pub(crate) fn digest(
12    nomrmalized_algorithm: &SubtleAlgorithm,
13    message: &[u8],
14) -> Result<Vec<u8>, Error> {
15    // Step 1.
16    // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-1":
17    //     Let result be the result of performing the SHA-1 hash function defined in Section 6.1 of
18    //     [FIPS-180-4] using message as the input message, M.
19    // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-256":
20    //     Let result be the result of performing the SHA-256 hash function defined in Section 6.2
21    //     of [FIPS-180-4] using message as the input message, M.
22    // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-384":
23    //     Let result be the result of performing the SHA-384 hash function defined in Section 6.5
24    //     of [FIPS-180-4] using message as the input message, M.
25    // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-512":
26    //     Let result be the result of performing the SHA-512 hash function defined in Section 6.4
27    //     of [FIPS-180-4] using message as the input message, M.
28    // Step 2. If performing the operation results in an error, then throw an OperationError.
29    let result = match nomrmalized_algorithm.name.as_str() {
30        ALG_SHA1 => digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, message)
31            .as_ref()
32            .to_vec(),
33        ALG_SHA256 => digest::digest(&digest::SHA256, message).as_ref().to_vec(),
34        ALG_SHA384 => digest::digest(&digest::SHA384, message).as_ref().to_vec(),
35        ALG_SHA512 => digest::digest(&digest::SHA512, message).as_ref().to_vec(),
36        _ => {
37            return Err(Error::NotSupported);
38        },
39    };
40
41    // Step 3. Return result.
42    Ok(result)
43}