password_hash/
error.rs

1//! Error types.
2
3use core::fmt;
4
5/// Result type.
6pub type Result<T> = core::result::Result<T, Error>;
7
8/// Password hashing errors.
9#[derive(Copy, Clone, Debug, Eq, PartialEq)]
10#[non_exhaustive]
11pub enum Error {
12    /// Unsupported algorithm.
13    Algorithm,
14
15    /// Cryptographic error.
16    Crypto,
17
18    /// Encoding errors (e.g. Base64).
19    EncodingInvalid,
20
21    /// Internal error within a password hashing library.
22    Internal,
23
24    /// Out of memory (heap allocation failure).
25    OutOfMemory,
26
27    /// Output size invalid.
28    OutputSize,
29
30    /// Invalid named parameter.
31    ParamInvalid {
32        /// Parameter name.
33        name: &'static str,
34    },
35
36    /// Invalid parameters.
37    ParamsInvalid,
38
39    /// Invalid password.
40    PasswordInvalid,
41
42    /// Invalid salt.
43    SaltInvalid,
44
45    /// Invalid algorithm version.
46    Version,
47}
48
49impl fmt::Display for Error {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> core::result::Result<(), fmt::Error> {
51        match self {
52            Self::Algorithm => write!(f, "unsupported algorithm"),
53            Self::Crypto => write!(f, "cryptographic error"),
54            Self::EncodingInvalid => write!(f, "invalid encoding"),
55            Self::Internal => write!(f, "internal password hashing algorithm error"),
56            Self::OutOfMemory => write!(f, "out of memory"),
57            Self::OutputSize => write!(f, "password hash output size invalid"),
58            Self::ParamInvalid { name } => write!(f, "invalid parameter: {name:?}"),
59            Self::ParamsInvalid => write!(f, "invalid parameters"),
60            Self::PasswordInvalid => write!(f, "invalid password"),
61            Self::SaltInvalid => write!(f, "invalid salt"),
62            Self::Version => write!(f, "invalid algorithm version"),
63        }
64    }
65}
66
67impl core::error::Error for Error {}
68
69#[cfg(feature = "phc")]
70impl From<phc::Error> for Error {
71    fn from(err: phc::Error) -> Self {
72        match err {
73            phc::Error::B64Encoding(_) | phc::Error::MissingField | phc::Error::TrailingData => {
74                Self::EncodingInvalid
75            }
76            phc::Error::OutputSize { .. } => Self::OutputSize,
77            phc::Error::ParamNameDuplicated
78            | phc::Error::ParamNameInvalid
79            | phc::Error::ParamValueTooLong
80            | phc::Error::ParamsMaxExceeded
81            | phc::Error::ValueTooLong => Self::ParamsInvalid,
82            phc::Error::SaltTooShort | phc::Error::SaltTooLong => Self::SaltInvalid,
83            _ => Self::Internal, // Branch since `phc::Error` is `non_exhaustive`
84        }
85    }
86}