1use core::fmt;
4
5#[cfg(feature = "pem")]
6use der::pem;
7
8pub type Result<T> = core::result::Result<T, Error>;
10
11#[derive(Copy, Clone, Debug, Eq, PartialEq)]
13#[non_exhaustive]
14pub enum Error {
15 Asn1(der::Error),
17
18 #[cfg(feature = "pkcs5")]
20 EncryptedPrivateKey(pkcs5::Error),
21
22 KeyMalformed(KeyError),
28
29 ParametersMalformed,
32
33 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(err) => write!(f, "PKCS#8 key malformed: {err}"),
44 Error::ParametersMalformed => write!(f, "PKCS#8 algorithm parameters malformed"),
45 Error::PublicKey(err) => write!(f, "public key error: {err}"),
46 }
47 }
48}
49
50impl core::error::Error for Error {
51 fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
52 match self {
53 Error::Asn1(err) => Some(err),
54 #[cfg(feature = "pkcs5")]
55 Error::EncryptedPrivateKey(err) => Some(err),
56 Error::KeyMalformed(err) => Some(err),
57 Error::PublicKey(err) => Some(err),
58 _ => None,
59 }
60 }
61}
62
63impl From<KeyError> for Error {
64 fn from(err: KeyError) -> Error {
65 Error::KeyMalformed(err)
66 }
67}
68
69impl From<der::Error> for Error {
70 fn from(err: der::Error) -> Error {
71 Error::Asn1(err)
72 }
73}
74
75impl From<der::ErrorKind> for Error {
76 fn from(err: der::ErrorKind) -> Error {
77 Error::Asn1(err.into())
78 }
79}
80
81#[cfg(feature = "pem")]
82impl From<pem::Error> for Error {
83 fn from(err: pem::Error) -> Error {
84 der::Error::from(err).into()
85 }
86}
87
88#[cfg(feature = "pkcs5")]
89impl From<pkcs5::Error> for Error {
90 fn from(err: pkcs5::Error) -> Error {
91 Error::EncryptedPrivateKey(err)
92 }
93}
94
95impl From<spki::Error> for Error {
96 fn from(err: spki::Error) -> Error {
97 Error::PublicKey(err)
98 }
99}
100
101impl From<Error> for spki::Error {
102 fn from(err: Error) -> spki::Error {
103 match err {
104 Error::Asn1(e) => spki::Error::Asn1(e),
105 Error::PublicKey(e) => e,
106 _ => spki::Error::KeyMalformed,
107 }
108 }
109}
110
111#[derive(Clone, Copy, Debug, Eq, PartialEq)]
113#[non_exhaustive]
114pub enum KeyError {
115 Invalid,
117
118 TooShort,
120
121 TooLong,
123}
124
125impl fmt::Display for KeyError {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 match self {
128 KeyError::Invalid => f.write_str("key invalid"),
129 KeyError::TooShort => f.write_str("key too short"),
130 KeyError::TooLong => f.write_str("key too long"),
131 }
132 }
133}
134
135impl core::error::Error for KeyError {}