laravel_rust_encryption/error.rs
1use std::fmt;
2
3/// Result type used throughout the crate.
4pub type Result<T> = std::result::Result<T, Error>;
5
6/// Errors returned by [`Encrypter`](crate::Encrypter).
7///
8/// The decryption variants mirror the cases of Laravel's `DecryptException`, so a tampered
9/// payload ([`InvalidMac`](Error::InvalidMac), [`Decrypt`](Error::Decrypt)) can be told
10/// apart from a malformed one ([`InvalidPayload`](Error::InvalidPayload)). The messages are
11/// Laravel's.
12#[derive(Debug, Clone, PartialEq, Eq)]
13#[non_exhaustive]
14pub enum Error {
15 /// The cipher name is not one of `aes-128-cbc`, `aes-256-cbc`, `aes-128-gcm` or
16 /// `aes-256-gcm`.
17 UnsupportedCipher,
18 /// The key is empty or is a malformed `base64:` value.
19 InvalidKey,
20 /// The key does not have the length the cipher requires.
21 InvalidKeyLength {
22 /// Key length required by the cipher, in bytes.
23 expected: usize,
24 /// Length of the key that was given, in bytes.
25 actual: usize,
26 },
27 /// The payload is not a valid Laravel payload (bad base64 or JSON, missing fields, wrong
28 /// IV length).
29 InvalidPayload,
30 /// The HMAC of a CBC payload does not match (tampered payload or wrong key).
31 InvalidMac,
32 /// The data could not be decrypted (bad GCM tag, wrong key, bad padding, or a tag where
33 /// the cipher does not use one).
34 Decrypt,
35 /// The data could not be encrypted.
36 Encrypt,
37 /// The decrypted plaintext is not valid PHP `serialize()` output, or uses a feature this
38 /// crate does not decode.
39 Unserialize,
40 /// The value cannot be PHP-serialized (see [`Value::Object`](crate::Value::Object)).
41 Serialize,
42 /// The decrypted plaintext is not valid UTF-8; use
43 /// [`Encrypter::decrypt_bytes`](crate::Encrypter::decrypt_bytes).
44 InvalidUtf8,
45}
46
47impl fmt::Display for Error {
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 match self {
50 Error::UnsupportedCipher => f.write_str(
51 "Unsupported cipher. Supported ciphers are: aes-128-cbc, aes-256-cbc, \
52 aes-128-gcm, aes-256-gcm.",
53 ),
54 Error::InvalidKey => f.write_str("The encryption key is empty or malformed."),
55 Error::InvalidKeyLength { expected, actual } => write!(
56 f,
57 "Incorrect key length for the cipher: expected {expected} bytes, got {actual}."
58 ),
59 Error::InvalidPayload => f.write_str("The payload is invalid."),
60 Error::InvalidMac => f.write_str("The MAC is invalid."),
61 Error::Decrypt => f.write_str("Could not decrypt the data."),
62 Error::Encrypt => f.write_str("Could not encrypt the data."),
63 Error::Unserialize => f.write_str("The decrypted data is not valid PHP serialization."),
64 Error::Serialize => f.write_str("The value cannot be PHP-serialized."),
65 Error::InvalidUtf8 => f.write_str("The decrypted data is not valid UTF-8."),
66 }
67 }
68}
69
70impl std::error::Error for Error {}