Skip to main content

pq_key_encoder/
error.rs

1use core::fmt;
2
3use pq_oid::Algorithm;
4
5use crate::types::KeyType;
6
7/// Error type for pq-key-encoder operations.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9#[non_exhaustive]
10pub enum Error {
11    /// Key bytes length does not match expected size for the algorithm.
12    KeySizeMismatch {
13        algorithm: Algorithm,
14        key_type: KeyType,
15        expected: usize,
16        actual: usize,
17    },
18    /// Invalid DER encoding.
19    InvalidDer(&'static str),
20    /// Invalid PEM encoding.
21    #[cfg(feature = "pem")]
22    InvalidPem(&'static str),
23    /// Invalid JWK encoding.
24    #[cfg(feature = "jwk")]
25    InvalidJwk(&'static str),
26    /// Invalid base64 encoding.
27    #[cfg(any(feature = "pem", feature = "jwk"))]
28    InvalidBase64(&'static str),
29    /// Unsupported or unrecognized algorithm OID.
30    UnsupportedAlgorithm,
31    /// Key bytes are empty.
32    EmptyKey,
33    /// Error from pq-oid crate.
34    Oid(pq_oid::Error),
35}
36
37impl fmt::Display for Error {
38    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
39        match self {
40            Error::KeySizeMismatch {
41                algorithm,
42                key_type,
43                expected,
44                actual,
45            } => write!(
46                f,
47                "{} {} key size mismatch: expected {} bytes, got {}",
48                algorithm, key_type, expected, actual
49            ),
50            Error::InvalidDer(msg) => write!(f, "invalid DER: {}", msg),
51            #[cfg(feature = "pem")]
52            Error::InvalidPem(msg) => write!(f, "invalid PEM: {}", msg),
53            #[cfg(feature = "jwk")]
54            Error::InvalidJwk(msg) => write!(f, "invalid JWK: {}", msg),
55            #[cfg(any(feature = "pem", feature = "jwk"))]
56            Error::InvalidBase64(msg) => write!(f, "invalid base64: {}", msg),
57            Error::UnsupportedAlgorithm => write!(f, "unsupported algorithm"),
58            Error::EmptyKey => write!(f, "empty key"),
59            Error::Oid(e) => write!(f, "OID error: {}", e),
60        }
61    }
62}
63
64impl From<pq_oid::Error> for Error {
65    fn from(e: pq_oid::Error) -> Self {
66        Error::Oid(e)
67    }
68}
69
70#[cfg(feature = "std")]
71impl std::error::Error for Error {}
72
73/// Result type for pq-key-encoder operations.
74pub type Result<T> = core::result::Result<T, Error>;