script/dom/webcrypto/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::{Algorithm, CryptoAlgorithm};
9
10/// <https://w3c.github.io/webcrypto/#sha-operations-digest>
11pub(crate) fn digest(nomrmalized_algorithm: &Algorithm, message: &[u8]) -> Result<Vec<u8>, Error> {
12 // Step 1.
13 // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-1":
14 // Let result be the result of performing the SHA-1 hash function defined in Section 6.1 of
15 // [FIPS-180-4] using message as the input message, M.
16 // If the name member of normalizedAlgorithm is a cases-sensitive string match for "SHA-256":
17 // Let result be the result of performing the SHA-256 hash function defined in Section 6.2
18 // of [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-384":
20 // Let result be the result of performing the SHA-384 hash function defined in Section 6.5
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-512":
23 // Let result be the result of performing the SHA-512 hash function defined in Section 6.4
24 // of [FIPS-180-4] 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 nomrmalized_algorithm.name {
27 CryptoAlgorithm::Sha1 => digest::digest(&digest::SHA1_FOR_LEGACY_USE_ONLY, message)
28 .as_ref()
29 .to_vec(),
30 CryptoAlgorithm::Sha256 => digest::digest(&digest::SHA256, message).as_ref().to_vec(),
31 CryptoAlgorithm::Sha384 => digest::digest(&digest::SHA384, message).as_ref().to_vec(),
32 CryptoAlgorithm::Sha512 => digest::digest(&digest::SHA512, message).as_ref().to_vec(),
33 _ => {
34 return Err(Error::NotSupported(Some("Algorithm not supported".into())));
35 },
36 };
37
38 // Step 3. Return result.
39 Ok(result)
40}