1 //! Error types
2 
3 use core::fmt;
4 
5 #[cfg(feature = "pem")]
6 use der::pem;
7 
8 /// Result type with `sec1` crate's [`Error`] 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     #[cfg(feature = "der")]
17     Asn1(der::Error),
18 
19     /// Cryptographic errors.
20     ///
21     /// These can be used by EC implementations to signal that a key is
22     /// invalid for cryptographic reasons. This means the document parsed
23     /// correctly, but one of the values contained within was invalid, e.g.
24     /// a number expected to be a prime was not a prime.
25     Crypto,
26 
27     /// PKCS#8 errors.
28     #[cfg(feature = "pkcs8")]
29     Pkcs8(pkcs8::Error),
30 
31     /// Errors relating to the `Elliptic-Curve-Point-to-Octet-String` or
32     /// `Octet-String-to-Elliptic-Curve-Point` encodings.
33     PointEncoding,
34 
35     /// Version errors
36     Version,
37 }
38 
39 impl fmt::Display for Error {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result40     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41         match self {
42             #[cfg(feature = "der")]
43             Error::Asn1(err) => write!(f, "SEC1 ASN.1 error: {}", err),
44             Error::Crypto => f.write_str("SEC1 cryptographic error"),
45             #[cfg(feature = "pkcs8")]
46             Error::Pkcs8(err) => write!(f, "{}", err),
47             Error::PointEncoding => f.write_str("elliptic curve point encoding error"),
48             Error::Version => f.write_str("SEC1 version error"),
49         }
50     }
51 }
52 
53 #[cfg(feature = "der")]
54 impl From<der::Error> for Error {
from(err: der::Error) -> Error55     fn from(err: der::Error) -> Error {
56         Error::Asn1(err)
57     }
58 }
59 
60 #[cfg(feature = "pem")]
61 impl From<pem::Error> for Error {
from(err: pem::Error) -> Error62     fn from(err: pem::Error) -> Error {
63         der::Error::from(err).into()
64     }
65 }
66 
67 #[cfg(feature = "pkcs8")]
68 impl From<pkcs8::Error> for Error {
from(err: pkcs8::Error) -> Error69     fn from(err: pkcs8::Error) -> Error {
70         Error::Pkcs8(err)
71     }
72 }
73 
74 #[cfg(feature = "pkcs8")]
75 impl From<pkcs8::spki::Error> for Error {
from(err: pkcs8::spki::Error) -> Error76     fn from(err: pkcs8::spki::Error) -> Error {
77         Error::Pkcs8(pkcs8::Error::PublicKey(err))
78     }
79 }
80 
81 #[cfg(feature = "std")]
82 impl std::error::Error for Error {}
83