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