1 //! Error types 2 3 use core::fmt; 4 5 #[cfg(feature = "pem")] 6 use der::pem; 7 8 /// Result type 9 pub type Result<T> = core::result::Result<T, Error>; 10 11 /// Error type 12 #[derive(Copy, Clone, Debug, Eq, PartialEq)] 13 #[non_exhaustive] 14 pub enum Error { 15 /// ASN.1 DER-related errors. 16 Asn1(der::Error), 17 18 /// Cryptographic errors. 19 /// 20 /// These can be used by RSA implementations to signal that a key is 21 /// invalid for cryptographic reasons. This means the document parsed 22 /// correctly, but one of the values contained within was invalid, e.g. 23 /// a number expected to be a prime was not a prime. 24 Crypto, 25 26 /// PKCS#8 errors. 27 #[cfg(feature = "pkcs8")] 28 Pkcs8(pkcs8::Error), 29 30 /// Version errors 31 Version, 32 } 33 34 impl fmt::Display for Error { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 36 match self { 37 Error::Asn1(err) => write!(f, "PKCS#1 ASN.1 error: {}", err), 38 Error::Crypto => f.write_str("PKCS#1 cryptographic error"), 39 #[cfg(feature = "pkcs8")] 40 Error::Pkcs8(err) => write!(f, "{}", err), 41 Error::Version => f.write_str("PKCS#1 version error"), 42 } 43 } 44 } 45 46 impl From<der::Error> for Error { from(err: der::Error) -> Error47 fn from(err: der::Error) -> Error { 48 Error::Asn1(err) 49 } 50 } 51 52 #[cfg(feature = "pem")] 53 impl From<pem::Error> for Error { from(err: pem::Error) -> Error54 fn from(err: pem::Error) -> Error { 55 der::Error::from(err).into() 56 } 57 } 58 59 #[cfg(feature = "pkcs8")] 60 impl From<Error> for pkcs8::Error { from(err: Error) -> pkcs8::Error61 fn from(err: Error) -> pkcs8::Error { 62 match err { 63 Error::Asn1(e) => pkcs8::Error::Asn1(e), 64 Error::Crypto | Error::Version => pkcs8::Error::KeyMalformed, 65 Error::Pkcs8(e) => e, 66 } 67 } 68 } 69 70 #[cfg(feature = "pkcs8")] 71 impl From<pkcs8::Error> for Error { from(err: pkcs8::Error) -> Error72 fn from(err: pkcs8::Error) -> Error { 73 Error::Pkcs8(err) 74 } 75 } 76 77 #[cfg(feature = "pkcs8")] 78 impl From<Error> for pkcs8::spki::Error { from(err: Error) -> pkcs8::spki::Error79 fn from(err: Error) -> pkcs8::spki::Error { 80 match err { 81 Error::Asn1(e) => pkcs8::spki::Error::Asn1(e), 82 _ => pkcs8::spki::Error::KeyMalformed, 83 } 84 } 85 } 86 87 #[cfg(feature = "pkcs8")] 88 impl From<pkcs8::spki::Error> for Error { from(err: pkcs8::spki::Error) -> Error89 fn from(err: pkcs8::spki::Error) -> Error { 90 Error::Pkcs8(pkcs8::Error::PublicKey(err)) 91 } 92 } 93 94 #[cfg(feature = "std")] 95 impl std::error::Error for Error {} 96