script_webcrypto/subtlecrypto/x448_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 elliptic_curve::ctutils::CtEq;
6use js::context::JSContext;
7use pkcs8::der::asn1::OctetStringRef;
8use pkcs8::der::{Decode, Encode};
9use pkcs8::{AlgorithmIdentifierRef, ObjectIdentifier, PrivateKeyInfoRef, SubjectPublicKeyInfoRef};
10use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
11 CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
12};
13use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
14use script_bindings::error::Error;
15use script_bindings::root::DomRoot;
16use script_bindings::str::DOMString;
17use script_bindings::trace::RootedTraceableBox;
18use x448::{PublicKey, StaticSecret};
19use zeroize::Zeroizing;
20
21use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
22use crate::subtlecrypto::{
23 CryptoAlgorithm, EcdhKeyDeriveParams, ExportedKey, JsonWebKeyHelper, JwkStringField,
24 KeyAlgorithm, KeyAlgorithmAndDerivatives, truncate_bit_sequence,
25};
26use crate::traits::Equivalence;
27
28/// `id-X448` object identifier defined in [RFC8410]
29const X448_OID_STRING: &str = "1.3.101.111";
30
31const PRIVATE_KEY_LENGTH: usize = 56;
32pub(crate) const SECRET_LENGTH: usize = 56;
33
34/// <https://wicg.github.io/webcrypto-secure-curves/#x448>
35pub(crate) fn derive_bits<D: Equivalence>(
36 normalized_algorithm: &EcdhKeyDeriveParams<D>,
37 key: &CryptoKey<D>,
38 length: Option<u32>,
39) -> Result<Vec<u8>, Error> {
40 // Step 1. If the [[type]] internal slot of key is not "private", then throw an
41 // InvalidAccessError.
42 key.ensure_type(KeyType::Private)?;
43
44 // Step 2. Let publicKey be the public member of normalizedAlgorithm.
45 let public_key = normalized_algorithm.public.root();
46
47 // Step 3. If the [[type]] internal slot of publicKey is not "public", then throw an
48 // InvalidAccessError.
49 public_key.ensure_type(KeyType::Public)?;
50
51 // Step 4. If the name attribute of the [[algorithm]] internal slot of publicKey is not equal to
52 // the name property of the [[algorithm]] internal slot of key, then throw an
53 // InvalidAccessError.
54 if public_key.algorithm().name() != key.algorithm().name() {
55 return Err(Error::InvalidAccess(Some(
56 "[[algorithm]] internal slot of publicKey does not match \
57 [[algorithm]] internal slot of key"
58 .into(),
59 )));
60 }
61
62 // Step 5. Let secret be the result of performing the X448 function specified in [RFC7748]
63 // Section 5 with key as the X448 private key k and the X448 public key represented by the
64 // [[handle]] internal slot of publicKey as the X448 public key u.
65 let Handle::X448PrivateKey(private_key) = key.handle() else {
66 return Err(Error::Operation(Some(
67 "[[handle]] internal slot of key is not an X448 private key".into(),
68 )));
69 };
70 let Handle::X448PublicKey(public_key) = public_key.handle() else {
71 return Err(Error::Operation(Some(
72 "[[handle]] internal slot of publicKey is not an X448 public key".into(),
73 )));
74 };
75 let secret = private_key.diffie_hellman(public_key);
76
77 // Step 6. If secret is the all-zero value, then throw a OperationError. This check must be
78 // performed in constant-time, as per [RFC7748] Section 6.2.
79 if secret.as_bytes().ct_eq(&[0u8; SECRET_LENGTH]).into() {
80 return Err(Error::Operation(Some(
81 "The secret is the all-zero value".into(),
82 )));
83 }
84
85 // Step 7.
86 // If length is null:
87 // Return secret
88 // Otherwise:
89 // If the length of secret in bits is less than length:
90 // throw an OperationError.
91 // Otherwise:
92 // Return an octet string containing the first length bits of secret.
93 let secret_slice = secret.as_bytes();
94 match length {
95 None => Ok(secret_slice.to_vec()),
96 Some(length) => {
97 if secret_slice.len() * 8 < length as usize {
98 Err(Error::Operation(Some("Derived secret is too short".into())))
99 } else {
100 let mut secret = secret_slice[..length.div_ceil(8) as usize].to_vec();
101 truncate_bit_sequence(&mut secret, length as usize);
102 Ok(secret)
103 }
104 },
105 }
106}
107
108/// <https://wicg.github.io/webcrypto-secure-curves/#x448-description>
109pub(crate) fn generate_key<D: Equivalence>(
110 cx: &mut JSContext,
111 global: &D::GlobalScope,
112 extractable: bool,
113 usages: Vec<KeyUsage>,
114) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
115 // Step 1. If usages contains an entry which is not "deriveKey" or "deriveBits" then throw a
116 // SyntaxError.
117 usages.ensure_only_contain_entries_from(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])?;
118
119 // Step 2. Generate an X448 key pair, with the private key being 56 random bytes, and the public
120 // key being X448(a, 5), as defined in [RFC7748], section 6.2.
121 let mut rng = rand::rng();
122 let private_key = StaticSecret::random_from_rng(&mut rng);
123 let public_key = PublicKey::from(&private_key);
124
125 // Step 3. Let algorithm be a new KeyAlgorithm object.
126 // Step 4. Set the name attribute of algorithm to "X448".
127 let algorithm = KeyAlgorithm {
128 name: CryptoAlgorithm::X448,
129 };
130
131 // Step 5. Let publicKey be a new CryptoKey associated with the relevant global object of this
132 // [HTML], and representing the public key of the generated key pair.
133 // Step 6. Set the [[type]] internal slot of publicKey to "public"
134 // Step 7. Set the [[algorithm]] internal slot of publicKey to algorithm.
135 // Step 8. Set the [[extractable]] internal slot of publicKey to true.
136 // Step 9. Set the [[usages]] internal slot of publicKey to be the empty list.
137 let public_key = CryptoKey::new(
138 cx,
139 global,
140 KeyType::Public,
141 true,
142 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm.clone()),
143 Vec::new(),
144 Handle::X448PublicKey(public_key),
145 );
146
147 // Step 10. Let privateKey be a new CryptoKey associated with the relevant global object of this
148 // [HTML], and representing the private key of the generated key pair.
149 // Step 11. Set the [[type]] internal slot of privateKey to "private"
150 // Step 12. Set the [[algorithm]] internal slot of privateKey to algorithm.
151 // Step 13. Set the [[extractable]] internal slot of privateKey to extractable.
152 // Step 14. Set the [[usages]] internal slot of privateKey to be the usage intersection of
153 // usages and [ "deriveKey", "deriveBits" ].
154 let private_key = CryptoKey::new(
155 cx,
156 global,
157 KeyType::Private,
158 extractable,
159 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
160 usages.usage_intersection(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits]),
161 Handle::X448PrivateKey(private_key),
162 );
163
164 // Step 15. Let result be a new CryptoKeyPair dictionary.
165 // Step 16. Set the publicKey attribute of result to be publicKey.
166 // Step 17. Set the privateKey attribute of result to be privateKey.
167 let result = RootedTraceableBox::new(CryptoKeyPair {
168 publicKey: Some(public_key.as_traced()),
169 privateKey: Some(private_key.as_traced()),
170 });
171
172 // Step 18. Return the result of converting result to an ECMAScript Object, as defined by
173 // [WebIDL].
174 // NOTE: The conversion of result to an ECMAScript Object is done in SubtleCrypto::Generate.
175 Ok(result)
176}
177
178/// <https://wicg.github.io/webcrypto-secure-curves/#x448-description>
179pub(crate) fn import_key<D: Equivalence>(
180 cx: &mut JSContext,
181 global: &D::GlobalScope,
182 format: KeyFormat,
183 key_data: &[u8],
184 extractable: bool,
185 usages: Vec<KeyUsage>,
186) -> Result<DomRoot<CryptoKey<D>>, Error> {
187 // Step 1. Let keyData be the key data to be imported.
188
189 // Step 2.
190 let key = match format {
191 // If format is "spki":
192 KeyFormat::Spki => {
193 // Step 2.1. If usages is not empty then throw a SyntaxError.
194 usages.ensure_only_contain_entries_from(&[])?;
195
196 // Step 2.2. Let spki be the result of running the parse a subjectPublicKeyInfo
197 // algorithm over keyData.
198 // Step 2.3. If an error occurred while parsing, then throw a DataError.
199 let spki = SubjectPublicKeyInfoRef::from_der(key_data).map_err(|_| {
200 Error::Data(Some(
201 "Failed to parse the X448 public key in SPKI format".into(),
202 ))
203 })?;
204
205 // Step 2.4. If the algorithm object identifier field of the algorithm
206 // AlgorithmIdentifier field of spki is not equal to the id-X448 object identifier
207 // defined in [RFC8410], then throw a DataError.
208 if spki.algorithm.oid != ObjectIdentifier::new_unwrap(X448_OID_STRING) {
209 return Err(Error::Data(Some(
210 "The algorithm object identifier field of the algorithm field of spki \
211 is not equal to the id-X448 object identifier"
212 .into(),
213 )));
214 }
215
216 // Step 2.5. If the parameters field of the algorithm AlgorithmIdentifier field of spki
217 // is present, then throw a DataError.
218 if spki.algorithm.parameters.is_some() {
219 return Err(Error::Data(Some(
220 "The parameters field of the algorithm field of spki is present".into(),
221 )));
222 }
223
224 // Step 2.6. Let publicKey be the X448 public key identified by the subjectPublicKey
225 // field of spki.
226 let key_bytes = spki.subject_public_key.as_bytes().ok_or(Error::Data(Some(
227 "The subjectPublicKey field in spki is not octet aligned".into(),
228 )))?;
229 let public_key = PublicKey::from_bytes_unchecked(key_bytes).ok_or(Error::Data(
230 Some("The length of the subjectPublicKey in spki is not 56 bytes".into()),
231 ))?;
232
233 // Step 2.7. Let key be a new CryptoKey associated with the relevant global object of
234 // this [HTML], and that represents publicKey.
235 // Step 2.8. Set the [[type]] internal slot of key to "public"
236 // Step 2.9. Let algorithm be a new KeyAlgorithm.
237 // Step 2.10. Set the name attribute of algorithm to "X448".
238 // Step 2.11. Set the [[algorithm]] internal slot of key to algorithm.
239 let algorithm = KeyAlgorithm {
240 name: CryptoAlgorithm::X448,
241 };
242 CryptoKey::new(
243 cx,
244 global,
245 KeyType::Public,
246 extractable,
247 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
248 usages.normalized_value(),
249 Handle::X448PublicKey(public_key),
250 )
251 },
252 // If format is "pkcs8":
253 KeyFormat::Pkcs8 => {
254 // Step 2.1. If usages contains an entry which is not "deriveKey" or "deriveBits" then
255 // throw a SyntaxError.
256 usages
257 .ensure_only_contain_entries_from(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])?;
258
259 // Step 2.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
260 // algorithm over keyData.
261 // Step 2.3. If an error occurs while parsing, then throw a DataError.
262 let private_key_info = PrivateKeyInfoRef::from_der(key_data).map_err(|_| {
263 Error::Data(Some(
264 "Failed to parse the X448 private key to PKCS#8 document".into(),
265 ))
266 })?;
267
268 // Step 2.4. If the algorithm object identifier field of the privateKeyAlgorithm
269 // PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-X448 object
270 // identifier defined in [RFC8410], then throw a DataError.
271 if private_key_info.algorithm.oid != ObjectIdentifier::new_unwrap(X448_OID_STRING) {
272 return Err(Error::Data(Some(
273 "The algorithm object identifier field of the privateKeyAlgorithm field of \
274 privateKeyInfo is not equal to the id-X448 object identifier"
275 .into(),
276 )));
277 }
278
279 // Step 2.5. If the parameters field of the privateKeyAlgorithm
280 // PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a
281 // DataError.
282 if private_key_info.algorithm.parameters.is_some() {
283 return Err(Error::Data(Some(
284 "The parameters field of the privateKeyAlgorithm field of privateKeyInfo \
285 is present"
286 .into(),
287 )));
288 }
289
290 // Step 2.6. Let curvePrivateKey be the result of performing the parse an ASN.1
291 // structure algorithm, with data as the privateKey field of privateKeyInfo, structure
292 // as the ASN.1 CurvePrivateKey structure specified in Section 7 of [RFC8410], and
293 // exactData set to true.
294 // Step 7. If an error occurred while parsing, then throw a DataError.
295 let curve_private_key = private_key_info
296 .private_key
297 .decode_into::<&OctetStringRef>()
298 .map_err(|_| {
299 Error::Data(Some(
300 "Failed to decode the privateKey field of PrivateKeyInfo ASN.1 structure"
301 .into(),
302 ))
303 })?;
304 let key_bytes: [u8; PRIVATE_KEY_LENGTH] =
305 curve_private_key.as_bytes().try_into().map_err(|_| {
306 Error::Data(Some(
307 "Failed to extract the raw bytes from the CurvePrivateKey ASN.1 structure"
308 .into(),
309 ))
310 })?;
311 let curve_private_key = StaticSecret::from(key_bytes);
312
313 // Step 2.8. Let key be a new CryptoKey associated with the relevant global object of
314 // this [HTML], and that represents the X448 private key identified by curvePrivateKey.
315 // Step 2.9. Set the [[type]] internal slot of key to "private"
316 // Step 2.10. Let algorithm be a new KeyAlgorithm.
317 // Step 2.11. Set the name attribute of algorithm to "X448".
318 // Step 2.12. Set the [[algorithm]] internal slot of key to algorithm.
319 let algorithm = KeyAlgorithm {
320 name: CryptoAlgorithm::X448,
321 };
322 CryptoKey::new(
323 cx,
324 global,
325 KeyType::Private,
326 extractable,
327 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
328 usages.normalized_value(),
329 Handle::X448PrivateKey(curve_private_key),
330 )
331 },
332 // If format is "jwk":
333 KeyFormat::Jwk => {
334 // Step 2.1.
335 // If keyData is a JsonWebKey dictionary:
336 // Let jwk equal keyData.
337 // Otherwise:
338 // Throw a DataError.
339 let jwk = JsonWebKey::parse(cx, key_data)?;
340
341 // Step 2.2. If the d field is present and if usages contains an entry which is not
342 // "deriveKey" or "deriveBits" then throw a SyntaxError.
343 // Step 2.3. If the d field is not present and if usages is not empty then throw a
344 // SyntaxError.
345 match jwk.d.as_ref() {
346 Some(_) => usages.ensure_only_contain_entries_from(&[
347 KeyUsage::DeriveKey,
348 KeyUsage::DeriveBits,
349 ])?,
350 None => usages.ensure_only_contain_entries_from(&[])?,
351 }
352
353 // Step 2.4. If the kty field of jwk is not "OKP", then throw a DataError.
354 if jwk.kty.as_ref().is_none_or(|kty| kty != "OKP") {
355 return Err(Error::Data(Some(
356 "The kty field of jwk is not \"OKP\"".into(),
357 )));
358 }
359
360 // Step 2.5. If the crv field of jwk is not "X448", then throw a DataError.
361 if jwk.crv.as_ref().is_none_or(|crv| crv != "X448") {
362 return Err(Error::Data(Some(
363 "The crv field of jwk is not \"X448\"".into(),
364 )));
365 }
366
367 // Step 2.6. If usages is non-empty and the use field of jwk is present and is not equal
368 // to "enc" then throw a DataError.
369 if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
370 return Err(Error::Data(Some(
371 "Usages is non-empty and the use field of jwk is present and is not equal to \
372 \"enc\""
373 .into(),
374 )));
375 }
376
377 // Step 2.7. If the key_ops field of jwk is present, and is invalid according to the
378 // requirements of JSON Web Key [JWK], or it does not contain all of the specified
379 // usages values, then throw a DataError.
380 jwk.check_key_ops(&usages)?;
381
382 // Step 2.8. If the ext field of jwk is present and has the value false and extractable
383 // is true, then throw a DataError.
384 if jwk.ext.is_some_and(|ext| !ext) && extractable {
385 return Err(Error::Data(Some(
386 "the ext field of jwk is present and has the value false \
387 and extractable is true"
388 .into(),
389 )));
390 }
391
392 // Step 2.9.
393 // If the d field is present:
394 let (handle, key_type) = if jwk.d.is_some() {
395 // Step 2.9.1. If jwk does not meet the requirements of the JWK private key format
396 // described in Section 2 of [RFC8037], then throw a DataError.
397 let d = jwk.decode_required_string_field(JwkStringField::D)?;
398 let x = jwk.decode_required_string_field(JwkStringField::X)?;
399 let private_key_bytes: [u8; PRIVATE_KEY_LENGTH] =
400 d.as_slice().try_into().map_err(|_| {
401 Error::Data(Some("Invalid length of private key in 'd' field".into()))
402 })?;
403 let public_key_bytes = x.as_slice();
404 let private_key = StaticSecret::from(private_key_bytes);
405 let public_key = PublicKey::from_bytes_unchecked(public_key_bytes).ok_or(
406 Error::Data(Some("Invalid length of private key in 'x' field".into())),
407 )?;
408 if PublicKey::from(&private_key) != public_key {
409 return Err(Error::Data(Some(
410 "Public key in 'x' field does not match private key in 'd' field".into(),
411 )));
412 }
413
414 // Step 2.9.2. Let key be a new CryptoKey object that represents the X448 private
415 // key identified by interpreting jwk according to Section 2 of [RFC8037].
416 // NOTE: CryptoKey is created in Step 2.10 - 2.12.
417 let handle = Handle::X448PrivateKey(private_key);
418
419 // Step 2.9.3. Set the [[type]] internal slot of Key to "private".
420 let key_type = KeyType::Private;
421
422 (handle, key_type)
423 }
424 // Otherwise:
425 else {
426 // Step 2.9.1. If jwk does not meet the requirements of the JWK public key format
427 // described in Section 2 of [RFC8037], then throw a DataError.
428 let x = jwk.decode_required_string_field(JwkStringField::X)?;
429 let public_key_bytes = x.as_slice();
430 let public_key = PublicKey::from_bytes_unchecked(public_key_bytes).ok_or(
431 Error::Data(Some("Invalid length of private key in 'x' field".into())),
432 )?;
433
434 // Step 2.9.2. Let key be a new CryptoKey object that represents the X448 public key
435 // identified by interpreting jwk according to Section 2 of [RFC8037].
436 // NOTE: CryptoKey is created in Step 2.10 - 2.12.
437 let handle = Handle::X448PublicKey(public_key);
438
439 // Step 2.9.3. Set the [[type]] internal slot of Key to "public".
440 let key_type = KeyType::Public;
441
442 (handle, key_type)
443 };
444
445 // Step 2.10. Let algorithm be a new instance of a KeyAlgorithm object.
446 // Step 2.11. Set the name attribute of algorithm to "X448".
447 // Step 2.12. Set the [[algorithm]] internal slot of key to algorithm.
448 let algorithm = KeyAlgorithm {
449 name: CryptoAlgorithm::X448,
450 };
451 CryptoKey::new(
452 cx,
453 global,
454 key_type,
455 extractable,
456 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
457 usages.normalized_value(),
458 handle,
459 )
460 },
461 // If format is "raw":
462 KeyFormat::Raw | KeyFormat::Raw_public => {
463 // Step 2.1. If usages is not empty then throw a SyntaxError.
464 usages.ensure_only_contain_entries_from(&[])?;
465
466 // Step 2.2. Let data be keyData.
467 let data = key_data;
468
469 // Step 2.3. If the length in bits of data is not 448 then throw a DataError.
470 if data.len() != 56 {
471 return Err(Error::Data(Some("The key length is not 448 bits".into())));
472 }
473
474 // Step 2.4. Let algorithm be a new KeyAlgorithm object.
475 // Step 2.5. Set the name attribute of algorithm to "X448".
476 let algorithm = KeyAlgorithm {
477 name: CryptoAlgorithm::X448,
478 };
479
480 // Step 2.6. Let key be a new CryptoKey associated with the relevant global object of
481 // this [HTML], and that represents data.
482 // Step 2.7. Set the [[type]] internal slot of key to "public"
483 // Step 2.8. Set the [[algorithm]] internal slot of key to algorithm.
484 let public_key = PublicKey::from_bytes_unchecked(data).ok_or(Error::Data(Some(
485 "Failed to import public key from raw bytes".into(),
486 )))?;
487 CryptoKey::new(
488 cx,
489 global,
490 KeyType::Public,
491 extractable,
492 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
493 usages.normalized_value(),
494 Handle::X448PublicKey(public_key),
495 )
496 },
497 // Otherwise:
498 _ => {
499 // throw a NotSupportedError.
500 return Err(Error::NotSupported(Some(
501 "Unsupported import key format for X448".into(),
502 )));
503 },
504 };
505
506 // Step 3. Return key
507 Ok(key)
508}
509
510/// <https://wicg.github.io/webcrypto-secure-curves/#x448>
511pub(crate) fn export_key<D: Equivalence>(
512 format: KeyFormat,
513 key: &CryptoKey<D>,
514) -> Result<ExportedKey, Error> {
515 // Step 1. Let key be the CryptoKey to be exported.
516
517 // Step 2. If the underlying cryptographic key material represented by the [[handle]] internal
518 // slot of key cannot be accessed, then throw an OperationError.
519 // NOTE: Done in Step 3.
520
521 // Step 3.
522 let result = match format {
523 // If format is "spki":
524 KeyFormat::Spki => {
525 // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
526 // InvalidAccessError.
527 key.ensure_type(KeyType::Public)?;
528
529 // Step 3.2. Let data be an instance of the subjectPublicKeyInfo ASN.1 structure defined
530 // in [RFC5280] with the following properties:
531 // * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following
532 // properties:
533 // * Set the algorithm object identifier to the id-X448 OID defined in [RFC8410].
534 // * Set the subjectPublicKey field to keyData.
535 let Handle::X448PublicKey(public_key) = key.handle() else {
536 return Err(Error::Operation(Some(
537 "[[handle]] internal slot of key is not an X448 public key".into(),
538 )));
539 };
540 let data = SubjectPublicKeyInfoRef {
541 algorithm: AlgorithmIdentifierRef {
542 oid: ObjectIdentifier::new_unwrap(X448_OID_STRING),
543 parameters: None,
544 },
545 subject_public_key: public_key.as_bytes().try_into().map_err(|_| {
546 Error::Data(Some(
547 "Failed to construct the subjectPublicKey field of subjectPublicKeyInfo \
548 ASN.1 structure"
549 .into(),
550 ))
551 })?,
552 };
553
554 // Step 3.3. Let result be a new ArrayBuffer associated with the relevant global object
555 // of this [HTML], and containing data.
556 // NOTE: The conversion to a new ArrayBuffer is done in SubtleCrypto::ExportKey.
557 ExportedKey::new_bytes(data.to_der().map_err(|_| {
558 Error::Operation(Some(
559 "Failed to encode the subjectPublicKeyInfo ASN.1 structure in DER-encoding"
560 .into(),
561 ))
562 })?)
563 },
564 // If format is "pkcs8":
565 KeyFormat::Pkcs8 => {
566 // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
567 // InvalidAccessError.
568 key.ensure_type(KeyType::Private)?;
569
570 // Step 3.2. Let data be an instance of the privateKeyInfo ASN.1 structure defined in
571 // [RFC5208] with the following properties:
572 // * Set the version field to 0.
573 // * Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type
574 // with the following properties:
575 // * Set the algorithm object identifier to the id-X448 OID defined in [RFC8410].
576 // * Set the privateKey field to the result of DER-encoding a CurvePrivateKey ASN.1
577 // type, as defined in Section 7 of [RFC8410], that represents the X448 private key
578 // represented by the [[handle]] internal slot of key
579 let Handle::X448PrivateKey(private_key) = key.handle() else {
580 return Err(Error::Operation(Some(
581 "[[handle]] internal slot of key is not an X448 private key".into(),
582 )));
583 };
584 let curve_private_key = OctetStringRef::new(private_key.as_bytes()).map_err(|_| {
585 Error::Operation(Some(
586 "Failed to construct CurvePrivateKey ASN.1 structure".into(),
587 ))
588 })?;
589 let encoded_curve_private_key: Zeroizing<Vec<u8>> = curve_private_key
590 .to_der()
591 .map_err(|_| {
592 Error::Operation(Some(
593 "Failed to encode CurvePrivateKey ASN.1 structure in DER-encoding".into(),
594 ))
595 })?
596 .into();
597 let private_key_field =
598 OctetStringRef::new(&encoded_curve_private_key).map_err(|_| {
599 Error::Operation(Some(
600 "Failed to construct privateKey field of privateKeyInfo ASN.1 structure"
601 .into(),
602 ))
603 })?;
604 let data = PrivateKeyInfoRef {
605 algorithm: AlgorithmIdentifierRef {
606 oid: ObjectIdentifier::new_unwrap(X448_OID_STRING),
607 parameters: None,
608 },
609 private_key: private_key_field,
610 public_key: None,
611 };
612
613 // Step 3.3. Let result be a new ArrayBuffer associated with the relevant global object
614 // of this [HTML], and containing data.
615 // NOTE: The conversion to a new ArrayBuffer is done in SubtleCrypto::ExportKey.
616 ExportedKey::new_bytes(data.to_der().map_err(|_| {
617 Error::Operation(Some(
618 "Failed to encode privateKeyInfo ASN.1 structure in DER-encoding".into(),
619 ))
620 })?)
621 },
622 // If format is "jwk":
623 KeyFormat::Jwk => {
624 // Step 3.1. Let jwk be a new JsonWebKey dictionary.
625 let mut jwk = JsonWebKey::default();
626
627 // Step 3.2. Set the kty attribute of jwk to "OKP".
628 jwk.kty = Some(DOMString::from_static("OKP"));
629
630 // Step 3.3. Set the crv attribute of jwk to "X448".
631 jwk.crv = Some(DOMString::from_static("X448"));
632
633 // Step 3.4. Set the x attribute of jwk according to the definition in Section 2 of
634 // [RFC8037].
635 match key.handle() {
636 Handle::X448PrivateKey(private_key) => {
637 let public_key = PublicKey::from(private_key);
638 jwk.encode_string_field(JwkStringField::X, public_key.as_bytes());
639 },
640 Handle::X448PublicKey(public_key) => {
641 jwk.encode_string_field(JwkStringField::X, public_key.as_bytes());
642 },
643 _ => {
644 return Err(Error::Operation(Some(
645 "[[handle]] internal slot of key is not an X448 key".into(),
646 )));
647 },
648 }
649
650 // Step 3.5. If the [[type]] internal slot of key is "private"
651 // Set the d attribute of jwk according to the definition in Section 2 of [RFC8037].
652 if key.Type() == KeyType::Private {
653 if let Handle::X448PrivateKey(private_key) = key.handle() {
654 jwk.encode_string_field(JwkStringField::D, private_key.as_bytes());
655 } else {
656 return Err(Error::Operation(Some(
657 "[[handle]] internal slot of key is not an X448 private key".into(),
658 )));
659 }
660 let Handle::X448PrivateKey(private_key) = key.handle() else {
661 return Err(Error::Operation(Some(
662 "[[handle]] internal slot of key is not an X448 private key".into(),
663 )));
664 };
665 jwk.encode_string_field(JwkStringField::D, private_key.as_bytes().as_slice());
666 }
667
668 // Step 3.6. Set the key_ops attribute of jwk to the usages attribute of key.
669 jwk.set_key_ops(key.usages());
670
671 // Step 3.7. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
672 jwk.ext = Some(key.Extractable());
673
674 // Step 3.8. Let result be the result of converting jwk to an ECMAScript Object, as
675 // defined by [WebIDL].
676 // NOTE: The conversion to an ECMAScript Object is done by SubtleCrypto::ExportKey.
677 ExportedKey::new_jwk(jwk)
678 },
679 // If format is "raw":
680 KeyFormat::Raw | KeyFormat::Raw_public => {
681 // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
682 // InvalidAccessError.
683 key.ensure_type(KeyType::Public)?;
684
685 // Step 3.2. Let data be an octet string representing the X448 public key represented by
686 // the [[handle]] internal slot of key.
687 let Handle::X448PublicKey(public_key) = key.handle() else {
688 return Err(Error::Operation(Some(
689 "[[handle]] internal slot of key is not an X448 public key".into(),
690 )));
691 };
692 let data = public_key.as_bytes();
693
694 // Step 3.3. Let result be a new ArrayBuffer associated with the relevant global object
695 // of this [HTML], and containing data.
696 // NOTE: The conversion to a new ArrayBuffer is done in SubtleCrypto::ExportKey.
697 ExportedKey::new_bytes(data.to_vec())
698 },
699 // Otherwise:
700 _ => {
701 // throw a NotSupportedError.
702 return Err(Error::NotSupported(Some(
703 "Unsupported export key format for X448".into(),
704 )));
705 },
706 };
707
708 // Step 4. Return result.
709 Ok(result)
710}
711
712/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
713/// Step 9 - 15, for X448
714pub(crate) fn get_public_key<D: Equivalence>(
715 cx: &mut JSContext,
716 global: &D::GlobalScope,
717 key: &CryptoKey<D>,
718 algorithm: &KeyAlgorithmAndDerivatives,
719 usages: Vec<KeyUsage>,
720) -> Result<DomRoot<CryptoKey<D>>, Error> {
721 // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
722 // identified by algorithm, then throw a SyntaxError.
723 //
724 // NOTE: See "importKey" operation for supported usages
725 usages.ensure_only_contain_entries_from(&[])?;
726
727 // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
728 // private key represented by the [[handle]] internal slot of key.
729 // Step 11. If an error occurred, then throw a OperationError.
730 // Step 12. Set the [[type]] internal slot of publicKey to "public".
731 // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
732 // Step 14. Set the [[extractable]] internal slot of publicKey to true.
733 // Step 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.
734 let Handle::X448PrivateKey(private_key) = key.handle() else {
735 return Err(Error::Operation(Some(
736 "[[handle]] internal slot of key is not an X448 private key".into(),
737 )));
738 };
739 let public_key = CryptoKey::new(
740 cx,
741 global,
742 KeyType::Public,
743 true,
744 algorithm.clone(),
745 usages.normalized_value(),
746 Handle::X448PublicKey(PublicKey::from(private_key)),
747 );
748
749 Ok(public_key)
750}