Skip to main content

script_webcrypto/subtlecrypto/
pbkdf2_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 std::num::NonZero;
6
7use aws_lc_rs::pbkdf2;
8use js::context::JSContext;
9use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{KeyType, KeyUsage};
10use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::KeyFormat;
11use script_bindings::error::Error;
12use script_bindings::root::DomRoot;
13
14use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
15use crate::subtlecrypto::{
16    CryptoAlgorithm, KeyAlgorithm, KeyAlgorithmAndDerivatives, NormalizedAlgorithm, Pbkdf2Params,
17};
18use crate::traits::Equivalence;
19
20/// <https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits>
21pub(crate) fn derive_bits<D: Equivalence>(
22    normalized_algorithm: &Pbkdf2Params,
23    key: &CryptoKey<D>,
24    length: Option<u32>,
25) -> Result<Vec<u8>, Error> {
26    // Step 1. If length is null or is not a multiple of 8, then throw an OperationError.
27    let Some(length) = length else {
28        return Err(Error::Operation(Some("Length is null".into())));
29    };
30    if length % 8 != 0 {
31        return Err(Error::Operation(Some(
32            "Length is not a multiple of 8".into(),
33        )));
34    };
35
36    // Step 2. If the iterations member of normalizedAlgorithm is zero, then throw an OperationError.
37    let Ok(iterations) = NonZero::<u32>::try_from(normalized_algorithm.iterations) else {
38        return Err(Error::Operation(Some(
39            "Normalized algorithm's iterations is zero".into(),
40        )));
41    };
42
43    // Step 3. If length is zero, return an empty byte sequence.
44    if length == 0 {
45        return Ok(Vec::new());
46    }
47
48    // Step 4. Let prf be the MAC Generation function described in Section 4 of [FIPS-198-1] using
49    // the hash function described by the hash member of normalizedAlgorithm.
50    let prf = match normalized_algorithm.hash.name() {
51        CryptoAlgorithm::Sha1 => pbkdf2::PBKDF2_HMAC_SHA1,
52        CryptoAlgorithm::Sha256 => pbkdf2::PBKDF2_HMAC_SHA256,
53        CryptoAlgorithm::Sha384 => pbkdf2::PBKDF2_HMAC_SHA384,
54        CryptoAlgorithm::Sha512 => pbkdf2::PBKDF2_HMAC_SHA512,
55        _ => {
56            return Err(Error::NotSupported(Some(
57                "Normalized algorithm's hash name is not supported".into(),
58            )));
59        },
60    };
61
62    // Step 5. Let result be the result of performing the PBKDF2 operation defined in Section 5.2
63    // of [RFC8018] using prf as the pseudo-random function, PRF, the password represented by the
64    // [[handle]] internal slot of key as the password, P, the salt attribute of
65    // normalizedAlgorithm as the salt, S, the value of the iterations attribute of
66    // normalizedAlgorithm as the iteration count, c, and length divided by 8 as the intended key
67    // length, dkLen.
68    let mut result = vec![0; length as usize / 8];
69    pbkdf2::derive(
70        prf,
71        iterations,
72        &normalized_algorithm.salt,
73        key.handle().as_bytes(),
74        &mut result,
75    );
76
77    // Step 5. If the key derivation operation fails, then throw an OperationError.
78    // TODO: Investigate when key derivation can fail and how ring handles that case
79    // (pbkdf2::derive does not return a Result type)
80
81    // Step 6. Return result
82    Ok(result)
83}
84
85/// <https://w3c.github.io/webcrypto/#pbkdf2-operations-import-key>
86pub(crate) fn import_key<D: Equivalence>(
87    cx: &mut JSContext,
88    global: &D::GlobalScope,
89    format: KeyFormat,
90    key_data: &[u8],
91    extractable: bool,
92    usages: Vec<KeyUsage>,
93) -> Result<DomRoot<CryptoKey<D>>, Error> {
94    // Step 1. If format is not "raw", throw a NotSupportedError
95    if !matches!(format, KeyFormat::Raw | KeyFormat::Raw_secret) {
96        return Err(Error::NotSupported(Some("Format is not raw".into())));
97    }
98
99    // Step 2. If usages contains a value that is not "deriveKey" or "deriveBits", then throw a SyntaxError.
100    usages.ensure_only_contain_entries_from(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])?;
101
102    // Step 3. If extractable is not false, then throw a SyntaxError.
103    if extractable {
104        return Err(Error::Syntax(Some("Extractable is not false".into())));
105    }
106
107    // Step 4. Let key be a new CryptoKey representing keyData.
108    // Step 5. Set the [[type]] internal slot of key to "secret".
109    // Step 6. Let algorithm be a new KeyAlgorithm object.
110    // Step 7. Set the name attribute of algorithm to "PBKDF2".
111    // Step 8. Set the [[algorithm]] internal slot of key to algorithm.
112    let algorithm = KeyAlgorithm {
113        name: CryptoAlgorithm::Pbkdf2,
114    };
115    let key = CryptoKey::new(
116        cx,
117        global,
118        KeyType::Secret,
119        extractable,
120        KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
121        usages.normalized_value(),
122        Handle::Pbkdf2(key_data.to_vec().into()),
123    );
124
125    // Step 9. Return key.
126    Ok(key)
127}
128
129/// <https://w3c.github.io/webcrypto/#pbkdf2-operations-get-key-length>
130pub(crate) fn get_key_length() -> Result<Option<u32>, Error> {
131    // Step 1. Return null.
132    Ok(None)
133}