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