Skip to main content

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