Skip to main content

oo7/crypto/
error.rs

1#[cfg(feature = "native_crypto")]
2use cbc::cipher;
3
4/// Cryptography specific errors.
5#[derive(Debug)]
6pub enum Error {
7    #[cfg(feature = "openssl_crypto")]
8    Openssl(openssl::error::ErrorStack),
9    #[cfg(feature = "native_crypto")]
10    PadError(cipher::inout::PadError),
11    Getrandom(getrandom::Error),
12}
13
14#[cfg(feature = "openssl_crypto")]
15impl From<openssl::error::ErrorStack> for Error {
16    fn from(value: openssl::error::ErrorStack) -> Self {
17        Self::Openssl(value)
18    }
19}
20
21#[cfg(feature = "native_crypto")]
22impl From<cipher::inout::PadError> for Error {
23    fn from(value: cipher::inout::PadError) -> Self {
24        Self::PadError(value)
25    }
26}
27
28impl From<getrandom::Error> for Error {
29    fn from(value: getrandom::Error) -> Self {
30        Self::Getrandom(value)
31    }
32}
33
34impl std::error::Error for Error {
35    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
36        match self {
37            #[cfg(feature = "openssl_crypto")]
38            Self::Openssl(e) => Some(e),
39            #[cfg(feature = "native_crypto")]
40            Self::PadError(_) => None,
41            Self::Getrandom(_) => None,
42        }
43    }
44}
45
46impl std::fmt::Display for Error {
47    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48        match self {
49            #[cfg(feature = "openssl_crypto")]
50            Self::Openssl(e) => f.write_fmt(format_args!("Openssl error: {e}")),
51            #[cfg(feature = "native_crypto")]
52            Self::PadError(e) => f.write_fmt(format_args!("Wrong padding error: {e}")),
53            Self::Getrandom(e) => f.write_fmt(format_args!("Random number generation error: {e}")),
54        }
55    }
56}
57
58#[cfg(feature = "native_crypto")]
59impl From<cipher::block_padding::Error> for Error {
60    fn from(_value: cipher::block_padding::Error) -> Self {
61        Self::PadError(cipher::inout::PadError)
62    }
63}