Skip to main content

sequoia_cryptoki/
import.rs

1use anyhow::Context as _;
2
3use cryptoki::{
4    object::{
5        Attribute,
6        KeyType,
7        MlDsaParameterSetType,
8        MlKemParameterSetType,
9        ObjectClass,
10        SlhDsaParameterSetType,
11    },
12    session::Session,
13};
14
15use sequoia_openpgp::{
16    crypto,
17    Profile,
18    packet,
19    packet::key,
20    types::Curve,
21    types::HashAlgorithm,
22    types::SymmetricAlgorithm,
23};
24
25use crate::Context;
26use crate::Key;
27use crate::PublicKeyAlgorithm;
28use crate::Result;
29use crate::Token;
30use crate::keyid::Bundling;
31
32/// Whether a key is for signing or encryption.
33///
34/// This is used with [`Context::import`].
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum KeyCapability {
37    Signing,
38    Encryption,
39}
40
41const TRACE: bool = false;
42
43/// Key import.
44impl Context {
45    /// Import a key to the specified token.
46    ///
47    /// The key must already be unencrypted.  (See
48    /// [Key::decrypt_secret].)
49    ///
50    /// [Key::decrypt_secret]: https://docs.rs/sequoia-openpgp/latest/sequoia_openpgp/packet/key/enum.Key.html#method.decrypt_secret
51    pub fn import(&self,
52                  session: &Session,
53                  token: Token,
54                  key_label: Option<&str>,
55                  key: &packet::Key<key::SecretParts,
56                                    key::UnspecifiedRole>,
57                  capability: KeyCapability)
58                  -> Result<Key>
59    {
60        tracer!(TRACE, "Context::import");
61
62        let skm = match key.secret() {
63            key::SecretKeyMaterial::Unencrypted(skm) => skm,
64            key::SecretKeyMaterial::Encrypted(_skm) => {
65                // XXX: Prompt for the password, if not provided.
66
67                // skm.decrypt(&key, password)
68
69                return Err(anyhow::anyhow!(
70                    "Can't import {}, it is password protected",
71                    key.fingerprint()));
72            }
73        };
74
75        let profile = match key.version() {
76            4 => Profile::RFC4880,
77            6 => Profile::RFC9580,
78            version => {
79                return Err(anyhow::anyhow!(
80                    "v{} keys are not supported", version));
81            }
82        };
83
84	let algo = PublicKeyAlgorithm::try_from(key)?;
85        t!("Importing a {} ({}) key", key.pk_algo(), u8::from(key.pk_algo()));
86
87        let (public_handle, constituent) = skm.map(|skm| match (key.mpis(), skm) {
88            (crypto::mpi::PublicKey::ECDH { q, hash, sym, .. },
89             crypto::mpi::SecretKeyMaterial::ECDH { scalar }) =>
90            {
91                if capability != KeyCapability::Encryption {
92                    return Err(anyhow::anyhow!(
93                        "ECDH keys cannot be used for signing"));
94                }
95
96                // Import a v4 ECDH secret key.
97
98                // Version 4 ECDH public keys include two parameters:
99                // a hash algorithm and a symmetric algorithm.  We
100                // need to add those to the key ID so that we can
101                // recreate the OpenPGP key.
102                let key_id_extra = {
103                    let hash_algo = match hash {
104                        HashAlgorithm::SHA256 => "sha256",
105                        HashAlgorithm::SHA384 => "sha384",
106                        HashAlgorithm::SHA512 => "sha512",
107                        algo => {
108                            return Err(anyhow::anyhow!(
109                                "{} cannot be used with a cv25519 key", algo));
110                        }
111                    };
112                    let sym_algo = match sym {
113                        SymmetricAlgorithm::AES128 => "aes128",
114                        SymmetricAlgorithm::AES192 => "aes192",
115                        SymmetricAlgorithm::AES256 => "aes256",
116                        algo => {
117                            return Err(anyhow::anyhow!(
118                                "{} cannot be used with a cv25519 key", algo));
119                        }
120                    };
121
122                    Some(format!("{}-{}", hash_algo, sym_algo))
123                };
124
125                let (key_id, key_label) = self.generate_key_id(
126                    algo.clone(), Profile::RFC4880, Bundling::Standalone,
127                    Some(key.creation_time()),
128                    key_id_extra.as_deref(), key_label)?;
129
130                // Note: the secret key material is stored in big
131                // endian form, but PKCS#11 expects it to be in little
132                // endian form:
133                //
134                //   5.5.5.6.1.1. Curve25519Legacy ECDH Secret Key
135                //   Material (Deprecated)
136                //
137                //   A Curve25519Legacy secret key is stored as a
138                //   standard integer in big-endian MPI
139                //   form. Curve25519Legacy MUST NOT be used in key
140                //   packets version 6 or above. Note that this form
141                //   is in reverse octet order from the little-endian
142                //   "native" form found in [RFC7748].
143                //
144                //   https://www.rfc-editor.org/rfc/rfc9580.html#section-5.5.5.6.1
145                let mut scalar = scalar.value().to_vec();
146                scalar.reverse();
147
148                let template = [
149                    Attribute::Class(ObjectClass::PRIVATE_KEY),
150                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
151                    Attribute::EcParams(vec![
152                        0x13, 0x0a, 0x63, 0x75, 0x72, 0x76, 0x65, 0x32,
153                        0x35, 0x35, 0x31, 0x39
154                    ]),
155                    Attribute::Value(scalar),
156                    Attribute::Id(key_id.as_bytes().to_vec()),
157                    Attribute::Label(key_label.as_bytes().to_vec()),
158                    // Prohibit exporting the secret key material.
159                    Attribute::Sensitive(true),
160                    // Persist it on the token.
161                    Attribute::Token(true),
162                    // Decryption is done by deriving a KEK from a
163                    // shared secret.  For PKCS#11, this means we use
164                    // the CKM_ECDH1_DERIVE mechanism.
165                    Attribute::Derive(true),
166                ];
167
168                let _priv_handle = session.create_object(&template)?;
169
170                // Extract the public key.  In OpenPGP it is encoded
171                // as follows:
172                //
173                //   11.2.2. Prefixed Native EC Point Wire Format
174                //
175                //   For a custom compressed point, the content of the
176                //   MPI is:
177                //
178                //     B = 40 || p
179                //
180                //   where p is the public key of the point encoded
181                //   using the rules defined for the specified
182                //   curve. This format is used for ECDH keys based on
183                //   curves expressed in Montgomery form and for
184                //   points when using EdDSA.
185                //
186                // https://www.rfc-editor.org/rfc/rfc9580.html#ec-point-prefixed-native
187                let ec_point = q.value();
188                if ec_point.len() != 33 || ec_point[0] != 0x40 {
189                    return Err(anyhow::anyhow!(
190                        "Invalid public key material (should be 33 bytes \
191                         where the first byte is 0x40)"));
192                }
193                let ec_point = ec_point[1..].to_vec();
194
195                let template = [
196                    Attribute::Class(ObjectClass::PUBLIC_KEY),
197                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
198                    Attribute::EcParams(crate::oids::X25519.into()),
199                    Attribute::EcPoint(ec_point),
200                    Attribute::Id(key_id.as_bytes().to_vec()),
201                    Attribute::Label(key_label.as_bytes().to_vec()),
202                    // Persist it on the token.
203                    Attribute::Token(true),
204                    Attribute::Derive(true),
205                ];
206
207                let public_handle = session.create_object(&template)?;
208
209                Ok((public_handle, None))
210            }
211            (crypto::mpi::PublicKey::MLKEM768_X25519 { ecdh, mlkem, },
212             crypto::mpi::SecretKeyMaterial::MLKEM768_X25519 {
213                 ecdh: ecdh_secret, mlkem: mlkem_seed,
214             }) => {
215                let (key_id, key_label) = self.generate_key_id(
216                    PublicKeyAlgorithm::MLKEM768_X25519,
217                    profile, Bundling::PostQuantumHalf,
218                    Some(key.creation_time()),
219                    None, key_label)?;
220
221                let template = [
222                    Attribute::Class(ObjectClass::PRIVATE_KEY),
223                    Attribute::KeyType(KeyType::ML_KEM),
224                    Attribute::ParameterSet(
225                        MlKemParameterSetType::ML_KEM_768.into()),
226                    Attribute::Seed(mlkem_seed.to_vec()),
227                    Attribute::Id(key_id.as_bytes().to_vec()),
228                    Attribute::Label(key_label.as_bytes().to_vec()),
229                    // Prohibit exporting the secret key material.
230                    Attribute::Sensitive(true),
231                    // Persist it on the token.
232                    Attribute::Token(true),
233                    Attribute::Decapsulate(true),
234                ];
235
236                let _priv_handle = session.create_object(&template)
237                    .context("Importing ML-KEM private key (perhaps the \
238                              token doesn't support ML-KEM keys, or importing \
239                              by seed is not supported)")?;
240
241                let template = [
242                    Attribute::Class(ObjectClass::PUBLIC_KEY),
243                    Attribute::KeyType(KeyType::ML_KEM),
244                    Attribute::ParameterSet(
245                        MlKemParameterSetType::ML_KEM_768.into()),
246                    Attribute::Value(mlkem.to_vec()),
247                    Attribute::Id(key_id.as_bytes().to_vec()),
248                    Attribute::Label(key_label.as_bytes().to_vec()),
249                    // Persist it on the token.
250                    Attribute::Token(true),
251                    Attribute::Encapsulate(true),
252                ];
253
254                let public_handle = session.create_object(&template)
255                    .context("Importing ML-KEM public key")?;
256
257                let constituent = Key::from_object(
258                    token.clone(), session, public_handle)?;
259
260                let key_label = constituent.key_label().map(|label| {
261                    String::from_utf8(label.to_vec())
262                        .expect("label is valid UTF-8")
263                });
264
265                let (key_id, key_label) = self.generate_key_id(
266                    PublicKeyAlgorithm::MLKEM768_X25519,
267                    profile, Bundling::TraditionalHalf,
268                    Some(key.creation_time()),
269                    None, key_label.as_deref())?;
270
271                let template = [
272                    Attribute::Class(ObjectClass::PRIVATE_KEY),
273                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
274                    Attribute::EcParams(crate::oids::X25519.into()),
275                    Attribute::Value(ecdh_secret.to_vec()),
276                    Attribute::Id(key_id.as_bytes().to_vec()),
277                    Attribute::Label(key_label.as_bytes().to_vec()),
278                    // Prohibit exporting the secret key material.
279                    Attribute::Sensitive(true),
280                    // Persist it on the token.
281                    Attribute::Token(true),
282                    Attribute::Derive(true),
283                ];
284
285                let _priv_handle2 = session.create_object(&template)
286                    .context("Importing X25519 private key")?;
287
288                let template = [
289                    Attribute::Class(ObjectClass::PUBLIC_KEY),
290                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
291                    Attribute::Id(key_id.as_bytes().to_vec()),
292                    Attribute::EcParams(crate::oids::X25519.into()),
293                    Attribute::EcPoint(ecdh.to_vec()),
294                    Attribute::Label(key_label.as_bytes().to_vec()),
295                    // Persist it on the token.
296                    Attribute::Token(true),
297                    Attribute::Derive(true),
298                ];
299
300                let public_handle2 = session.create_object(&template)
301                    .context("Importing X25519 public key")?;
302
303                Ok((public_handle2, Some(constituent)))
304            }
305            (crypto::mpi::PublicKey::MLKEM1024_X448 { ecdh, mlkem, },
306             crypto::mpi::SecretKeyMaterial::MLKEM1024_X448 {
307                 ecdh: ecdh_secret, mlkem: mlkem_seed,
308             }) => {
309                let (key_id, key_label) = self.generate_key_id(
310                    PublicKeyAlgorithm::MLKEM1024_X448,
311                    profile, Bundling::PostQuantumHalf,
312                    Some(key.creation_time()),
313                    None, key_label)?;
314
315                let template = [
316                    Attribute::Class(ObjectClass::PRIVATE_KEY),
317                    Attribute::KeyType(KeyType::ML_KEM),
318                    Attribute::ParameterSet(
319                        MlKemParameterSetType::ML_KEM_1024.into()),
320                    Attribute::Seed(mlkem_seed.to_vec()),
321                    Attribute::Id(key_id.as_bytes().to_vec()),
322                    Attribute::Label(key_label.as_bytes().to_vec()),
323                    // Prohibit exporting the secret key material.
324                    Attribute::Sensitive(true),
325                    // Persist it on the token.
326                    Attribute::Token(true),
327                    Attribute::Decapsulate(true),
328                ];
329
330                let _priv_handle = session.create_object(&template)
331                    .context("Importing ML-KEM private key (perhaps the \
332                              token doesn't support ML-KEM keys, or importing \
333                              by seed is not supported)")?;
334
335                let template = [
336                    Attribute::Class(ObjectClass::PUBLIC_KEY),
337                    Attribute::KeyType(KeyType::ML_KEM),
338                    Attribute::ParameterSet(
339                        MlKemParameterSetType::ML_KEM_1024.into()),
340                    Attribute::Value(mlkem.to_vec()),
341                    Attribute::Id(key_id.as_bytes().to_vec()),
342                    Attribute::Label(key_label.as_bytes().to_vec()),
343                    // Persist it on the token.
344                    Attribute::Token(true),
345                    Attribute::Encapsulate(true),
346                ];
347
348                let public_handle = session.create_object(&template)
349                    .context("Importing ML-KEM public key")?;
350
351                let constituent = Key::from_object(
352                    token.clone(), session, public_handle)?;
353
354                let key_label = constituent.key_label().map(|label| {
355                    String::from_utf8(label.to_vec())
356                        .expect("label is valid UTF-8")
357                });
358
359                let (key_id, key_label) = self.generate_key_id(
360                    PublicKeyAlgorithm::MLKEM1024_X448,
361                    profile, Bundling::TraditionalHalf,
362                    Some(key.creation_time()),
363                    None, key_label.as_deref())?;
364
365                let template = [
366                    Attribute::Class(ObjectClass::PRIVATE_KEY),
367                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
368                    Attribute::EcParams(crate::oids::X448.into()),
369                    Attribute::Value(ecdh_secret.to_vec()),
370                    Attribute::Id(key_id.as_bytes().to_vec()),
371                    Attribute::Label(key_label.as_bytes().to_vec()),
372                    // Prohibit exporting the secret key material.
373                    Attribute::Sensitive(true),
374                    // Persist it on the token.
375                    Attribute::Token(true),
376                    Attribute::Derive(true),
377                ];
378
379                let _priv_handle2 = session.create_object(&template)
380                    .context("Importing X448 private key")?;
381
382                let template = [
383                    Attribute::Class(ObjectClass::PUBLIC_KEY),
384                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
385                    Attribute::Id(key_id.as_bytes().to_vec()),
386                    Attribute::EcParams(crate::oids::X448.into()),
387                    Attribute::EcPoint(ecdh.to_vec()),
388                    Attribute::Label(key_label.as_bytes().to_vec()),
389                    // Persist it on the token.
390                    Attribute::Token(true),
391                    Attribute::Derive(true),
392                ];
393
394                let public_handle2 = session.create_object(&template)
395                    .context("Importing X448 public key")?;
396
397                Ok((public_handle2, Some(constituent)))
398            }
399            (crypto::mpi::PublicKey::X25519 { u },
400             crypto::mpi::SecretKeyMaterial::X25519 { x }) =>
401            {
402                let (key_id, key_label) = self.generate_key_id(
403                    PublicKeyAlgorithm::X25519,
404                    profile, Bundling::Standalone,
405                    Some(key.creation_time()),
406                    None, key_label)?;
407
408                let template = [
409                    Attribute::Class(ObjectClass::PRIVATE_KEY),
410                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
411                    Attribute::EcParams(crate::oids::X25519.into()),
412                    Attribute::Value(x.to_vec()),
413                    Attribute::Id(key_id.as_bytes().to_vec()),
414                    Attribute::Label(key_label.as_bytes().to_vec()),
415                    // Prohibit exporting the secret key material.
416                    Attribute::Sensitive(true),
417                    // Persist it on the token.
418                    Attribute::Token(true),
419                    Attribute::Derive(true),
420                ];
421
422                let _priv_handle = session.create_object(&template)?;
423
424                let template = [
425                    Attribute::Class(ObjectClass::PUBLIC_KEY),
426                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
427                    Attribute::Id(key_id.as_bytes().to_vec()),
428                    Attribute::EcParams(crate::oids::X25519.into()),
429                    Attribute::EcPoint(u.to_vec()),
430                    Attribute::Label(key_label.as_bytes().to_vec()),
431                    // Persist it on the token.
432                    Attribute::Token(true),
433                    Attribute::Derive(true),
434                ];
435
436                let public_handle = session.create_object(&template)?;
437
438                Ok((public_handle, None))
439            }
440            (crypto::mpi::PublicKey::X448 { u },
441             crypto::mpi::SecretKeyMaterial::X448 { x }) =>
442            {
443                let (key_id, key_label) = self.generate_key_id(
444                    PublicKeyAlgorithm::X448,
445                    profile, Bundling::Standalone,
446                    Some(key.creation_time()),
447                    None, key_label)?;
448
449                let template = [
450                    Attribute::Class(ObjectClass::PRIVATE_KEY),
451                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
452                    Attribute::EcParams(crate::oids::X448.into()),
453                    Attribute::Value(x.to_vec()),
454                    Attribute::Id(key_id.as_bytes().to_vec()),
455                    Attribute::Label(key_label.as_bytes().to_vec()),
456                    // Prohibit exporting the secret key material.
457                    Attribute::Sensitive(true),
458                    // Persist it on the token.
459                    Attribute::Token(true),
460                    Attribute::Derive(true),
461                ];
462
463                let _priv_handle = session.create_object(&template)?;
464
465                let template = [
466                    Attribute::Class(ObjectClass::PUBLIC_KEY),
467                    Attribute::KeyType(KeyType::EC_MONTGOMERY),
468                    Attribute::Id(key_id.as_bytes().to_vec()),
469                    Attribute::EcParams(crate::oids::X448.into()),
470                    Attribute::EcPoint(u.to_vec()),
471                    Attribute::Label(key_label.as_bytes().to_vec()),
472                    // Persist it on the token.
473                    Attribute::Token(true),
474                    Attribute::Derive(true),
475                ];
476
477                let public_handle = session.create_object(&template)?;
478
479                Ok((public_handle, None))
480            }
481            (crypto::mpi::PublicKey::EdDSA { curve, q },
482             crypto::mpi::SecretKeyMaterial::EdDSA { scalar }) =>
483            {
484                t!("Key uses curve {}", curve);
485
486                if capability != KeyCapability::Signing {
487                    return Err(anyhow::anyhow!(
488                        "EdDSA keys cannot be used for encryption"));
489                }
490
491                let (key_id, key_label) = self.generate_key_id(
492                    PublicKeyAlgorithm::EdDSA,
493                    Profile::RFC4880, Bundling::Standalone,
494                    Some(key.creation_time()),
495                    None, key_label)?;
496
497                // Section 5.5.5.4. Algorithm-Specific Part for ECDSA Keys
498                //
499                // For ECDSA keys, the public key consists of this
500                // series of values:
501                //
502                // - A variable-length field containing a curve OID,
503                //   which is formatted as follows:
504                //
505                //   - A 1-octet size of the following field; values 0
506                //     and 0xFF are reserved for future extensions.
507                //
508                //   - The octets representing a curve OID, as defined
509                //     in Section 9.2.
510                //
511                // - An MPI of an EC point representing a public key.
512                //
513                // The secret key consists of this single
514                // multiprecision integer:
515                //
516                // - An MPI of an integer representing the secret key,
517                //   which is a scalar of the public EC point.
518                //
519                // https://www.rfc-editor.org/rfc/rfc9580.html#name-algorithm-specific-part-for-ec
520
521                match curve {
522                    Curve::Ed25519 => (),
523                    curve => {
524                        return Err(anyhow::anyhow!(
525                            "{} keys using curve {} are not yet supported",
526                            key.pk_algo(), curve));
527                    }
528                }
529
530                let template = [
531                    Attribute::Class(ObjectClass::PRIVATE_KEY),
532                    Attribute::KeyType(KeyType::EC_EDWARDS),
533                    Attribute::Id(key_id.as_bytes().to_vec()),
534                    Attribute::Label(key_label.as_bytes().to_vec()),
535                    // Prohibit exporting the secret key material.
536                    Attribute::Sensitive(true),
537                    // Persist it on the token.
538                    Attribute::Token(true),
539                    Attribute::Sign(true),
540                    Attribute::EcParams(crate::oids::Ed25519.to_vec()),
541                    Attribute::Value(scalar.value().to_vec()),
542                ];
543
544                let _priv_handle = session.create_object(&template)?;
545
546                // 11.2.2. Prefixed Native EC Point Wire Format
547                //
548                // For a custom compressed point, the content of the
549                // MPI is:
550                //
551                //   B = 40 || p
552                //
553                // where p is the public key of the point encoded
554                // using the rules defined for the specified
555                // curve. This format is used for ECDH keys based on
556                // curves expressed in Montgomery form and for points
557                // when using EdDSA.
558                //
559                // https://www.rfc-editor.org/rfc/rfc9580.html#section-11.2.2
560
561                let ec_point = q.value();
562                if ec_point.len() != 33 || ec_point[0] != 0x40 {
563                    return Err(anyhow::anyhow!(
564                        "Invalid public key material (should be 33 bytes \
565                         where the first byte is 0x40)"));
566                }
567                let ec_point = ec_point[1..].to_vec();
568
569                let template = [
570                    Attribute::Class(ObjectClass::PUBLIC_KEY),
571                    Attribute::KeyType(KeyType::EC_EDWARDS),
572                    Attribute::Id(key_id.as_bytes().to_vec()),
573                    Attribute::Label(key_label.as_bytes().to_vec()),
574                    // Persist it on the token.
575                    Attribute::Token(true),
576                    Attribute::Verify(true),
577                    Attribute::EcParams(crate::oids::Ed25519.into()),
578                    Attribute::EcPoint(ec_point),
579                ];
580
581                let public_handle = session.create_object(&template)?;
582
583                Ok((public_handle, None))
584            }
585            (crypto::mpi::PublicKey::Ed25519 { a },
586             crypto::mpi::SecretKeyMaterial::Ed25519 { x }) =>
587            {
588                let (key_id, key_label) = self.generate_key_id(
589                    PublicKeyAlgorithm::Ed25519,
590                    profile, Bundling::Standalone,
591                    Some(key.creation_time()),
592                    None, key_label)?;
593
594                let template = [
595                    Attribute::Class(ObjectClass::PRIVATE_KEY),
596                    Attribute::KeyType(KeyType::EC_EDWARDS),
597                    Attribute::EcParams(crate::oids::Ed25519.into()),
598                    Attribute::Value(x.to_vec()),
599                    Attribute::Id(key_id.as_bytes().to_vec()),
600                    Attribute::Label(key_label.as_bytes().to_vec()),
601                    // Prohibit exporting the secret key material.
602                    Attribute::Sensitive(true),
603                    // Persist it on the token.
604                    Attribute::Token(true),
605                    Attribute::Sign(true),
606                ];
607
608                let _priv_handle = session.create_object(&template)?;
609
610                let template = [
611                    Attribute::Class(ObjectClass::PUBLIC_KEY),
612                    Attribute::KeyType(KeyType::EC_EDWARDS),
613                    Attribute::Id(key_id.as_bytes().to_vec()),
614                    Attribute::EcParams(crate::oids::Ed25519.into()),
615                    Attribute::EcPoint(a.to_vec()),
616                    Attribute::Label(key_label.as_bytes().to_vec()),
617                    // Persist it on the token.
618                    Attribute::Token(true),
619                    Attribute::Verify(true),
620                ];
621
622                let public_handle = session.create_object(&template)?;
623
624                Ok((public_handle, None))
625            }
626            (crypto::mpi::PublicKey::Ed448 { a },
627             crypto::mpi::SecretKeyMaterial::Ed448 { x }) =>
628            {
629                let (key_id, key_label) = self.generate_key_id(
630                    PublicKeyAlgorithm::Ed448,
631                    profile, Bundling::Standalone,
632                    Some(key.creation_time()),
633                    None, key_label)?;
634
635                let template = [
636                    Attribute::Class(ObjectClass::PRIVATE_KEY),
637                    Attribute::KeyType(KeyType::EC_EDWARDS),
638                    Attribute::EcParams(crate::oids::Ed448.into()),
639                    Attribute::Value(x.to_vec()),
640                    Attribute::Id(key_id.as_bytes().to_vec()),
641                    Attribute::Label(key_label.as_bytes().to_vec()),
642                    // Prohibit exporting the secret key material.
643                    Attribute::Sensitive(true),
644                    // Persist it on the token.
645                    Attribute::Token(true),
646                    Attribute::Sign(true),
647                ];
648
649                let _priv_handle = session.create_object(&template)?;
650
651                let template = [
652                    Attribute::Class(ObjectClass::PUBLIC_KEY),
653                    Attribute::KeyType(KeyType::EC_EDWARDS),
654                    Attribute::Id(key_id.as_bytes().to_vec()),
655                    Attribute::EcParams(crate::oids::Ed448.into()),
656                    Attribute::EcPoint(a.to_vec()),
657                    Attribute::Label(key_label.as_bytes().to_vec()),
658                    // Persist it on the token.
659                    Attribute::Token(true),
660                    Attribute::Verify(true),
661                ];
662
663                let public_handle = session.create_object(&template)?;
664
665                Ok((public_handle, None))
666            }
667            (crypto::mpi::PublicKey::MLDSA65_Ed25519 { eddsa, mldsa },
668             crypto::mpi::SecretKeyMaterial::MLDSA65_Ed25519 {
669                 eddsa: eddsa_secret,
670                 mldsa: mldsa_seed,
671             }) =>
672            {
673                let (key_id, key_label) = self.generate_key_id(
674                    PublicKeyAlgorithm::MLDSA65_Ed25519,
675                    profile, Bundling::PostQuantumHalf,
676                    Some(key.creation_time()),
677                    None, key_label)?;
678
679                let template = [
680                    Attribute::Class(ObjectClass::PRIVATE_KEY),
681                    Attribute::KeyType(KeyType::ML_DSA),
682                    Attribute::ParameterSet(
683                        MlDsaParameterSetType::ML_DSA_65.into()),
684                    Attribute::Seed(mldsa_seed.to_vec()),
685                    Attribute::Id(key_id.as_bytes().to_vec()),
686                    Attribute::Label(key_label.as_bytes().to_vec()),
687                    // Prohibit exporting the secret key material.
688                    Attribute::Sensitive(true),
689                    // Persist it on the token.
690                    Attribute::Token(true),
691                    Attribute::Sign(true),
692                ];
693
694                let _priv_handle = session.create_object(&template)
695                    .context("Importing ML-DSA private key (perhaps the \
696                              token doesn't support ML-DSA keys, or importing \
697                              by seed is not supported)")?;
698
699                let template = [
700                    Attribute::Class(ObjectClass::PUBLIC_KEY),
701                    Attribute::KeyType(KeyType::ML_DSA),
702                    Attribute::ParameterSet(
703                        MlDsaParameterSetType::ML_DSA_65.into()),
704                    Attribute::Value(mldsa.to_vec()),
705                    Attribute::Id(key_id.as_bytes().to_vec()),
706                    Attribute::Label(key_label.as_bytes().to_vec()),
707                    // Persist it on the token.
708                    Attribute::Token(true),
709                    Attribute::Verify(true),
710                ];
711
712                let public_handle = session.create_object(&template)
713                    .context("Importing ML-DSA public key")?;
714
715                let constituent = Key::from_object(
716                    token.clone(), session, public_handle)?;
717
718                let key_label = constituent.key_label().map(|label| {
719                    String::from_utf8(label.to_vec())
720                        .expect("label is valid UTF-8")
721                });
722
723                let (key_id, key_label) = self.generate_key_id(
724                    PublicKeyAlgorithm::MLDSA65_Ed25519,
725                    profile, Bundling::TraditionalHalf,
726                    Some(key.creation_time()),
727                    None, key_label.as_deref())?;
728
729                let template = [
730                    Attribute::Class(ObjectClass::PRIVATE_KEY),
731                    Attribute::KeyType(KeyType::EC_EDWARDS),
732                    Attribute::EcParams(crate::oids::Ed25519.into()),
733                    Attribute::Value(eddsa_secret.to_vec()),
734                    Attribute::Id(key_id.as_bytes().to_vec()),
735                    Attribute::Label(key_label.as_bytes().to_vec()),
736                    // Prohibit exporting the secret key material.
737                    Attribute::Sensitive(true),
738                    // Persist it on the token.
739                    Attribute::Token(true),
740                    Attribute::Sign(true),
741                ];
742
743                let _priv_handle2 = session.create_object(&template)
744                    .context("Importing Ed25519 public key")?;
745
746                let template = [
747                    Attribute::Class(ObjectClass::PUBLIC_KEY),
748                    Attribute::KeyType(KeyType::EC_EDWARDS),
749                    Attribute::Id(key_id.as_bytes().to_vec()),
750                    Attribute::EcParams(crate::oids::Ed25519.into()),
751                    Attribute::EcPoint(eddsa.to_vec()),
752                    Attribute::Label(key_label.as_bytes().to_vec()),
753                    // Persist it on the token.
754                    Attribute::Token(true),
755                    Attribute::Verify(true),
756                ];
757
758                let public_handle2 = session.create_object(&template)
759                    .context("Importing Ed25519 public key")?;
760
761                Ok((public_handle2, Some(constituent)))
762            }
763            (crypto::mpi::PublicKey::MLDSA87_Ed448 { eddsa, mldsa },
764             crypto::mpi::SecretKeyMaterial::MLDSA87_Ed448 {
765                 eddsa: eddsa_secret,
766                 mldsa: mldsa_seed,
767             }) =>
768            {
769                let (key_id, key_label) = self.generate_key_id(
770                    PublicKeyAlgorithm::MLDSA87_Ed448,
771                    profile, Bundling::PostQuantumHalf,
772                    Some(key.creation_time()),
773                    None, key_label)?;
774
775                let template = [
776                    Attribute::Class(ObjectClass::PRIVATE_KEY),
777                    Attribute::KeyType(KeyType::ML_DSA),
778                    Attribute::ParameterSet(
779                        MlDsaParameterSetType::ML_DSA_87.into()),
780                    Attribute::Seed(mldsa_seed.to_vec()),
781                    Attribute::Id(key_id.as_bytes().to_vec()),
782                    Attribute::Label(key_label.as_bytes().to_vec()),
783                    // Prohibit exporting the secret key material.
784                    Attribute::Sensitive(true),
785                    // Persist it on the token.
786                    Attribute::Token(true),
787                    Attribute::Sign(true),
788                ];
789
790                let _priv_handle = session.create_object(&template)
791                    .context("Importing ML-DSA private key (perhaps the \
792                              token doesn't support ML-DSA keys, or importing \
793                              by seed is not supported)")?;
794
795                let template = [
796                    Attribute::Class(ObjectClass::PUBLIC_KEY),
797                    Attribute::KeyType(KeyType::ML_DSA),
798                    Attribute::ParameterSet(
799                        MlDsaParameterSetType::ML_DSA_87.into()),
800                    Attribute::Value(mldsa.to_vec()),
801                    Attribute::Id(key_id.as_bytes().to_vec()),
802                    Attribute::Label(key_label.as_bytes().to_vec()),
803                    // Persist it on the token.
804                    Attribute::Token(true),
805                    Attribute::Verify(true),
806                ];
807
808                let public_handle = session.create_object(&template)
809                    .context("Importing ML-DSA public key")?;
810
811                let constituent = Key::from_object(
812                    token.clone(), session, public_handle)?;
813
814                let key_label = constituent.key_label().map(|label| {
815                    String::from_utf8(label.to_vec())
816                        .expect("label is valid UTF-8")
817                });
818
819                let (key_id, key_label) = self.generate_key_id(
820                    PublicKeyAlgorithm::MLDSA87_Ed448,
821                    profile, Bundling::TraditionalHalf,
822                    Some(key.creation_time()),
823                    None, key_label.as_deref())?;
824
825                let template = [
826                    Attribute::Class(ObjectClass::PRIVATE_KEY),
827                    Attribute::KeyType(KeyType::EC_EDWARDS),
828                    Attribute::EcParams(crate::oids::Ed448.into()),
829                    Attribute::Value(eddsa_secret.to_vec()),
830                    Attribute::Id(key_id.as_bytes().to_vec()),
831                    Attribute::Label(key_label.as_bytes().to_vec()),
832                    // Prohibit exporting the secret key material.
833                    Attribute::Sensitive(true),
834                    // Persist it on the token.
835                    Attribute::Token(true),
836                    Attribute::Sign(true),
837                ];
838
839                let _priv_handle2 = session.create_object(&template)
840                    .context("Importing Ed448 private key")?;
841
842                let template = [
843                    Attribute::Class(ObjectClass::PUBLIC_KEY),
844                    Attribute::KeyType(KeyType::EC_EDWARDS),
845                    Attribute::Id(key_id.as_bytes().to_vec()),
846                    Attribute::EcParams(crate::oids::Ed448.into()),
847                    Attribute::EcPoint(eddsa.to_vec()),
848                    Attribute::Label(key_label.as_bytes().to_vec()),
849                    // Persist it on the token.
850                    Attribute::Token(true),
851                    Attribute::Verify(true),
852                ];
853
854                let public_handle2 = session.create_object(&template)
855                    .context("Importing Ed448 public key")?;
856
857                Ok((public_handle2, Some(constituent)))
858            }
859            (crypto::mpi::PublicKey::SLHDSA128s { public },
860             crypto::mpi::SecretKeyMaterial::SLHDSA128s { secret }) =>
861            {
862                let (key_id, key_label) = self.generate_key_id(
863                    PublicKeyAlgorithm::SLHDSA128s,
864                    profile, Bundling::Standalone,
865                    Some(key.creation_time()),
866                    None, key_label)?;
867
868                let template = [
869                    Attribute::Class(ObjectClass::PRIVATE_KEY),
870                    Attribute::KeyType(KeyType::SLH_DSA),
871                    Attribute::ParameterSet(
872                        SlhDsaParameterSetType::SHAKE_128S.into()),
873                    Attribute::Value(secret.to_vec()),
874                    Attribute::Id(key_id.as_bytes().to_vec()),
875                    Attribute::Label(key_label.as_bytes().to_vec()),
876                    // Prohibit exporting the secret key material.
877                    Attribute::Sensitive(true),
878                    // Persist it on the token.
879                    Attribute::Token(true),
880                    Attribute::Sign(true),
881                ];
882
883                let _priv_handle = session.create_object(&template)?;
884
885                let template = [
886                    Attribute::Class(ObjectClass::PUBLIC_KEY),
887                    Attribute::KeyType(KeyType::SLH_DSA),
888                    Attribute::ParameterSet(
889                        SlhDsaParameterSetType::SHAKE_128S.into()),
890                    Attribute::Value(public.to_vec()),
891                    Attribute::Id(key_id.as_bytes().to_vec()),
892                    Attribute::Label(key_label.as_bytes().to_vec()),
893                    // Persist it on the token.
894                    Attribute::Token(true),
895                    Attribute::Verify(true),
896                ];
897
898                let public_handle = session.create_object(&template)?;
899
900                Ok((public_handle, None))
901            }
902            (crypto::mpi::PublicKey::SLHDSA128f { public },
903             crypto::mpi::SecretKeyMaterial::SLHDSA128f { secret }) =>
904            {
905                let (key_id, key_label) = self.generate_key_id(
906                    PublicKeyAlgorithm::SLHDSA128f,
907                    profile, Bundling::Standalone,
908                    Some(key.creation_time()),
909                    None, key_label)?;
910
911                let template = [
912                    Attribute::Class(ObjectClass::PRIVATE_KEY),
913                    Attribute::KeyType(KeyType::SLH_DSA),
914                    Attribute::ParameterSet(
915                        SlhDsaParameterSetType::SHAKE_128F.into()),
916                    Attribute::Value(secret.to_vec()),
917                    Attribute::Id(key_id.as_bytes().to_vec()),
918                    Attribute::Label(key_label.as_bytes().to_vec()),
919                    // Prohibit exporting the secret key material.
920                    Attribute::Sensitive(true),
921                    // Persist it on the token.
922                    Attribute::Token(true),
923                    Attribute::Sign(true),
924                ];
925
926                let _priv_handle = session.create_object(&template)?;
927
928                let template = [
929                    Attribute::Class(ObjectClass::PUBLIC_KEY),
930                    Attribute::KeyType(KeyType::SLH_DSA),
931                    Attribute::ParameterSet(
932                        SlhDsaParameterSetType::SHAKE_128F.into()),
933                    Attribute::Value(public.to_vec()),
934                    Attribute::Id(key_id.as_bytes().to_vec()),
935                    Attribute::Label(key_label.as_bytes().to_vec()),
936                    // Persist it on the token.
937                    Attribute::Token(true),
938                    Attribute::Verify(true),
939                ];
940
941                let public_handle = session.create_object(&template)?;
942
943                Ok((public_handle, None))
944            }
945            (crypto::mpi::PublicKey::SLHDSA256s { public },
946             crypto::mpi::SecretKeyMaterial::SLHDSA256s { secret }) =>
947            {
948                let (key_id, key_label) = self.generate_key_id(
949                    PublicKeyAlgorithm::SLHDSA256s,
950                    profile, Bundling::Standalone,
951                    Some(key.creation_time()),
952                    None, key_label)?;
953
954                let template = [
955                    Attribute::Class(ObjectClass::PRIVATE_KEY),
956                    Attribute::KeyType(KeyType::SLH_DSA),
957                    Attribute::ParameterSet(
958                        SlhDsaParameterSetType::SHAKE_256S.into()),
959                    Attribute::Value(secret.to_vec()),
960                    Attribute::Id(key_id.as_bytes().to_vec()),
961                    Attribute::Label(key_label.as_bytes().to_vec()),
962                    // Prohibit exporting the secret key material.
963                    Attribute::Sensitive(true),
964                    // Persist it on the token.
965                    Attribute::Token(true),
966                    Attribute::Sign(true),
967                ];
968
969                let _priv_handle = session.create_object(&template)?;
970
971                let template = [
972                    Attribute::Class(ObjectClass::PUBLIC_KEY),
973                    Attribute::KeyType(KeyType::SLH_DSA),
974                    Attribute::ParameterSet(
975                        SlhDsaParameterSetType::SHAKE_256S.into()),
976                    Attribute::Value(public.to_vec()),
977                    Attribute::Id(key_id.as_bytes().to_vec()),
978                    Attribute::Label(key_label.as_bytes().to_vec()),
979                    // Persist it on the token.
980                    Attribute::Token(true),
981                    Attribute::Verify(true),
982                ];
983
984                let public_handle = session.create_object(&template)?;
985
986                Ok((public_handle, None))
987            }
988            (crypto::mpi::PublicKey::RSA { e, n },
989             crypto::mpi::SecretKeyMaterial::RSA { d, p, q, u }) =>
990            {
991                let (key_id, key_label) = self.generate_key_id(
992		    PublicKeyAlgorithm::RSA,
993                    profile, Bundling::Standalone,
994                    Some(key.creation_time()),
995                    None, key_label)?;
996
997                let template = [
998                    Attribute::Class(ObjectClass::PRIVATE_KEY),
999                    Attribute::KeyType(KeyType::RSA),
1000                    Attribute::Id(key_id.as_bytes().to_vec()),
1001                    Attribute::Label(key_label.as_bytes().to_vec()),
1002                    // Prohibit exporting the secret key material.
1003                    Attribute::Sensitive(true),
1004                    // Persist it on the token.
1005                    Attribute::Token(true),
1006                    if capability == KeyCapability::Signing {
1007                        Attribute::Sign(true)
1008                    } else {
1009                        Attribute::Decrypt(true)
1010                    },
1011                    Attribute::Modulus(n.value().to_vec()),
1012                    Attribute::PublicExponent(e.value().to_vec()),
1013                    Attribute::PrivateExponent(d.value().to_vec()),
1014                    Attribute::Prime1(p.value().to_vec()),
1015                    Attribute::Prime2(q.value().to_vec()),
1016                    Attribute::Coefficient(u.value().to_vec()),
1017                ];
1018
1019                let _priv_handle = session.create_object(&template)?;
1020
1021                let template = [
1022                    Attribute::Class(ObjectClass::PUBLIC_KEY),
1023                    Attribute::KeyType(KeyType::RSA),
1024                    Attribute::Id(key_id.as_bytes().to_vec()),
1025                    Attribute::Label(key_label.as_bytes().to_vec()),
1026                    // Persist it on the token.
1027                    Attribute::Token(true),
1028                    if capability == KeyCapability::Signing {
1029                        Attribute::Verify(true)
1030                    } else {
1031                        Attribute::Encrypt(true)
1032                    },
1033                    Attribute::Modulus(n.value().to_vec()),
1034                    Attribute::PublicExponent(e.value().to_vec()),
1035                ];
1036
1037                let public_handle = session.create_object(&template)?;
1038
1039                Ok((public_handle, None))
1040            }
1041            _ => {
1042                return Err(anyhow::anyhow!(
1043                    "{} keys are not yet supported",
1044                    key.pk_algo()));
1045            }
1046        })?;
1047
1048        let mut key = Key::from_object(token, session, public_handle)?;
1049        if let Some(constituent) = constituent {
1050            key.combine_with(constituent);
1051        }
1052
1053        Ok(key)
1054    }
1055}