pkcs8/
error.rs

1//! Error types
2
3use core::fmt;
4
5#[cfg(feature = "pem")]
6use der::pem;
7
8/// Result type
9pub type Result<T> = core::result::Result<T, Error>;
10
11/// Error type
12#[derive(Copy, Clone, Debug, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum Error {
15    /// ASN.1 DER-related errors.
16    Asn1(der::Error),
17
18    /// Errors relating to PKCS#5-encrypted keys.
19    #[cfg(feature = "pkcs5")]
20    EncryptedPrivateKey(pkcs5::Error),
21
22    /// Malformed cryptographic key contained in a PKCS#8 document.
23    ///
24    /// This is intended for relaying errors related to the raw data contained
25    /// within [`PrivateKeyInfo::private_key`][`crate::PrivateKeyInfo::private_key`]
26    /// or [`SubjectPublicKeyInfo::subject_public_key`][`crate::SubjectPublicKeyInfo::subject_public_key`].
27    KeyMalformed,
28
29    /// [`AlgorithmIdentifier::parameters`][`crate::AlgorithmIdentifier::parameters`]
30    /// is malformed or otherwise encoded in an unexpected manner.
31    ParametersMalformed,
32
33    /// Public key errors propagated from the [`spki::Error`] type.
34    PublicKey(spki::Error),
35}
36
37impl fmt::Display for Error {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Error::Asn1(err) => write!(f, "PKCS#8 ASN.1 error: {}", err),
41            #[cfg(feature = "pkcs5")]
42            Error::EncryptedPrivateKey(err) => write!(f, "{}", err),
43            Error::KeyMalformed => f.write_str("PKCS#8 cryptographic key data malformed"),
44            Error::ParametersMalformed => f.write_str("PKCS#8 algorithm parameters malformed"),
45            Error::PublicKey(err) => write!(f, "public key error: {}", err),
46        }
47    }
48}
49
50#[cfg(feature = "std")]
51impl std::error::Error for Error {}
52
53impl From<der::Error> for Error {
54    fn from(err: der::Error) -> Error {
55        Error::Asn1(err)
56    }
57}
58
59impl From<der::ErrorKind> for Error {
60    fn from(err: der::ErrorKind) -> Error {
61        Error::Asn1(err.into())
62    }
63}
64
65#[cfg(feature = "pem")]
66impl From<pem::Error> for Error {
67    fn from(err: pem::Error) -> Error {
68        der::Error::from(err).into()
69    }
70}
71
72#[cfg(feature = "pkcs5")]
73impl From<pkcs5::Error> for Error {
74    fn from(err: pkcs5::Error) -> Error {
75        Error::EncryptedPrivateKey(err)
76    }
77}
78
79impl From<spki::Error> for Error {
80    fn from(err: spki::Error) -> Error {
81        Error::PublicKey(err)
82    }
83}
84
85impl From<Error> for spki::Error {
86    fn from(err: Error) -> spki::Error {
87        match err {
88            Error::Asn1(e) => spki::Error::Asn1(e),
89            Error::PublicKey(e) => e,
90            _ => spki::Error::KeyMalformed,
91        }
92    }
93}