Skip to main content

sequoia_cryptoki/
export.rs

1use anyhow::Context;
2
3use chrono::{
4    DateTime,
5    Utc,
6};
7
8use sequoia_openpgp as openpgp;
9use openpgp::Profile;
10use openpgp::crypto::{PublicKeyAlgorithm, mpi};
11use openpgp::packet::key::{Key4, Key6};
12use openpgp::packet::key::UnspecifiedRole;
13use openpgp::packet::key::PublicParts;
14use openpgp::packet::key;
15use openpgp::packet;
16use openpgp::types::HashAlgorithm;
17use openpgp::types::SymmetricAlgorithm;
18
19use cryptoki::object::Attribute;
20use cryptoki::object::AttributeType;
21use cryptoki::object::KeyType;
22use cryptoki::object::ObjectClass;
23use cryptoki::object::ParameterSetType;
24
25use crate::Result;
26use crate::keyid::Bundling;
27use crate::objects::Key;
28use crate::oids::oid_to_str;
29
30const TRACE: bool = false;
31
32/// Although PKCS#11 says that the EC_POINT for ECDSA and EDDSA keys
33/// should be "Public key bytes in little endian order", some HSMs
34/// return the public key in DER encoding.
35///
36/// When DER encoded, the payload looks like this:
37///
38/// ```text
39/// 0x04 (payload len byte) payload bytes
40/// ```
41///
42/// This is easy to distinguish from byte in little endian order,
43/// since we know the expected length length.
44fn decode_ec_point(value: &[u8], expected_len: u8)
45    -> Result<&[u8]>
46{
47    if value.len() == expected_len as usize {
48        Ok(value)
49    } else if value.len() == expected_len as usize + 2
50        && value[0] == 0x04
51        && value[1] == expected_len
52    {
53        Ok(&value[2..])
54    } else {
55        Err(anyhow::anyhow!("HSM returned an invalid ec parameter (got {} bytes, {})",
56                            value.len(),
57                            value
58                                .iter()
59                                .map(|k| format!("{:02X}", k))
60                                .collect::<Vec<_>>()
61                                .join("")))
62    }
63}
64
65impl Key {
66    // Convert the key object to an OpenPGP key object.
67    pub fn to_openpgp_key(&self)
68        -> Result<packet::Key<PublicParts, UnspecifiedRole>>
69    {
70        tracer!(TRACE, "Key::to_openpgp_key");
71
72        let mut openpgp_key = self.openpgp_key.lock().unwrap();
73        if let Some(key) = openpgp_key.as_ref() {
74            return Ok(key.clone());
75        }
76
77        struct KeyInfo {
78            key_id: Option<Vec<u8>>,
79            key_type: Option<KeyType>,
80            key_value: Option<Vec<u8>>,
81            ec_params: Option<Vec<u8>>,
82            ec_point: Option<Vec<u8>>,
83            modulus: Option<Vec<u8>>,
84            exponent: Option<Vec<u8>>,
85            opaque_parameters: Option<ParameterSetType>,
86        }
87
88        fn get_key_info(key: &Key) -> Result<KeyInfo> {
89            let typs = &[
90                AttributeType::Id,
91                AttributeType::Class,
92                AttributeType::KeyType,
93                // Generic key value:
94                AttributeType::Value,
95                // ECC:
96                AttributeType::EcParams,
97                AttributeType::EcPoint,
98                // RSA:
99                AttributeType::PublicExponent,
100                AttributeType::Modulus,
101                // ML-DSA:
102                AttributeType::ParameterSet,
103            ][..];
104
105            let (session, object) = key.open_ro_session()?;
106            let attributes = session.get_attributes(object.clone(), &typs)?;
107
108            let mut key_id = None;
109            let mut object_class = None;
110            let mut key_type = None;
111            let mut key_value = None;
112            let mut ec_params = None;
113            let mut ec_point = None;
114            let mut modulus = None;
115            let mut exponent = None;
116            let mut opaque_parameters = None;
117
118            for attr in attributes.into_iter() {
119                match attr {
120                    Attribute::Id(value) => key_id = Some(value),
121                    Attribute::Class(value) => object_class = Some(value),
122                    Attribute::KeyType(value) => key_type = Some(value),
123                    Attribute::Value(value) => key_value = Some(value),
124                    Attribute::EcParams(value) => ec_params = Some(value),
125                    Attribute::EcPoint(value) => ec_point = Some(value),
126                    Attribute::PublicExponent(value) => exponent = Some(value),
127                    Attribute::Modulus(value) => modulus = Some(value),
128                    Attribute::ParameterSet(v) => opaque_parameters = Some(v),
129                    _ => {
130                        panic!("PKCS#11 driver returned unrequested attribute: {:?}",
131                               attr);
132                    }
133                }
134            }
135
136            match object_class {
137                None => {
138                    return Err(anyhow::anyhow!(
139                        "Token appears to be broken: key is missing object class \
140                         attribute"));
141                }
142                Some(ObjectClass::PUBLIC_KEY) => (),
143                Some(cls) => {
144                    return Err(anyhow::anyhow!(
145                        "Unsupported object class: {:?}", cls));
146                }
147            }
148
149            Ok(KeyInfo {
150                key_id,
151                key_type,
152                key_value,
153                ec_params,
154                ec_point,
155                exponent,
156                modulus,
157                opaque_parameters,
158            })
159        }
160
161        let key_info = get_key_info(self)?;
162        let composite_info = if let Some(key) = self.composite_key() {
163            Some(get_key_info(key)?)
164        } else {
165            None
166        };
167
168        macro_rules! value {
169            ($key:expr, $name:expr, $attr:expr) => {{
170                let attr: &Option<_> = &$attr;
171                if let Some(value) = attr {
172                    Ok(value)
173                } else {
174                    Err(anyhow::anyhow!(
175                        "Can't export the {} key: the {} attribute is missing",
176                        $key, $name))
177                }
178            }};
179        }
180
181        // Extract the parameters from the key ID.
182	let key_id = if let Some(key_id) = key_info.key_id.as_ref() {
183	    key_id
184	} else {
185	    return Err(anyhow::anyhow!("Key is missing a key ID"));
186	};
187
188	let key_id = match String::from_utf8(key_id.to_vec()) {
189	    Ok(key_id) => key_id,
190	    Err(err) => {
191		return Err(err).context(format!(
192		    "Key ID {:?} does not identify an OpenPGP key",
193		    String::from_utf8_lossy(key_id)));
194	    }
195	};
196
197	t!("key id: {}", key_id);
198
199	let invalid_key_id = |err: Option<anyhow::Error>| -> Result<_> {
200	    if let Some(err) = err {
201		Err(err).context(format!(
202		    "Key ID {:?} does not identify an OpenPGP key",
203		    key_id))
204	    } else {
205		Err(anyhow::anyhow!(
206		    "Key ID {:?} does not identify an OpenPGP key",
207		    key_id))
208	    }
209	};
210
211        let id = if let Some(id) = key_id.strip_prefix("pgp:v") {
212            id
213        } else {
214            t!("Invalid key ID: Missing pgp:v prefix");
215            return invalid_key_id(Some(anyhow::anyhow!("Missing pgp:v prefix")));
216        };
217        let mut parts = id.split(':');
218
219        // Recover the profile.
220        let Some(version) = parts.next() else {
221	    return invalid_key_id(Some(anyhow::anyhow!("Missing version")));
222	};
223	t!("version component: {}", version);
224        let (profile, bundling) = match version {
225            "6" => (openpgp::Profile::RFC9580,
226                    Bundling::Standalone),
227            "6t" => (openpgp::Profile::RFC9580,
228                     Bundling::TraditionalHalf),
229            "6pq" => (openpgp::Profile::RFC9580,
230                      Bundling::PostQuantumHalf),
231
232            "4" => (openpgp::Profile::RFC4880,
233                    Bundling::Standalone),
234            "4t" => (openpgp::Profile::RFC4880,
235                     Bundling::TraditionalHalf),
236            "4pq" => (openpgp::Profile::RFC4880,
237                      Bundling::PostQuantumHalf),
238
239            v => {
240                t!("Invalid key ID: Unsupported version ({})", v);
241		return invalid_key_id(Some(
242		    anyhow::anyhow!("Unsupported version ({})", v)));
243            }
244        };
245
246	// Recover the algorithm.
247	let Some(algo_parts) = parts.next() else {
248	    return invalid_key_id(Some(anyhow::anyhow!("Missing algorithm")));
249	};
250	t!("algo component: {}", algo_parts);
251	let mut algo_parts = algo_parts.split("-");
252	let Some(algo) = algo_parts.next() else {
253	    return invalid_key_id(Some(anyhow::anyhow!("Empty algorithm")));
254	};
255	let algo = if let Ok(algo) = algo.parse::<crate::PublicKeyAlgorithm>() {
256	    algo
257	} else {
258            t!("Invalid algorithm ({})", algo);
259	    return invalid_key_id(Some(
260		anyhow::anyhow!("Invalid algorithm ({})", algo)));
261	};
262
263        // Extract the hash algorithm and the symmetric algorithm.
264        // This is only used needed for v4 ECDH keys.
265	let mut hash_algo = None;
266	let mut sym_algo = None;
267        if profile == openpgp::Profile::RFC4880 {
268	    if let Some(part) = algo_parts.next() {
269                hash_algo = match part {
270		    "sha256" => Some(HashAlgorithm::SHA256),
271		    "sha384" => Some(HashAlgorithm::SHA384),
272		    "sha512" => Some(HashAlgorithm::SHA512),
273		    _ => None,
274                };
275	    }
276
277	    if let Some(part) = algo_parts.next() {
278                sym_algo = match part {
279		    "aes128" => Some(SymmetricAlgorithm::AES128),
280		    "aes192" => Some(SymmetricAlgorithm::AES192),
281		    "aes256" => Some(SymmetricAlgorithm::AES256),
282		    _ => None,
283                };
284	    }
285        } else if let Some(part) = algo_parts.next() {
286	    return invalid_key_id(Some(
287		anyhow::anyhow!("Unknown algorithm parameter ({})", part)));
288	}
289
290        // Recover the creation time, which we encode using
291        // ISO 8601-1:2019's basic format.
292        let Some(time) = parts.next() else {
293	    return invalid_key_id(Some(anyhow::anyhow!("Missing creation time")));
294	};
295	t!("creation time component: {}", time);
296        let l = "19700101T000000Z".len();
297        if time.len() < l {
298            t!("Invalid key ID: Invalid creation time: string is too short");
299	    return invalid_key_id(Some(anyhow::anyhow!(
300		"Invalid creation time: string is too short")));
301        }
302        let creation_time: DateTime<Utc> = match DateTime::parse_from_str(
303	    &time[..l], "%Y%m%dT%H%M%S%#z")
304	{
305	    Ok(time) => time.into(),
306	    Err(err) => {
307                t!("Invalid key ID: Invalid time: {}", err);
308                return invalid_key_id(Some(err.into()));
309            }
310	};
311	let creation_time: std::time::SystemTime = creation_time.into();
312
313        t!("Key ID => profile: {:?}, bundling: {:?}, algo: {:?}, creation time: {}, \
314            hash: {:?}, sym: {:?}",
315           profile, bundling, algo,
316           DateTime::<Utc>::from(creation_time.clone()).format("%Y%m%dT%H%M%SZ"),
317           hash_algo, sym_algo);
318
319        let ec_edwards_to_key = |key_info: &KeyInfo|
320            -> Result<key::Key<key::PublicParts, key::UnspecifiedRole>>
321        {
322            // PKCS#11, v3.2, Section 6.3.5. Edwards Elliptic
323            // Curve public key objects
324            //
325            // DER encoding of the parameters.
326            let ec_params = value!("ECC", "EC params", key_info.ec_params)?;
327
328            // PKCS#11, v3.2, Section 6.3.5. Edwards Elliptic
329            // Curve public key objects:
330            //
331            //   Public key bytes in little endian order as defined
332            //   in [RFC 8032].
333            //
334            // Unfortunately, reality is a bit more complicated: some
335            // HSMs DER encode the result.
336
337            let key = match (algo.clone(), profile, &ec_params[..]) {
338                (crate::PublicKeyAlgorithm::Ed25519
339		 | crate::PublicKeyAlgorithm::MLDSA65_Ed25519,
340		 Profile::RFC9580,
341		 crate::oids::Ed25519) => {
342                    let ec_point = decode_ec_point(
343                        value!("ECC", "EC point", key_info.ec_point)?,
344                        32)?;
345
346                    Key6::<key::PublicParts, key::UnspecifiedRole>
347                        ::import_public_ed25519(&ec_point, creation_time)?
348                        .into()
349                },
350
351                (crate::PublicKeyAlgorithm::Ed448
352		 | crate::PublicKeyAlgorithm::MLDSA87_Ed448,
353		 Profile::RFC9580,
354		 crate::oids::Ed448) => {
355                    let ec_point = decode_ec_point(
356                        value!("ECC", "EC point", key_info.ec_point)?,
357                        57)?;
358
359                    Key6::<key::PublicParts, key::UnspecifiedRole>
360                        ::import_public_ed448(&ec_point, creation_time)?
361                        .into()
362                }
363
364                (crate::PublicKeyAlgorithm::EdDSA,
365		 Profile::RFC4880,
366		 crate::oids::Ed25519) => {
367                    let ec_point = decode_ec_point(
368                        value!("ECC", "EC point", key_info.ec_point)?,
369                        32)?;
370
371		    // import_public_ed25519 imports a legacy Ed25519
372		    // key.
373                    Key4::<key::PublicParts, key::UnspecifiedRole>
374                        ::import_public_ed25519(&ec_point, creation_time)?
375                        .into()
376		}
377
378                (crate::PublicKeyAlgorithm::Ed25519,
379		 Profile::RFC4880,
380		 crate::oids::Ed25519) => {
381                    let ec_point = decode_ec_point(
382                        value!("ECC", "EC point", key_info.ec_point)?,
383                        32)?;
384
385		    // Despite its name, `Key4::import_public_ed25519`
386		    // imports a legacy Ed25519 key, i.e., an EdDSA
387		    // key, not an Ed25519 key.  There is no function
388		    // to import a v4 Ed25519, but we can hack it
389		    // together.
390		    Key4::new(creation_time,
391			      PublicKeyAlgorithm::Ed25519,
392			      mpi::PublicKey::Ed25519 {
393				  a: ec_point.try_into()?,
394			      })?.into()
395                }
396
397                (crate::PublicKeyAlgorithm::Ed448,
398		 Profile::RFC4880,
399		 crate::oids::Ed448) => {
400                    let ec_point = decode_ec_point(
401                        value!("ECC", "EC point", key_info.ec_point)?,
402                        57)?;
403
404                    Key4::<key::PublicParts, key::UnspecifiedRole>
405                        ::import_public_ed448(&ec_point, creation_time)?
406                        .into()
407                }
408
409                _ => {
410                    return Err(anyhow::anyhow!(
411                        "unsupported key (algo: {}, profile: {:?}, curve: {})",
412                        algo, profile, oid_to_str(&ec_params[..])));
413                }
414            };
415
416            Ok(key)
417        };
418
419        let ec_montgomery_to_key = |key_info: &KeyInfo|
420            -> Result<key::Key<key::PublicParts, key::UnspecifiedRole>>
421        {
422            // PKCS#11, v3.2, Section 6.3.7. Montgomery Elliptic
423            // Curve public key objects
424            //
425            // DER encoding of the parameters.
426            let ec_params = value!("ECC", "EC params", key_info.ec_params)?;
427
428            // PKCS#11, v3.2, Section 6.3.7. Montgomery Elliptic
429            // Curve public key objects
430            //
431            // Public key bytes in little endian order as defined
432            // in [RFC 7748].
433            let ec_point = value!("ECC", "EC point", key_info.ec_point)?;
434
435            // RFC 9580, Section 5.5.5.6. Algorithm-Specific Part
436            // for ECDH Keys
437            //
438            // An MPI of an EC point representing a public key, in
439            // the point format associated with the curve, as
440            // specified in Section 9.2.1.
441            //
442            // https://www.rfc-editor.org/rfc/rfc9580.html#name-algorithm-specific-part-for-ecd
443
444            let key = match (algo.clone(), profile, &ec_params[..]) {
445                (crate::PublicKeyAlgorithm::X25519
446		 | crate::PublicKeyAlgorithm::MLKEM768_X25519,
447		 Profile::RFC9580,
448		 crate::oids::X25519) =>
449                    Key6::<key::PublicParts, key::UnspecifiedRole>
450                    ::import_public_x25519(&ec_point, creation_time)?
451                    .into(),
452
453                (crate::PublicKeyAlgorithm::X448
454		 | crate::PublicKeyAlgorithm::MLKEM1024_X448,
455		 Profile::RFC9580,
456		 crate::oids::X448) =>
457                    Key6::<key::PublicParts, key::UnspecifiedRole>
458                    ::import_public_x448(&ec_point, creation_time)?
459                    .into(),
460
461                (crate::PublicKeyAlgorithm::Cv25519,
462		 Profile::RFC4880,
463		 crate::oids::X25519) => {
464                    // These parameters are part of the OpenPGP
465                    // public key.  If not `None`, then we were
466                    // able to derive them from the token.
467                    // Otherwise, we use reasonable defaults, as
468                    // per RFC 9580, section 11.5.1. ECDH
469                    // Parameters.
470                    //
471                    // https://www.rfc-editor.org/rfc/rfc9580.html#ecdh
472                    let hash_algo
473                        = hash_algo.unwrap_or(HashAlgorithm::SHA256);
474                    let sym_algo
475                        = sym_algo.unwrap_or(SymmetricAlgorithm::AES128);
476
477                    Key4::<key::PublicParts, key::UnspecifiedRole>
478                        ::import_public_cv25519(&ec_point, hash_algo,
479                                                sym_algo, creation_time)?
480                        .into()
481		}
482
483                (crate::PublicKeyAlgorithm::X25519
484		 | crate::PublicKeyAlgorithm::MLKEM768_X25519,
485		 Profile::RFC4880,
486		 crate::oids::X25519) => {
487                    Key4::<key::PublicParts, key::UnspecifiedRole>
488                        ::import_public_x25519(&ec_point, creation_time)?
489                        .into()
490                },
491
492                (crate::PublicKeyAlgorithm::X448
493		 | crate::PublicKeyAlgorithm::MLKEM1024_X448,
494		 Profile::RFC4880,
495		 crate::oids::X448) =>
496                    Key4::<key::PublicParts, key::UnspecifiedRole>
497                    ::import_public_x448(&ec_point, creation_time)?
498                    .into(),
499
500                _=> {
501                    return Err(anyhow::anyhow!(
502                        "unsupported key (algo: {}, profile: {:?}, curve: {})",
503                        algo, profile, oid_to_str(&ec_params[..])));
504                }
505            };
506
507            Ok(key)
508        };
509
510        let key = match (key_info.key_type, composite_info.as_ref().map(|ki| ki.key_type)) {
511            (None, _) => {
512                return Err(anyhow::anyhow!(
513                    "Token appears to be broken: key is missing key type \
514                     attribute"));
515            }
516            (Some(_), Some(None)) => {
517                return Err(anyhow::anyhow!(
518                    "Token appears to be broken: key is missing key type \
519                     attribute"));
520            }
521
522            (Some(KeyType::EC_EDWARDS), None) => {
523                ec_edwards_to_key(&key_info)?
524            }
525
526            (Some(KeyType::EC_MONTGOMERY), None) => {
527                ec_montgomery_to_key(&key_info)?
528            },
529
530            (Some(KeyType::RSA), None) => {
531                let modulus = value!("RSA", "modulus", key_info.modulus)?;
532                let exponent = value!("RSA", "exponent", key_info.exponent)?;
533
534                match profile {
535                    Profile::RFC9580 =>
536                        Key6::<key::PublicParts, key::UnspecifiedRole>
537                        ::import_public_rsa(&exponent, &modulus, creation_time)?
538                            .into(),
539
540                    Profile::RFC4880 =>
541                        Key4::<key::PublicParts, key::UnspecifiedRole>
542                        ::import_public_rsa(&exponent, &modulus, creation_time)?
543                            .into(),
544
545                    _ => return Err(anyhow::anyhow!("unsupported profile")),
546                }
547            },
548
549            (Some(KeyType::ML_DSA), Some(Some(KeyType::EC_EDWARDS)))
550                | (Some(KeyType::EC_EDWARDS), Some(Some(KeyType::ML_DSA))) =>
551            {
552                let (mldsa_info, eddsa_info)
553                    = if key_info.key_type == Some(KeyType::ML_DSA)
554                {
555                    (key_info, composite_info.unwrap())
556                } else {
557                    (composite_info.unwrap(), key_info)
558                };
559
560                let eddsa = ec_edwards_to_key(&eddsa_info)?;
561
562                use cryptoki::object::MlDsaParameterSetType;
563                let mldsa = mldsa_info.key_value
564                    .ok_or(anyhow::anyhow!("key value not returned by token"))?;
565                let ml_dsa_parameters: Option<MlDsaParameterSetType>
566                    = mldsa_info.opaque_parameters.map(|p| p.into());
567
568                match ml_dsa_parameters {
569                    Some(MlDsaParameterSetType::ML_DSA_65) => {
570                        let eddsa = match eddsa.mpis() {
571                            mpi::PublicKey::Ed25519 { a } =>
572                                Box::new(a.clone()),
573                            _ => return Err(anyhow::anyhow!(
574                                "expected an Ed25519 key in \
575                                 composite construction")),
576                        };
577
578                        let mldsa = mldsa.try_into()
579                            .map_err(|_| anyhow::anyhow!(
580                                "ML-DSA key has wrong size"))?;
581
582                        Key6::new(creation_time,
583                                  PublicKeyAlgorithm::MLDSA65_Ed25519,
584                                  mpi::PublicKey::MLDSA65_Ed25519 {
585                                      eddsa,
586                                      mldsa,
587                                  })?.into()
588                    },
589
590                    Some(MlDsaParameterSetType::ML_DSA_87) => {
591                        let eddsa = match eddsa.mpis() {
592                            mpi::PublicKey::Ed448 { a } =>
593                                a.clone(),
594                            _ => return Err(anyhow::anyhow!(
595                                "expected an Ed448 key in \
596                                 composite construction")),
597                        };
598
599                        let mldsa = mldsa.try_into()
600                            .map_err(|_| anyhow::anyhow!(
601                                "ML-DSA key has wrong size"))?;
602
603                        Key6::new(creation_time,
604                                  PublicKeyAlgorithm::MLDSA87_Ed448,
605                                  mpi::PublicKey::MLDSA87_Ed448 {
606                                      eddsa,
607                                      mldsa,
608                                  })?.into()
609                    },
610
611                    Some(p) => return Err(anyhow::anyhow!(
612                        "ML-DSA parameters {:?} not supported by OpenPGP", p)),
613
614                    None => return Err(anyhow::anyhow!(
615                        "ML-DSA parameters not returned by token")),
616                }
617            },
618
619            (Some(KeyType::SLH_DSA), None) => {
620                use cryptoki::object::SlhDsaParameterSetType;
621                let slh_dsa = key_info.key_value
622                    .ok_or(anyhow::anyhow!("key value not returned by token"))?;
623                let slh_dsa_parameters: Option<SlhDsaParameterSetType>
624                    = key_info.opaque_parameters.map(|p| p.into());
625
626                match slh_dsa_parameters {
627                    Some(SlhDsaParameterSetType::SHAKE_128S) => {
628                        let slh_dsa = slh_dsa.try_into()
629                            .map_err(|_| anyhow::anyhow!(
630                                "SLH-DSA key has wrong size"))?;
631
632                        Key6::new(creation_time,
633                                  PublicKeyAlgorithm::SLHDSA128s,
634                                  mpi::PublicKey::SLHDSA128s {
635                                      public: slh_dsa,
636                                  })?.into()
637                    },
638
639                    Some(SlhDsaParameterSetType::SHAKE_128F) => {
640                        let slh_dsa = slh_dsa.try_into()
641                            .map_err(|_| anyhow::anyhow!(
642                                "SLH-DSA key has wrong size"))?;
643
644                        Key6::new(creation_time,
645                                  PublicKeyAlgorithm::SLHDSA128f,
646                                  mpi::PublicKey::SLHDSA128f {
647                                      public: slh_dsa,
648                                  })?.into()
649                    },
650
651                    Some(SlhDsaParameterSetType::SHAKE_256S) => {
652                        let slh_dsa = slh_dsa.try_into()
653                            .map_err(|_| anyhow::anyhow!(
654                                "SLH-DSA key has wrong size"))?;
655
656                        Key6::new(creation_time,
657                                  PublicKeyAlgorithm::SLHDSA256s,
658                                  mpi::PublicKey::SLHDSA256s {
659                                      public: slh_dsa,
660                                  })?.into()
661                    },
662
663                    Some(p) => return Err(anyhow::anyhow!(
664                        "SLH-DSA parameters {} not supported by OpenPGP", p)),
665
666                    None => return Err(anyhow::anyhow!(
667                        "SLH-DSA parameters not returned by token")),
668                }
669            },
670
671            (Some(KeyType::ML_KEM), Some(Some(KeyType::EC_MONTGOMERY)))
672                | (Some(KeyType::EC_MONTGOMERY), Some(Some(KeyType::ML_KEM))) =>
673            {
674                let (mlkem_info, ecdh_info)
675                    = if key_info.key_type == Some(KeyType::ML_KEM)
676                {
677                    (key_info, composite_info.unwrap())
678                } else {
679                    (composite_info.unwrap(), key_info)
680                };
681
682                let ecdh = ec_montgomery_to_key(&ecdh_info)?;
683
684                use cryptoki::object::MlKemParameterSetType;
685                let mlkem = mlkem_info.key_value
686                    .ok_or(anyhow::anyhow!("key value not returned by token"))?;
687                let mlkem_parameters: Option<MlKemParameterSetType>
688                    = mlkem_info.opaque_parameters.map(|p| p.into());
689
690                match mlkem_parameters {
691                    Some(MlKemParameterSetType::ML_KEM_768) => {
692                        let ecdh = match ecdh.mpis() {
693                            mpi::PublicKey::X25519 { u } =>
694                                Box::new(u.clone()),
695                            _ => return Err(anyhow::anyhow!(
696                                "expected an X25519 key in \
697                                 composite construction, got {:?}", ecdh)),
698                        };
699
700                        let mlkem = mlkem.try_into()
701                            .map_err(|_| anyhow::anyhow!(
702                                "ML-KEM key has wrong size"))?;
703
704                        match profile {
705                            Profile::RFC9580 => {
706                                Key6::new(creation_time,
707                                          PublicKeyAlgorithm::MLKEM768_X25519,
708                                          mpi::PublicKey::MLKEM768_X25519 {
709                                              ecdh,
710                                              mlkem,
711                                          })?.into()
712                            }
713                            Profile::RFC4880 => {
714                                Key4::new(creation_time,
715                                          PublicKeyAlgorithm::MLKEM768_X25519,
716                                          mpi::PublicKey::MLKEM768_X25519 {
717                                              ecdh,
718                                              mlkem,
719                                          })?.into()
720                            }
721                            _ => return Err(anyhow::anyhow!(
722                                "unsupported profile {:?}", profile)),
723                        }
724                    },
725
726                    Some(MlKemParameterSetType::ML_KEM_1024) => {
727                        let ecdh = match ecdh.mpis() {
728                            mpi::PublicKey::X448 { u } =>
729                                u.clone(),
730                            _ => return Err(anyhow::anyhow!(
731                                "expected an X448 key in \
732                                 composite construction")),
733                        };
734
735                        let mlkem = mlkem.try_into()
736                            .map_err(|_| anyhow::anyhow!(
737                                "ML-KEM key has wrong size"))?;
738
739                        match profile {
740                            Profile::RFC9580 => {
741                                Key6::new(creation_time,
742                                          PublicKeyAlgorithm::MLKEM1024_X448,
743                                          mpi::PublicKey::MLKEM1024_X448 {
744                                              ecdh,
745                                              mlkem,
746                                          })?.into()
747                            }
748                            Profile::RFC4880 => {
749                                Key4::new(creation_time,
750                                          PublicKeyAlgorithm::MLKEM1024_X448,
751                                          mpi::PublicKey::MLKEM1024_X448 {
752                                              ecdh,
753                                              mlkem,
754                                          })?.into()
755                            }
756                            _ => return Err(anyhow::anyhow!(
757                                "unsupported profile {:?}", profile)),
758                        }
759                    },
760
761                    Some(p) => return Err(anyhow::anyhow!(
762                        "ML-KEM parameters {:?} not supported by OpenPGP", p)),
763
764                    None => return Err(anyhow::anyhow!(
765                        "ML-KEM parameters not returned by token")),
766                }
767            },
768
769            (Some(kt), Some(Some(other))) => {
770                return Err(anyhow::anyhow!(
771                    "Can't export key: unsupported composite key: {}+{}",
772                    kt, other));
773            }
774
775            (Some(kt), None) => {
776                return Err(anyhow::anyhow!(
777                    "Can't export key: unsupported key type: {}", kt));
778            }
779        };
780
781        *openpgp_key = Some(key.clone());
782
783        Ok(key)
784    }
785
786    /// Return armor headers.
787    pub fn armor_headers(&self) -> Vec<(&'static str, String)> {
788        let mut headers = Vec::new();
789
790        // Unique ID.
791        if let Some(unique_id) = self.key_unique_id() {
792            if unique_id.iter().all(u8::is_ascii_alphanumeric) {
793                // If the unique ID is just ASCII, use as is.
794                headers.push((
795                    "UniqueID",
796                    String::from_utf8_lossy(unique_id).to_string()));
797            } else {
798                // Otherwise, use the hex encoded version.
799
800                // If Key::key_unique_id returns something, so will
801                // Key::key_unique_id_hex.
802                headers.push((
803                    "Cryptoki-UniqueID",
804                    self.key_unique_id_hex().unwrap()));
805            }
806        }
807
808        // ID.
809        if let Some(id) = self.key_id() {
810            headers.push((
811                "Cryptoki-ID",
812                String::from_utf8_lossy(id).to_string()));
813        }
814
815        // Label.
816        if let Some(label) = self.key_label() {
817            headers.push((
818                "Cryptoki-Label",
819                String::from_utf8_lossy(label).to_string()));
820        }
821
822        if let Some(composite_key) = self.composite_key() {
823            // Constituent Key ID.
824            if let Some(id) = composite_key.key_id() {
825                headers.push((
826                    "Cryptoki-Constituent-ID",
827                    String::from_utf8_lossy(id).to_string()));
828            }
829        }
830
831
832        headers
833    }
834}