hpke_core/
error.rs

1//! Error types
2
3use core::fmt;
4
5use hpke_crypto::CryptoError;
6
7/// HPKE Error types.
8#[derive(Debug)]
9pub enum Error {
10    /// Generic invalid input.
11    InvalidInput(&'static str),
12
13    /// Inconsistent PSK input.
14    InconsistentPsk,
15
16    /// PSK input is required but missing.
17    MissingPsk,
18
19    /// PSK input is provided but not needed.
20    UnnecessaryPsk,
21
22    /// PSK input is too short (needs to be at least 32 bytes).
23    InsecurePsk,
24
25    /// The message limit for this AEAD, key, and nonce.
26    MessageLimitReached,
27
28    /// Error passed from the underlying crypto implementation.
29    CryptoError(CryptoError),
30}
31
32impl Error {
33    /// Returns true if the error is `Error::InvalidInput`.
34    pub const fn is_invalid_input(&self) -> bool {
35        matches!(self, Error::InvalidInput(_))
36    }
37
38    /// Returns true if the error is due to the crypto backend not supporting
39    /// the requested KEM.
40    pub const fn is_unsupported_kem(&self) -> bool {
41        matches!(self, Error::CryptoError(CryptoError::KemUnsupported))
42    }
43}
44
45impl core::error::Error for Error {
46    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
47        match self {
48            Error::CryptoError(e) => Some(e),
49            _ => None,
50        }
51    }
52}
53
54impl fmt::Display for Error {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            Error::InvalidInput(msg) => write!(f, "Invalid input: {msg}"),
58            Error::InconsistentPsk => write!(f, "Inconsistent PSK input"),
59            Error::MissingPsk => write!(f, "PSK input is required but missing"),
60            Error::UnnecessaryPsk => write!(f, "PSK input is provided but not needed"),
61            Error::InsecurePsk => {
62                write!(f, "PSK input is too short (needs to be at least 32 bytes)")
63            }
64            Error::MessageLimitReached => {
65                write!(f, "The message limit for this AEAD, key, and nonce")
66            }
67            Error::CryptoError(e) => write!(f, "Crypto error: {e}"),
68        }
69    }
70}
71
72impl From<CryptoError> for Error {
73    fn from(e: CryptoError) -> Self {
74        Error::CryptoError(e)
75    }
76}