Skip to main content

script_webcrypto/
cryptokey.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 std::marker::PhantomData;
6use std::str::FromStr;
7
8use dom_struct::dom_struct;
9use itertools::Itertools;
10use js::context::NoGC;
11use js::conversions::ToJSValConvertible;
12use js::jsapi::{Heap, JSObject, Value};
13use js::rooted;
14use js::rust::MutableHandleObject;
15use jstraceable_derive::JSTraceable;
16use malloc_size_of::{MallocSizeOf, MallocSizeOfOps};
17use malloc_size_of_derive::MallocSizeOf;
18use rustc_hash::FxHashMap;
19use script_bindings::DomTypes;
20use script_bindings::codegen::GenericBindings::CryptoKeyBinding::{
21    CryptoKeyMethods, CryptoKeyPair, KeyType, KeyUsage, Wrap as CryptoKeyWrap,
22};
23use script_bindings::error::{Error, ErrorResult};
24use script_bindings::reflector::{Reflector, reflect_dom_object_with_wrap};
25use script_bindings::root::DomRoot;
26use script_bindings::serializable::Serializable;
27use script_bindings::structuredclone::StructuredData;
28use script_bindings::trace::RootedTraceableBox;
29use servo_base::id::{CryptoKeyId, CryptoKeyIndex};
30use servo_constellation_traits::{SerializableCryptoKey, SerializableCryptoKeyHandle};
31use strum::VariantArray;
32use zeroize::Zeroizing;
33
34use crate::subtlecrypto::KeyAlgorithmAndDerivatives;
35use crate::traits::Equivalence;
36
37pub(crate) enum CryptoKeyOrCryptoKeyPair<D: DomTypes> {
38    CryptoKey(DomRoot<CryptoKey<D>>),
39    CryptoKeyPair(RootedTraceableBox<CryptoKeyPair<D>>),
40}
41
42/// The underlying cryptographic data this key represents.
43///
44/// Please make sure the inner types for secret variants implement the `zeroize::ZeroizeOnDrop`
45/// trait, which signifies that the type will call `Zeroize::zeroize` on `Drop` to securely erase
46/// the secret from memory.
47pub(crate) enum Handle {
48    RsaPrivateKey(rsa::PrivateKey),
49    RsaPublicKey(rsa::PublicKey),
50    P256PrivateKey(p256::SecretKey),
51    P384PrivateKey(p384::SecretKey),
52    P521PrivateKey(p521::SecretKey),
53    P256PublicKey(p256::PublicKey),
54    P384PublicKey(p384::PublicKey),
55    P521PublicKey(p521::PublicKey),
56    Ed25519PrivateKey(ed25519_dalek::SigningKey),
57    Ed25519PublicKey(ed25519_dalek::VerifyingKey),
58    X25519PrivateKey(x25519_dalek::StaticSecret),
59    X25519PublicKey(x25519_dalek::PublicKey),
60    Ed448PrivateKey(ed448_goldilocks::SigningKey),
61    Ed448PublicKey(ed448_goldilocks::VerifyingKey),
62    X448PrivateKey(x448::StaticSecret),
63    X448PublicKey(x448::PublicKey),
64    Aes128Key(aes::cipher::common::Key<aes::Aes128>),
65    Aes192Key(aes::cipher::common::Key<aes::Aes192>),
66    Aes256Key(aes::cipher::common::Key<aes::Aes256>),
67    HkdfSecret(Zeroizing<Vec<u8>>),
68    Pbkdf2Password(Zeroizing<Vec<u8>>),
69    Hmac(Zeroizing<Vec<u8>>),
70    MlKem512PrivateKey(ml_kem::DecapsulationKey<ml_kem::MlKem512>),
71    MlKem768PrivateKey(ml_kem::DecapsulationKey<ml_kem::MlKem768>),
72    MlKem1024PrivateKey(ml_kem::DecapsulationKey<ml_kem::MlKem1024>),
73    MlKem512PublicKey(ml_kem::EncapsulationKey<ml_kem::MlKem512>),
74    MlKem768PublicKey(ml_kem::EncapsulationKey<ml_kem::MlKem768>),
75    MlKem1024PublicKey(ml_kem::EncapsulationKey<ml_kem::MlKem1024>),
76    MlKem768X25519PrivateKey(x_wing::DecapsulationKey),
77    MlKem768X25519PublicKey(x_wing::EncapsulationKey),
78    MlDsa44PrivateKey(ml_dsa::SigningKey<ml_dsa::MlDsa44>),
79    MlDsa65PrivateKey(ml_dsa::SigningKey<ml_dsa::MlDsa65>),
80    MlDsa87PrivateKey(ml_dsa::SigningKey<ml_dsa::MlDsa87>),
81    MlDsa44PublicKey(ml_dsa::VerifyingKey<ml_dsa::MlDsa44>),
82    MlDsa65PublicKey(ml_dsa::VerifyingKey<ml_dsa::MlDsa65>),
83    MlDsa87PublicKey(ml_dsa::VerifyingKey<ml_dsa::MlDsa87>),
84    ChaCha20Poly1305Key(chacha20poly1305::Key),
85    KmacKey(Zeroizing<Vec<u8>>),
86    Argon2Password(Zeroizing<Vec<u8>>),
87}
88
89/// <https://w3c.github.io/webcrypto/#cryptokey-interface>
90#[dom_struct]
91pub struct CryptoKey<D: DomTypes> {
92    reflector_: Reflector,
93
94    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-type>
95    key_type: KeyType,
96
97    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-extractable>
98    extractable: bool,
99
100    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-algorithm>
101    ///
102    /// The contents of the [[algorithm]] internal slot shall be, or be derived from, a
103    /// KeyAlgorithm.
104    #[no_trace]
105    algorithm: KeyAlgorithmAndDerivatives,
106
107    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-algorithm_cached>
108    #[ignore_malloc_size_of = "Defined in mozjs"]
109    algorithm_cached: Heap<*mut JSObject>,
110
111    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-usages>
112    ///
113    /// The contents of the [[usages]] internal slot shall be of type Sequence<KeyUsage>.
114    usages: Vec<KeyUsage>,
115
116    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-usages_cached>
117    #[ignore_malloc_size_of = "Defined in mozjs"]
118    usages_cached: Heap<*mut JSObject>,
119
120    /// <https://w3c.github.io/webcrypto/#dfn-CryptoKey-slot-handle>
121    #[no_trace]
122    handle: Handle,
123
124    #[no_trace = "PhantomData does not exist"]
125    phantom: PhantomData<D>,
126}
127
128impl<D> CryptoKey<D>
129where
130    D: Equivalence,
131{
132    fn new_inherited(
133        key_type: KeyType,
134        extractable: bool,
135        algorithm: KeyAlgorithmAndDerivatives,
136        usages: Vec<KeyUsage>,
137        handle: Handle,
138    ) -> CryptoKey<D> {
139        CryptoKey {
140            reflector_: Reflector::new(),
141            key_type,
142            extractable,
143            algorithm,
144            algorithm_cached: Heap::default(),
145            usages,
146            usages_cached: Heap::default(),
147            handle,
148            phantom: PhantomData,
149        }
150    }
151
152    pub(crate) fn new(
153        cx: &mut js::context::JSContext,
154        global: &D::GlobalScope,
155        key_type: KeyType,
156        extractable: bool,
157        algorithm: KeyAlgorithmAndDerivatives,
158        usages: Vec<KeyUsage>,
159        handle: Handle,
160    ) -> DomRoot<CryptoKey<D>> {
161        let crypto_key = reflect_dom_object_with_wrap::<D, _, _>(
162            cx,
163            Box::new(CryptoKey::new_inherited(
164                key_type,
165                extractable,
166                algorithm.clone(),
167                usages.clone(),
168                handle,
169            )),
170            global,
171            CryptoKeyWrap::<D>,
172        );
173
174        // Create and store a cached object of algorithm
175        rooted!(&in(cx) let mut algorithm_object_value: Value);
176        algorithm.to_jsval(cx, algorithm_object_value.handle_mut());
177        crypto_key
178            .algorithm_cached
179            .set(algorithm_object_value.to_object());
180
181        // Create and store a cached object of usages
182        rooted!(&in(cx) let mut usages_object_value: Value);
183        usages.to_jsval(cx, usages_object_value.handle_mut());
184        crypto_key
185            .usages_cached
186            .set(usages_object_value.to_object());
187
188        crypto_key
189    }
190
191    pub(crate) fn algorithm(&self) -> &KeyAlgorithmAndDerivatives {
192        &self.algorithm
193    }
194
195    pub(crate) fn usages(&self) -> &[KeyUsage] {
196        &self.usages
197    }
198
199    pub(crate) fn handle(&self) -> &Handle {
200        &self.handle
201    }
202
203    /// Ensure that the [[type]] internal slot of key is same as `expected`. If the [[type]]
204    /// internal slot of key is not same as `expected`, then throw an InvalidAccessError.
205    pub(crate) fn ensure_type(&self, expected: KeyType) -> ErrorResult {
206        if self.key_type == expected {
207            Ok(())
208        } else {
209            Err(Error::InvalidAccess(Some(match expected {
210                KeyType::Public => "The key is not a public key".into(),
211                KeyType::Private => "The key is not a private key".into(),
212                KeyType::Secret => "The key is not a secret key".into(),
213            })))
214        }
215    }
216}
217
218impl<D> CryptoKeyMethods<D> for CryptoKey<D>
219where
220    D: DomTypes,
221{
222    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-type>
223    fn Type(&self) -> KeyType {
224        // Reflects the [[type]] internal slot, which contains the type of the underlying key.
225        self.key_type
226    }
227
228    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-extractable>
229    fn Extractable(&self) -> bool {
230        // Reflects the [[extractable]] internal slot, which indicates whether or not the raw
231        // keying material may be exported by the application.
232        self.extractable
233    }
234
235    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-algorithm>
236    fn Algorithm(&self, mut return_value: MutableHandleObject) {
237        // Returns the cached ECMAScript object associated with the [[algorithm]] internal slot.
238        return_value.set(self.algorithm_cached.get())
239    }
240
241    /// <https://w3c.github.io/webcrypto/#dom-cryptokey-usages>
242    fn Usages(&self, mut return_value: MutableHandleObject) {
243        // Returns the cached ECMAScript object associated with the [[usages]] internal slot, which
244        // indicates which cryptographic operations are permissible to be used with this key.
245        return_value.set(self.usages_cached.get())
246    }
247}
248
249impl<D> Serializable<D> for CryptoKey<D>
250where
251    D: Equivalence,
252{
253    type Index = CryptoKeyIndex;
254    type Data = SerializableCryptoKey;
255
256    /// <https://w3c.github.io/webcrypto/#cryptokey-interface-serializable>
257    fn serialize(&self, _no_gc: &NoGC) -> Result<(CryptoKeyId, Self::Data), ()> {
258        // Step 1. Set serialized.[[Type]] to the [[type]] internal slot of value.
259        // Step 2. Set serialized.[[Extractable]] to the [[extractable]] internal slot of value.
260        // Step 3. Set serialized.[[Algorithm]] to the sub-serialization of the [[algorithm]]
261        // internal slot of value.
262        // Step 4. Set serialized.[[Usages]] to the sub-serialization of the [[usages]] internal
263        // slot of value.
264        // Step 5. Set serialized.[[Handle]] to the [[handle]] internal slot of value.
265        let serialized = SerializableCryptoKey {
266            key_type: self.key_type.as_str().into(),
267            extractable: self.extractable,
268            algorithm: (&self.algorithm).into(),
269            usages: self
270                .usages
271                .iter()
272                .map(|usage| usage.as_str().into())
273                .collect(),
274            handle: (&self.handle).try_into()?,
275        };
276        Ok((CryptoKeyId::new(), serialized))
277    }
278
279    /// <https://w3c.github.io/webcrypto/#cryptokey-interface-serializable>
280    fn deserialize(
281        cx: &mut js::context::JSContext,
282        owner: &D::GlobalScope,
283        serialized: Self::Data,
284    ) -> Result<DomRoot<Self>, ()> {
285        // Step 1. Initialize the [[type]] internal slot of value to serialized.[[Type]].
286        // Step 2. Initialize the [[extractable]] internal slot of value to
287        // serialized.[[Extractable]].
288        // Step 3. Initialize the [[algorithm]] internal slot of value to the sub-deserialization of
289        // serialized.[[Algorithm]].
290        // Step 4. Initialize the [[usages]] internal slot of value to the sub-deserialization of
291        // serialized.[[Usages]].
292        // Step 5. Initialize the [[handle]] internal slot of value to serialized.[[Handle]].
293        Ok(CryptoKey::new(
294            cx,
295            owner,
296            KeyType::from_str(&serialized.key_type)?,
297            serialized.extractable,
298            serialized.algorithm.try_into()?,
299            serialized
300                .usages
301                .iter()
302                .map(|usage| KeyUsage::from_str(usage))
303                .collect::<Result<Vec<_>, _>>()?,
304            serialized.handle.try_into()?,
305        ))
306    }
307
308    fn serialized_storage<'a>(
309        reader: StructuredData<'a, '_>,
310    ) -> &'a mut Option<FxHashMap<CryptoKeyId, Self::Data>> {
311        match reader {
312            StructuredData::Reader(reader) => &mut reader.crypto_keys,
313            StructuredData::Writer(writer) => &mut writer.crypto_keys,
314        }
315    }
316}
317
318impl Handle {
319    pub(crate) fn as_bytes(&self) -> &[u8] {
320        match self {
321            Self::Hmac(bytes) => bytes,
322            _ => unreachable!(),
323        }
324    }
325}
326
327impl MallocSizeOf for Handle {
328    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
329        match self {
330            Handle::RsaPrivateKey(private_key) => private_key.size_of(ops),
331            Handle::RsaPublicKey(public_key) => public_key.size_of(ops),
332            Handle::P256PrivateKey(private_key) => private_key.size_of(ops),
333            Handle::P384PrivateKey(private_key) => private_key.size_of(ops),
334            Handle::P521PrivateKey(private_key) => private_key.size_of(ops),
335            Handle::P256PublicKey(public_key) => public_key.size_of(ops),
336            Handle::P384PublicKey(public_key) => public_key.size_of(ops),
337            Handle::P521PublicKey(public_key) => public_key.size_of(ops),
338            Handle::Ed25519PrivateKey(bytes) => bytes.size_of(ops),
339            Handle::Ed25519PublicKey(bytes) => bytes.size_of(ops),
340            Handle::X25519PrivateKey(private_key) => private_key.size_of(ops),
341            Handle::X25519PublicKey(public_key) => public_key.size_of(ops),
342            Handle::Ed448PrivateKey(private_key) => private_key.size_of(ops),
343            Handle::Ed448PublicKey(public_key) => public_key.size_of(ops),
344            Handle::X448PrivateKey(private_key) => private_key.size_of(ops),
345            Handle::X448PublicKey(public_key) => public_key.size_of(ops),
346            Handle::Aes128Key(key) => key.size_of(ops),
347            Handle::Aes192Key(key) => key.size_of(ops),
348            Handle::Aes256Key(key) => key.size_of(ops),
349            Handle::HkdfSecret(secret) => secret.size_of(ops),
350            Handle::Pbkdf2Password(password) => password.size_of(ops),
351            Handle::Hmac(bytes) => bytes.size_of(ops),
352            Handle::MlKem512PrivateKey(private_key) => private_key.size_of(ops),
353            Handle::MlKem768PrivateKey(private_key) => private_key.size_of(ops),
354            Handle::MlKem1024PrivateKey(private_key) => private_key.size_of(ops),
355            Handle::MlKem512PublicKey(public_key) => public_key.size_of(ops),
356            Handle::MlKem768PublicKey(public_key) => public_key.size_of(ops),
357            Handle::MlKem1024PublicKey(public_key) => public_key.size_of(ops),
358            Handle::MlKem768X25519PrivateKey(private_key) => private_key.size_of(ops),
359            Handle::MlKem768X25519PublicKey(public_key) => public_key.size_of(ops),
360            Handle::MlDsa44PrivateKey(private_key) => private_key.size_of(ops),
361            Handle::MlDsa65PrivateKey(private_key) => private_key.size_of(ops),
362            Handle::MlDsa87PrivateKey(private_key) => private_key.size_of(ops),
363            Handle::MlDsa44PublicKey(public_key) => public_key.size_of(ops),
364            Handle::MlDsa65PublicKey(public_key) => public_key.size_of(ops),
365            Handle::MlDsa87PublicKey(public_key) => public_key.size_of(ops),
366            Handle::ChaCha20Poly1305Key(key) => key.size_of(ops),
367            Handle::KmacKey(key) => key.size_of(ops),
368            Handle::Argon2Password(password) => password.size_of(ops),
369        }
370    }
371}
372
373impl TryFrom<SerializableCryptoKeyHandle> for Handle {
374    type Error = ();
375
376    fn try_from(value: SerializableCryptoKeyHandle) -> Result<Self, Self::Error> {
377        match &value {
378            SerializableCryptoKeyHandle::RsaPrivateKey(private_key) => Ok(Handle::RsaPrivateKey(
379                rsa::pkcs8::DecodePrivateKey::from_pkcs8_der(private_key).map_err(|_| ())?,
380            )),
381            SerializableCryptoKeyHandle::RsaPublicKey(public_key) => Ok(Handle::RsaPublicKey(
382                rsa::pkcs8::spki::DecodePublicKey::from_public_key_der(public_key)
383                    .map_err(|_| ())?,
384            )),
385            SerializableCryptoKeyHandle::P256PrivateKey(private_key) => Ok(Handle::P256PrivateKey(
386                p256::SecretKey::from_slice(private_key).map_err(|_| ())?,
387            )),
388            SerializableCryptoKeyHandle::P384PrivateKey(private_key) => Ok(Handle::P384PrivateKey(
389                p384::SecretKey::from_slice(private_key).map_err(|_| ())?,
390            )),
391            SerializableCryptoKeyHandle::P521PrivateKey(private_key) => Ok(Handle::P521PrivateKey(
392                p521::SecretKey::from_slice(private_key).map_err(|_| ())?,
393            )),
394            SerializableCryptoKeyHandle::P256PublicKey(public_key) => Ok(Handle::P256PublicKey(
395                p256::PublicKey::from_sec1_bytes(public_key).map_err(|_| ())?,
396            )),
397            SerializableCryptoKeyHandle::P384PublicKey(public_key) => Ok(Handle::P384PublicKey(
398                p384::PublicKey::from_sec1_bytes(public_key).map_err(|_| ())?,
399            )),
400            SerializableCryptoKeyHandle::P521PublicKey(public_key) => Ok(Handle::P521PublicKey(
401                p521::PublicKey::from_sec1_bytes(public_key).map_err(|_| ())?,
402            )),
403            SerializableCryptoKeyHandle::Ed25519PrivateKey(private_key) => Ok(
404                Handle::Ed25519PrivateKey(ed25519_dalek::SigningKey::from_bytes(private_key)),
405            ),
406            SerializableCryptoKeyHandle::Ed25519PublicKey(public_key) => {
407                Ok(Handle::Ed25519PublicKey(
408                    ed25519_dalek::VerifyingKey::from_bytes(public_key).map_err(|_| ())?,
409                ))
410            },
411            SerializableCryptoKeyHandle::X25519PrivateKey(private_key) => {
412                Ok(Handle::X25519PrivateKey((*private_key).into()))
413            },
414            SerializableCryptoKeyHandle::X25519PublicKey(public_key) => {
415                Ok(Handle::X25519PublicKey((*public_key).into()))
416            },
417            SerializableCryptoKeyHandle::Ed448PrivateKey(private_key) => {
418                Ok(Handle::Ed448PrivateKey(
419                    ed448_goldilocks::SigningKey::try_from(private_key).map_err(|_| ())?,
420                ))
421            },
422            SerializableCryptoKeyHandle::Ed448PublicKey(public_key) => Ok(Handle::Ed448PublicKey(
423                ed448_goldilocks::VerifyingKey::from_bytes(
424                    public_key.as_slice().try_into().map_err(|_| ())?,
425                )
426                .map_err(|_| ())?,
427            )),
428            SerializableCryptoKeyHandle::X448PrivateKey(private_key) => {
429                Ok(Handle::X448PrivateKey(x448::StaticSecret::from(
430                    <[u8; 56]>::try_from(private_key.as_slice()).map_err(|_| ())?,
431                )))
432            },
433            SerializableCryptoKeyHandle::X448PublicKey(public_key) => Ok(Handle::X448PublicKey(
434                x448::PublicKey::from_bytes_unchecked(public_key).ok_or(())?,
435            )),
436            SerializableCryptoKeyHandle::Aes128Key(key) => Ok(Handle::Aes128Key(
437                aes::cipher::common::Key::<aes::Aes128>::try_from(key).map_err(|_| ())?,
438            )),
439            SerializableCryptoKeyHandle::Aes192Key(key) => Ok(Handle::Aes192Key(
440                aes::cipher::common::Key::<aes::Aes192>::try_from(key).map_err(|_| ())?,
441            )),
442            SerializableCryptoKeyHandle::Aes256Key(key) => Ok(Handle::Aes256Key(
443                aes::cipher::common::Key::<aes::Aes256>::try_from(key).map_err(|_| ())?,
444            )),
445            SerializableCryptoKeyHandle::Hmac(bytes) => Ok(Handle::Hmac(bytes.clone().into())),
446            SerializableCryptoKeyHandle::HkdfSecret(bytes) => {
447                Ok(Handle::HkdfSecret(bytes.clone().into()))
448            },
449            SerializableCryptoKeyHandle::Pbkdf2Password(password) => {
450                Ok(Handle::Pbkdf2Password(password.clone().into()))
451            },
452            SerializableCryptoKeyHandle::MlKem512PrivateKey(private_key) => {
453                Ok(Handle::MlKem512PrivateKey(
454                    ml_kem::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
455                ))
456            },
457            SerializableCryptoKeyHandle::MlKem768PrivateKey(private_key) => {
458                Ok(Handle::MlKem768PrivateKey(
459                    ml_kem::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
460                ))
461            },
462            SerializableCryptoKeyHandle::MlKem1024PrivateKey(private_key) => {
463                Ok(Handle::MlKem1024PrivateKey(
464                    ml_kem::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
465                ))
466            },
467            SerializableCryptoKeyHandle::MlKem512PublicKey(public_key) => {
468                Ok(Handle::MlKem512PublicKey(
469                    ml_kem::TryKeyInit::new_from_slice(public_key).map_err(|_| ())?,
470                ))
471            },
472            SerializableCryptoKeyHandle::MlKem768PublicKey(public_key) => {
473                Ok(Handle::MlKem768PublicKey(
474                    ml_kem::TryKeyInit::new_from_slice(public_key).map_err(|_| ())?,
475                ))
476            },
477            SerializableCryptoKeyHandle::MlKem1024PublicKey(public_key) => {
478                Ok(Handle::MlKem1024PublicKey(
479                    ml_kem::TryKeyInit::new_from_slice(public_key).map_err(|_| ())?,
480                ))
481            },
482            SerializableCryptoKeyHandle::MlKem768X25519PrivateKey(private_key) => {
483                Ok(Handle::MlKem768X25519PrivateKey(
484                    x_wing::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
485                ))
486            },
487            SerializableCryptoKeyHandle::MlKem768X25519PublicKey(public_key) => {
488                Ok(Handle::MlKem768X25519PublicKey(
489                    x_wing::TryKeyInit::new_from_slice(public_key).map_err(|_| ())?,
490                ))
491            },
492            SerializableCryptoKeyHandle::MlDsa44PrivateKey(private_key) => {
493                Ok(Handle::MlDsa44PrivateKey(
494                    ml_dsa::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
495                ))
496            },
497            SerializableCryptoKeyHandle::MlDsa65PrivateKey(private_key) => {
498                Ok(Handle::MlDsa65PrivateKey(
499                    ml_dsa::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
500                ))
501            },
502            SerializableCryptoKeyHandle::MlDsa87PrivateKey(private_key) => {
503                Ok(Handle::MlDsa87PrivateKey(
504                    ml_dsa::KeyInit::new_from_slice(private_key).map_err(|_| ())?,
505                ))
506            },
507            SerializableCryptoKeyHandle::MlDsa44PublicKey(public_key) => {
508                Ok(Handle::MlDsa44PublicKey(
509                    ml_dsa::KeyInit::new_from_slice(public_key).map_err(|_| ())?,
510                ))
511            },
512            SerializableCryptoKeyHandle::MlDsa65PublicKey(public_key) => {
513                Ok(Handle::MlDsa65PublicKey(
514                    ml_dsa::KeyInit::new_from_slice(public_key).map_err(|_| ())?,
515                ))
516            },
517            SerializableCryptoKeyHandle::MlDsa87PublicKey(public_key) => {
518                Ok(Handle::MlDsa87PublicKey(
519                    ml_dsa::KeyInit::new_from_slice(public_key).map_err(|_| ())?,
520                ))
521            },
522            SerializableCryptoKeyHandle::ChaCha20Poly1305Key(key) => Ok(
523                Handle::ChaCha20Poly1305Key(chacha20poly1305::Key::try_from(key).map_err(|_| ())?),
524            ),
525            SerializableCryptoKeyHandle::KmacKey(key) => Ok(Handle::KmacKey(key.clone().into())),
526            SerializableCryptoKeyHandle::Argon2Password(password) => {
527                Ok(Handle::Argon2Password(password.clone().into()))
528            },
529        }
530    }
531}
532
533/// To serialize the key in the `Handle`, we convert the key into byte sequences. For most
534/// cryptographic algorithms, this conversion is straightforward since the key can natually be
535/// expressed as a byte sequence. However, some cryptographic algorithms require preprocessing
536/// before their key can be represented in byte sequences. For example, an RSA private key needs to
537/// be first converted into DER-encoded PKCS#8 format before it can be expressed as a byte sequence.
538impl TryFrom<&Handle> for SerializableCryptoKeyHandle {
539    type Error = ();
540
541    fn try_from(value: &Handle) -> Result<Self, Self::Error> {
542        match value {
543            Handle::RsaPrivateKey(private_key) => Ok(SerializableCryptoKeyHandle::RsaPrivateKey(
544                rsa::pkcs8::EncodePrivateKey::to_pkcs8_der(private_key)
545                    .map_err(|_| ())?
546                    .as_bytes()
547                    .to_vec(),
548            )),
549            Handle::RsaPublicKey(public_key) => Ok(SerializableCryptoKeyHandle::RsaPublicKey(
550                rsa::pkcs8::spki::EncodePublicKey::to_public_key_der(public_key)
551                    .map_err(|_| ())?
552                    .into_vec(),
553            )),
554            Handle::P256PrivateKey(private_key) => Ok(SerializableCryptoKeyHandle::P256PrivateKey(
555                private_key.to_bytes().as_slice().to_vec(),
556            )),
557            Handle::P384PrivateKey(private_key) => Ok(SerializableCryptoKeyHandle::P384PrivateKey(
558                private_key.to_bytes().as_slice().to_vec(),
559            )),
560            Handle::P521PrivateKey(private_key) => Ok(SerializableCryptoKeyHandle::P521PrivateKey(
561                private_key.to_bytes().as_slice().to_vec(),
562            )),
563            Handle::P256PublicKey(public_key) => Ok(SerializableCryptoKeyHandle::P256PublicKey(
564                public_key.to_sec1_bytes().to_vec(),
565            )),
566            Handle::P384PublicKey(public_key) => Ok(SerializableCryptoKeyHandle::P384PublicKey(
567                public_key.to_sec1_bytes().to_vec(),
568            )),
569            Handle::P521PublicKey(public_key) => Ok(SerializableCryptoKeyHandle::P521PublicKey(
570                public_key.to_sec1_bytes().to_vec(),
571            )),
572            Handle::Ed25519PrivateKey(private_key) => Ok(
573                SerializableCryptoKeyHandle::Ed25519PrivateKey(private_key.to_bytes()),
574            ),
575            Handle::Ed25519PublicKey(public_key) => Ok(
576                SerializableCryptoKeyHandle::Ed25519PublicKey(public_key.to_bytes()),
577            ),
578            Handle::X25519PrivateKey(private_key) => Ok(
579                SerializableCryptoKeyHandle::X25519PrivateKey(private_key.to_bytes()),
580            ),
581            Handle::X25519PublicKey(public_key) => Ok(
582                SerializableCryptoKeyHandle::X25519PublicKey(public_key.to_bytes()),
583            ),
584            Handle::Ed448PrivateKey(private_key) => Ok(
585                SerializableCryptoKeyHandle::Ed448PrivateKey(private_key.as_bytes().to_vec()),
586            ),
587            Handle::Ed448PublicKey(public_key) => Ok(SerializableCryptoKeyHandle::Ed448PublicKey(
588                public_key.as_bytes().to_vec(),
589            )),
590            Handle::X448PrivateKey(private_key) => Ok(SerializableCryptoKeyHandle::X448PrivateKey(
591                private_key.as_bytes().to_vec(),
592            )),
593            Handle::X448PublicKey(public_key) => Ok(SerializableCryptoKeyHandle::X448PublicKey(
594                public_key.as_bytes().to_vec(),
595            )),
596            Handle::Aes128Key(key) => Ok(SerializableCryptoKeyHandle::Aes128Key(key.to_vec())),
597            Handle::Aes192Key(key) => Ok(SerializableCryptoKeyHandle::Aes192Key(key.to_vec())),
598            Handle::Aes256Key(key) => Ok(SerializableCryptoKeyHandle::Aes256Key(key.to_vec())),
599            Handle::Hmac(bytes) => Ok(SerializableCryptoKeyHandle::Hmac(bytes.to_vec())),
600            Handle::HkdfSecret(bytes) => {
601                Ok(SerializableCryptoKeyHandle::HkdfSecret(bytes.to_vec()))
602            },
603            Handle::Pbkdf2Password(password) => Ok(SerializableCryptoKeyHandle::Pbkdf2Password(
604                password.to_vec(),
605            )),
606            Handle::MlKem512PrivateKey(private_key) => {
607                Ok(SerializableCryptoKeyHandle::MlKem512PrivateKey(
608                    private_key
609                        .to_seed()
610                        .expect("This decapsulation key should contain seed value")
611                        .as_slice()
612                        .to_vec(),
613                ))
614            },
615            Handle::MlKem768PrivateKey(private_key) => {
616                Ok(SerializableCryptoKeyHandle::MlKem768PrivateKey(
617                    private_key
618                        .to_seed()
619                        .expect("This decapsulation key should contain seed value")
620                        .as_slice()
621                        .to_vec(),
622                ))
623            },
624            Handle::MlKem1024PrivateKey(private_key) => {
625                Ok(SerializableCryptoKeyHandle::MlKem1024PrivateKey(
626                    private_key
627                        .to_seed()
628                        .expect("This decapsulation key should contain seed value")
629                        .as_slice()
630                        .to_vec(),
631                ))
632            },
633            Handle::MlKem512PublicKey(public_key) => {
634                Ok(SerializableCryptoKeyHandle::MlKem512PublicKey(
635                    ml_kem::KeyExport::to_bytes(public_key).as_slice().to_vec(),
636                ))
637            },
638            Handle::MlKem768PublicKey(public_key) => {
639                Ok(SerializableCryptoKeyHandle::MlKem768PublicKey(
640                    ml_kem::KeyExport::to_bytes(public_key).as_slice().to_vec(),
641                ))
642            },
643            Handle::MlKem1024PublicKey(public_key) => {
644                Ok(SerializableCryptoKeyHandle::MlKem1024PublicKey(
645                    ml_kem::KeyExport::to_bytes(public_key).as_slice().to_vec(),
646                ))
647            },
648            Handle::MlKem768X25519PrivateKey(private_key) => {
649                Ok(SerializableCryptoKeyHandle::MlKem768X25519PrivateKey(
650                    private_key.as_bytes().to_vec(),
651                ))
652            },
653            Handle::MlKem768X25519PublicKey(public_key) => {
654                Ok(SerializableCryptoKeyHandle::MlKem768X25519PublicKey(
655                    x_wing::KeyExport::to_bytes(public_key).to_vec(),
656                ))
657            },
658            Handle::MlDsa44PrivateKey(private_key) => {
659                Ok(SerializableCryptoKeyHandle::MlDsa44PrivateKey(
660                    private_key.as_seed().as_slice().to_vec(),
661                ))
662            },
663            Handle::MlDsa65PrivateKey(private_key) => {
664                Ok(SerializableCryptoKeyHandle::MlDsa65PrivateKey(
665                    private_key.as_seed().as_slice().to_vec(),
666                ))
667            },
668            Handle::MlDsa87PrivateKey(private_key) => {
669                Ok(SerializableCryptoKeyHandle::MlDsa87PrivateKey(
670                    private_key.as_seed().as_slice().to_vec(),
671                ))
672            },
673            Handle::MlDsa44PublicKey(public_key) => {
674                Ok(SerializableCryptoKeyHandle::MlDsa44PublicKey(
675                    ml_dsa::KeyExport::to_bytes(public_key).as_slice().to_vec(),
676                ))
677            },
678            Handle::MlDsa65PublicKey(public_key) => {
679                Ok(SerializableCryptoKeyHandle::MlDsa65PublicKey(
680                    ml_dsa::KeyExport::to_bytes(public_key).as_slice().to_vec(),
681                ))
682            },
683            Handle::MlDsa87PublicKey(public_key) => {
684                Ok(SerializableCryptoKeyHandle::MlDsa87PublicKey(
685                    ml_dsa::KeyExport::to_bytes(public_key).as_slice().to_vec(),
686                ))
687            },
688            Handle::ChaCha20Poly1305Key(key) => Ok(
689                SerializableCryptoKeyHandle::ChaCha20Poly1305Key(key.as_slice().to_vec()),
690            ),
691            Handle::KmacKey(key) => Ok(SerializableCryptoKeyHandle::KmacKey(key.to_vec())),
692            Handle::Argon2Password(password) => Ok(SerializableCryptoKeyHandle::Argon2Password(
693                password.to_vec(),
694            )),
695        }
696    }
697}
698
699/// The trait providing helper functions for `&[KeyUsage]`
700pub(crate) trait KeyUsageSliceHelper {
701    /// <https://w3c.github.io/webcrypto/#concept-usage-intersection>
702    fn usage_intersection(&self, other: &[KeyUsage]) -> Vec<KeyUsage>;
703
704    /// <https://w3c.github.io/webcrypto/#concept-normalized-usages>
705    fn normalized_value(&self) -> Vec<KeyUsage>;
706
707    /// Ensure that the key usage list only contains entries which are in `allowed`. If the key
708    /// usage list contains an entry which is not in `allowed`, then throw a SyntaxError. Note that,
709    /// if `allowed` is set to empty, it throws a SyntaxError when the key usage list is not empty.
710    fn ensure_only_contain_entries_from(&self, allowed: &[KeyUsage]) -> ErrorResult;
711}
712
713impl KeyUsageSliceHelper for [KeyUsage] {
714    fn usage_intersection(&self, other: &[KeyUsage]) -> Vec<KeyUsage> {
715        // When this specification says to calculate the usage intersection of two sequences, a and
716        // b the result shall be a sequence containing each recognized key usage value that appears
717        // in both a and b, in the order listed in the list of recognized key usage values, where a
718        // value is said to appear in a sequence if an element of the sequence exists that is a
719        // case-sensitive string match for that value.
720        let mut intersection = self
721            .iter()
722            .filter(|usage| other.contains(usage))
723            .cloned()
724            .collect::<Vec<KeyUsage>>();
725        intersection.sort();
726        intersection.dedup();
727
728        intersection
729    }
730
731    fn normalized_value(&self) -> Vec<KeyUsage> {
732        // When this specification says to calculate the normalized value of a usages list, usages
733        // the result shall be the usage intersection of usages and a sequence containing all
734        // recognized key usage values.
735        self.usage_intersection(KeyUsage::VARIANTS)
736    }
737
738    fn ensure_only_contain_entries_from(&self, allowed: &[KeyUsage]) -> ErrorResult {
739        if self.iter().all(|usage| allowed.contains(usage)) {
740            Ok(())
741        } else {
742            Err(Error::Syntax(Some(if allowed.is_empty() {
743                "Usages is not empty".into()
744            } else {
745                format!(
746                    "Usages contains an entry which is not {}",
747                    allowed.iter().map(|usage| usage.as_ref()).join(" or "),
748                )
749            })))
750        }
751    }
752}