script_webcrypto/subtlecrypto/rsa_common.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 base64ct::{Base64UrlUnpadded, Encoding};
6use crypto_bigint::NonZero;
7use js::context::JSContext;
8use rsa::pkcs8::spki::{DecodePublicKey, EncodePublicKey};
9use rsa::pkcs8::{DecodePrivateKey, EncodePrivateKey};
10use rsa::traits::{PrivateKeyParts, PublicKeyParts};
11use rsa::{BoxedUint, PrivateKey, PublicKey};
12use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
13 CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
14};
15use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{
16 AlgorithmIdentifier, JsonWebKey, KeyFormat, RsaOtherPrimesInfo,
17};
18use script_bindings::error::Error;
19use script_bindings::root::DomRoot;
20use script_bindings::str::DOMString;
21use script_bindings::trace::RootedTraceableBox;
22
23use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
24use crate::subtlecrypto::{
25 CryptoAlgorithm, DigestOperation, ExportedKey, JsonWebKeyHelper, JwkStringField,
26 KeyAlgorithmAndDerivatives, NormalizedAlgorithm, RsaHashedImportParams, RsaHashedKeyAlgorithm,
27 RsaHashedKeyGenParams, normalize_algorithm,
28};
29use crate::traits::Equivalence;
30
31pub(crate) enum RsaAlgorithm {
32 RsassaPkcs1v1_5,
33 RsaPss,
34 RsaOaep,
35}
36
37/// <https://w3c.github.io/webcrypto/#rsassa-pkcs1-operations-generate-key>
38/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-generate-key>
39/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-generate-key>
40pub(crate) fn generate_key<D: Equivalence>(
41 cx: &mut JSContext,
42 global: &D::GlobalScope,
43 rsa_algorithm: RsaAlgorithm,
44 normalized_algorithm: &RsaHashedKeyGenParams,
45 extractable: bool,
46 usages: Vec<KeyUsage>,
47) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
48 match rsa_algorithm {
49 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
50 // Step 1. If usages contains an entry which is not "sign" or "verify", then throw a
51 // SyntaxError.
52 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
53 },
54 RsaAlgorithm::RsaOaep => {
55 // Step 1. If usages contains an entry which is not "encrypt", "decrypt", "wrapKey" or
56 // "unwrapKey", then throw a SyntaxError.
57 usages.ensure_only_contain_entries_from(&[
58 KeyUsage::Encrypt,
59 KeyUsage::Decrypt,
60 KeyUsage::WrapKey,
61 KeyUsage::UnwrapKey,
62 ])?;
63 },
64 }
65
66 // Step 2. Perform the validate RSA key generation parameters algorithm with
67 // normalizedAlgorithm.
68 normalized_algorithm.validate_parameters()?;
69
70 // Step 3. Generate an RSA key pair, as defined in [RFC3447], with RSA modulus length equal to
71 // the modulusLength attribute of normalizedAlgorithm and RSA public exponent equal to the
72 // publicExponent attribute of normalizedAlgorithm.
73 // Step 4. If generation of the key pair fails, then throw an OperationError.
74 let mut rng = rand::rng();
75 let modulus_length = normalized_algorithm.modulus_length as usize;
76 let public_exponent = BoxedUint::from_be_slice_vartime(&normalized_algorithm.public_exponent);
77 let private_key = PrivateKey::new_with_exp(&mut rng, modulus_length, public_exponent)
78 .map_err(|_| Error::Operation(Some("Failed to generate RSA private key".into())))?;
79 let public_key = private_key.to_public_key();
80
81 // Step 5. Let algorithm be a new RsaHashedKeyAlgorithm dictionary.
82 // Step 7. Set the modulusLength attribute of algorithm to equal the modulusLength attribute of
83 // normalizedAlgorithm.
84 // Step 8. Set the publicExponent attribute of algorithm to equal the publicExponent attribute
85 // of normalizedAlgorithm.
86 // Step 9. Set the hash attribute of algorithm to equal the hash member of normalizedAlgorithm.
87 let algorithm = RsaHashedKeyAlgorithm {
88 name: match rsa_algorithm {
89 // Step 6. Set the name attribute of algorithm to "RSASSA-PKCS1-v1_5".
90 RsaAlgorithm::RsassaPkcs1v1_5 => CryptoAlgorithm::RsassaPkcs1V1_5,
91 // Step 6. Set the name attribute of algorithm to "RSA-PSS".
92 RsaAlgorithm::RsaPss => CryptoAlgorithm::RsaPss,
93 // Step 6. Set the name attribute of algorithm to "RSA-OAEP".
94 RsaAlgorithm::RsaOaep => CryptoAlgorithm::RsaOaep,
95 },
96 modulus_length: normalized_algorithm.modulus_length,
97 public_exponent: normalized_algorithm.public_exponent.clone(),
98 hash: normalized_algorithm.hash.clone(),
99 };
100
101 // Step 10. Let publicKey be a new CryptoKey representing the public key of the generated key
102 // pair.
103 // Step 11. Set the [[type]] internal slot of publicKey to "public"
104 // Step 12. Set the [[algorithm]] internal slot of publicKey to algorithm.
105 // Step 13. Set the [[extractable]] internal slot of publicKey to true.
106 let intersected_usages = match rsa_algorithm {
107 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
108 // Step 14. Set the [[usages]] internal slot of publicKey to be the usage intersection
109 // of usages and [ "verify" ].
110 usages.usage_intersection(&[KeyUsage::Verify])
111 },
112 RsaAlgorithm::RsaOaep => {
113 // Step 14. Set the [[usages]] internal slot of publicKey to be the usage intersection
114 // of usages and [ "encrypt", "wrapKey" ].
115 usages.usage_intersection(&[KeyUsage::Encrypt, KeyUsage::WrapKey])
116 },
117 };
118 let public_key = CryptoKey::new(
119 cx,
120 global,
121 KeyType::Public,
122 true,
123 KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm.clone()),
124 intersected_usages,
125 Handle::RsaPublicKey(public_key),
126 );
127
128 // Step 15. Let privateKey be a new CryptoKey representing the private key of the generated key
129 // pair.
130 // Step 16. Set the [[type]] internal slot of privateKey to "private"
131 // Step 17. Set the [[algorithm]] internal slot of privateKey to algorithm.
132 // Step 18. Set the [[extractable]] internal slot of privateKey to extractable.
133 let intersected_usages = match rsa_algorithm {
134 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
135 // Step 19. Set the [[usages]] internal slot of privateKey to be the usage intersection
136 // of usages and [ "sign" ].
137 usages.usage_intersection(&[KeyUsage::Sign])
138 },
139 RsaAlgorithm::RsaOaep => {
140 // Step 19. Set the [[usages]] internal slot of privateKey to be the usage intersection
141 // of usages and [ "decrypt", "unwrapKey" ].
142 usages.usage_intersection(&[KeyUsage::Decrypt, KeyUsage::UnwrapKey])
143 },
144 };
145 let private_key = CryptoKey::new(
146 cx,
147 global,
148 KeyType::Private,
149 extractable,
150 KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm),
151 intersected_usages,
152 Handle::RsaPrivateKey(private_key),
153 );
154
155 // Step 20. Let result be a new CryptoKeyPair dictionary.
156 // Step 21. Set the publicKey attribute of result to be publicKey.
157 // Step 22. Set the privateKey attribute of result to be privateKey.
158 let result = RootedTraceableBox::new(CryptoKeyPair {
159 publicKey: Some(public_key.as_traced()),
160 privateKey: Some(private_key.as_traced()),
161 });
162
163 // Step 23. Return result.
164 Ok(result)
165}
166
167/// <https://w3c.github.io/webcrypto/#rsassa-pkcs1-operations-import-key>
168/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-import-key>
169/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-import-key>
170///
171/// This implementation is based on the specification for RSA-PSS.
172/// When format is "jwk", Step 2.7 in the specification for RSASSA-PKCS1-v1_5 is skipped since it is redundent.
173/// When format is "jwk", Step 2.2 and 2.3 in the specification of RSA-OAEP are combined into a single step.
174#[allow(clippy::too_many_arguments)]
175pub(crate) fn import_key<D: Equivalence>(
176 cx: &mut JSContext,
177 global: &D::GlobalScope,
178 rsa_algorithm: RsaAlgorithm,
179 normalized_algorithm: &RsaHashedImportParams,
180 format: KeyFormat,
181 key_data: &[u8],
182 extractable: bool,
183 usages: Vec<KeyUsage>,
184) -> Result<DomRoot<CryptoKey<D>>, Error> {
185 // Step 1. Let keyData be the key data to be imported.
186
187 // Step 2.
188 let (key_handle, key_type) = match format {
189 // If format is "spki":
190 KeyFormat::Spki => {
191 match &rsa_algorithm {
192 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
193 // Step 2.1. If usages contains an entry which is not "verify" then throw a
194 // SyntaxError.
195 usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
196 },
197 RsaAlgorithm::RsaOaep => {
198 // Step 2.1. If usages contains an entry which is not "encrypt" or "wrapKey",
199 // then throw a SyntaxError.
200 usages.ensure_only_contain_entries_from(&[
201 KeyUsage::Encrypt,
202 KeyUsage::WrapKey,
203 ])?;
204 },
205 }
206
207 // Step 2.2. Let spki be the result of running the parse a subjectPublicKeyInfo
208 // algorithm over keyData.
209 // Step 2.3. If an error occurred while parsing, then throw a DataError.
210 // Step 2.4. If the algorithm object identifier field of the algorithm
211 // AlgorithmIdentifier field of spki is not equal to the rsaEncryption object
212 // identifier defined in [RFC3447], then throw a DataError.
213 // Step 2.5. Let publicKey be the result of performing the parse an ASN.1 structure
214 // algorithm, with data as the subjectPublicKeyInfo field of spki, structure as the
215 // RSAPublicKey structure specified in Section A.1.1 of [RFC3447], and exactData set to
216 // true.
217 // Step 2.6. If an error occurred while parsing, or it can be determined that publicKey
218 // is not a valid public key according to [RFC3447], then throw a DataError.
219 let public_key = PublicKey::from_public_key_der(key_data).map_err(|_| {
220 Error::Data(Some(
221 "Failed to import RSA public key in SPKI format".into(),
222 ))
223 })?;
224
225 // Step 2.7. Let key be a new CryptoKey that represents the RSA public key identified
226 // by publicKey.
227 // Step 2.8. Set the [[type]] internal slot of key to "public"
228 // NOTE: Done in Step 3-8.
229 let key_handle = Handle::RsaPublicKey(public_key);
230 let key_type = KeyType::Public;
231 (key_handle, key_type)
232 },
233 // If format is "pkcs8":
234 KeyFormat::Pkcs8 => {
235 match &rsa_algorithm {
236 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
237 // Step 2.1. If usages contains an entry which is not "sign" then throw a
238 // SyntaxError.
239 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?;
240 },
241 RsaAlgorithm::RsaOaep => {
242 // Step 2.1. If usages contains an entry which is not "decrypt" or "unwrapKey",
243 // then throw a SyntaxError.
244 usages.ensure_only_contain_entries_from(&[
245 KeyUsage::Decrypt,
246 KeyUsage::UnwrapKey,
247 ])?;
248 },
249 }
250
251 // Step 2.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
252 // algorithm over keyData.
253 // Step 2.3. If an error occurred while parsing, then throw a DataError.
254 // Step 2.4. If the algorithm object identifier field of the privateKeyAlgorithm
255 // PrivateKeyAlgorithm field of privateKeyInfo is not equal to the rsaEncryption object
256 // identifier defined in [RFC3447], then throw a DataError.
257 // Step 2.5. Let rsaPrivateKey be the result of performing the parse an ASN.1 structure
258 // algorithm, with data as the privateKey field of privateKeyInfo, structure as the
259 // RSAPrivateKey structure specified in Section A.1.2 of [RFC3447], and exactData set
260 // to true.
261 // Step 2.6. If an error occurred while parsing, or if rsaPrivateKey is not a valid RSA
262 // private key according to [RFC3447], then throw a DataError.
263 let rsa_private_key = PrivateKey::from_pkcs8_der(key_data).map_err(|_| {
264 Error::Data(Some(
265 "Failed to import RSA private key in PKCS#8 format".into(),
266 ))
267 })?;
268
269 // Step 2.7. Let key be a new CryptoKey that represents the RSA private key identified
270 // by rsaPrivateKey.
271 // Step 2.8. Set the [[type]] internal slot of key to "private"
272 // NOTE: Done in Step 3-8.
273 let key_handle = Handle::RsaPrivateKey(rsa_private_key);
274 let key_type = KeyType::Private;
275 (key_handle, key_type)
276 },
277 // If format is "jwk":
278 KeyFormat::Jwk => {
279 // Step 2.1.
280 // If keyData is a JsonWebKey dictionary:
281 // Let jwk equal keyData.
282 // Otherwise:
283 // Throw a DataError.
284 let jwk = JsonWebKey::parse(cx, key_data)?;
285
286 match &rsa_algorithm {
287 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
288 // Step 2.2. If the d field of jwk is present and usages contains an entry
289 // which is not "sign", or, if the d field of jwk is not present and usages
290 // contains an entry which is not "verify" then throw a SyntaxError.
291 match jwk.d.as_ref() {
292 Some(_) => usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?,
293 None => usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?,
294 }
295 },
296 RsaAlgorithm::RsaOaep => {
297 // Step 2.2.
298 // * If the d field of jwk is present and usages contains an entry which is not
299 // "decrypt" or "unwrapKey", then throw a SyntaxError.
300 // * If the d field of jwk is not present and usages contains an entry which is
301 // not "encrypt" or "wrapKey", then throw a SyntaxError.
302 match jwk.d.as_ref() {
303 Some(_) => usages.ensure_only_contain_entries_from(&[
304 KeyUsage::Decrypt,
305 KeyUsage::UnwrapKey,
306 ])?,
307 None => usages.ensure_only_contain_entries_from(&[
308 KeyUsage::Encrypt,
309 KeyUsage::WrapKey,
310 ])?,
311 }
312 },
313 }
314
315 // Step 2.3. If the kty field of jwk is not a case-sensitive string match to "RSA",
316 // then throw a DataError.
317 if jwk.kty.as_ref().is_none_or(|kty| kty != "RSA") {
318 return Err(Error::Data(Some(
319 "The kty field of jwk is not a case-sensitive string match to \"RSA\""
320 .to_string(),
321 )));
322 }
323
324 match &rsa_algorithm {
325 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
326 // Step 2.4. If usages is non-empty and the use field of jwk is present and is
327 // not a case-sensitive string match to "sig", then throw a DataError.
328 if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
329 return Err(Error::Data(Some(
330 "Usages is non-empty and the use field of jwk is present and \
331 is not a case-sensitive string match to \"sig\""
332 .to_string(),
333 )));
334 }
335 },
336 RsaAlgorithm::RsaOaep => {
337 // Step 2.4. If usages is non-empty and the use field of jwk is present and is
338 // not a case-sensitive string match to "enc", then throw a DataError.
339 if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
340 return Err(Error::Data(Some(
341 "Usages is non-empty and the use field of jwk is present and \
342 is not a case-sensitive string match to \"enc\""
343 .to_string(),
344 )));
345 }
346 },
347 }
348
349 // Step 2.5. If the key_ops field of jwk is present, and is invalid according to the
350 // requirements of JSON Web Key [JWK] or does not contain all of the specified usages
351 // values, then throw a DataError.
352 jwk.check_key_ops(&usages)?;
353
354 // Step 2.6. If the ext field of jwk is present and has the value false and extractable
355 // is true, then throw a DataError.
356 if jwk.ext.is_some_and(|ext| !ext) && extractable {
357 return Err(Error::Data(Some(
358 "The ext field of jwk is present and \
359 has the value false and extractable is true"
360 .to_string(),
361 )));
362 }
363
364 let hash = match &rsa_algorithm {
365 RsaAlgorithm::RsassaPkcs1v1_5 => {
366 // Step 2.7.
367 // If the alg field of jwk is not present:
368 // Let hash be undefined.
369 // If the alg field is equal to the string "RS1":
370 // Let hash be the string "SHA-1".
371 // If the alg field is equal to the string "RS256":
372 // Let hash be the string "SHA-256".
373 // If the alg field is equal to the string "RS384":
374 // Let hash be the string "SHA-384".
375 // If the alg field is equal to the string "RS512":
376 // Let hash be the string "SHA-512".
377 // Otherwise:
378 // Perform any key import steps defined by other applicable specifications,
379 // passing format, jwk and obtaining hash.
380 // If an error occurred or there are no applicable specifications, throw a
381 // DataError.
382 match &jwk.alg {
383 None => None,
384 Some(alg) => match &*alg.str() {
385 "RS1" => Some("SHA-1"),
386 "RS256" => Some("SHA-256"),
387 "RS384" => Some("SHA-384"),
388 "RS512" => Some("SHA-512"),
389 _ => None,
390 },
391 }
392 },
393 RsaAlgorithm::RsaPss => {
394 // Step 2.7.
395 // If the alg field of jwk is not present:
396 // Let hash be undefined.
397 // If the alg field is equal to the string "PS1":
398 // Let hash be the string "SHA-1".
399 // If the alg field is equal to the string "PS256":
400 // Let hash be the string "SHA-256".
401 // If the alg field is equal to the string "PS384":
402 // Let hash be the string "SHA-384".
403 // If the alg field is equal to the string "PS512":
404 // Let hash be the string "SHA-512".
405 // Otherwise:
406 // Perform any key import steps defined by other applicable specifications,
407 // passing format, jwk and obtaining hash.
408 // If an error occurred or there are no applicable specifications, throw a
409 // DataError.
410 match &jwk.alg {
411 None => None,
412 Some(alg) => match &*alg.str() {
413 "PS1" => Some("SHA-1"),
414 "PS256" => Some("SHA-256"),
415 "PS384" => Some("SHA-384"),
416 "PS512" => Some("SHA-512"),
417 _ => None,
418 },
419 }
420 },
421 RsaAlgorithm::RsaOaep => {
422 // Step 2.7.
423 // If the alg field of jwk is not present:
424 // Let hash be undefined.
425 // If the alg field of jwk is equal to "RSA-OAEP":
426 // Let hash be the string "SHA-1".
427 // If the alg field of jwk is equal to "RSA-OAEP-256":
428 // Let hash be the string "SHA-256".
429 // If the alg field of jwk is equal to "RSA-OAEP-384":
430 // Let hash be the string "SHA-384".
431 // If the alg field of jwk is equal to "RSA-OAEP-512":
432 // Let hash be the string "SHA-512".
433 // Otherwise:
434 // Perform any key import steps defined by other applicable specifications,
435 // passing format, jwk and obtaining hash.
436 // If an error occurred or there are no applicable specifications, throw a
437 // DataError.
438 match &jwk.alg {
439 None => None,
440 Some(alg) => match &*alg.str() {
441 "RSA-OAEP" => Some("SHA-1"),
442 "RSA-OAEP-256" => Some("SHA-256"),
443 "RSA-OAEP-384" => Some("SHA-384"),
444 "RSA-OAEP-512" => Some("SHA-512"),
445 _ => None,
446 },
447 }
448 },
449 };
450
451 // Step 2.8. If hash is not undefined:
452 if let Some(hash) = hash {
453 // Step 2.8.1. Let normalizedHash be the result of normalize an algorithm with alg
454 // set to hash and op set to digest.
455 let normalized_hash = normalize_algorithm::<DigestOperation>(
456 cx,
457 &AlgorithmIdentifier::String(DOMString::from(hash)),
458 )?;
459
460 // Step 2.8.2. If normalizedHash is not equal to the hash member of
461 // normalizedAlgorithm, throw a DataError.
462 if normalized_hash.name() != normalized_algorithm.hash.name() {
463 return Err(Error::Data(Some(
464 "The normalizedHash is not equal to the hash member of normalizedAlgorithm"
465 .to_string(),
466 )));
467 }
468 }
469
470 // Step 2.9.
471 // If the d field of jwk is present:
472 if jwk.d.is_some() {
473 // Step 2.9.1. If jwk does not meet the requirements of Section 6.3.2 of JSON Web
474 // Algorithms [JWA], then throw a DataError.
475 let n = jwk.decode_required_string_field(JwkStringField::N)?;
476 let e = jwk.decode_required_string_field(JwkStringField::E)?;
477 let d = jwk.decode_required_string_field(JwkStringField::D)?;
478 let p = jwk.decode_optional_string_field(JwkStringField::P)?;
479 let q = jwk.decode_optional_string_field(JwkStringField::Q)?;
480 let dp = jwk.decode_optional_string_field(JwkStringField::DP)?;
481 let dq = jwk.decode_optional_string_field(JwkStringField::DQ)?;
482 let qi = jwk.decode_optional_string_field(JwkStringField::QI)?;
483 let mut primes = match (p, q, dp, dq, qi) {
484 (Some(p), Some(q), Some(_dp), Some(_dq), Some(_qi)) => vec![p, q],
485 (None, None, None, None, None) => Vec::new(),
486 _ => return Err(Error::Data(Some(
487 "The p, q, dp, dq, qi fields of jwk must be either all-present or all-absent"
488 .to_string(),
489 ))),
490 };
491 jwk.decode_primes_from_oth_field(&mut primes)?;
492
493 // Step 2.9.2. Let privateKey represents the RSA private key identified by
494 // interpreting jwk according to Section 6.3.2 of JSON Web Algorithms [JWA].
495 // Step 2.9.3. If privateKey is not a valid RSA private key according to [RFC3447],
496 // then throw a DataError.
497 let private_key = PrivateKey::from_components(
498 BoxedUint::from_be_slice_vartime(&n),
499 BoxedUint::from_be_slice_vartime(&e),
500 BoxedUint::from_be_slice_vartime(&d),
501 primes
502 .into_iter()
503 .map(|prime| BoxedUint::from_be_slice_vartime(&prime))
504 .collect(),
505 )
506 .map_err(|_| {
507 Error::Data(Some(
508 "Failed to construct RSA private key from values in jwk".to_string(),
509 ))
510 })?;
511
512 // Step 2.9.4. Let key be a new CryptoKey object that represents privateKey.
513 // Step 2.9.5. Set the [[type]] internal slot of key to "private"
514 // NOTE: Done in Step 3-8.
515 let key_handle = Handle::RsaPrivateKey(private_key);
516 let key_type = KeyType::Private;
517 (key_handle, key_type)
518 }
519 // Otherwise:
520 else {
521 // Step 2.9.1. If jwk does not meet the requirements of Section 6.3.1 of JSON Web
522 // Algorithms [JWA], then throw a DataError.
523 let n = jwk.decode_required_string_field(JwkStringField::N)?;
524 let e = jwk.decode_required_string_field(JwkStringField::E)?;
525
526 // Step 2.9.2. Let publicKey represent the RSA public key identified by
527 // interpreting jwk according to Section 6.3.1 of JSON Web Algorithms [JWA].
528 // Step 2.9.3. If publicKey can be determined to not be a valid RSA public key
529 // according to [RFC3447], then throw a DataError.
530 let public_key = PublicKey::new(
531 BoxedUint::from_be_slice_vartime(&n),
532 BoxedUint::from_be_slice_vartime(&e),
533 )
534 .map_err(|_| {
535 Error::Data(Some(
536 "Failed to construct RSA public key from values in jwk".into(),
537 ))
538 })?;
539
540 // Step 2.9.4. Let key be a new CryptoKey representing publicKey.
541 // Step 2.9.5. Set the [[type]] internal slot of key to "public"
542 // NOTE: Done in Step 3-8.
543 let key_handle = Handle::RsaPublicKey(public_key);
544 let key_type = KeyType::Public;
545 (key_handle, key_type)
546 }
547 },
548 // Otherwise:
549 _ => {
550 // throw a NotSupportedError.
551 return Err(Error::NotSupported(Some(
552 "Unsupported import key format for RSA key".to_string(),
553 )));
554 },
555 };
556
557 // Step 3. Let algorithm be a new RsaHashedKeyAlgorithm dictionary.
558 // Step 5. Set the modulusLength attribute of algorithm to the length, in bits, of the RSA
559 // public modulus.
560 // Step 6. Set the publicExponent attribute of algorithm to the BigInteger representation of
561 // the RSA public exponent.
562 // Step 7. Set the hash attribute of algorithm to the hash member of normalizedAlgorithm.
563 // Step 8. Set the [[algorithm]] internal slot of key to algorithm
564 let (modulus_length, public_exponent) = match &key_handle {
565 Handle::RsaPrivateKey(private_key) => (
566 private_key.size() as u32 * 8,
567 private_key.e().to_be_bytes_trimmed_vartime().to_vec(),
568 ),
569 Handle::RsaPublicKey(public_key) => (
570 public_key.size() as u32 * 8,
571 public_key.e().to_be_bytes_trimmed_vartime().to_vec(),
572 ),
573 _ => unreachable!(),
574 };
575 let algorithm = RsaHashedKeyAlgorithm {
576 name: match &rsa_algorithm {
577 RsaAlgorithm::RsassaPkcs1v1_5 => {
578 // Step 4. Set the name attribute of algorithm to "RSASSA-PKCS1-v1_5"
579 CryptoAlgorithm::RsassaPkcs1V1_5
580 },
581 RsaAlgorithm::RsaPss => {
582 // Step 4. Set the name attribute of algorithm to "RSA-PSS"
583 CryptoAlgorithm::RsaPss
584 },
585 RsaAlgorithm::RsaOaep => {
586 // Step 4. Set the name attribute of algorithm to "RSA-OAEP"
587 CryptoAlgorithm::RsaOaep
588 },
589 },
590 modulus_length,
591 public_exponent,
592 hash: normalized_algorithm.hash.clone(),
593 };
594 let key = CryptoKey::new(
595 cx,
596 global,
597 key_type,
598 extractable,
599 KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm),
600 usages.normalized_value(),
601 key_handle,
602 );
603
604 // Step 9. Return key.
605 Ok(key)
606}
607
608/// <https://w3c.github.io/webcrypto/#rsassa-pkcs1-operations-export-key>
609/// <https://w3c.github.io/webcrypto/#rsa-pss-operations-export-key>
610/// <https://w3c.github.io/webcrypto/#rsa-oaep-operations-export-key>
611pub(crate) fn export_key<D: Equivalence>(
612 rsa_algorithm: RsaAlgorithm,
613 format: KeyFormat,
614 key: &CryptoKey<D>,
615) -> Result<ExportedKey, Error> {
616 // Step 1. Let key be the key to be exported.
617
618 // Step 2. If the underlying cryptographic key material represented by the [[handle]] internal
619 // slot of key cannot be accessed, then throw an OperationError.
620 // NOTE: Done in Step 3.
621
622 // Step 3.
623 let result = match format {
624 // If format is "spki"
625 KeyFormat::Spki => {
626 // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
627 // InvalidAccessError.
628 key.ensure_type(KeyType::Public)?;
629
630 // Step 3.2.
631 // Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in
632 // [RFC5280] with the following properties:
633 //
634 // Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following
635 // properties:
636 //
637 // Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
638 //
639 // Set the params field to the ASN.1 type NULL.
640 //
641 // Set the subjectPublicKey field to the result of DER-encoding an RSAPublicKey
642 // ASN.1 type, as defined in [RFC3447], Appendix A.1.1, that represents the RSA
643 // public key represented by the [[handle]] internal slot of key
644 let Handle::RsaPublicKey(public_key) = key.handle() else {
645 return Err(Error::Operation(Some(
646 "The [[handle]] internal slot of key is not an RSA public key".to_string(),
647 )));
648 };
649 let data = public_key.to_public_key_der().map_err(|_| {
650 Error::Operation(Some(
651 "Failed to convert RSA public key to SubjectPublicKeyInfo".to_string(),
652 ))
653 })?;
654
655 // Step 3.3. Let result be the result of DER-encoding data.
656 ExportedKey::new_bytes(data.into_vec())
657 },
658 // If format is "pkcs8":
659 KeyFormat::Pkcs8 => {
660 // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
661 // InvalidAccessError.
662 key.ensure_type(KeyType::Private)?;
663
664 // Step 3.2.
665 // Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208]
666 // with the following properties:
667 //
668 // Set the version field to 0.
669 //
670 // Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type
671 // with the following properties:
672 //
673 // Set the algorithm field to the OID rsaEncryption defined in [RFC3447].
674 //
675 // Set the params field to the ASN.1 type NULL.
676 //
677 // Set the privateKey field to the result of DER-encoding an RSAPrivateKey ASN.1
678 // type, as defined in [RFC3447], Appendix A.1.2, that represents the RSA private
679 // key represented by the [[handle]] internal slot of key
680 let Handle::RsaPrivateKey(private_key) = key.handle() else {
681 return Err(Error::Operation(Some(
682 "The [[handle]] internal slot of key is not an RSA private key".to_string(),
683 )));
684 };
685 let data = private_key.to_pkcs8_der().map_err(|_| {
686 Error::Operation(Some(
687 "Failed to convert RSA private key to PrivateKeyInfo".to_string(),
688 ))
689 })?;
690
691 // Step 3.3. Let result be the result of DER-encoding data.
692 ExportedKey::new_bytes(data.as_bytes().to_vec())
693 },
694 // If format is "jwk":
695 KeyFormat::Jwk => {
696 // Step 3.1. Let jwk be a new JsonWebKey dictionary.
697 let mut jwk = JsonWebKey::default();
698
699 // Step 3.2. Set the kty attribute of jwk to the string "RSA".
700 jwk.kty = Some(DOMString::from_static("RSA"));
701
702 // Step 3.3. Let hash be the name attribute of the hash attribute of the [[algorithm]]
703 // internal slot of key.
704 let KeyAlgorithmAndDerivatives::RsaHashedKeyAlgorithm(algorithm) = key.algorithm()
705 else {
706 return Err(Error::Operation(Some(
707 "The [[algorithm]] internal slot of key is not an RsaHashedKeyAlgorithm"
708 .to_string(),
709 )));
710 };
711 let hash = algorithm.hash.name();
712
713 match rsa_algorithm {
714 RsaAlgorithm::RsassaPkcs1v1_5 => {
715 // Step 3.4.
716 // If hash is "SHA-1":
717 // Set the alg attribute of jwk to the string "RS1".
718 // If hash is "SHA-256":
719 // Set the alg attribute of jwk to the string "RS256".
720 // If hash is "SHA-384":
721 // Set the alg attribute of jwk to the string "RS384".
722 // If hash is "SHA-512":
723 // Set the alg attribute of jwk to the string "RS512".
724 // Otherwise:
725 // Perform any key export steps defined by other applicable specifications,
726 // passing format and the hash attribute of the [[algorithm]] internal slot
727 // of key and obtaining alg.
728 // Set the alg attribute of jwk to alg.
729 let alg = match hash {
730 CryptoAlgorithm::Sha1 => "RS1",
731 CryptoAlgorithm::Sha256 => "RS256",
732 CryptoAlgorithm::Sha384 => "RS384",
733 CryptoAlgorithm::Sha512 => "RS512",
734 _ => {
735 return Err(Error::NotSupported(Some(format!(
736 "Unsupported \"{}\" hash for RSASSA-PKCS1-v1_5",
737 hash.as_str()
738 ))));
739 },
740 };
741 jwk.alg = Some(DOMString::from(alg));
742 },
743 RsaAlgorithm::RsaPss => {
744 // Step 3.4.
745 // If hash is "SHA-1":
746 // Set the alg attribute of jwk to the string "PS1".
747 // If hash is "SHA-256":
748 // Set the alg attribute of jwk to the string "PS256".
749 // If hash is "SHA-384":
750 // Set the alg attribute of jwk to the string "PS384".
751 // If hash is "SHA-512":
752 // Set the alg attribute of jwk to the string "PS512".
753 // Otherwise:
754 // Perform any key export steps defined by other applicable specifications,
755 // passing format and the hash attribute of the [[algorithm]] internal slot
756 // of key and obtaining alg.
757 // Set the alg attribute of jwk to alg.
758 let alg = match hash {
759 CryptoAlgorithm::Sha1 => "PS1",
760 CryptoAlgorithm::Sha256 => "PS256",
761 CryptoAlgorithm::Sha384 => "PS384",
762 CryptoAlgorithm::Sha512 => "PS512",
763 _ => {
764 return Err(Error::NotSupported(Some(format!(
765 "Unsupported \"{}\" hash for RSA-PSS",
766 hash.as_str()
767 ))));
768 },
769 };
770 jwk.alg = Some(DOMString::from(alg));
771 },
772 RsaAlgorithm::RsaOaep => {
773 // Step 3.4.
774 // If hash is "SHA-1":
775 // Set the alg attribute of jwk to the string "RSA-OAEP".
776 // If hash is "SHA-256":
777 // Set the alg attribute of jwk to the string "RSA-OAEP-256".
778 // If hash is "SHA-384":
779 // Set the alg attribute of jwk to the string "RSA-OAEP-384".
780 // If hash is "SHA-512":
781 // Set the alg attribute of jwk to the string "RSA-OAEP-512".
782 // Otherwise:
783 // Perform any key export steps defined by other applicable specifications,
784 // passing format and the hash attribute of the [[algorithm]] internal slot
785 // of key and obtaining alg.
786 // Set the alg attribute of jwk to alg.
787 let alg = match hash {
788 CryptoAlgorithm::Sha1 => "RSA-OAEP",
789 CryptoAlgorithm::Sha256 => "RSA-OAEP-256",
790 CryptoAlgorithm::Sha384 => "RSA-OAEP-384",
791 CryptoAlgorithm::Sha512 => "RSA-OAEP-512",
792 _ => {
793 return Err(Error::NotSupported(Some(format!(
794 "Unsupported \"{}\" hash for RSA-OAEP",
795 hash.as_str()
796 ))));
797 },
798 };
799 jwk.alg = Some(DOMString::from(alg));
800 },
801 }
802
803 // Step 3.5. Set the attributes n and e of jwk according to the corresponding
804 // definitions in JSON Web Algorithms [JWA], Section 6.3.1.
805 let (n, e) = match key.handle() {
806 Handle::RsaPrivateKey(private_key) => (private_key.n(), private_key.e()),
807 Handle::RsaPublicKey(public_key) => (public_key.n(), public_key.e()),
808 _ => {
809 return Err(Error::Operation(Some(
810 "Failed to extract modulus n and public exponent e from RSA key"
811 .to_string(),
812 )));
813 },
814 };
815 jwk.encode_string_field(JwkStringField::N, &n.to_be_bytes_trimmed_vartime());
816 jwk.encode_string_field(JwkStringField::E, &e.to_be_bytes_trimmed_vartime());
817
818 // Step 3.6. If the [[type]] internal slot of key is "private":
819 if key.Type() == KeyType::Private {
820 // Step 3.6.1. Set the attributes named d, p, q, dp, dq, and qi of jwk according to
821 // the corresponding definitions in JSON Web Algorithms [JWA], Section 6.3.2.
822 let Handle::RsaPrivateKey(private_key) = key.handle() else {
823 return Err(Error::Operation(Some(
824 "The [[handle]] internal slot of key is not an RSA private key".to_string(),
825 )));
826 };
827 let mut private_key = private_key.clone();
828 private_key.precompute().map_err(|_| {
829 Error::Operation(Some("Failed to perform RSA pre-computation".to_string()))
830 })?;
831 let primes = private_key.primes();
832 let d = private_key.d();
833 let p = primes.first().ok_or(Error::Operation(Some(
834 "Failed to extract first prime factor p from RSA private key".to_string(),
835 )))?;
836 let q = primes.get(1).ok_or(Error::Operation(Some(
837 "Failed to extract second prime factor q from RSA private key".to_string(),
838 )))?;
839 let dp = private_key.dp().ok_or(Error::Operation(Some(
840 "Failed to extract first factor CRT exponent dp from RSA private key"
841 .to_string(),
842 )))?;
843 let dq = private_key.dq().ok_or(Error::Operation(Some(
844 "Failed to extract second factor CRT exponent dq from RSA private key"
845 .to_string(),
846 )))?;
847 let qi = private_key.crt_coefficient().ok_or(Error::Operation(Some(
848 "Failed to extract first CRT coefficient qi from RSA private key".into(),
849 )))?;
850 jwk.encode_string_field(JwkStringField::D, &d.to_be_bytes_trimmed_vartime());
851 jwk.encode_string_field(JwkStringField::P, &p.to_be_bytes_trimmed_vartime());
852 jwk.encode_string_field(JwkStringField::Q, &q.to_be_bytes_trimmed_vartime());
853 jwk.encode_string_field(JwkStringField::DP, &dp.to_be_bytes_trimmed_vartime());
854 jwk.encode_string_field(JwkStringField::DQ, &dq.to_be_bytes_trimmed_vartime());
855 jwk.encode_string_field(JwkStringField::QI, &qi.to_be_bytes_trimmed_vartime());
856
857 // Step 3.6.2. If the underlying RSA private key represented by the [[handle]]
858 // internal slot of key is represented by more than two primes, set the attribute
859 // named oth of jwk according to the corresponding definition in JSON Web
860 // Algorithms [JWA], Section 6.3.2.7
861 let mut oth = Vec::new();
862 for (i, p_i) in primes.iter().enumerate().skip(2) {
863 // d_i = d mod (p_i - 1)
864 // t_i = (p_1 * p_2 * ... * p_(i-1)) ^ (-1) mod p_i
865 let d_i = private_key.d().rem(
866 &NonZero::new(p_i.wrapping_sub(BoxedUint::one()))
867 .expect("Prime numbers must be greater than one"),
868 );
869 let non_zero_pi =
870 NonZero::new(p_i.clone().get()).expect("Prime numbers must be non-zero");
871 let t_i = primes
872 .iter()
873 .take(i - 1)
874 .fold(BoxedUint::one(), |product, p_j| {
875 product.mul_mod(p_j, &non_zero_pi)
876 })
877 .invert_mod(&non_zero_pi)
878 .ok_or(Error::Operation(Some(
879 "Failed to compute factor CRT coefficient of other RSA primes".into(),
880 )))?;
881 oth.push(RsaOtherPrimesInfo {
882 r: Some(
883 Base64UrlUnpadded::encode_string(&p_i.to_be_bytes_trimmed_vartime())
884 .into(),
885 ),
886 d: Some(
887 Base64UrlUnpadded::encode_string(&d_i.to_be_bytes_trimmed_vartime())
888 .into(),
889 ),
890 t: Some(
891 Base64UrlUnpadded::encode_string(&t_i.to_be_bytes_trimmed_vartime())
892 .into(),
893 ),
894 });
895 }
896 if !oth.is_empty() {
897 jwk.oth = Some(oth);
898 }
899 }
900
901 // Step 3.7. Set the key_ops attribute of jwk to the usages attribute of key.
902 jwk.set_key_ops(key.usages());
903
904 // Step 3.8. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
905 jwk.ext = Some(key.Extractable());
906
907 // Step 3.9. Let result be jwk.
908 ExportedKey::new_jwk(jwk)
909 },
910 // Otherwise
911 _ => {
912 // throw a NotSupportedError.
913 return Err(Error::NotSupported(Some(
914 "Unsupported export key format for RSA key".to_string(),
915 )));
916 },
917 };
918
919 // Step 4. Return result.
920 Ok(result)
921}
922
923/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
924/// Step 9 - 15, for RSA algorithms
925pub(crate) fn get_public_key<D: Equivalence>(
926 cx: &mut JSContext,
927 global: &D::GlobalScope,
928 rsa_algorithm: RsaAlgorithm,
929 key: &CryptoKey<D>,
930 algorithm: &KeyAlgorithmAndDerivatives,
931 usages: Vec<KeyUsage>,
932) -> Result<DomRoot<CryptoKey<D>>, Error> {
933 // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
934 // identified by algorithm, then throw a SyntaxError.
935 //
936 // NOTE: See "importKey" operation for supported usages
937 match rsa_algorithm {
938 RsaAlgorithm::RsassaPkcs1v1_5 | RsaAlgorithm::RsaPss => {
939 usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
940 },
941 RsaAlgorithm::RsaOaep => {
942 usages.ensure_only_contain_entries_from(&[KeyUsage::Encrypt, KeyUsage::WrapKey])?;
943 },
944 }
945
946 // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
947 // private key represented by the [[handle]] internal slot of key.
948 // Step 11. If an error occurred, then throw a OperationError.
949 // Step 12. Set the [[type]] internal slot of publicKey to "public".
950 // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
951 // Step 14. Set the [[extractable]] internal slot of publicKey to true.
952 // Step 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.
953 let Handle::RsaPrivateKey(private_key) = key.handle() else {
954 return Err(Error::Operation(Some(
955 "[[handle]] internal slot of key is not an RSA private key".to_string(),
956 )));
957 };
958 let public_key = CryptoKey::new(
959 cx,
960 global,
961 KeyType::Public,
962 true,
963 algorithm.clone(),
964 usages.normalized_value(),
965 Handle::RsaPublicKey(private_key.into()),
966 );
967
968 Ok(public_key)
969}