script_webcrypto/subtlecrypto/
pbkdf2_operation.rs1use 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
20pub(crate) fn derive_bits<D: Equivalence>(
22 normalized_algorithm: &Pbkdf2Params,
23 key: &CryptoKey<D>,
24 length: Option<u32>,
25) -> Result<Vec<u8>, Error> {
26 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 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 if length == 0 {
45 return Ok(Vec::new());
46 }
47
48 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 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 Ok(result)
83}
84
85pub(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 if !matches!(format, KeyFormat::Raw | KeyFormat::Raw_secret) {
96 return Err(Error::NotSupported(Some("Format is not raw".into())));
97 }
98
99 usages.ensure_only_contain_entries_from(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])?;
101
102 if extractable {
104 return Err(Error::Syntax(Some("Extractable is not false".into())));
105 }
106
107 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 Ok(key)
127}
128
129pub(crate) fn get_key_length() -> Result<Option<u32>, Error> {
131 Ok(None)
133}