1use std::fmt;
10
11#[derive(Debug, Clone, PartialEq, Eq)]
13pub enum Error {
14 InvalidKeyLength {
16 label: &'static str,
17 expected: usize,
18 got: usize,
19 },
20 InvalidPrefix { label: &'static str },
22 TooShort { label: &'static str },
24 MacVerificationFailed { label: &'static str },
26 DecryptionFailed { label: &'static str },
28 EncryptionFailed { label: &'static str },
30 SignFailed { label: &'static str },
32 VerificationFailed { label: &'static str },
34 UnknownIdentifier {
36 kind: &'static str,
37 identifier: String,
38 },
39 InvalidMasterKey { got: usize },
41 InvalidKey { label: &'static str },
43 InvalidIterations,
45 InvalidKdfParams { label: &'static str },
47 InvalidOutputLength { requested: usize, max: usize },
49 InvalidHex,
51 UnsupportedNationalAlgorithm {
53 name: &'static str,
54 hint: &'static str,
55 },
56 MissingConfig { key: &'static str },
58}
59
60impl fmt::Display for Error {
61 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62 match self {
63 Error::InvalidKeyLength {
64 label,
65 expected,
66 got,
67 } => write!(f, "{label} length must be {expected} (got {got})."),
68 Error::InvalidPrefix { label } => write!(f, "Invalid {label} ciphertext prefix."),
69 Error::TooShort { label } => write!(f, "{label} ciphertext too short."),
70 Error::MacVerificationFailed { label } => write!(f, "{label} MAC verification failed."),
71 Error::DecryptionFailed { label } => write!(f, "{label} decryption failed."),
72 Error::EncryptionFailed { label } => write!(f, "{label} encryption failed."),
73 Error::SignFailed { label } => write!(f, "{label} signing failed."),
74 Error::VerificationFailed { label } => {
75 write!(f, "{label} signature verification failed.")
76 }
77 Error::UnknownIdentifier { kind, identifier } => {
78 write!(f, "Unknown {kind} identifier \"{identifier}\".")
79 }
80 Error::InvalidMasterKey { got } => {
81 write!(f, "Master key must be exactly 32 bytes (got {got}).")
82 }
83 Error::InvalidKey { label } => write!(f, "Invalid {label} key."),
84 Error::InvalidIterations => write!(f, "PBKDF2 iterations must be positive."),
85 Error::InvalidKdfParams { label } => write!(f, "Invalid {label} parameters."),
86 Error::InvalidOutputLength { requested, max } => {
87 if *requested == 0 {
88 write!(f, "Output length must be positive.")
89 } else {
90 write!(f, "Output length {requested} exceeds the maximum of {max}.")
91 }
92 }
93 Error::InvalidHex => write!(f, "Invalid hex string."),
94 Error::UnsupportedNationalAlgorithm { name, hint } => {
95 write!(f, "{name} is not provided by this library: {hint}")
96 }
97 Error::MissingConfig { key } => {
98 write!(f, "Required configuration \"{key}\" was not found.")
99 }
100 }
101 }
102}
103
104impl std::error::Error for Error {}
105
106pub type Result<T> = std::result::Result<T, Error>;