Skip to main content

signstar_crypto/key/import/
mod.rs

1//! Functionality for importing of cryptographic key material.
2
3#[cfg(feature = "nethsm")]
4pub mod nethsm;
5
6use std::fmt::Debug;
7
8use rsa::{
9    RsaPrivateKey,
10    pkcs8::DecodePrivateKey,
11    traits::PrivateKeyParts,
12    traits::PublicKeyParts,
13};
14
15#[cfg(doc)]
16use crate::key::MIN_RSA_BIT_LENGTH;
17use crate::key::{Error, KeyType, key_type_matches_length};
18
19/// The data for private key import
20// Allow dead code here, as the variants of `PrivateKeyData` are only used with a backend, which
21// requires enabling a feature.
22pub enum PrivateKeyData {
23    /// Data for [`KeyType::Curve25519`]
24    Curve25519(Vec<u8>),
25    /// Data for [`KeyType::EcBp256`]
26    EcBp256(Vec<u8>),
27    /// Data for [`KeyType::EcBp384`]
28    EcBp384(Vec<u8>),
29    /// Data for [`KeyType::EcK256`]
30    EcK256(Vec<u8>),
31    /// Data for [`KeyType::EcP224`]
32    EcP224(Vec<u8>),
33    /// Data for [`KeyType::EcP256`]
34    EcP256(Vec<u8>),
35    /// Data for [`KeyType::EcP384`]
36    EcP384(Vec<u8>),
37    /// Data for [`KeyType::EcP521`]
38    EcP521(Vec<u8>),
39    /// Data for [`KeyType::Rsa`]
40    Rsa {
41        /// The prime number `p`.
42        prime_p: Vec<u8>,
43        /// The prime number `q`.
44        prime_q: Vec<u8>,
45        /// The public exponent `e`.
46        public_exponent: Vec<u8>,
47    },
48}
49
50impl Debug for PrivateKeyData {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        const REDACTED: &&str = &"[REDACTED]";
53        match self {
54            Self::Curve25519(_) => f.debug_tuple("Curve25519").field(REDACTED).finish(),
55            Self::EcBp256(_) => f.debug_tuple("EcBp256").field(REDACTED).finish(),
56            Self::EcBp384(_) => f.debug_tuple("EcBp384").field(REDACTED).finish(),
57            Self::EcK256(_) => f.debug_tuple("EcK256").field(REDACTED).finish(),
58            Self::EcP224(_) => f.debug_tuple("EcP224").field(REDACTED).finish(),
59            Self::EcP256(_) => f.debug_tuple("EcP256").field(REDACTED).finish(),
60            Self::EcP384(_) => f.debug_tuple("EcP384").field(REDACTED).finish(),
61            Self::EcP521(_) => f.debug_tuple("EcP521").field(REDACTED).finish(),
62            Self::Rsa {
63                public_exponent, ..
64            } => f
65                .debug_struct("Rsa")
66                .field("prime_p", REDACTED)
67                .field("prime_q", REDACTED)
68                .field("public_exponent", public_exponent)
69                .finish(),
70        }
71    }
72}
73
74impl From<&PrivateKeyData> for KeyType {
75    fn from(value: &PrivateKeyData) -> Self {
76        match value {
77            PrivateKeyData::Curve25519(_) => Self::Curve25519,
78            PrivateKeyData::EcBp256(_) => Self::EcBp256,
79            PrivateKeyData::EcBp384(_) => Self::EcBp384,
80            PrivateKeyData::EcK256(_) => Self::EcK256,
81            PrivateKeyData::EcP224(_) => Self::EcP224,
82            PrivateKeyData::EcP256(_) => Self::EcP256,
83            PrivateKeyData::EcP384(_) => Self::EcP384,
84            PrivateKeyData::EcP521(_) => Self::EcP521,
85            PrivateKeyData::Rsa { .. } => Self::Rsa,
86        }
87    }
88}
89
90/// The key data required when importing a secret key
91#[derive(Debug)]
92pub struct PrivateKeyImport {
93    key_data: PrivateKeyData,
94}
95
96/// Creates a new vector with bytes in `buf`, left-padded with zeros so
97/// that the result is exactly `len` big.
98///
99/// # Errors
100///
101/// Returns an an error, if the input buffer `buf` is longer than the targeted `len`.
102///
103/// # Examples
104///
105/// ```no_compile
106/// let input = vec![1, 2, 3];
107/// let output = pad(&input, 4)?;
108/// assert_eq!(output, vec![0, 1, 2, 3]);
109/// ```
110fn pad(buf: &[u8], len: usize) -> Result<Vec<u8>, Error> {
111    let buffer_len = buf.len();
112    if len < buf.len() {
113        return Err(Error::PaddingInputTooLong {
114            buffer_len,
115            pad_len: len,
116        });
117    }
118    let mut v = vec![0; len];
119    v[len - buf.len()..].copy_from_slice(buf);
120    Ok(v)
121}
122
123impl PrivateKeyImport {
124    /// Creates a new [`PrivateKeyImport`]
125    ///
126    /// Accepts a [`KeyType`] (all except [`KeyType::Generic`]) and a bytes array representing a
127    /// matching PKCS#8 private key in ASN.1 DER-encoded format.
128    ///
129    /// # Errors
130    ///
131    /// Returns an error if
132    ///
133    /// - `key_data` can not be deserialized to a respective private key format.
134    /// - an RSA private key does not have prime P or prime Q.
135    /// - an RSA private key is shorter than [`MIN_RSA_BIT_LENGTH`].
136    /// - `key_type` is the unsupported [`KeyType::Generic`] or [`KeyType::EcBp512`].
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// # use testresult::TestResult;
142    /// use ed25519_dalek::{SigningKey, pkcs8::EncodePrivateKey};
143    /// use rand::rngs::OsRng;
144    /// use signstar_crypto::key::{KeyType, PrivateKeyImport};
145    /// # fn main() -> TestResult {
146    ///
147    /// let key_data = {
148    ///     let mut csprng = OsRng;
149    ///     let signing_key: SigningKey = SigningKey::generate(&mut csprng);
150    ///     signing_key.to_pkcs8_der()?.as_bytes().to_vec()
151    /// };
152    ///
153    /// assert!(PrivateKeyImport::new(KeyType::Curve25519, &key_data).is_ok());
154    /// # Ok(())
155    /// # }
156    /// ```
157    pub fn new(key_type: KeyType, key_data: &[u8]) -> Result<Self, crate::Error> {
158        Ok(match key_type {
159            KeyType::Curve25519 => {
160                let key_pair = ed25519_dalek::pkcs8::KeypairBytes::from_pkcs8_der(key_data)
161                    .map_err(Error::Pkcs8)?;
162                Self {
163                    key_data: PrivateKeyData::Curve25519(key_pair.secret_key.to_vec()),
164                }
165            }
166            KeyType::EcBp256 => {
167                let private_key =
168                    bp256::r1::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
169                Self {
170                    key_data: PrivateKeyData::EcBp256(private_key.to_bytes().as_slice().to_owned()),
171                }
172            }
173            KeyType::EcBp384 => {
174                let private_key =
175                    bp384::r1::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
176                Self {
177                    key_data: PrivateKeyData::EcBp384(private_key.to_bytes().as_slice().to_owned()),
178                }
179            }
180            KeyType::EcBp512 => return Err(Error::UnsupportedKeyType(key_type).into()),
181            KeyType::EcK256 => {
182                let private_key =
183                    k256::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
184                Self {
185                    key_data: PrivateKeyData::EcK256(private_key.to_bytes().as_slice().to_owned()),
186                }
187            }
188            KeyType::EcP224 => {
189                let private_key =
190                    p224::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
191                Self {
192                    key_data: PrivateKeyData::EcP224(private_key.to_bytes().as_slice().to_owned()),
193                }
194            }
195            KeyType::EcP256 => {
196                let private_key =
197                    p256::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
198                Self {
199                    key_data: PrivateKeyData::EcP256(private_key.to_bytes().as_slice().to_owned()),
200                }
201            }
202            KeyType::EcP384 => {
203                let private_key =
204                    p384::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
205                Self {
206                    key_data: PrivateKeyData::EcP384(private_key.to_bytes().as_slice().to_owned()),
207                }
208            }
209            KeyType::EcP521 => {
210                let private_key =
211                    p521::SecretKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
212                Self {
213                    key_data: PrivateKeyData::EcP521(private_key.to_bytes().as_slice().to_owned()),
214                }
215            }
216            KeyType::Generic => return Err(Error::UnsupportedKeyType(KeyType::Generic).into()),
217            KeyType::Rsa => {
218                let private_key = RsaPrivateKey::from_pkcs8_der(key_data).map_err(Error::Pkcs8)?;
219                // ensure, that we have sufficient bit length
220                key_type_matches_length(key_type, Some(private_key.size() as u32 * 8))?;
221                Self {
222                    key_data: PrivateKeyData::Rsa {
223                        prime_p: private_key
224                            .primes()
225                            .first()
226                            .ok_or(Error::NoPrimes)?
227                            .to_bytes_be(),
228                        prime_q: private_key
229                            .primes()
230                            .get(1)
231                            .ok_or(Error::NoPrimes)?
232                            .to_bytes_be(),
233                        public_exponent: private_key.e().to_bytes_be(),
234                    },
235                }
236            }
237        })
238    }
239
240    /// Creates a new [`PrivateKeyImport`]
241    ///
242    /// Accepts a [`KeyType`] (all except [`KeyType::Generic`]) and a string slice representing a
243    /// matching PKCS#8 private key in PEM-encoded format.
244    ///
245    /// # Errors
246    ///
247    /// Returns an error if
248    ///
249    /// - `key_data` can not be deserialized to a respective private key format.
250    /// - an RSA private key does not have prime P or prime Q.
251    /// - an RSA private key is shorter than [`MIN_RSA_BIT_LENGTH`].
252    /// - `key_type` is the unsupported [`KeyType::Generic`] or [`KeyType::EcBp512`].
253    ///
254    /// # Examples
255    ///
256    /// ```
257    /// # use testresult::TestResult;
258    /// use std::ops::Deref;
259    ///
260    /// use ed25519_dalek::{SigningKey, pkcs8::EncodePrivateKey, pkcs8::spki::der::pem::LineEnding};
261    /// use rand::rngs::OsRng;
262    /// use signstar_crypto::key::{KeyType, PrivateKeyImport};
263    /// # fn main() -> TestResult {
264    ///
265    /// let key_data = {
266    ///     let mut csprng = OsRng;
267    ///     let signing_key: SigningKey = SigningKey::generate(&mut csprng);
268    ///     signing_key.to_pkcs8_pem(LineEnding::default())?
269    /// };
270    ///
271    /// assert!(PrivateKeyImport::from_pkcs8_pem(KeyType::Curve25519, key_data.deref()).is_ok());
272    /// # Ok(())
273    /// # }
274    /// ```
275    pub fn from_pkcs8_pem(key_type: KeyType, key_data: &str) -> Result<Self, crate::Error> {
276        Ok(match key_type {
277            KeyType::Curve25519 => {
278                let key_pair = ed25519_dalek::pkcs8::KeypairBytes::from_pkcs8_pem(key_data)
279                    .map_err(Error::Pkcs8)?;
280                Self {
281                    key_data: PrivateKeyData::Curve25519(key_pair.secret_key.to_vec()),
282                }
283            }
284            KeyType::EcBp256 => {
285                let private_key =
286                    bp256::r1::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
287                Self {
288                    key_data: PrivateKeyData::EcBp256(private_key.to_bytes().as_slice().to_owned()),
289                }
290            }
291            KeyType::EcBp384 => {
292                let private_key =
293                    bp384::r1::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
294                Self {
295                    key_data: PrivateKeyData::EcBp384(private_key.to_bytes().as_slice().to_owned()),
296                }
297            }
298            KeyType::EcBp512 => return Err(Error::UnsupportedKeyType(key_type).into()),
299            KeyType::EcK256 => {
300                let private_key =
301                    k256::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
302                Self {
303                    key_data: PrivateKeyData::EcK256(private_key.to_bytes().as_slice().to_owned()),
304                }
305            }
306            KeyType::EcP224 => {
307                let private_key =
308                    p224::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
309                Self {
310                    key_data: PrivateKeyData::EcP224(private_key.to_bytes().as_slice().to_owned()),
311                }
312            }
313            KeyType::EcP256 => {
314                let private_key =
315                    p256::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
316                Self {
317                    key_data: PrivateKeyData::EcP256(private_key.to_bytes().as_slice().to_owned()),
318                }
319            }
320            KeyType::EcP384 => {
321                let private_key =
322                    p384::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
323                Self {
324                    key_data: PrivateKeyData::EcP384(private_key.to_bytes().as_slice().to_owned()),
325                }
326            }
327            KeyType::EcP521 => {
328                let private_key =
329                    p521::SecretKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
330                Self {
331                    key_data: PrivateKeyData::EcP521(private_key.to_bytes().as_slice().to_owned()),
332                }
333            }
334            KeyType::Generic => return Err(Error::UnsupportedKeyType(KeyType::Generic).into()),
335            KeyType::Rsa => {
336                let private_key = RsaPrivateKey::from_pkcs8_pem(key_data).map_err(Error::Pkcs8)?;
337                // ensure, that we have sufficient bit length
338                key_type_matches_length(key_type, Some(private_key.size() as u32 * 8))?;
339                Self {
340                    key_data: PrivateKeyData::Rsa {
341                        prime_p: private_key
342                            .primes()
343                            .first()
344                            .ok_or(Error::NoPrimes)?
345                            .to_bytes_be(),
346                        prime_q: private_key
347                            .primes()
348                            .get(1)
349                            .ok_or(Error::NoPrimes)?
350                            .to_bytes_be(),
351                        public_exponent: private_key.e().to_bytes_be(),
352                    },
353                }
354            }
355        })
356    }
357
358    /// Create [`PrivateKeyImport`] object from raw, private RSA key parts.
359    ///
360    /// The function takes two primes (*p* and *q*) and the public exponent,
361    /// which usually is 65537 (`[0x01, 0x00, 0x01]`).
362    ///
363    /// # Examples
364    ///
365    /// ```rust
366    /// use signstar_crypto::key::PrivateKeyImport;
367    ///
368    /// # fn main() -> testresult::TestResult {
369    /// let prime_p = vec![7];
370    /// let prime_q = vec![11];
371    /// let public_exponent = vec![1, 0, 1];
372    ///
373    /// let _import = PrivateKeyImport::from_rsa(prime_p, prime_q, public_exponent);
374    /// # Ok(()) }
375    /// ```
376    pub fn from_rsa(prime_p: Vec<u8>, prime_q: Vec<u8>, public_exponent: Vec<u8>) -> Self {
377        Self {
378            key_data: PrivateKeyData::Rsa {
379                prime_p,
380                prime_q,
381                public_exponent,
382            },
383        }
384    }
385
386    /// Create [`PrivateKeyImport`] object from raw, private Elliptic Curve bytes.
387    ///
388    /// The function takes two parameters:
389    /// - the type of elliptic curve,
390    /// - raw bytes in a curve-specific encoding
391    ///
392    /// Elliptic curve keys require the `bytes` to be zero-padded to be of correct size.
393    /// This function automatically applies padding accordingly.
394    ///
395    /// # Examples
396    ///
397    /// ```rust
398    /// use signstar_crypto::key::{KeyType, PrivateKeyImport};
399    ///
400    /// # fn main() -> testresult::TestResult {
401    /// let bytes = vec![0x00; 32];
402    ///
403    /// let _import = PrivateKeyImport::from_raw_bytes(KeyType::Curve25519, bytes)?;
404    /// # Ok(()) }
405    /// ```
406    pub fn from_raw_bytes(ec: KeyType, bytes: impl AsRef<[u8]>) -> Result<Self, crate::Error> {
407        let bytes = bytes.as_ref();
408        Ok(Self {
409            key_data: match ec {
410                KeyType::EcP256 => PrivateKeyData::EcP256(pad(bytes, 32)?),
411                KeyType::EcP384 => PrivateKeyData::EcP384(pad(bytes, 48)?),
412                KeyType::EcP521 => PrivateKeyData::EcP521(pad(bytes, 66)?),
413                KeyType::Curve25519 => PrivateKeyData::Curve25519(pad(bytes, 32)?),
414                key_type => return Err(Error::UnsupportedKeyType(key_type).into()),
415            },
416        })
417    }
418
419    /// Get the matching [`KeyType`] for the data contained in the [`PrivateKeyImport`]
420    pub fn key_type(&self) -> KeyType {
421        KeyType::from(&self.key_data)
422    }
423}
424
425#[cfg(test)]
426mod tests {
427    use rsa::RsaPrivateKey;
428    use rsa::pkcs8::EncodePrivateKey;
429    use rstest::rstest;
430    use testresult::TestResult;
431
432    use super::*;
433
434    fn ed25519_private_key() -> TestResult<Vec<u8>> {
435        use ed25519_dalek::SigningKey;
436        use rand::rngs::OsRng;
437        let mut csprng = OsRng;
438        let signing_key: SigningKey = SigningKey::generate(&mut csprng);
439        Ok(signing_key.to_pkcs8_der()?.as_bytes().to_vec())
440    }
441
442    fn bp256_private_key() -> TestResult<Vec<u8>> {
443        use bp256::elliptic_curve::rand_core::OsRng;
444        let private_key = bp256::r1::SecretKey::random(&mut OsRng);
445        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
446    }
447
448    fn bp384_private_key() -> TestResult<Vec<u8>> {
449        use bp384::elliptic_curve::rand_core::OsRng;
450        let private_key = bp384::r1::SecretKey::random(&mut OsRng);
451        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
452    }
453
454    fn k256_private_key() -> TestResult<Vec<u8>> {
455        use k256::elliptic_curve::rand_core::OsRng;
456        let private_key = k256::SecretKey::random(&mut OsRng);
457        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
458    }
459
460    fn p224_private_key() -> TestResult<Vec<u8>> {
461        use p224::elliptic_curve::rand_core::OsRng;
462        let private_key = p224::SecretKey::random(&mut OsRng);
463        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
464    }
465
466    fn p256_private_key() -> TestResult<Vec<u8>> {
467        use p256::elliptic_curve::rand_core::OsRng;
468        let private_key = p256::SecretKey::random(&mut OsRng);
469        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
470    }
471
472    fn p384_private_key() -> TestResult<Vec<u8>> {
473        use p384::elliptic_curve::rand_core::OsRng;
474        let private_key = p384::SecretKey::random(&mut OsRng);
475        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
476    }
477
478    fn p521_private_key() -> TestResult<Vec<u8>> {
479        use p521::elliptic_curve::rand_core::OsRng;
480        let private_key = p521::SecretKey::random(&mut OsRng);
481        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
482    }
483
484    fn rsa_private_key() -> TestResult<Vec<u8>> {
485        let mut rng = rand::thread_rng();
486        let private_key = RsaPrivateKey::new(&mut rng, 2048.try_into()?)?;
487        Ok(private_key.to_pkcs8_der()?.as_bytes().to_vec())
488    }
489
490    #[rstest]
491    #[case::curve25519(KeyType::Curve25519)]
492    #[case::ecbp256(KeyType::EcBp256)]
493    #[case::ecbp384(KeyType::EcBp384)]
494    #[case::eck256(KeyType::EcK256)]
495    #[case::ecp224(KeyType::EcP224)]
496    #[case::ecp256(KeyType::EcP256)]
497    #[case::ecp384(KeyType::EcP384)]
498    #[case::ecp521(KeyType::EcP521)]
499    #[case::rsa(KeyType::Rsa)]
500    fn key_data(#[case] key_type: KeyType) -> TestResult {
501        let bp256_private_key = bp256_private_key()?;
502        let bp384_private_key = bp384_private_key()?;
503        let ed25519_private_key = ed25519_private_key()?;
504        let k256_private_key = k256_private_key()?;
505        let p224_private_key = p224_private_key()?;
506        let p256_private_key = p256_private_key()?;
507        let p384_private_key = p384_private_key()?;
508        let p521_private_key = p521_private_key()?;
509        let rsa_private_key = rsa_private_key()?;
510
511        let (ok_cases, error_cases) = match key_type {
512            KeyType::Curve25519 => (
513                [&ed25519_private_key],
514                [
515                    &bp256_private_key,
516                    &bp384_private_key,
517                    &k256_private_key,
518                    &p224_private_key,
519                    &p256_private_key,
520                    &p384_private_key,
521                    &p521_private_key,
522                    &rsa_private_key,
523                ],
524            ),
525            KeyType::EcBp256 => (
526                [&bp256_private_key],
527                [
528                    &bp384_private_key,
529                    &ed25519_private_key,
530                    &k256_private_key,
531                    &p224_private_key,
532                    &p256_private_key,
533                    &p384_private_key,
534                    &p521_private_key,
535                    &rsa_private_key,
536                ],
537            ),
538            KeyType::EcBp384 => (
539                [&bp384_private_key],
540                [
541                    &bp256_private_key,
542                    &ed25519_private_key,
543                    &k256_private_key,
544                    &p224_private_key,
545                    &p256_private_key,
546                    &p384_private_key,
547                    &p521_private_key,
548                    &rsa_private_key,
549                ],
550            ),
551            KeyType::EcK256 => (
552                [&k256_private_key],
553                [
554                    &bp256_private_key,
555                    &bp384_private_key,
556                    &ed25519_private_key,
557                    &p224_private_key,
558                    &p256_private_key,
559                    &p384_private_key,
560                    &p521_private_key,
561                    &rsa_private_key,
562                ],
563            ),
564            KeyType::EcP224 => (
565                [&p224_private_key],
566                [
567                    &bp256_private_key,
568                    &bp384_private_key,
569                    &ed25519_private_key,
570                    &k256_private_key,
571                    &p256_private_key,
572                    &p384_private_key,
573                    &p521_private_key,
574                    &rsa_private_key,
575                ],
576            ),
577            KeyType::EcP256 => (
578                [&p256_private_key],
579                [
580                    &bp256_private_key,
581                    &bp384_private_key,
582                    &ed25519_private_key,
583                    &k256_private_key,
584                    &p224_private_key,
585                    &p384_private_key,
586                    &p521_private_key,
587                    &rsa_private_key,
588                ],
589            ),
590            KeyType::EcP384 => (
591                [&p384_private_key],
592                [
593                    &bp256_private_key,
594                    &bp384_private_key,
595                    &ed25519_private_key,
596                    &k256_private_key,
597                    &p224_private_key,
598                    &p256_private_key,
599                    &p521_private_key,
600                    &rsa_private_key,
601                ],
602            ),
603            KeyType::EcP521 => (
604                [&p521_private_key],
605                [
606                    &bp256_private_key,
607                    &bp384_private_key,
608                    &ed25519_private_key,
609                    &k256_private_key,
610                    &p224_private_key,
611                    &p256_private_key,
612                    &p384_private_key,
613                    &rsa_private_key,
614                ],
615            ),
616            KeyType::Rsa => (
617                [&rsa_private_key],
618                [
619                    &bp256_private_key,
620                    &bp384_private_key,
621                    &ed25519_private_key,
622                    &k256_private_key,
623                    &p224_private_key,
624                    &p256_private_key,
625                    &p384_private_key,
626                    &p521_private_key,
627                ],
628            ),
629            KeyType::Generic => unimplemented!("generic key types are not supported"),
630            KeyType::EcBp512 => unimplemented!("there is currently no rustcrypto support"),
631        };
632
633        for ok_case in ok_cases.iter() {
634            assert!(PrivateKeyImport::new(key_type, ok_case).is_ok());
635        }
636
637        for error_case in error_cases.iter() {
638            assert!(PrivateKeyImport::new(key_type, error_case).is_err());
639        }
640
641        Ok(())
642    }
643
644    #[rstest]
645    #[case::curve_25519(PrivateKeyImport::new(KeyType::Curve25519, ed25519_private_key()?.as_slice())?, KeyType::Curve25519)]
646    #[case::ecbp256(PrivateKeyImport::new(KeyType::EcBp256, bp256_private_key()?.as_slice())?, KeyType::EcBp256)]
647    #[case::ecbp384(PrivateKeyImport::new(KeyType::EcBp384, bp384_private_key()?.as_slice())?, KeyType::EcBp384)]
648    #[case::eck256(PrivateKeyImport::new(KeyType::EcK256, k256_private_key()?.as_slice())?, KeyType::EcK256)]
649    #[case::ecp224(PrivateKeyImport::new(KeyType::EcP224, p224_private_key()?.as_slice())?, KeyType::EcP224)]
650    #[case::ecp256(PrivateKeyImport::new(KeyType::EcP256, p256_private_key()?.as_slice())?, KeyType::EcP256)]
651    #[case::ecp384(PrivateKeyImport::new(KeyType::EcP384, p384_private_key()?.as_slice())?, KeyType::EcP384)]
652    #[case::ecp521(PrivateKeyImport::new(KeyType::EcP521, p521_private_key()?.as_slice())?, KeyType::EcP521)]
653    #[case::rsa(PrivateKeyImport::new(KeyType::Rsa, rsa_private_key()?.as_slice())?, KeyType::Rsa)]
654    fn private_key_import_key_data_matches(
655        #[case] private_key_data: PrivateKeyImport,
656        #[case] key_type: KeyType,
657    ) -> TestResult {
658        assert_eq!(private_key_data.key_type(), key_type);
659
660        Ok(())
661    }
662}