Skip to main content

pkcs1/
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    /// 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    /// Malformed cryptographic key contained in a PKCS#1 document.
27    ///
28    /// This is intended for relaying errors when decoding fields of a PKCS#1 document.
29    KeyMalformed,
30
31    /// Version errors
32    Version,
33}
34
35impl core::error::Error for Error {
36    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
37        match self {
38            Error::Asn1(err) => Some(err),
39            _ => None,
40        }
41    }
42}
43
44impl fmt::Display for Error {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        match self {
47            Error::Asn1(err) => write!(f, "PKCS#1 ASN.1 error: {err}"),
48            Error::KeyMalformed => f.write_str("PKCS#1 cryptographic key data malformed"),
49            Error::Crypto => f.write_str("PKCS#1 cryptographic error"),
50            Error::Version => f.write_str("PKCS#1 version error"),
51        }
52    }
53}
54
55impl From<der::Error> for Error {
56    fn from(err: der::Error) -> Error {
57        Error::Asn1(err)
58    }
59}
60
61#[cfg(feature = "pem")]
62impl From<pem::Error> for Error {
63    fn from(err: pem::Error) -> Error {
64        der::Error::from(err).into()
65    }
66}