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