Skip to main content

script_webcrypto/subtlecrypto/
ec_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 elliptic_curve::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
6use elliptic_curve::sec1::{ModulusSize, Sec1Point, ToSec1Point, ValidatePublicKey};
7use elliptic_curve::{Curve, FieldBytesSize, Generate, PublicKey, SecretKey};
8use js::context::JSContext;
9use p256::NistP256;
10use p384::NistP384;
11use p521::NistP521;
12use script_bindings::trace::RootedTraceableBox;
13
14use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
15use crate::dom::bindings::codegen::GenericBindings::CryptoKeyBinding::{
16    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
17};
18use crate::dom::bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
19use crate::dom::bindings::error::{Error, ErrorResult};
20use crate::dom::bindings::root::DomRoot;
21use crate::dom::bindings::str::DOMString;
22use crate::subtlecrypto::{
23    CryptoAlgorithm, EcKeyAlgorithm, EcKeyGenParams, EcKeyImportParams, ExportedKey,
24    JsonWebKeyHelper, JwkStringField, KeyAlgorithmAndDerivatives, NAMED_CURVE_P256,
25    NAMED_CURVE_P384, NAMED_CURVE_P521, SUPPORTED_CURVES,
26};
27use crate::traits::Equivalence;
28
29#[derive(PartialEq)]
30pub(crate) enum EcAlgorithm {
31    Ecdsa,
32    Ecdh,
33}
34
35/// <https://w3c.github.io/webcrypto/#ecdsa-operations-generate-key>
36/// <https://w3c.github.io/webcrypto/#ecdh-operations-generate-key>
37pub(crate) fn generate_key<D: Equivalence>(
38    cx: &mut JSContext,
39    global: &D::GlobalScope,
40    ec_algorithm: EcAlgorithm,
41    normalized_algorithm: &EcKeyGenParams,
42    extractable: bool,
43    usages: Vec<KeyUsage>,
44) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
45    match ec_algorithm {
46        EcAlgorithm::Ecdsa => {
47            // Step 1. If usages contains a value which is not one of "sign" or "verify", then throw
48            // a SyntaxError.
49            usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
50        },
51        EcAlgorithm::Ecdh => {
52            // Step 1. If usages contains an entry which is not "deriveKey" or "deriveBits" then
53            // throw a SyntaxError.
54            usages
55                .ensure_only_contain_entries_from(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])?;
56        },
57    }
58
59    // Step 2.
60    // If the namedCurve member of normalizedAlgorithm is "P-256", "P-384" or "P-521":
61    //     Generate an Elliptic Curve key pair, as defined in [RFC6090] with domain parameters for
62    //     the curve identified by the namedCurve member of normalizedAlgorithm.
63    // If the namedCurve member of normalizedAlgorithm is a value specified in an applicable
64    // specification:
65    //     Perform the ECDSA generation steps specified in that specification, passing in
66    //     normalizedAlgorithm and resulting in an elliptic curve key pair.
67    // Otherwise:
68    //     throw a NotSupportedError
69    // Step 3. If performing the key generation operation results in an error, then throw an
70    // OperationError.
71    // NOTE: We currently do not support other applicable specifications.
72    let (private_key_handle, public_key_handle) = match normalized_algorithm.named_curve.as_str() {
73        NAMED_CURVE_P256 => {
74            let private_key = SecretKey::<NistP256>::try_generate().map_err(|_| {
75                Error::Operation(Some("Failed to generate P-256 private key".into()))
76            })?;
77            let public_key = private_key.public_key();
78            (
79                Handle::P256PrivateKey(private_key),
80                Handle::P256PublicKey(public_key),
81            )
82        },
83        NAMED_CURVE_P384 => {
84            let private_key = SecretKey::<NistP384>::try_generate().map_err(|_| {
85                Error::Operation(Some("Failed to generate P-384 private key".into()))
86            })?;
87            let public_key = private_key.public_key();
88            (
89                Handle::P384PrivateKey(private_key),
90                Handle::P384PublicKey(public_key),
91            )
92        },
93        NAMED_CURVE_P521 => {
94            let private_key = SecretKey::<NistP521>::try_generate().map_err(|_| {
95                Error::Operation(Some("Failed to generate P-521 private key".into()))
96            })?;
97            let public_key = private_key.public_key();
98            (
99                Handle::P521PrivateKey(private_key),
100                Handle::P521PublicKey(public_key),
101            )
102        },
103        named_curve => {
104            return Err(Error::NotSupported(Some(format!(
105                "Unsupported named curve: {}",
106                named_curve
107            ))));
108        },
109    };
110
111    // Step 4. Let algorithm be a new EcKeyAlgorithm object.
112    // Step 6. Set the namedCurve attribute of algorithm to equal the namedCurve member of
113    // normalizedAlgorithm.
114    let algorithm = EcKeyAlgorithm {
115        name: match ec_algorithm {
116            EcAlgorithm::Ecdsa => {
117                // Step 5. Set the name attribute of algorithm to "ECDSA".
118                CryptoAlgorithm::Ecdsa
119            },
120            EcAlgorithm::Ecdh => {
121                // Step 5. Set the name member of algorithm to "ECDH".
122                CryptoAlgorithm::Ecdh
123            },
124        },
125        named_curve: normalized_algorithm.named_curve.clone(),
126    };
127
128    // Step 7. Let publicKey be a new CryptoKey representing the public key of the generated key pair.
129    // Step 8. Set the [[type]] internal slot of publicKey to "public"
130    // Step 9. Set the [[algorithm]] internal slot of publicKey to algorithm.
131    // Step 10. Set the [[extractable]] internal slot of publicKey to true.
132    let public_key_usage = match ec_algorithm {
133        EcAlgorithm::Ecdsa => {
134            // Step 11. Set the [[usages]] internal slot of publicKey to be the usage intersection
135            // of usages and [ "verify" ].
136            usages.usage_intersection(&[KeyUsage::Verify])
137        },
138        EcAlgorithm::Ecdh => {
139            // Step 11. Set the [[usages]] internal slot of publicKey to be the empty list.
140            Vec::new()
141        },
142    };
143    let public_key = CryptoKey::new(
144        cx,
145        global,
146        KeyType::Public,
147        true,
148        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm.clone()),
149        public_key_usage,
150        public_key_handle,
151    );
152
153    // Step 12. Let privateKey be a new CryptoKey representing the private key of the generated key pair.
154    // Step 13. Set the [[type]] internal slot of privateKey to "private"
155    // Step 14. Set the [[algorithm]] internal slot of privateKey to algorithm.
156    // Step 15. Set the [[extractable]] internal slot of privateKey to extractable.
157    let private_key_usage = match ec_algorithm {
158        EcAlgorithm::Ecdsa => {
159            // Step 16. Set the [[usages]] internal slot of privateKey to be the usage intersection
160            // of usages and [ "sign" ].
161            usages.usage_intersection(&[KeyUsage::Sign])
162        },
163        EcAlgorithm::Ecdh => {
164            // Step 16. Set the [[usages]] internal slot of privateKey to be the usage intersection
165            // of usages and [ "deriveKey", "deriveBits" ].
166            usages.usage_intersection(&[KeyUsage::DeriveKey, KeyUsage::DeriveBits])
167        },
168    };
169    let private_key = CryptoKey::new(
170        cx,
171        global,
172        KeyType::Private,
173        extractable,
174        KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
175        private_key_usage,
176        private_key_handle,
177    );
178
179    // Step 17. Let result be a new CryptoKeyPair dictionary.
180    // Step 18. Set the publicKey attribute of result to be publicKey.
181    // Step 19. Set the privateKey attribute of result to be privateKey.
182    let result = RootedTraceableBox::new(CryptoKeyPair {
183        publicKey: Some(public_key.as_traced()),
184        privateKey: Some(private_key.as_traced()),
185    });
186
187    // Step 20. Return result.
188    Ok(result)
189}
190
191/// <https://w3c.github.io/webcrypto/#ecdsa-operations-import-key>
192/// <https://w3c.github.io/webcrypto/#ecdh-operations-import-key>
193///
194/// This implementation is based on the specification of the importKey operation of ECDSA. When
195/// format is "jwk", Step 3.2 and Step 3.3 in the specification of the importKey operation of ECDH
196/// are combined into a single step, and Step 3.9.1 to Step 3.9.3 here are skipped for ECDH.
197#[allow(clippy::too_many_arguments)]
198pub(crate) fn import_key<D: Equivalence>(
199    cx: &mut JSContext,
200    global: &D::GlobalScope,
201    ec_algorithm: EcAlgorithm,
202    normalized_algorithm: &EcKeyImportParams,
203    format: KeyFormat,
204    key_data: &[u8],
205    extractable: bool,
206    usages: Vec<KeyUsage>,
207) -> Result<DomRoot<CryptoKey<D>>, Error> {
208    // Step 1. If the namedCurve member of normalizedAlgorithm is not one of "P-256", "P-384" or
209    // "P-521", and is not a value specified in an applicable specification that specifies the use
210    // of that value with ECDSA, then throw a NotSupportedError.
211    if !SUPPORTED_CURVES.contains(&normalized_algorithm.named_curve.as_str()) {
212        return Err(Error::NotSupported(Some("Unsupported namedCurve".into())));
213    }
214
215    // Step 2. Let keyData be the key data to be imported.
216
217    // Step 3.
218    let key = match format {
219        // If format is "spki":
220        KeyFormat::Spki => {
221            match ec_algorithm {
222                EcAlgorithm::Ecdsa => {
223                    // Step 3.1. If usages contains a value which is not "verify" then throw a
224                    // SyntaxError.
225                    usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
226                },
227                EcAlgorithm::Ecdh => {
228                    // Step 3.1. If usages is not empty then throw a SyntaxError.
229                    usages.ensure_only_contain_entries_from(&[])?;
230                },
231            }
232
233            // Step 3.2. Let spki be the result of running the parse a subjectPublicKeyInfo
234            // algorithm over keyData
235            // Step 3.3. If an error occurred while parsing, then throw a DataError.
236            // Step 3.4. If the algorithm object identifier field of the algorithm
237            // AlgorithmIdentifier field of spki is not equal to the id-ecPublicKey object
238            // identifier defined in [RFC5480], then throw a DataError.
239            // Step 3.5. If the parameters field of the algorithm AlgorithmIdentifier field of spki
240            // is absent, then throw a DataError.
241            // Step 3.6. Let params be the parameters field of the algorithm AlgorithmIdentifier
242            // field of spki.
243            // Step 3.7. If params is not an instance of the ECParameters ASN.1 type defined in
244            // [RFC5480] that specifies a namedCurve, then throw a DataError.
245            // Step 3.8. Let namedCurve be a string whose initial value is undefined.
246            // Step 3.9.
247            //     If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
248            //         Set namedCurve "P-256".
249            //     If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
250            //         Set namedCurve "P-384".
251            //     If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
252            //         Set namedCurve "P-521".
253            // Step 3.10.
254            //     If namedCurve is not undefined:
255            //         Step 3.10.1. Let publicKey be the Elliptic Curve public key identified by
256            //         performing the conversion steps defined in Section 2.3.4 of [SEC1] using the
257            //         subjectPublicKey field of spki. The uncompressed point format MUST be
258            //         supported.
259            //         Step 3.10.2. If the implementation does not support the compressed point
260            //         format and a compressed point is provided, throw a DataError.
261            //         Step 3.10.3. If a decode error occurs or an identity point is found, throw a
262            //         DataError.
263            //         Step 3.10.4. Let key be a new CryptoKey that represents publicKey.
264            //     Otherwise:
265            //         Step 3.10.1. Perform any key import steps defined by other applicable
266            //         specifications, passing format, spki and obtaining namedCurve and key.
267            //         Step 3.10.2. If an error occurred or there are no applicable specifications,
268            //         throw a DataError.
269            // Step 3.11. If namedCurve is defined, and not equal to the namedCurve member of
270            // normalizedAlgorithm, throw a DataError.
271            // Step 3.12. If the public key value is not a valid point on the Elliptic Curve
272            // identified by the namedCurve member of normalizedAlgorithm throw a DataError.
273            //
274            // NOTE: The new CryptoKey in Step 3.10.4 is created in Step 3.13 - 3.17.
275            let handle = match normalized_algorithm.named_curve.as_str() {
276                NAMED_CURVE_P256 => Handle::P256PublicKey(
277                    PublicKey::<NistP256>::from_public_key_der(key_data).map_err(|_| {
278                        Error::Data(Some(
279                            "Failed to parse the P-256 elliptic-curve public key in SPKI format"
280                                .into(),
281                        ))
282                    })?,
283                ),
284                NAMED_CURVE_P384 => Handle::P384PublicKey(
285                    PublicKey::<NistP384>::from_public_key_der(key_data).map_err(|_| {
286                        Error::Data(Some(
287                            "Failed to parse the P-384 elliptic-curve public key in SPKI format"
288                                .into(),
289                        ))
290                    })?,
291                ),
292                NAMED_CURVE_P521 => Handle::P521PublicKey(
293                    PublicKey::<NistP521>::from_public_key_der(key_data).map_err(|_| {
294                        Error::Data(Some(
295                            "Failed to parse the P-521 elliptic-curve public key in SPKI format"
296                                .into(),
297                        ))
298                    })?,
299                ),
300                _ => return Err(Error::Data(Some("Unsupported namedCurve".into()))),
301            };
302
303            // Step 3.13. Set the [[type]] internal slot of key to "public"
304            // Step 3.14. Let algorithm be a new EcKeyAlgorithm.
305            // Step 3.16. Set the namedCurve attribute of algorithm to namedCurve.
306            // Step 3.17. Set the [[algorithm]] internal slot of key to algorithm.
307            let algorithm = EcKeyAlgorithm {
308                name: match ec_algorithm {
309                    EcAlgorithm::Ecdsa => {
310                        // Step 3.15. Set the name attribute of algorithm to "ECDSA".
311                        CryptoAlgorithm::Ecdsa
312                    },
313                    EcAlgorithm::Ecdh => {
314                        // Step 3.15. Set the name attribute of algorithm to "ECDH".
315                        CryptoAlgorithm::Ecdh
316                    },
317                },
318                named_curve: normalized_algorithm.named_curve.clone(),
319            };
320            CryptoKey::new(
321                cx,
322                global,
323                KeyType::Public,
324                extractable,
325                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
326                usages.normalized_value(),
327                handle,
328            )
329        },
330        // If format is "pkcs8":
331        KeyFormat::Pkcs8 => {
332            match ec_algorithm {
333                EcAlgorithm::Ecdsa => {
334                    // Step 3.1. If usages contains a value which is not "sign" then throw a
335                    // SyntaxError.
336                    usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?;
337                },
338                EcAlgorithm::Ecdh => {
339                    // Step 3.1. If usages contains an entry which is not "deriveKey" or
340                    // "deriveBits" then throw a SyntaxError.
341                    usages.ensure_only_contain_entries_from(&[
342                        KeyUsage::DeriveKey,
343                        KeyUsage::DeriveBits,
344                    ])?;
345                },
346            }
347
348            // Step 3.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
349            // algorithm over keyData.
350            // Step 3.3. If an error occurs while parsing, throw a DataError.
351            // Step 3.4. If the algorithm object identifier field of the privateKeyAlgorithm
352            // PrivateKeyAlgorithm field of privateKeyInfo is not equal to the id-ecPublicKey
353            // object identifier defined in [RFC5480], throw a DataError.
354            // Step 3.5. If the parameters field of the privateKeyAlgorithm
355            // PrivateKeyAlgorithmIdentifier field of privateKeyInfo is not present, throw a
356            // DataError.
357            // Step 3.6. Let params be the parameters field of the privateKeyAlgorithm
358            // PrivateKeyAlgorithmIdentifier field of privateKeyInfo.
359            // Step 3.7. If params is not an instance of the ECParameters ASN.1 type defined in
360            // [RFC5480] that specifies a namedCurve, then throw a DataError.
361            // Step 3.8. Let namedCurve be a string whose initial value is undefined.
362            // Step 3.9.
363            //     If params is equivalent to the secp256r1 object identifier defined in [RFC5480]:
364            //         Set namedCurve to "P-256".
365            //     If params is equivalent to the secp384r1 object identifier defined in [RFC5480]:
366            //         Set namedCurve to "P-384".
367            //     If params is equivalent to the secp521r1 object identifier defined in [RFC5480]:
368            //         Set namedCurve to "P-521".
369            // Step 3.10.
370            //     If namedCurve is not undefined:
371            //         Step 3.10.1. Let ecPrivateKey be the result of performing the parse an ASN.1
372            //         structure algorithm, with data as the privateKey field of privateKeyInfo,
373            //         structure as the ASN.1 ECPrivateKey structure specified in Section 3 of
374            //         [RFC5915], and exactData set to true.
375            //         Step 3.10.2. If an error occurred while parsing, then throw a DataError.
376            //         Step 3.10.3. If the parameters field of ecPrivateKey is present, and is not
377            //         an instance of the namedCurve ASN.1 type defined in [RFC5480], or does not
378            //         contain the same object identifier as the parameters field of the
379            //         privateKeyAlgorithm PrivateKeyAlgorithmIdentifier field of privateKeyInfo,
380            //         then throw a DataError.
381            //         Step 3.10.4. Let key be a new CryptoKey that represents the Elliptic Curve
382            //         private key identified by performing the conversion steps defined in Section
383            //         3 of [RFC5915] using ecPrivateKey.
384            //     Otherwise:
385            //         Step 3.10.1. Perform any key import steps defined by other applicable
386            //         specifications, passing format, privateKeyInfo and obtaining namedCurve and
387            //         key.
388            //         Step 3.10.2. If an error occurred or there are no applicable specifications,
389            //         throw a DataError.
390            // Step 3.11. If namedCurve is defined, and not equal to the namedCurve member of
391            // normalizedAlgorithm, throw a DataError.
392            // Step 3.12. If the private key value is not a valid point on the Elliptic Curve
393            // identified by the namedCurve member of normalizedAlgorithm throw a DataError.
394            //
395            // NOTE: The new CryptoKey in Step 3.10.4 is created in Step 3.13 - 3.17.
396            let handle = match normalized_algorithm.named_curve.as_str() {
397                NAMED_CURVE_P256 => Handle::P256PrivateKey(
398                    SecretKey::<NistP256>::from_pkcs8_der(key_data).map_err(|_| {
399                        Error::Data(Some(
400                            "Failed to parse the P-256 elliptic-curve private key in PKCS#8 format"
401                                .into(),
402                        ))
403                    })?,
404                ),
405                NAMED_CURVE_P384 => Handle::P384PrivateKey(
406                    SecretKey::<NistP384>::from_pkcs8_der(key_data).map_err(|_| {
407                        Error::Data(Some(
408                            "Failed to parse the P-384 elliptic-curve private key in PKCS#8 format"
409                                .into(),
410                        ))
411                    })?,
412                ),
413                NAMED_CURVE_P521 => Handle::P521PrivateKey(
414                    SecretKey::<NistP521>::from_pkcs8_der(key_data).map_err(|_| {
415                        Error::Data(Some(
416                            "Failed to parse the P-521 elliptic-curve private key in PKCS#8 format"
417                                .into(),
418                        ))
419                    })?,
420                ),
421                _ => return Err(Error::Data(Some("Unsupported namedCurve".into()))),
422            };
423
424            // Step 3.13. Set the [[type]] internal slot of key to "private".
425            // Step 3.14. Let algorithm be a new EcKeyAlgorithm.
426            // Step 3.16. Set the namedCurve attribute of algorithm to namedCurve.
427            // Step 3.17. Set the [[algorithm]] internal slot of key to algorithm.
428            let algorithm = EcKeyAlgorithm {
429                name: match ec_algorithm {
430                    EcAlgorithm::Ecdsa => {
431                        // Step 3.15. Set the name attribute of algorithm to "ECDSA".
432                        CryptoAlgorithm::Ecdsa
433                    },
434                    EcAlgorithm::Ecdh => {
435                        // Step 3.15. Set the name attribute of algorithm to "ECDH".
436                        CryptoAlgorithm::Ecdh
437                    },
438                },
439                named_curve: normalized_algorithm.named_curve.clone(),
440            };
441            CryptoKey::new(
442                cx,
443                global,
444                KeyType::Private,
445                extractable,
446                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
447                usages.normalized_value(),
448                handle,
449            )
450        },
451        // If format is "jwk":
452        KeyFormat::Jwk => {
453            // Step 3.1.
454            // If keyData is a JsonWebKey dictionary:
455            //     Let jwk equal keyData.
456            // Otherwise:
457            //     Throw a DataError.
458            let jwk = JsonWebKey::parse(cx, key_data)?;
459
460            match ec_algorithm {
461                EcAlgorithm::Ecdsa => {
462                    // Step 3.2. If the d field is present and usages contains a value which is not
463                    // "sign", or, if the d field is not present and usages contains a value which
464                    // is not "verify" then throw a SyntaxError.
465                    match jwk.d.as_ref() {
466                        Some(_) => usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?,
467                        None => usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?,
468                    }
469                },
470                EcAlgorithm::Ecdh => {
471                    // Step 3.2. If the d field is present and if usages contains an entry which is
472                    // not "deriveKey" or "deriveBits" then throw a SyntaxError. If the d field is
473                    // not present and if usages is not empty then throw a SyntaxError.
474                    match jwk.d.as_ref() {
475                        Some(_) => usages.ensure_only_contain_entries_from(&[
476                            KeyUsage::DeriveKey,
477                            KeyUsage::DeriveBits,
478                        ])?,
479                        None => usages.ensure_only_contain_entries_from(&[])?,
480                    }
481                },
482            }
483
484            // Step 3.3. If the kty field of jwk is not "EC", then throw a DataError.
485            if jwk.kty.as_ref().is_none_or(|kty| kty != "EC") {
486                return Err(Error::Data(Some("JWK `kty` field is not \"EC\"".into())));
487            }
488
489            match ec_algorithm {
490                EcAlgorithm::Ecdsa => {
491                    // Step 3.4. If usages is non-empty and the use field of jwk is present and is
492                    // not "sig", then throw a DataError.
493                    if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "sig") {
494                        return Err(Error::Data(Some(
495                            "Usages is not empty, JWK `use` field is present, \
496                                and it is not \"sign\""
497                                .into(),
498                        )));
499                    }
500                },
501                EcAlgorithm::Ecdh => {
502                    // Step 3.4. If usages is non-empty and the use field of jwk is present and is
503                    // not equal to "enc" then throw a DataError.
504                    if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
505                        return Err(Error::Data(Some(
506                            "Usages is not empty, JWK `use` field is present, \
507                                and it is not \"enc\""
508                                .into(),
509                        )));
510                    }
511                },
512            }
513
514            // Step 3.5. If the key_ops field of jwk is present, and is invalid according to the
515            // requirements of JSON Web Key [JWK], or it does not contain all of the specified
516            // usages values, then throw a DataError.
517            jwk.check_key_ops(&usages)?;
518
519            // Step 3.6. If the ext field of jwk is present and has the value false and extractable
520            // is true, then throw a DataError.
521            if jwk.ext.is_some_and(|ext| !ext) && extractable {
522                return Err(Error::Data(Some("JWK is not extractable".into())));
523            }
524
525            // Step 3.7. Let namedCurve be a string whose value is equal to the crv field of jwk.
526            // Step 3.8. If namedCurve is not equal to the namedCurve member of
527            // normalizedAlgorithm, throw a DataError.
528            let named_curve = jwk
529                .crv
530                .as_ref()
531                .filter(|crv| **crv == normalized_algorithm.named_curve)
532                .map(|crv| crv.to_string())
533                .ok_or(Error::Data(Some(
534                    "JWK named curve does not match algorithm named curve".into(),
535                )))?;
536
537            // Step 3.9.
538            // If namedCurve is "P-256", "P-384" or "P-521":
539            let (handle, key_type) = if matches!(
540                named_curve.as_str(),
541                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
542            ) {
543                if ec_algorithm == EcAlgorithm::Ecdsa {
544                    // Step 3.9.1. Let algNamedCurve be a string whose initial value is undefined.
545                    // Step 3.9.2.
546                    // If the alg field is not present:
547                    //     Let algNamedCurve be undefined.
548                    // If the alg field is equal to the string "ES256":
549                    //     Let algNamedCurve be the string "P-256".
550                    // If the alg field is equal to the string "ES384":
551                    //     Let algNamedCurve be the string "P-384".
552                    // If the alg field is equal to the string "ES512":
553                    //     Let algNamedCurve be the string "P-521".
554                    // otherwise:
555                    //     throw a DataError.
556                    let alg = jwk.alg.as_ref().map(|alg| alg.to_string());
557                    let alg_named_curve = match alg.as_deref() {
558                        None => None,
559                        Some("ES256") => Some(NAMED_CURVE_P256),
560                        Some("ES384") => Some(NAMED_CURVE_P384),
561                        Some("ES521") => Some(NAMED_CURVE_P521),
562                        Some(alg) => {
563                            return Err(Error::Data(Some(format!(
564                                "Unsupported alg field in JsonWebKey: {}",
565                                alg
566                            ))));
567                        },
568                    };
569
570                    // Step 3.9.3. If algNamedCurve is defined, and is not equal to namedCurve,
571                    // throw a DataError.
572                    if alg_named_curve.is_some_and(|alg_named_curve| alg_named_curve != named_curve)
573                    {
574                        return Err(Error::Data(Some(
575                            "The algNamedCurve is defined, and is not equal to namedCurve".into(),
576                        )));
577                    }
578                }
579
580                // Step 3.9.4.
581                // If the d field is present:
582                if jwk.d.is_some() {
583                    // Step 3.9.4.1. If jwk does not meet the requirements of Section 6.2.2 of JSON
584                    // Web Algorithms [JWA], then throw a DataError.
585                    let x = jwk.decode_required_string_field(JwkStringField::X)?;
586                    let y = jwk.decode_required_string_field(JwkStringField::Y)?;
587                    let d = jwk.decode_required_string_field(JwkStringField::D)?;
588
589                    // Step 3.9.4.2. Let key be a new CryptoKey object that represents the Elliptic
590                    // Curve private key identified by interpreting jwk according to Section 6.2.2
591                    // of JSON Web Algorithms [JWA].
592                    // NOTE: CryptoKey is created in Step 3.11 - 3.14.
593                    let handle = match named_curve.as_str() {
594                        NAMED_CURVE_P256 => {
595                            let private_key =
596                                SecretKey::<NistP256>::from_slice(&d).map_err(|_| {
597                                    Error::Data(Some("Failed to parse P-256 private key".into()))
598                                })?;
599                            validate_public_key::<NistP256>(
600                                &private_key,
601                                &x_y_to_sec1_bytes(&x, &y),
602                            )?;
603                            Handle::P256PrivateKey(private_key)
604                        },
605                        NAMED_CURVE_P384 => {
606                            let private_key =
607                                SecretKey::<NistP384>::from_slice(&d).map_err(|_| {
608                                    Error::Data(Some("Failed to parse P-384 private key".into()))
609                                })?;
610                            validate_public_key::<NistP384>(
611                                &private_key,
612                                &x_y_to_sec1_bytes(&x, &y),
613                            )?;
614                            Handle::P384PrivateKey(private_key)
615                        },
616                        NAMED_CURVE_P521 => {
617                            let private_key =
618                                SecretKey::<NistP521>::from_slice(&d).map_err(|_| {
619                                    Error::Data(Some("Failed to parse P-521 private key".into()))
620                                })?;
621                            validate_public_key::<NistP521>(
622                                &private_key,
623                                &x_y_to_sec1_bytes(&x, &y),
624                            )?;
625                            Handle::P521PrivateKey(private_key)
626                        },
627                        _ => unreachable!(),
628                    };
629
630                    // Step 3.9.4.3. Set the [[type]] internal slot of Key to "private".
631                    // NOTE: CryptoKey is created in Step 3.11 - 3.14.
632                    let key_type = KeyType::Private;
633
634                    (handle, key_type)
635                }
636                // Otherwise:
637                else {
638                    // Step 3.9.4.1. If jwk does not meet the requirements of Section 6.2.1 of JSON
639                    // Web Algorithms [JWA], then throw a DataError.
640                    let x = jwk.decode_required_string_field(JwkStringField::X)?;
641                    let y = jwk.decode_required_string_field(JwkStringField::Y)?;
642
643                    // Step 3.9.4.2. Let key be a new CryptoKey object that represents the Elliptic
644                    // Curve public key identified by interpreting jwk according to Section 6.2.1 of
645                    // JSON Web Algorithms [JWA].
646                    // NOTE: CryptoKey is created in Step 3.11 - 3.14.
647                    let handle = match named_curve.as_str() {
648                        NAMED_CURVE_P256 => {
649                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
650                            let public_key = PublicKey::<NistP256>::from_sec1_bytes(&sec1_bytes)
651                                .map_err(|_| {
652                                    Error::Data(Some("Failed to decode P-256 public key".into()))
653                                })?;
654                            Handle::P256PublicKey(public_key)
655                        },
656                        NAMED_CURVE_P384 => {
657                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
658                            let public_key = PublicKey::<NistP384>::from_sec1_bytes(&sec1_bytes)
659                                .map_err(|_| {
660                                    Error::Data(Some("Failed to decode P-384 public key".into()))
661                                })?;
662                            Handle::P384PublicKey(public_key)
663                        },
664                        NAMED_CURVE_P521 => {
665                            let sec1_bytes = x_y_to_sec1_bytes(&x, &y);
666                            let public_key = PublicKey::<NistP521>::from_sec1_bytes(&sec1_bytes)
667                                .map_err(|_| {
668                                    Error::Data(Some("Failed to decode P-521 public key".into()))
669                                })?;
670                            Handle::P521PublicKey(public_key)
671                        },
672                        _ => unreachable!(),
673                    };
674
675                    // Step 3.9.4.4. Set the [[type]] internal slot of Key to "public".
676                    // NOTE: CryptoKey is created in Step 3.11 - 3.14.
677                    let key_type = KeyType::Public;
678
679                    (handle, key_type)
680                }
681            }
682            // Otherwise
683            else {
684                // Step 3.9.1. Perform any key import steps defined by other applicable
685                // specifications, passing format, jwk and obtaining key.
686                // Step 3.9.2. If an error occurred or there are no applicable specifications, throw
687                // a DataError.
688                // NOTE: We currently do not support applicable specifications.
689                return Err(Error::NotSupported(Some("Unsupported namedCurve".into())));
690            };
691
692            // Step 3.10. If the key value is not a valid point on the Elliptic Curve identified by
693            // the namedCurve member of normalizedAlgorithm throw a DataError.
694            // NOTE: Done in Step 3.9.
695
696            // Step 3.11. Let algorithm be a new instance of an EcKeyAlgorithm object.
697            // Step 3.13. Set the namedCurve attribute of algorithm to namedCurve.
698            // Step 3.14. Set the [[algorithm]] internal slot of key to algorithm.
699            let algorithm = EcKeyAlgorithm {
700                name: match ec_algorithm {
701                    EcAlgorithm::Ecdsa => {
702                        // Step 3.12. Set the name attribute of algorithm to "ECDSA".
703                        CryptoAlgorithm::Ecdsa
704                    },
705                    EcAlgorithm::Ecdh => {
706                        // Step 3.12. Set the name attribute of algorithm to "ECDH".
707                        CryptoAlgorithm::Ecdh
708                    },
709                },
710                named_curve,
711            };
712            CryptoKey::new(
713                cx,
714                global,
715                key_type,
716                extractable,
717                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
718                usages.normalized_value(),
719                handle,
720            )
721        },
722        // If format is "raw":
723        KeyFormat::Raw | KeyFormat::Raw_public => {
724            // Step 3.1. If the namedCurve member of normalizedAlgorithm is not a named curve, then
725            // throw a DataError.
726            if !SUPPORTED_CURVES
727                .iter()
728                .any(|&supported_curve| supported_curve == normalized_algorithm.named_curve)
729            {
730                return Err(Error::Data(Some("Unsupported namedCurve".into())));
731            }
732
733            match ec_algorithm {
734                EcAlgorithm::Ecdsa => {
735                    // Step 3.2. If usages contains a value which is not "verify" then throw a
736                    // SyntaxError.
737                    usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
738                },
739                EcAlgorithm::Ecdh => {
740                    // Step 3.2. If usages is not the empty list, then throw a SyntaxError.
741                    usages.ensure_only_contain_entries_from(&[])?;
742                },
743            }
744
745            // Step 3.3.
746            // If namedCurve is "P-256", "P-384" or "P-521":
747            let handle = if matches!(
748                normalized_algorithm.named_curve.as_str(),
749                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
750            ) {
751                // Step 3.3.1. Let Q be the Elliptic Curve public key on the curve identified by the
752                // namedCurve member of normalizedAlgorithm identified by performing the conversion
753                // steps defined in Section 2.3.4 of [SEC1] to keyData. The uncompressed point
754                // format MUST be supported.
755                // Step 3.3.2. If the implementation does not support the compressed point format
756                // and a compressed point is provided, throw a DataError.
757                // Step 3.3.3. If a decode error occurs or an identity point is found, throw a
758                // DataError.
759                match normalized_algorithm.named_curve.as_str() {
760                    NAMED_CURVE_P256 => {
761                        let q = PublicKey::<NistP256>::from_sec1_bytes(key_data).map_err(|_| {
762                            Error::Data(Some("Failed to decode P-256 public key".into()))
763                        })?;
764                        Handle::P256PublicKey(q)
765                    },
766                    NAMED_CURVE_P384 => {
767                        let q = PublicKey::<NistP384>::from_sec1_bytes(key_data).map_err(|_| {
768                            Error::Data(Some("Failed to decode P-384 public key".into()))
769                        })?;
770                        Handle::P384PublicKey(q)
771                    },
772                    NAMED_CURVE_P521 => {
773                        let q = PublicKey::<NistP521>::from_sec1_bytes(key_data).map_err(|_| {
774                            Error::Data(Some("Failed to decode P-521 public key".into()))
775                        })?;
776                        Handle::P521PublicKey(q)
777                    },
778                    _ => unreachable!(),
779                }
780
781                // Step 3.3.4. Let key be a new CryptoKey that represents Q.
782                // NOTE: CryptoKey is created in Step 3.7 - 3.8.
783            }
784            // Otherwise:
785            else {
786                // Step 3.3.1. Perform any key import steps defined by other applicable
787                // specifications, passing format, keyData and obtaining key.
788                // Step 3.3.2. If an error occurred or there are no applicable specifications,
789                // throw a DataError.
790                // NOTE: We currently do not support applicable specifications.
791                return Err(Error::NotSupported(Some("Unsupported namedCurve".into())));
792            };
793
794            // Step 3.4. Let algorithm be a new EcKeyAlgorithm object.
795            // Step 3.6. Set the namedCurve attribute of algorithm to equal the namedCurve member
796            // of normalizedAlgorithm.
797            let algorithm = EcKeyAlgorithm {
798                name: match ec_algorithm {
799                    EcAlgorithm::Ecdsa => {
800                        // Step 3.5. Set the name attribute of algorithm to "ECDSA".
801                        CryptoAlgorithm::Ecdsa
802                    },
803                    EcAlgorithm::Ecdh => {
804                        // Step 3.5. Set the name attribute of algorithm to "ECDH".
805                        CryptoAlgorithm::Ecdh
806                    },
807                },
808                named_curve: normalized_algorithm.named_curve.clone(),
809            };
810
811            // Step 3.7. Set the [[type]] internal slot of key to "public"
812            // Step 3.8. Set the [[algorithm]] internal slot of key to algorithm.
813            CryptoKey::new(
814                cx,
815                global,
816                KeyType::Public,
817                extractable,
818                KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm),
819                usages.normalized_value(),
820                handle,
821            )
822        },
823        // Otherwise:
824        _ => {
825            // throw a NotSupportedError.
826            return Err(Error::NotSupported(Some("Unsupported key format".into())));
827        },
828    };
829
830    // Step 3. Return key.
831    Ok(key)
832}
833
834/// <https://w3c.github.io/webcrypto/#ecdsa-operations-export-key>
835/// <https://w3c.github.io/webcrypto/#ecdh-operations-export-key>
836pub(crate) fn export_key<D: Equivalence>(
837    format: KeyFormat,
838    key: &CryptoKey<D>,
839) -> Result<ExportedKey, Error> {
840    // Step 1. Let key be the CryptoKey to be exported.
841
842    // Step 2. If the underlying cryptographic key material represented by the [[handle]] internal
843    // slot of key cannot be accessed, then throw an OperationError.
844    // NOTE: Done in Step 3.
845
846    // Step 3.
847    let result = match format {
848        // If format is "spki":
849        KeyFormat::Spki => {
850            // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
851            // InvalidAccessError.
852            key.ensure_type(KeyType::Public)?;
853
854            // Step 3.2.
855            // Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in
856            // [RFC5280] with the following properties:
857            //     * Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the
858            //       following properties:
859            //         * Set the algorithm field to the OID id-ecPublicKey defined in [RFC5480].
860            //         * Set the parameters field to an instance of the ECParameters ASN.1 type
861            //           defined in [RFC5480] as follows:
862            //             If the namedCurve attribute of the [[algorithm]] internal slot of key is
863            //             "P-256", "P-384" or "P-521":
864            //                 Let keyData be the byte sequence that represents the Elliptic Curve
865            //                 public key represented by the [[handle]] internal slot of key
866            //                 according to the encoding rules specified in Section 2.2 of
867            //                 [RFC5480] and using the uncompressed form. and keyData.
868            //                     If the namedCurve attribute of the [[algorithm]] internal slot
869            //                     of key is "P-256":
870            //                         Set parameters to the namedCurve choice with value equal to
871            //                         the object identifier secp256r1 defined in [RFC5480]
872            //                     If the namedCurve attribute of the [[algorithm]] internal slot
873            //                     of key is "P-384":
874            //                         Set parameters to the namedCurve choice with value equal to
875            //                         the object identifier secp384r1 defined in [RFC5480]
876            //                     If the namedCurve attribute of the [[algorithm]] internal slot
877            //                     of key is "P-521":
878            //                         Set parameters to the namedCurve choice with value equal to
879            //                         the object identifier secp521r1 defined in [RFC5480]
880            //             Otherwise:
881            //                 1. Perform any key export steps defined by other applicable
882            //                    specifications, passing format and the namedCurve attribute of
883            //                    the [[algorithm]] internal slot of key and obtaining
884            //                    namedCurveOid and keyData.
885            //                 2. Set parameters to the namedCurve choice with value equal to the
886            //                    object identifier namedCurveOid.
887            //     * Set the subjectPublicKey field to keyData.
888            // NOTE: We currently do not support other applicable specifications.
889            let data = match key.handle() {
890                Handle::P256PublicKey(public_key) => public_key.to_public_key_der(),
891                Handle::P384PublicKey(public_key) => public_key.to_public_key_der(),
892                Handle::P521PublicKey(public_key) => public_key.to_public_key_der(),
893                _ => {
894                    return Err(Error::Operation(Some(
895                        "The key is not an elliptic curve public key".into(),
896                    )));
897                },
898            }
899            .map_err(|_| {
900                Error::Operation(Some("Failed to export elliptic curve public key".into()))
901            })?;
902
903            // Step 3.3. Let result be the result of DER-encoding data.
904            ExportedKey::new_bytes(data.to_vec())
905        },
906        // If format is "pkcs8":
907        KeyFormat::Pkcs8 => {
908            // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
909            // InvalidAccessError.
910            key.ensure_type(KeyType::Private)?;
911
912            // Step 3.2.
913            // Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208]
914            // with the following properties:
915            //     * Set the version field to 0.
916            //     * Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1
917            //       type with the following properties:
918            //         * Set the algorithm field to the OID id-ecPublicKey defined in [RFC5480].
919            //         * Set the parameters field to an instance of the ECParameters ASN.1 type
920            //           defined in [RFC5480] as follows:
921            //             If the namedCurve attribute of the [[algorithm]] internal slot of key is
922            //             "P-256", "P-384" or "P-521":
923            //                 Let keyData be the result of DER-encoding an instance of the
924            //                 ECPrivateKey structure defined in Section 3 of [RFC5915] for the
925            //                 Elliptic Curve private key represented by the [[handle]] internal
926            //                 slot of key and that conforms to the following:
927            //                     * The parameters field is present, and is equivalent to the
928            //                       parameters field of the privateKeyAlgorithm field of this
929            //                       PrivateKeyInfo ASN.1 structure.
930            //                     * The publicKey field is present and represents the Elliptic
931            //                       Curve public key associated with the Elliptic Curve private key
932            //                       represented by the [[handle]] internal slot of key.
933            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
934            //                       of key is "P-256":
935            //                         Set parameters to the namedCurve choice with value equal to
936            //                         the object identifier secp256r1 defined in [RFC5480]
937            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
938            //                       of key is "P-384":
939            //                         Set parameters to the namedCurve choice with value equal to
940            //                         the object identifier secp384r1 defined in [RFC5480]
941            //                     * If the namedCurve attribute of the [[algorithm]] internal slot
942            //                       of key is "P-521":
943            //                         Set parameters to the namedCurve choice with value equal to
944            //                         the object identifier secp521r1 defined in [RFC5480]
945            //             Otherwise:
946            //                 1. Perform any key export steps defined by other applicable
947            //                    specifications, passing format and the namedCurve attribute of
948            //                    the [[algorithm]] internal slot of key and obtaining
949            //                    namedCurveOid and keyData.
950            //                 2. Set parameters to the namedCurve choice with value equal to the
951            //                    object identifier namedCurveOid.
952            //     * Set the privateKey field to keyData.
953            // NOTE: We currently do not support other applicable specifications.
954            let data = match key.handle() {
955                Handle::P256PrivateKey(private_key) => private_key.to_pkcs8_der(),
956                Handle::P384PrivateKey(private_key) => private_key.to_pkcs8_der(),
957                Handle::P521PrivateKey(private_key) => private_key.to_pkcs8_der(),
958                _ => {
959                    return Err(Error::Operation(Some(
960                        "The key is not an elliptic curve public key".into(),
961                    )));
962                },
963            }
964            .map_err(|_| {
965                Error::Operation(Some("Failed to export elliptic curve private key".into()))
966            })?;
967
968            // Step 3.3. Let result be the result of DER-encoding data.
969            ExportedKey::new_bytes(data.as_bytes().to_vec())
970        },
971        // If format is "jwk":
972        KeyFormat::Jwk => {
973            // Step 3.1. Let jwk be a new JsonWebKey dictionary.
974            let mut jwk = JsonWebKey::default();
975
976            // Step 3.2. Set the kty attribute of jwk to "EC".
977            jwk.kty = Some(DOMString::from_static("EC"));
978
979            // Step 3.3.
980            let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
981                return Err(Error::Operation(Some(
982                    "The key is not an elliptic curve key".into(),
983                )));
984            };
985            // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256",
986            // "P-384" or "P-521":
987            if matches!(
988                algorithm.named_curve.as_str(),
989                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
990            ) {
991                // Step 3.3.1.
992                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
993                // "P-256":
994                //     Set the crv attribute of jwk to "P-256"
995                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
996                // "P-384":
997                //     Set the crv attribute of jwk to "P-384"
998                // If the namedCurve attribute of the [[algorithm]] internal slot of key is
999                // "P-521":
1000                //     Set the crv attribute of jwk to "P-521"
1001                jwk.crv = Some(DOMString::from(algorithm.named_curve.as_str()));
1002
1003                // Step 3.3.2. Set the x attribute of jwk according to the definition in Section
1004                // 6.2.1.2 of JSON Web Algorithms [JWA].
1005                // Step 3.3.3. Set the y attribute of jwk according to the definition in Section
1006                // 6.2.1.3 of JSON Web Algorithms [JWA].
1007                let extraction_error = || {
1008                    Error::Operation(Some(
1009                        "Failed to extract encoded point from elliptic curve key".into(),
1010                    ))
1011                };
1012                let (x, y) = match key.handle() {
1013                    Handle::P256PublicKey(public_key) => {
1014                        let encoded_point = public_key.to_sec1_point(false);
1015                        (
1016                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1017                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1018                        )
1019                    },
1020                    Handle::P384PublicKey(public_key) => {
1021                        let encoded_point = public_key.to_sec1_point(false);
1022                        (
1023                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1024                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1025                        )
1026                    },
1027                    Handle::P521PublicKey(public_key) => {
1028                        let encoded_point = public_key.to_sec1_point(false);
1029                        (
1030                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1031                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1032                        )
1033                    },
1034                    Handle::P256PrivateKey(private_key) => {
1035                        let public_key = private_key.public_key();
1036                        let encoded_point = public_key.to_sec1_point(false);
1037                        (
1038                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1039                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1040                        )
1041                    },
1042                    Handle::P384PrivateKey(private_key) => {
1043                        let public_key = private_key.public_key();
1044                        let encoded_point = public_key.to_sec1_point(false);
1045                        (
1046                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1047                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1048                        )
1049                    },
1050                    Handle::P521PrivateKey(private_key) => {
1051                        let public_key = private_key.public_key();
1052                        let encoded_point = public_key.to_sec1_point(false);
1053                        (
1054                            encoded_point.x().ok_or(extraction_error())?.to_vec(),
1055                            encoded_point.y().ok_or(extraction_error())?.to_vec(),
1056                        )
1057                    },
1058                    _ => {
1059                        return Err(Error::Operation(Some(
1060                            "The key is not an elliptic curve key".into(),
1061                        )));
1062                    },
1063                };
1064                jwk.encode_string_field(JwkStringField::X, &x);
1065                jwk.encode_string_field(JwkStringField::Y, &y);
1066
1067                // Step 3.3.4.
1068                // If the [[type]] internal slot of key is "private"
1069                //     Set the d attribute of jwk according to the definition in Section 6.2.2.1 of
1070                //     JSON Web Algorithms [JWA].
1071                if key.Type() == KeyType::Private {
1072                    let d = match key.handle() {
1073                        Handle::P256PrivateKey(private_key) => {
1074                            private_key.to_bytes().as_slice().to_vec()
1075                        },
1076                        Handle::P384PrivateKey(private_key) => {
1077                            private_key.to_bytes().as_slice().to_vec()
1078                        },
1079                        Handle::P521PrivateKey(private_key) => {
1080                            private_key.to_bytes().as_slice().to_vec()
1081                        },
1082                        _ => {
1083                            return Err(Error::Operation(Some(
1084                                "The key is not an elliptic curve private key".into(),
1085                            )));
1086                        },
1087                    };
1088                    jwk.encode_string_field(JwkStringField::D, &d);
1089                }
1090            }
1091            // Otherwise:
1092            else {
1093                // Step 3.3.1. Perform any key export steps defined by other applicable
1094                // specifications, passing format and the namedCurve attribute of the [[algorithm]]
1095                // internal slot of key and obtaining namedCurve and a new value of jwk.
1096                // Step 3.3.2. Set the crv attribute of jwk to namedCurve.
1097                // NOTE: We currently do not support other applicable specifications.
1098                return Err(Error::NotSupported(Some("Unsupported named curve".into())));
1099            }
1100
1101            // Step 3.4. Set the key_ops attribute of jwk to the usages attribute of key.
1102            jwk.set_key_ops(key.usages());
1103
1104            // Step 3.4. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
1105            jwk.ext = Some(key.Extractable());
1106
1107            // Step 3.4. Let result be jwk.
1108            ExportedKey::new_jwk(jwk)
1109        },
1110        // If format is "raw":
1111        KeyFormat::Raw | KeyFormat::Raw_public => {
1112            // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
1113            // InvalidAccessError.
1114            key.ensure_type(KeyType::Public)?;
1115
1116            // Step 3.2.
1117            // If the namedCurve attribute of the [[algorithm]] internal slot of key is "P-256",
1118            // "P-384" or "P-521":
1119            //     Let data be a byte sequence representing the Elliptic Curve point Q represented
1120            //     by the [[handle]] internal slot of key according to [SEC1] 2.3.3 using the
1121            //     uncompressed format.
1122            // Otherwise:
1123            //     Perform any key export steps defined by other applicable specifications, passing
1124            //     format and the namedCurve attribute of the [[algorithm]] internal slot of key
1125            //     and obtaining namedCurve and data.
1126            //     NOTE: We currently do not support other applicable specifications.
1127            let KeyAlgorithmAndDerivatives::EcKeyAlgorithm(algorithm) = key.algorithm() else {
1128                return Err(Error::Operation(Some(
1129                    "The key is not an elliptic curve key".into(),
1130                )));
1131            };
1132            let data = if matches!(
1133                algorithm.named_curve.as_str(),
1134                NAMED_CURVE_P256 | NAMED_CURVE_P384 | NAMED_CURVE_P521
1135            ) {
1136                match key.handle() {
1137                    Handle::P256PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
1138                    Handle::P384PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
1139                    Handle::P521PublicKey(public_key) => public_key.to_sec1_bytes().to_vec(),
1140                    _ => {
1141                        return Err(Error::Operation(Some(
1142                            "The key is not an elliptic curve public key".into(),
1143                        )));
1144                    },
1145                }
1146            } else {
1147                return Err(Error::NotSupported(Some("Unsupported named curve".into())));
1148            };
1149
1150            // Step 3.3. Let result be data.
1151            ExportedKey::new_bytes(data)
1152        },
1153        // Otherwise:
1154        _ => {
1155            // throw a NotSupportedError.
1156            return Err(Error::NotSupported(Some("Unsupported key format".into())));
1157        },
1158    };
1159
1160    // Step 4. Return result.
1161    Ok(result)
1162}
1163
1164/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
1165/// Step 9 - 15, for elliptic curve cryptography
1166pub(crate) fn get_public_key<D: Equivalence>(
1167    cx: &mut JSContext,
1168    global: &D::GlobalScope,
1169    ec_algorithm: EcAlgorithm,
1170    key: &CryptoKey<D>,
1171    algorithm: &KeyAlgorithmAndDerivatives,
1172    usages: Vec<KeyUsage>,
1173) -> Result<DomRoot<CryptoKey<D>>, Error> {
1174    // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
1175    // identified by algorithm, then throw a SyntaxError.
1176    //
1177    // NOTE: See "importKey" operation for supported usages
1178    match ec_algorithm {
1179        EcAlgorithm::Ecdsa => {
1180            usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
1181        },
1182        EcAlgorithm::Ecdh => {
1183            usages.ensure_only_contain_entries_from(&[])?;
1184        },
1185    }
1186
1187    // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
1188    // private key represented by the [[handle]] internal slot of key.
1189    // Step 11. If an error occurred, then throw a OperationError.
1190    // Step 12. Set the [[type]] internal slot of publicKey to "public".
1191    // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
1192    // Step 14. Set the [[extractable]] internal slot of publicKey to true.
1193    // Step 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.
1194    let public_key_handle = match key.handle() {
1195        Handle::P256PrivateKey(private_key) => Handle::P256PublicKey(private_key.public_key()),
1196        Handle::P384PrivateKey(private_key) => Handle::P384PublicKey(private_key.public_key()),
1197        Handle::P521PrivateKey(private_key) => Handle::P521PublicKey(private_key.public_key()),
1198        _ => {
1199            return Err(Error::Operation(Some(
1200                "[[handle]] internal slot of key is not an elliptic curve private key".to_string(),
1201            )));
1202        },
1203    };
1204    let public_key = CryptoKey::new(
1205        cx,
1206        global,
1207        KeyType::Public,
1208        true,
1209        algorithm.clone(),
1210        usages.normalized_value(),
1211        public_key_handle,
1212    );
1213
1214    Ok(public_key)
1215}
1216
1217/// Concatenate big endian serialized coordinates of an elliptic curve point, to form an
1218/// uncompressed SEC1 encoded curve point, with prefix `0x04` indicating it is an uncompressed
1219/// point.
1220fn x_y_to_sec1_bytes(x: &[u8], y: &[u8]) -> Vec<u8> {
1221    let mut sec1_bytes = Vec::with_capacity(1 + x.len() + y.len());
1222    sec1_bytes.push(4u8);
1223    sec1_bytes.extend_from_slice(x);
1224    sec1_bytes.extend_from_slice(y);
1225    sec1_bytes
1226}
1227
1228/// Validate the public key in form of uncompressed SEC1 encoded curve point, against a private key.
1229fn validate_public_key<C>(private_key: &SecretKey<C>, sec1_bytes: &[u8]) -> ErrorResult
1230where
1231    C: Curve + ValidatePublicKey,
1232    FieldBytesSize<C>: ModulusSize,
1233{
1234    let sec1_point = Sec1Point::<C>::from_bytes(sec1_bytes)
1235        .map_err(|_| Error::Data(Some("Failed to encode curve point".into())))?;
1236    C::validate_public_key(private_key, &sec1_point)
1237        .map_err(|_| Error::Data(Some("The public key does not match the private key".into())))
1238}