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