Skip to main content

script/dom/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;
9
10use crate::dom::bindings::codegen::Bindings::CryptoKeyBinding::{KeyType, KeyUsage};
11use crate::dom::bindings::codegen::Bindings::SubtleCryptoBinding::KeyFormat;
12use crate::dom::bindings::error::Error;
13use crate::dom::bindings::root::DomRoot;
14use crate::dom::cryptokey::{CryptoKey, Handle, KeyUsageVecHelper};
15use crate::dom::globalscope::GlobalScope;
16use crate::dom::subtlecrypto::{
17    CryptoAlgorithm, KeyAlgorithm, KeyAlgorithmAndDerivatives, NormalizedAlgorithm, Pbkdf2Params,
18};
19
20/// <https://w3c.github.io/webcrypto/#pbkdf2-operations-derive-bits>
21pub(crate) fn derive_bits(
22    normalized_algorithm: &Pbkdf2Params,
23    key: &CryptoKey,
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(
87    cx: &mut JSContext,
88    global: &GlobalScope,
89    format: KeyFormat,
90    key_data: &[u8],
91    extractable: bool,
92    usages: Vec<KeyUsage>,
93) -> Result<DomRoot<CryptoKey>, 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    if usages
101        .iter()
102        .any(|usage| !matches!(usage, KeyUsage::DeriveKey | KeyUsage::DeriveBits)) ||
103        usages.is_empty()
104    {
105        return Err(Error::Syntax(Some(
106            "Usages is empty or contains a value that is not a 'deriveKey' or 'deriveBits'".into(),
107        )));
108    }
109
110    // Step 3. If extractable is not false, then throw a SyntaxError.
111    if extractable {
112        return Err(Error::Syntax(Some("Extractable is not false".into())));
113    }
114
115    // Step 4. Let key be a new CryptoKey representing keyData.
116    // Step 5. Set the [[type]] internal slot of key to "secret".
117    // Step 6. Let algorithm be a new KeyAlgorithm object.
118    // Step 7. Set the name attribute of algorithm to "PBKDF2".
119    // Step 8. Set the [[algorithm]] internal slot of key to algorithm.
120    let algorithm = KeyAlgorithm {
121        name: CryptoAlgorithm::Pbkdf2,
122    };
123    let key = CryptoKey::new(
124        cx,
125        global,
126        KeyType::Secret,
127        extractable,
128        KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
129        usages.normalized_value(),
130        Handle::Pbkdf2(key_data.to_vec().into()),
131    );
132
133    // Step 9. Return key.
134    Ok(key)
135}
136
137/// <https://w3c.github.io/webcrypto/#pbkdf2-operations-get-key-length>
138pub(crate) fn get_key_length() -> Result<Option<u32>, Error> {
139    // Step 1. Return null.
140    Ok(None)
141}