use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
InvalidKeyLength {
label: &'static str,
expected: usize,
got: usize,
},
InvalidPrefix { label: &'static str },
TooShort { label: &'static str },
MacVerificationFailed { label: &'static str },
DecryptionFailed { label: &'static str },
EncryptionFailed { label: &'static str },
SignFailed { label: &'static str },
VerificationFailed { label: &'static str },
UnknownIdentifier {
kind: &'static str,
identifier: String,
},
InvalidMasterKey { got: usize },
InvalidKey { label: &'static str },
InvalidIterations,
InvalidKdfParams { label: &'static str },
InvalidOutputLength { requested: usize, max: usize },
InvalidHex,
UnsupportedNationalAlgorithm {
name: &'static str,
hint: &'static str,
},
MissingConfig { key: &'static str },
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::InvalidKeyLength {
label,
expected,
got,
} => write!(f, "{label} length must be {expected} (got {got})."),
Error::InvalidPrefix { label } => write!(f, "Invalid {label} ciphertext prefix."),
Error::TooShort { label } => write!(f, "{label} ciphertext too short."),
Error::MacVerificationFailed { label } => write!(f, "{label} MAC verification failed."),
Error::DecryptionFailed { label } => write!(f, "{label} decryption failed."),
Error::EncryptionFailed { label } => write!(f, "{label} encryption failed."),
Error::SignFailed { label } => write!(f, "{label} signing failed."),
Error::VerificationFailed { label } => {
write!(f, "{label} signature verification failed.")
}
Error::UnknownIdentifier { kind, identifier } => {
write!(f, "Unknown {kind} identifier \"{identifier}\".")
}
Error::InvalidMasterKey { got } => {
write!(f, "Master key must be exactly 32 bytes (got {got}).")
}
Error::InvalidKey { label } => write!(f, "Invalid {label} key."),
Error::InvalidIterations => write!(f, "PBKDF2 iterations must be positive."),
Error::InvalidKdfParams { label } => write!(f, "Invalid {label} parameters."),
Error::InvalidOutputLength { requested, max } => {
if *requested == 0 {
write!(f, "Output length must be positive.")
} else {
write!(f, "Output length {requested} exceeds the maximum of {max}.")
}
}
Error::InvalidHex => write!(f, "Invalid hex string."),
Error::UnsupportedNationalAlgorithm { name, hint } => {
write!(f, "{name} is not provided by this library: {hint}")
}
Error::MissingConfig { key } => {
write!(f, "Required configuration \"{key}\" was not found.")
}
}
}
}
impl std::error::Error for Error {}
pub type Result<T> = std::result::Result<T, Error>;