1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
//! Error types

use core::fmt;
use der::asn1::ObjectIdentifier;

/// Result type with `spki` crate's [`Error`] type.
pub type Result<T> = core::result::Result<T, Error>;

#[cfg(feature = "pem")]
use der::pem;

/// Error type
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum Error {
    /// Algorithm parameters are missing.
    AlgorithmParametersMissing,

    /// ASN.1 DER-related errors.
    Asn1(der::Error),

    /// Malformed cryptographic key contained in a SPKI document.
    ///
    /// This is intended for relaying errors related to the raw data contained
    /// in [`SubjectPublicKeyInfo::subject_public_key`][`crate::SubjectPublicKeyInfo::subject_public_key`].
    KeyMalformed,

    /// Unknown algorithm OID.
    OidUnknown {
        /// Unrecognized OID value found in e.g. a SPKI `AlgorithmIdentifier`.
        oid: ObjectIdentifier,
    },
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Error::AlgorithmParametersMissing => {
                f.write_str("AlgorithmIdentifier parameters missing")
            }
            Error::Asn1(err) => write!(f, "ASN.1 error: {}", err),
            Error::KeyMalformed => f.write_str("SPKI cryptographic key data malformed"),
            Error::OidUnknown { oid } => {
                write!(f, "unknown/unsupported algorithm OID: {}", oid)
            }
        }
    }
}

impl From<der::Error> for Error {
    fn from(err: der::Error) -> Error {
        if let der::ErrorKind::OidUnknown { oid } = err.kind() {
            Error::OidUnknown { oid }
        } else {
            Error::Asn1(err)
        }
    }
}

#[cfg(feature = "pem")]
impl From<pem::Error> for Error {
    fn from(err: pem::Error) -> Error {
        der::Error::from(err).into()
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}