script_webcrypto/subtlecrypto/ml_dsa_operation.rs
1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5use js::context::JSContext;
6use ml_dsa::common::getrandom::SysRng;
7use ml_dsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
8use ml_dsa::{
9 Generate, KeyExport, KeyInit, Keypair, MlDsa44, MlDsa65, MlDsa87, Signature, SignatureEncoding,
10 SigningKey, VerifyingKey,
11};
12use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
13 CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage,
14};
15use script_bindings::codegen::GenericBindings::SubtleCryptoBinding::{JsonWebKey, KeyFormat};
16use script_bindings::error::Error;
17use script_bindings::root::DomRoot;
18use script_bindings::str::DOMString;
19use script_bindings::trace::RootedTraceableBox;
20
21use crate::cryptokey::{CryptoKey, Handle, KeyUsageSliceHelper};
22use crate::subtlecrypto::{
23 Algorithm, ContextParams, CryptoAlgorithm, ExportedKey, JsonWebKeyHelper, JwkStringField,
24 KeyAlgorithm, KeyAlgorithmAndDerivatives,
25};
26use crate::traits::Equivalence;
27
28/// <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-sign>
29pub(crate) fn sign<D: Equivalence>(
30 normalized_algorithm: &ContextParams,
31 key: &CryptoKey<D>,
32 message: &[u8],
33) -> Result<Vec<u8>, Error> {
34 // Step 1. If the context member of normalizedAlgorithm is present and has a length greater than
35 // 255 bytes, then throw an OperationError.
36 if normalized_algorithm
37 .context
38 .as_ref()
39 .is_some_and(|context| context.len() > 255)
40 {
41 return Err(Error::Operation(Some(
42 "The context is present and has a length greater than 255 bytes".into(),
43 )));
44 }
45
46 // Step 2. If the [[type]] internal slot of key is not "private", then throw an
47 // InvalidAccessError.
48 key.ensure_type(KeyType::Private)?;
49
50 // Step 3. Let context be the context member of normalizedAlgorithm or the empty octet string
51 // if the context member of normalizedAlgorithm is not present.
52 let context = normalized_algorithm.context.as_deref().unwrap_or_default();
53
54 // Step 4. Let result be the result of performing the ML-DSA.Sign signing algorithm, as
55 // specified in Section 5.2 of [FIPS-204], with the parameter set indicated by the name member
56 // of normalizedAlgorithm, using the ML-DSA private key associated with key as sk, message as M
57 // and context as ctx.
58 // Step 5. If the ML-DSA.Sign algorithm returned an error, throw an OperationError.
59 let result = match normalized_algorithm.name {
60 CryptoAlgorithm::MlDsa44 => {
61 let Handle::MlDsa44PrivateKey(private_key) = key.handle() else {
62 return Err(Error::Operation(Some(
63 "The key handle is not representing an ML-DSA-44 private key".into(),
64 )));
65 };
66 private_key
67 .expanded_key()
68 .sign_randomized(message, context, &mut SysRng)
69 .map_err(|_| Error::Operation(Some("ML-DSA-44 failed to sign the message".into())))?
70 .to_vec()
71 },
72 CryptoAlgorithm::MlDsa65 => {
73 let Handle::MlDsa65PrivateKey(private_key) = key.handle() else {
74 return Err(Error::Operation(Some(
75 "The key handle is not representing an ML-DSA-65 private key".into(),
76 )));
77 };
78 private_key
79 .expanded_key()
80 .sign_randomized(message, context, &mut SysRng)
81 .map_err(|_| Error::Operation(Some("ML-DSA-65 failed to sign the message".into())))?
82 .to_vec()
83 },
84 CryptoAlgorithm::MlDsa87 => {
85 let Handle::MlDsa87PrivateKey(private_key) = key.handle() else {
86 return Err(Error::Operation(Some(
87 "The key handle is not representing an ML-DSA-87 private key".into(),
88 )));
89 };
90 private_key
91 .expanded_key()
92 .sign_randomized(message, context, &mut SysRng)
93 .map_err(|_| Error::Operation(Some("ML-DSA-87 failed to sign the message".into())))?
94 .to_vec()
95 },
96 _ => {
97 return Err(Error::NotSupported(Some(format!(
98 "{} is not an ML-DSA algorithm",
99 normalized_algorithm.name.as_str()
100 ))));
101 },
102 };
103
104 // Step 6. Return result.
105 Ok(result)
106}
107
108/// <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-verify>
109pub(crate) fn verify<D: Equivalence>(
110 normalized_algorithm: &ContextParams,
111 key: &CryptoKey<D>,
112 message: &[u8],
113 signature: &[u8],
114) -> Result<bool, Error> {
115 // Step 1. If the context member of normalizedAlgorithm is present and has a length greater than
116 // 255 bytes, then throw an OperationError.
117 if normalized_algorithm
118 .context
119 .as_ref()
120 .is_some_and(|context| context.len() > 255)
121 {
122 return Err(Error::Operation(Some(
123 "The context is present and has a length greater than 255 bytes".into(),
124 )));
125 }
126
127 // Step 2. If the [[type]] internal slot of key is not "public", then throw an
128 // InvalidAccessError.
129 key.ensure_type(KeyType::Public)?;
130
131 // Step 3. Let context be the context member of normalizedAlgorithm or the empty octet string
132 // if the context member of normalizedAlgorithm is not present.
133 let context = normalized_algorithm.context.as_deref().unwrap_or_default();
134
135 // Step 4. Let result be the result of performing the ML-DSA.Verify verification algorithm, as
136 // specified in Section 5.3 of [FIPS-204], with the parameter set indicated by the name member
137 // of normalizedAlgorithm, using the ML-DSA public key associated with key as pk, message as M,
138 // signature as σ and context as ctx.
139 // Step 5. If the ML-DSA.Verify algorithm returned an error, throw an OperationError.
140 let result = match normalized_algorithm.name {
141 CryptoAlgorithm::MlDsa44 => {
142 let Handle::MlDsa44PublicKey(public_key) = key.handle() else {
143 return Err(Error::Operation(Some(
144 "The key handle is not representing an ML-DSA-44 public key".into(),
145 )));
146 };
147 match Signature::try_from(signature) {
148 Ok(signature) => public_key.verify_with_context(message, context, &signature),
149 Err(_) => false,
150 }
151 },
152 CryptoAlgorithm::MlDsa65 => {
153 let Handle::MlDsa65PublicKey(public_key) = key.handle() else {
154 return Err(Error::Operation(Some(
155 "The key handle is not representing an ML-DSA-65 public key".into(),
156 )));
157 };
158 match Signature::try_from(signature) {
159 Ok(signature) => public_key.verify_with_context(message, context, &signature),
160 Err(_) => false,
161 }
162 },
163 CryptoAlgorithm::MlDsa87 => {
164 let Handle::MlDsa87PublicKey(public_key) = key.handle() else {
165 return Err(Error::Operation(Some(
166 "The key handle is not representing an ML-DSA-87 public key".into(),
167 )));
168 };
169 match Signature::try_from(signature) {
170 Ok(signature) => public_key.verify_with_context(message, context, &signature),
171 Err(_) => false,
172 }
173 },
174 _ => {
175 return Err(Error::NotSupported(Some(format!(
176 "{} is not an ML-DSA algorithm",
177 normalized_algorithm.name.as_str()
178 ))));
179 },
180 };
181
182 // Step 6. Return result.
183 Ok(result)
184}
185
186/// <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-generate-key>
187pub(crate) fn generate_key<D: Equivalence>(
188 cx: &mut JSContext,
189 global: &D::GlobalScope,
190 normalized_algorithm: &Algorithm,
191 extractable: bool,
192 usages: Vec<KeyUsage>,
193) -> Result<RootedTraceableBox<CryptoKeyPair<D>>, Error> {
194 // Step 1. If usages contains a value which is not one of "sign" or "verify", then throw a
195 // SyntaxError.
196 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign, KeyUsage::Verify])?;
197
198 // Step 2. Generate an ML-DSA key pair, as described in Section 5.1 of [FIPS-204], with the
199 // parameter set indicated by the name member of normalizedAlgorithm.
200 // Step 3. If the key generation step fails, then throw an OperationError.
201 let (private_key_handle, public_key_handle) = match normalized_algorithm.name {
202 CryptoAlgorithm::MlDsa44 => {
203 let signing_key = SigningKey::<MlDsa44>::generate();
204 let verifying_key = signing_key.verifying_key();
205 (
206 Handle::MlDsa44PrivateKey(signing_key),
207 Handle::MlDsa44PublicKey(verifying_key),
208 )
209 },
210 CryptoAlgorithm::MlDsa65 => {
211 let signing_key = SigningKey::<MlDsa65>::generate();
212 let verifying_key = signing_key.verifying_key();
213 (
214 Handle::MlDsa65PrivateKey(signing_key),
215 Handle::MlDsa65PublicKey(verifying_key),
216 )
217 },
218 CryptoAlgorithm::MlDsa87 => {
219 let signing_key = SigningKey::<MlDsa87>::generate();
220 let verifying_key = signing_key.verifying_key();
221 (
222 Handle::MlDsa87PrivateKey(signing_key),
223 Handle::MlDsa87PublicKey(verifying_key),
224 )
225 },
226 name => {
227 return Err(Error::NotSupported(Some(format!(
228 "{} is not an ML-DSA algorithm",
229 name.as_str()
230 ))));
231 },
232 };
233
234 // Step 4. Let algorithm be a new KeyAlgorithm object.
235 // Step 5. Set the name attribute of algorithm to the name attribute of normalizedAlgorithm.
236 let algorithm = KeyAlgorithm {
237 name: normalized_algorithm.name,
238 };
239
240 // Step 6. Let publicKey be a new CryptoKey representing the public key of the generated key
241 // pair.
242 // Step 7. Set the [[type]] internal slot of publicKey to "public".
243 // Step 8. Set the [[algorithm]] internal slot of publicKey to algorithm.
244 // Step 9. Set the [[extractable]] internal slot of publicKey to true.
245 // Step 10. Set the [[usages]] internal slot of publicKey to be the usage intersection of
246 // usages and [ "verify" ].
247 let public_key = CryptoKey::new(
248 cx,
249 global,
250 KeyType::Public,
251 true,
252 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm.clone()),
253 usages.usage_intersection(&[KeyUsage::Verify]),
254 public_key_handle,
255 );
256
257 // Step 11. Let privateKey be a new CryptoKey representing the private key of the generated key
258 // pair.
259 // Step 12. Set the [[type]] internal slot of privateKey to "private".
260 // Step 13. Set the [[algorithm]] internal slot of privateKey to algorithm.
261 // Step 14. Set the [[extractable]] internal slot of privateKey to extractable.
262 // Step 15. Set the [[usages]] internal slot of privateKey to be the usage intersection of
263 // usages and [ "sign" ].
264 let private_key = CryptoKey::new(
265 cx,
266 global,
267 KeyType::Private,
268 extractable,
269 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
270 usages.usage_intersection(&[KeyUsage::Sign]),
271 private_key_handle,
272 );
273
274 // Step 16. Let result be a new CryptoKeyPair dictionary.
275 // Step 17. Set the publicKey attribute of result to be publicKey.
276 // Step 18. Set the privateKey attribute of result to be privateKey.
277 let result = RootedTraceableBox::new(CryptoKeyPair {
278 publicKey: Some(public_key.as_traced()),
279 privateKey: Some(private_key.as_traced()),
280 });
281
282 // Step 19. Return result.
283 Ok(result)
284}
285
286/// <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-import-key>
287pub(crate) fn import_key<D: Equivalence>(
288 cx: &mut JSContext,
289 global: &D::GlobalScope,
290 normalized_algorithm: &Algorithm,
291 format: KeyFormat,
292 key_data: &[u8],
293 extractable: bool,
294 usages: Vec<KeyUsage>,
295) -> Result<DomRoot<CryptoKey<D>>, Error> {
296 // Step 1. Let keyData be the key data to be imported.
297
298 // Step 2.
299 let key = match format {
300 // If format is "spki":
301 KeyFormat::Spki => {
302 // Step 2.1. If usages contains a value which is not "verify" then throw a SyntaxError.
303 usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
304
305 // Step 2.2. Let spki be the result of running the parse a subjectPublicKeyInfo
306 // algorithm over keyData.
307 // Step 2.3. If an error occurred while parsing, then throw a DataError.
308 // Step 2.4.
309 // If the name member of normalizedAlgorithm is "ML-DSA-44":
310 // Let expectedOid be id-ml-dsa-44 (2.16.840.1.101.3.4.3.17).
311 // If the name member of normalizedAlgorithm is "ML-DSA-65":
312 // Let expectedOid be id-ml-dsa-65 (2.16.840.1.101.3.4.3.18).
313 // If the name member of normalizedAlgorithm is "ML-DSA-87":
314 // Let expectedOid be id-ml-dsa-87 (2.16.840.1.101.3.4.3.19).
315 // Otherwise:
316 // throw a NotSupportedError.
317 // Step 2.5. If the algorithm object identifier field of the algorithm
318 // AlgorithmIdentifier field of spki is not equal to expectedOid, then throw a
319 // DataError.
320 // Step 2.6. If the parameters field of the algorithm AlgorithmIdentifier field of spki
321 // is present, then throw a DataError.
322 // Step 2.7. Let publicKey be the ML-DSA public key identified by the subjectPublicKey
323 // field of spki.
324 let public_key = match normalized_algorithm.name {
325 CryptoAlgorithm::MlDsa44 => Handle::MlDsa44PublicKey(
326 VerifyingKey::from_public_key_der(key_data).map_err(|_| {
327 Error::Data(Some(
328 "Failed to decode the ML-DSA-44 public key from SPKI format".into(),
329 ))
330 })?,
331 ),
332 CryptoAlgorithm::MlDsa65 => Handle::MlDsa65PublicKey(
333 VerifyingKey::from_public_key_der(key_data).map_err(|_| {
334 Error::Data(Some(
335 "Failed to decode the ML-DSA-65 public key from SPKI format".into(),
336 ))
337 })?,
338 ),
339 CryptoAlgorithm::MlDsa87 => Handle::MlDsa87PublicKey(
340 VerifyingKey::from_public_key_der(key_data).map_err(|_| {
341 Error::Data(Some(
342 "Failed to decode the ML-DSA-87 pulic key from SPKI format".into(),
343 ))
344 })?,
345 ),
346 name => {
347 return Err(Error::NotSupported(Some(format!(
348 "{} is not an ML-DSA algorithm",
349 name.as_str()
350 ))));
351 },
352 };
353
354 // Step 2.8. Let key be a new CryptoKey that represents publicKey.
355 // Step 2.9. Set the [[type]] internal slot of key to "public"
356 // Step 2.10. Let algorithm be a new KeyAlgorithm.
357 // Step 2.11. Set the name attribute of algorithm to the name attribute of
358 // normalizedAlgorithm.
359 // Step 2.12. Set the [[algorithm]] internal slot of key to algorithm.
360 let algorithm = KeyAlgorithm {
361 name: normalized_algorithm.name,
362 };
363 CryptoKey::new(
364 cx,
365 global,
366 KeyType::Public,
367 extractable,
368 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
369 usages.normalized_value(),
370 public_key,
371 )
372 },
373 // If format is "pkcs8":
374 KeyFormat::Pkcs8 => {
375 // Step 2.1. If usages contains a value which is not "sign" then throw a SyntaxError.
376 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?;
377
378 // Step 2.2. Let privateKeyInfo be the result of running the parse a privateKeyInfo
379 // algorithm over keyData.
380 // Step 2.3. If an error occurs while parsing, then throw a DataError.
381 // Step 2.4.
382 // If the name member of normalizedAlgorithm is "ML-DSA-44":
383 // Let expectedOid be id-ml-dsa-44 (2.16.840.1.101.3.4.3.17).
384 // Let asn1Structure be the ASN.1 ML-DSA-44-PrivateKey structure.
385 // If the name member of normalizedAlgorithm is "ML-DSA-65":
386 // Let expectedOid be id-ml-dsa-65 (2.16.840.1.101.3.4.3.18).
387 // Let asn1Structure be the ASN.1 ML-DSA-65-PrivateKey structure.
388 // If the name member of normalizedAlgorithm is "ML-DSA-87":
389 // Let expectedOid be id-ml-dsa-87 (2.16.840.1.101.3.4.3.19).
390 // Let asn1Structure be the ASN.1 ML-DSA-87-PrivateKey structure.
391 // Otherwise:
392 // throw a NotSupportedError.
393 // Step 2.5. If the algorithm object identifier field of the privateKeyAlgorithm
394 // PrivateKeyAlgorithm field of privateKeyInfo is not equal to expectedOid, then throw
395 // a DataError.
396 // Step 2.6. If the parameters field of the privateKeyAlgorithm
397 // PrivateKeyAlgorithmIdentifier field of privateKeyInfo is present, then throw a
398 // DataError.
399 // Step 2.7. Let mlDsaPrivateKey be the result of performing the parse an ASN.1
400 // structure algorithm, with data as the privateKey field of privateKeyInfo, structure
401 // as asn1Structure, and exactData set to true.
402 // Step 2.8. If an error occurred while parsing, then throw a DataError.
403 // Step 2.9. If mlDsaPrivateKey represents an ML-DSA key in the expandedKey format, or
404 // if mlDsaPrivateKey represents an ML-DSA key in the both format and the both format
405 // is not supported, throw a NotSupportedError.
406 // Step 2.10. If mlDsaPrivateKey represents an ML-DSA key in the both format, and the
407 // seed field does not correspond to the expandedKey field, throw a DataError.
408 //
409 // NOTE: We do not support the `both` format.
410 let ml_dsa_private_key = match normalized_algorithm.name {
411 CryptoAlgorithm::MlDsa44 => Handle::MlDsa44PrivateKey(
412 SigningKey::from_pkcs8_der(key_data).map_err(|_| {
413 Error::Data(Some(
414 "Failed to decode the ML-DSA-44 private key from PKCS#8 format".into(),
415 ))
416 })?,
417 ),
418 CryptoAlgorithm::MlDsa65 => Handle::MlDsa65PrivateKey(
419 SigningKey::from_pkcs8_der(key_data).map_err(|_| {
420 Error::Data(Some(
421 "Failed to decode the ML-DSA-65 private key from PKCS#8 format".into(),
422 ))
423 })?,
424 ),
425 CryptoAlgorithm::MlDsa87 => Handle::MlDsa87PrivateKey(
426 SigningKey::from_pkcs8_der(key_data).map_err(|_| {
427 Error::Data(Some(
428 "Failed to decode the ML-DSA-87 private key from PKCS#8 format".into(),
429 ))
430 })?,
431 ),
432 name => {
433 return Err(Error::NotSupported(Some(format!(
434 "{} is not an ML-DSA algorithm",
435 name.as_str()
436 ))));
437 },
438 };
439
440 // Step 2.11. Let key be a new CryptoKey that represents the ML-DSA private key
441 // identified by mlDsaPrivateKey.
442 // Step 2.12. Set the [[type]] internal slot of key to "private"
443 // Step 2.13. Let algorithm be a new KeyAlgorithm.
444 // Step 2.14. Set the name attribute of algorithm to the name attribute of
445 // normalizedAlgorithm.
446 // Step 2.15. Set the [[algorithm]] internal slot of key to algorithm.
447 let algorithm = KeyAlgorithm {
448 name: normalized_algorithm.name,
449 };
450 CryptoKey::new(
451 cx,
452 global,
453 KeyType::Private,
454 extractable,
455 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
456 usages.normalized_value(),
457 ml_dsa_private_key,
458 )
459 },
460 // If format is "raw-public":
461 KeyFormat::Raw_public => {
462 // Step 2.1. If usages contains a value which is not "verify" then throw a SyntaxError.
463 usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
464
465 // Step 2.2. Let algorithm be a new KeyAlgorithm object.
466 // Step 2.3. Set the name attribute of algorithm to the name attribute of
467 // normalizedAlgorithm.
468 // Step 2.4. Let key be a new CryptoKey representing the key data provided in keyData.
469 // Step 2.5. Set the [[type]] internal slot of key to "public"
470 // Step 2.6. Set the [[algorithm]] internal slot of key to algorithm.
471 let public_key = match normalized_algorithm.name {
472 CryptoAlgorithm::MlDsa44 => {
473 let verifying_key = VerifyingKey::new_from_slice(key_data).map_err(|_| {
474 Error::Data(Some(
475 "Failed to parse the public ML-DSA-44 key in raw format".into(),
476 ))
477 })?;
478 Handle::MlDsa44PublicKey(verifying_key)
479 },
480 CryptoAlgorithm::MlDsa65 => {
481 let verifying_key = VerifyingKey::new_from_slice(key_data).map_err(|_| {
482 Error::Data(Some(
483 "Failed to parse the public ML-DSA-65 key in raw format".into(),
484 ))
485 })?;
486 Handle::MlDsa65PublicKey(verifying_key)
487 },
488 CryptoAlgorithm::MlDsa87 => {
489 let verifying_key = VerifyingKey::new_from_slice(key_data).map_err(|_| {
490 Error::Data(Some(
491 "Failed to parse the public ML-DSA-87 key in raw format".into(),
492 ))
493 })?;
494 Handle::MlDsa87PublicKey(verifying_key)
495 },
496 name => {
497 return Err(Error::NotSupported(Some(format!(
498 "{} is not an ML-DSA algorithm",
499 name.as_str()
500 ))));
501 },
502 };
503 let algorithm = KeyAlgorithm {
504 name: normalized_algorithm.name,
505 };
506 CryptoKey::new(
507 cx,
508 global,
509 KeyType::Public,
510 extractable,
511 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
512 usages.normalized_value(),
513 public_key,
514 )
515 },
516 // If format is "raw-seed":
517 KeyFormat::Raw_seed => {
518 // Step 2.1. If usages contains an entry which is not "sign" then throw a SyntaxError.
519 usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?;
520
521 // Step 2.2. Let data be keyData.
522 // Step 2.3. If the length in bits of data is not 256 then throw a DataError.
523 // Step 2.4. Let privateKey be the result of performing the ML-DSA.KeyGen_internal
524 // function described in Section 6.1 of [FIPS-204] with the parameter set indicated by
525 // the name member of normalizedAlgorithm, using data as ξ.
526 let private_key = match normalized_algorithm.name {
527 CryptoAlgorithm::MlDsa44 => {
528 let signing_key = SigningKey::new_from_slice(key_data).map_err(|_| {
529 Error::Data(Some(
530 "Failed to parse the private ML-DSA-44 key in raw format".into(),
531 ))
532 })?;
533 Handle::MlDsa44PrivateKey(signing_key)
534 },
535 CryptoAlgorithm::MlDsa65 => {
536 let signing_key = SigningKey::new_from_slice(key_data).map_err(|_| {
537 Error::Data(Some(
538 "Failed to parse the private ML-DSA-65 key in raw format".into(),
539 ))
540 })?;
541 Handle::MlDsa65PrivateKey(signing_key)
542 },
543 CryptoAlgorithm::MlDsa87 => {
544 let signing_key = SigningKey::new_from_slice(key_data).map_err(|_| {
545 Error::Data(Some(
546 "Failed to parse the private ML-DSA-87 key in raw format".into(),
547 ))
548 })?;
549 Handle::MlDsa87PrivateKey(signing_key)
550 },
551 name => {
552 return Err(Error::NotSupported(Some(format!(
553 "{} is not an ML-DSA algorithm",
554 name.as_str()
555 ))));
556 },
557 };
558
559 // Step 2.5. Let key be a new CryptoKey that represents the ML-DSA private key
560 // identified by privateKey.
561 // Step 2.6. Set the [[type]] internal slot of key to "private"
562 // Step 2.7. Let algorithm be a new KeyAlgorithm.
563 // Step 2.8. Set the name attribute of algorithm to the name attribute of
564 // normalizedAlgorithm.
565 // Step 2.9. Set the [[algorithm]] internal slot of key to algorithm.
566 let algorithm = KeyAlgorithm {
567 name: normalized_algorithm.name,
568 };
569 CryptoKey::new(
570 cx,
571 global,
572 KeyType::Private,
573 extractable,
574 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
575 usages.normalized_value(),
576 private_key,
577 )
578 },
579 // If format is "jwk":
580 KeyFormat::Jwk => {
581 // Step 2.1.
582 // If keyData is a JsonWebKey dictionary:
583 // Let jwk equal keyData.
584 // Otherwise:
585 // Throw a DataError.
586 let jwk = JsonWebKey::parse(cx, key_data)?;
587
588 // Step 2.2. If the priv field is present and usages contains a value which is not
589 // "sign", or, if the priv field is not present and usages contains a value which is
590 // not "verify" then throw a SyntaxError.
591 match jwk.priv_.as_ref() {
592 Some(_) => usages.ensure_only_contain_entries_from(&[KeyUsage::Sign])?,
593 None => usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?,
594 }
595
596 // Step 2.3. If the kty field of jwk is not "AKP", then throw a DataError.
597 if jwk.kty.as_ref().is_none_or(|kty| kty != "AKP") {
598 return Err(Error::Data(Some(
599 "The kty field of jwk is not \"AKP\"".into(),
600 )));
601 }
602
603 // Step 2.4. If the alg field of jwk is not equal to the name member of
604 // normalizedAlgorithm, then throw a DataError.
605 if jwk
606 .alg
607 .as_ref()
608 .is_none_or(|alg| alg != normalized_algorithm.name.as_str())
609 {
610 return Err(Error::Data(Some(
611 "The alg field of jwk is not equal to the name member of normalizedAlgorithm"
612 .into(),
613 )));
614 }
615
616 // Step 2.5. If usages is non-empty and the use field of jwk is present and is not
617 // equal to "sig", then throw a DataError.
618 if !usages.is_empty() && jwk.use_.as_ref().is_some_and(|use_| use_ != "enc") {
619 return Err(Error::Data(Some(
620 "Usages is non-empty and the use field of jwk is present and is not \
621 equal to \"sig\""
622 .into(),
623 )));
624 }
625
626 // Step 2.6. If the key_ops field of jwk is present, and is invalid according to the
627 // requirements of JSON Web Key [JWK], or it does not contain all of the specified
628 // usages values, then throw a DataError.
629 jwk.check_key_ops(&usages)?;
630
631 // Step 2.7. If the ext field of jwk is present and has the value false and extractable
632 // is true, then throw a DataError.
633 if jwk.ext.is_some_and(|ext| !ext) && extractable {
634 return Err(Error::Data(Some(
635 "The ext field of jwk is present and has the value false and extractable \
636 is true"
637 .into(),
638 )));
639 }
640
641 // Step 2.8.
642 // If the priv field of jwk is present:
643 let (key_type, key_handle) = if jwk.priv_.is_some() {
644 // Step 2.8.1. If the priv attribute of jwk does not contain a valid base64url
645 // encoded seed representing an ML-DSA private key, then throw a DataError.
646 let priv_bytes = jwk.decode_required_string_field(JwkStringField::Priv)?;
647
648 // Step 2.8.2. Let key be a new CryptoKey object that represents the ML-DSA private
649 // key identified by interpreting the priv attribute of jwk as a base64url encoded
650 // seed.
651 // Step 2.8.3. Set the [[type]] internal slot of key to "private".
652 // Step 2.8.4. If the pub attribute of jwk does not contain the base64url encoded
653 // public key representing the ML-DSA public key corresponding to key, then throw a
654 // DataError.
655 // NOTE: The CryptoKey object is created in Step 2.9 - 2.11.
656 let pub_bytes = jwk.decode_required_string_field(JwkStringField::Pub)?;
657 let private_key_handle = match normalized_algorithm.name {
658 CryptoAlgorithm::MlDsa44 => {
659 let signing_key =
660 SigningKey::new_from_slice(&priv_bytes).map_err(|_| {
661 Error::Data(Some(
662 "Failed to parse the private ML-DSA-44 key in priv attribute"
663 .into(),
664 ))
665 })?;
666 let verifying_key =
667 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
668 Error::Data(Some(
669 "Failed to parse the public ML-DSA-44 key in pub attribute"
670 .into(),
671 ))
672 })?;
673 if signing_key.verifying_key() != verifying_key {
674 return Err(Error::Data(Some(
675 "The public key in pub attribute does not match \
676 the private key in priv attribute"
677 .into(),
678 )));
679 }
680 Handle::MlDsa44PrivateKey(signing_key)
681 },
682 CryptoAlgorithm::MlDsa65 => {
683 let signing_key =
684 SigningKey::new_from_slice(&priv_bytes).map_err(|_| {
685 Error::Data(Some(
686 "Failed to parse the private ML-DSA-65 key in priv attribute"
687 .into(),
688 ))
689 })?;
690 let verifying_key =
691 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
692 Error::Data(Some(
693 "Failed to parse the public ML-DSA-65 key in pub attribute"
694 .into(),
695 ))
696 })?;
697 if signing_key.verifying_key() != verifying_key {
698 return Err(Error::Data(Some(
699 "The public key in pub attribute does not match \
700 the private key in priv attribute"
701 .into(),
702 )));
703 }
704 Handle::MlDsa65PrivateKey(signing_key)
705 },
706 CryptoAlgorithm::MlDsa87 => {
707 let signing_key =
708 SigningKey::new_from_slice(&priv_bytes).map_err(|_| {
709 Error::Data(Some(
710 "Failed to parse the private ML-DSA-87 key in priv attribute"
711 .into(),
712 ))
713 })?;
714 let verifying_key =
715 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
716 Error::Data(Some(
717 "Failed to parse the public ML-DSA-87 key in pub attribute"
718 .into(),
719 ))
720 })?;
721 if signing_key.verifying_key() != verifying_key {
722 return Err(Error::Data(Some(
723 "The public key in pub attribute does not match \
724 the private key in priv attribute"
725 .into(),
726 )));
727 }
728 Handle::MlDsa87PrivateKey(signing_key)
729 },
730 name => {
731 return Err(Error::NotSupported(Some(format!(
732 "{} is not an ML-DSA algorithm",
733 name.as_str()
734 ))));
735 },
736 };
737 (KeyType::Private, private_key_handle)
738 }
739 // Otherwise:
740 else {
741 // Step 2.8.1. If the pub attribute of jwk does not contain a valid base64url
742 // encoded public key representing an ML-DSA public key, then throw a DataError.
743 let pub_bytes = jwk.decode_required_string_field(JwkStringField::Pub)?;
744
745 // Step 2.8.2. Let key be a new CryptoKey object that represents the ML-DSA public
746 // key identified by interpreting the pub attribute of jwk as a base64url encoded
747 // public key.
748 // Step 2.8.3. Set the [[type]] internal slot of key to "public".
749 // NOTE: The CryptoKey object is created in Step 2.9 - 2.11.
750 let public_key_handle = match normalized_algorithm.name {
751 CryptoAlgorithm::MlDsa44 => {
752 let verifying_key =
753 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
754 Error::Data(Some(
755 "Failed to parse the public ML-DSA-44 key in pub attribute"
756 .into(),
757 ))
758 })?;
759 Handle::MlDsa44PublicKey(verifying_key)
760 },
761 CryptoAlgorithm::MlDsa65 => {
762 let verifying_key =
763 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
764 Error::Data(Some(
765 "Failed to parse the public ML-DSA-65 key in pub attribute"
766 .into(),
767 ))
768 })?;
769 Handle::MlDsa65PublicKey(verifying_key)
770 },
771 CryptoAlgorithm::MlDsa87 => {
772 let verifying_key =
773 VerifyingKey::new_from_slice(&pub_bytes).map_err(|_| {
774 Error::Data(Some(
775 "Failed to parse the public ML-DSA-87 key in pub attribute"
776 .into(),
777 ))
778 })?;
779 Handle::MlDsa87PublicKey(verifying_key)
780 },
781 name => {
782 return Err(Error::NotSupported(Some(format!(
783 "{} is not an ML-DSA algorithm",
784 name.as_str()
785 ))));
786 },
787 };
788 (KeyType::Public, public_key_handle)
789 };
790
791 // Step 2.9. Let algorithm be a new instance of a KeyAlgorithm object.
792 // Step 2.10. Set the name attribute of algorithm to the name member of
793 // normalizedAlgorithm.
794 // Step 2.11. Set the [[algorithm]] internal slot of key to algorithm.
795 let algorithm = KeyAlgorithm {
796 name: normalized_algorithm.name,
797 };
798 CryptoKey::new(
799 cx,
800 global,
801 key_type,
802 extractable,
803 KeyAlgorithmAndDerivatives::KeyAlgorithm(algorithm),
804 usages.normalized_value(),
805 key_handle,
806 )
807 },
808 // Otherwise:
809 _ => {
810 // throw a NotSupportedError.
811 return Err(Error::NotSupported(Some(
812 "Unsupported import key format for ML-DSA key".into(),
813 )));
814 },
815 };
816
817 // Step 3. Return key.
818 Ok(key)
819}
820
821/// <https://wicg.github.io/webcrypto-modern-algos/#ml-dsa-operations-export-key>
822pub(crate) fn export_key<D: Equivalence>(
823 format: KeyFormat,
824 key: &CryptoKey<D>,
825) -> Result<ExportedKey, Error> {
826 // Step 1. Let key be the CryptoKey to be exported.
827
828 // Step 2. If the underlying cryptographic key material represented by the [[handle]] internal
829 // slot of key cannot be accessed, then throw an OperationError.
830
831 // Step 3.
832 let result = match format {
833 KeyFormat::Spki => {
834 // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
835 // InvalidAccessError.
836 key.ensure_type(KeyType::Public)?;
837
838 // Step 3.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
839 let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
840 return Err(Error::Operation(Some(
841 "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
842 )));
843 };
844
845 // Step 3.3.
846 // Let data be an instance of the SubjectPublicKeyInfo ASN.1 structure defined in
847 // [RFC5280] with the following properties:
848 //
849 // Set the algorithm field to an AlgorithmIdentifier ASN.1 type with the following
850 // properties:
851 //
852 // If the name member of keyAlgorithm is "ML-DSA-44":
853 // Set the algorithm object identifier to the id-ml-dsa-44
854 // (2.16.840.1.101.3.4.3.17) OID.
855 //
856 // If the name member of keyAlgorithm is "ML-DSA-65":
857 // Set the algorithm object identifier to the id-ml-dsa-65
858 // (2.16.840.1.101.3.4.3.18) OID.
859 //
860 // If the name member of keyAlgorithm is "ML-DSA-87":
861 // Set the algorithm object identifier to the id-ml-dsa-87
862 // (2.16.840.1.101.3.4.3.19) OID.
863 //
864 // Otherwise:
865 // throw a NotSupportedError.
866 //
867 // Set the subjectPublicKey field to keyData.
868 let data = match (key_algorithm.name, key.handle()) {
869 (CryptoAlgorithm::MlDsa44, Handle::MlDsa44PublicKey(public_key)) => {
870 public_key.to_public_key_der().map_err(|_| {
871 Error::Operation(Some(
872 "Failed to encode the ML-DSA-44 public key into SPKI format".into(),
873 ))
874 })?
875 },
876 (CryptoAlgorithm::MlDsa65, Handle::MlDsa65PublicKey(public_key)) => {
877 public_key.to_public_key_der().map_err(|_| {
878 Error::Operation(Some(
879 "Failed to encode the ML-DSA-65 public key into SPKI format".into(),
880 ))
881 })?
882 },
883 (CryptoAlgorithm::MlDsa87, Handle::MlDsa87PublicKey(public_key)) => {
884 public_key.to_public_key_der().map_err(|_| {
885 Error::Operation(Some(
886 "Failed to encode the ML-DSA-87 public key into SPKI format".into(),
887 ))
888 })?
889 },
890 _ => {
891 return Err(Error::Operation(Some(
892 "The key handle is not representing an ML-DSA public key".into(),
893 )));
894 },
895 };
896
897 // Step 3.4. Let result be the result of DER-encoding data.
898 ExportedKey::new_bytes(data.into_vec())
899 },
900 KeyFormat::Pkcs8 => {
901 // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
902 // InvalidAccessError.
903 key.ensure_type(KeyType::Private)?;
904
905 // Step 3.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
906 let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
907 return Err(Error::Operation(Some(
908 "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
909 )));
910 };
911
912 // Step 3.3.
913 // Let data be an instance of the PrivateKeyInfo ASN.1 structure defined in [RFC5208]
914 // with the following properties:
915 //
916 // Set the version field to 0.
917 //
918 // Set the privateKeyAlgorithm field to a PrivateKeyAlgorithmIdentifier ASN.1 type
919 // with the following properties:
920 //
921 // If the name member of keyAlgorithm is "ML-DSA-44":
922 // Set the algorithm object identifier to the id-ml-dsa-44
923 // (2.16.840.1.101.3.4.3.17) OID.
924 //
925 // If the name member of keyAlgorithm is "ML-DSA-65":
926 // Set the algorithm object identifier to the id-ml-dsa-65
927 // (2.16.840.1.101.3.4.3.18) OID.
928 //
929 // If the name member of keyAlgorithm is "ML-DSA-87":
930 // Set the algorithm object identifier to the id-ml-dsa-87
931 // (2.16.840.1.101.3.4.3.19) OID.
932 //
933 // Otherwise:
934 // throw a NotSupportedError.
935 //
936 // Set the privateKey field as follows:
937 //
938 // If the name member of keyAlgorithm is "ML-DSA-44":
939 // Set the privateKey field to the result of DER-encoding a
940 // ML-DSA-44-PrivateKey ASN.1 type that represents the ML-DSA private key
941 // seed represented by the [[handle]] internal slot of key using the
942 // seed-only format (using a context-specific [0] primitive tag with an
943 // implicit encoding of OCTET STRING).
944 //
945 // If the name member of keyAlgorithm is "ML-DSA-65":
946 // Set the privateKey field to the result of DER-encoding a
947 // ML-DSA-65-PrivateKey ASN.1 type that represents the ML-DSA private key
948 // seed represented by the [[handle]] internal slot of key using the
949 // seed-only format (using a context-specific [0] primitive tag with an
950 // implicit encoding of OCTET STRING).
951 //
952 // If the name member of keyAlgorithm is "ML-DSA-87":
953 // Set the privateKey field to the result of DER-encoding a
954 // ML-DSA-87-PrivateKey ASN.1 type that represents the ML-DSA private key
955 // seed represented by the [[handle]] internal slot of key using the
956 // seed-only format (using a context-specific [0] primitive tag with an
957 // implicit encoding of OCTET STRING).
958 //
959 // Otherwise:
960 // throw a NotSupportedError.
961 let private_key_info = match (key_algorithm.name, key.handle()) {
962 (CryptoAlgorithm::MlDsa44, Handle::MlDsa44PrivateKey(private_key)) => {
963 private_key.to_pkcs8_der().map_err(|_| {
964 Error::Operation(Some(
965 "Failed to encode the ML-DSA-44 private key into PKCS#8 format".into(),
966 ))
967 })?
968 },
969 (CryptoAlgorithm::MlDsa65, Handle::MlDsa65PrivateKey(private_key)) => {
970 private_key.to_pkcs8_der().map_err(|_| {
971 Error::Operation(Some(
972 "Failed to encode the ML-DSA-65 private key into PKCS#8 format".into(),
973 ))
974 })?
975 },
976 (CryptoAlgorithm::MlDsa87, Handle::MlDsa87PrivateKey(private_key)) => {
977 private_key.to_pkcs8_der().map_err(|_| {
978 Error::Operation(Some(
979 "Failed to encode the ML-DSA-87 private key into PKCS#8 format".into(),
980 ))
981 })?
982 },
983 _ => {
984 return Err(Error::Operation(Some(
985 "The key handle is not representing an ML-DSA private key".into(),
986 )));
987 },
988 };
989
990 // Step 3.4. Let result be the result of DER-encoding data.
991 ExportedKey::Bytes(private_key_info.to_bytes())
992 },
993 // If format is "raw-public":
994 KeyFormat::Raw_public => {
995 // Step 3.1. If the [[type]] internal slot of key is not "public", then throw an
996 // InvalidAccessError.
997 key.ensure_type(KeyType::Public)?;
998
999 // Step 3.2. Let data be a byte sequence containing the ML-DSA public key represented
1000 // by the [[handle]] internal slot of key.
1001 let data = match key.handle() {
1002 Handle::MlDsa44PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1003 Handle::MlDsa65PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1004 Handle::MlDsa87PublicKey(public_key) => public_key.to_bytes().as_slice().to_vec(),
1005 _ => {
1006 return Err(Error::Operation(Some(
1007 "The key handle is not representing an ML-DSA public key".into(),
1008 )));
1009 },
1010 };
1011
1012 // Step 3.2. Let result be data.
1013 ExportedKey::new_bytes(data)
1014 },
1015 // If format is "raw-seed":
1016 KeyFormat::Raw_seed => {
1017 // Step 3.1. If the [[type]] internal slot of key is not "private", then throw an
1018 // InvalidAccessError.
1019 key.ensure_type(KeyType::Private)?;
1020
1021 // Step 3.2. Let data be a byte sequence containing the ξ seed variable of the key
1022 // represented by the [[handle]] internal slot of key.
1023 let data = match key.handle() {
1024 Handle::MlDsa44PrivateKey(private_key) => private_key.as_seed().as_slice().to_vec(),
1025 Handle::MlDsa65PrivateKey(private_key) => private_key.as_seed().as_slice().to_vec(),
1026 Handle::MlDsa87PrivateKey(private_key) => private_key.as_seed().as_slice().to_vec(),
1027 _ => {
1028 return Err(Error::Operation(Some(
1029 "The key handle is not representing an ML-DSA private key".into(),
1030 )));
1031 },
1032 };
1033
1034 // Step 3.3. Let result be data.
1035 ExportedKey::new_bytes(data)
1036 },
1037 // If format is "jwk":
1038 KeyFormat::Jwk => {
1039 // Step 3.1. Let jwk be a new JsonWebKey dictionary.
1040 let mut jwk = JsonWebKey::default();
1041
1042 // Step 3.2. Let keyAlgorithm be the [[algorithm]] internal slot of key.
1043 let KeyAlgorithmAndDerivatives::KeyAlgorithm(key_algorithm) = key.algorithm() else {
1044 return Err(Error::Operation(Some(
1045 "[[algorithm]] internal slot of key is not a KeyAlgorithm".into(),
1046 )));
1047 };
1048
1049 // Step 3.3. Set the kty attribute of jwk to "AKP".
1050 jwk.kty = Some(DOMString::from_static("AKP"));
1051
1052 // Step 3.4. Set the alg attribute of jwk to the name member of normalizedAlgorithm.
1053 jwk.alg = Some(DOMString::from(key_algorithm.name.as_str()));
1054
1055 // Step 3.5. Set the pub attribute of jwk to the base64url encoded public key
1056 // corresponding to the [[handle]] internal slot of key.
1057 // Step 3.6.
1058 // If the [[type]] internal slot of key is "private":
1059 // Set the priv attribute of jwk to the base64url encoded seed represented by the
1060 // [[handle]] internal slot of key.
1061 if key.Type() == KeyType::Private {
1062 match key.handle() {
1063 Handle::MlDsa44PrivateKey(private_key) => {
1064 jwk.encode_string_field(
1065 JwkStringField::Priv,
1066 private_key.as_seed().as_slice(),
1067 );
1068 jwk.encode_string_field(
1069 JwkStringField::Pub,
1070 private_key.as_ref().to_bytes().as_slice(),
1071 );
1072 },
1073 Handle::MlDsa65PrivateKey(private_key) => {
1074 jwk.encode_string_field(
1075 JwkStringField::Priv,
1076 private_key.as_seed().as_slice(),
1077 );
1078 jwk.encode_string_field(
1079 JwkStringField::Pub,
1080 private_key.as_ref().to_bytes().as_slice(),
1081 );
1082 },
1083 Handle::MlDsa87PrivateKey(private_key) => {
1084 jwk.encode_string_field(
1085 JwkStringField::Priv,
1086 private_key.as_seed().as_slice(),
1087 );
1088 jwk.encode_string_field(
1089 JwkStringField::Pub,
1090 private_key.as_ref().to_bytes().as_slice(),
1091 );
1092 },
1093 _ => {
1094 return Err(Error::Operation(Some(
1095 "The key handle is not representing an ML-DSA private key".into(),
1096 )));
1097 },
1098 }
1099 } else {
1100 match key.handle() {
1101 Handle::MlDsa44PublicKey(public_key) => {
1102 jwk.encode_string_field(
1103 JwkStringField::Pub,
1104 public_key.to_bytes().as_slice(),
1105 );
1106 },
1107 Handle::MlDsa65PublicKey(public_key) => {
1108 jwk.encode_string_field(
1109 JwkStringField::Pub,
1110 public_key.to_bytes().as_slice(),
1111 );
1112 },
1113 Handle::MlDsa87PublicKey(public_key) => {
1114 jwk.encode_string_field(
1115 JwkStringField::Pub,
1116 public_key.to_bytes().as_slice(),
1117 );
1118 },
1119 _ => {
1120 return Err(Error::Operation(Some(
1121 "The key handle is not representing an ML-DSA public key".into(),
1122 )));
1123 },
1124 };
1125 }
1126
1127 // Step 3.7. Set the key_ops attribute of jwk to the usages attribute of key.
1128 jwk.set_key_ops(key.usages());
1129
1130 // Step 3.8. Set the ext attribute of jwk to the [[extractable]] internal slot of key.
1131 jwk.ext = Some(key.Extractable());
1132
1133 // Step 3.9. Let result be jwk.
1134 ExportedKey::new_jwk(jwk)
1135 },
1136 // Otherwise:
1137 _ => {
1138 // throw a NotSupportedError.
1139 return Err(Error::NotSupported(Some(
1140 "Unsupported export key format for ML-DSA key".into(),
1141 )));
1142 },
1143 };
1144
1145 // Step 3. Return result.
1146 Ok(result)
1147}
1148
1149/// <https://wicg.github.io/webcrypto-modern-algos/#SubtleCrypto-method-getPublicKey>
1150/// Step 9 - 15, for ML-DSA
1151pub(crate) fn get_public_key<D: Equivalence>(
1152 cx: &mut JSContext,
1153 global: &D::GlobalScope,
1154 key: &CryptoKey<D>,
1155 algorithm: &KeyAlgorithmAndDerivatives,
1156 usages: Vec<KeyUsage>,
1157) -> Result<DomRoot<CryptoKey<D>>, Error> {
1158 // Step 9. If usages contains an entry which is not supported for a public key by the algorithm
1159 // identified by algorithm, then throw a SyntaxError.
1160 //
1161 // NOTE: See "importKey" operation for supported usages
1162 usages.ensure_only_contain_entries_from(&[KeyUsage::Verify])?;
1163
1164 // Step 10. Let publicKey be a new CryptoKey representing the public key corresponding to the
1165 // private key represented by the [[handle]] internal slot of key.
1166 // Step 11. If an error occurred, then throw a OperationError.
1167 // Step 12. Set the [[type]] internal slot of publicKey to "public".
1168 // Step 13. Set the [[algorithm]] internal slot of publicKey to algorithm.
1169 // Step 14. Set the [[extractable]] internal slot of publicKey to true.
1170 // Step 15. Set the [[usages]] internal slot of publicKey to the normalized value of usages.
1171 let public_key_handle = match key.handle() {
1172 Handle::MlDsa44PrivateKey(private_key) => {
1173 Handle::MlDsa44PublicKey(private_key.verifying_key())
1174 },
1175 Handle::MlDsa65PrivateKey(private_key) => {
1176 Handle::MlDsa65PublicKey(private_key.verifying_key())
1177 },
1178 Handle::MlDsa87PrivateKey(private_key) => {
1179 Handle::MlDsa87PublicKey(private_key.verifying_key())
1180 },
1181 _ => {
1182 return Err(Error::Operation(Some(
1183 "[[handle]] internal slot of key is not an ML-DSA private key".into(),
1184 )));
1185 },
1186 };
1187 let public_key = CryptoKey::new(
1188 cx,
1189 global,
1190 KeyType::Public,
1191 true,
1192 algorithm.clone(),
1193 usages.normalized_value(),
1194 public_key_handle,
1195 );
1196
1197 Ok(public_key)
1198}