seal_crypto_wrapper/
error.rs

1//! Error types and handling for the seal-crypto-wrapper library.
2//!
3//! seal-crypto-wrapper 库的错误类型和处理。
4//!
5//! ## Overview | 概述
6//!
7//! This module defines a comprehensive error hierarchy that covers all possible
8//! failure modes in cryptographic operations. The error types are designed to
9//! provide clear, actionable information while maintaining security by not
10//! leaking sensitive details.
11//!
12//! 此模块定义了一个全面的错误层次结构,涵盖密码操作中所有可能的失败模式。
13//! 错误类型旨在提供清晰、可操作的信息,同时通过不泄露敏感细节来维护安全性。
14//!
15//! ## Error Categories | 错误分类
16//!
17//! - **Cryptographic Errors**: Algorithm-specific failures from the underlying crypto library
18//! - **OS Errors**: System-level failures (e.g., random number generation)
19//! - **Format Errors**: Data serialization, key format, and ciphertext structure issues
20//!
21//! - **密码学错误**: 来自底层密码库的算法特定失败
22//! - **操作系统错误**: 系统级失败(例如随机数生成)
23//! - **格式错误**: 数据序列化、密钥格式和密文结构问题
24//!
25//! ## Error Handling Best Practices | 错误处理最佳实践
26//!
27//! - Always handle cryptographic errors gracefully
28//! - Never ignore authentication failures
29//! - Log errors appropriately without exposing sensitive data
30//! - Use proper error propagation with the `?` operator
31//!
32//! - 始终优雅地处理密码学错误
33//! - 永远不要忽略认证失败
34//! - 适当记录错误而不暴露敏感数据
35//! - 使用 `?` 操作符进行适当的错误传播
36
37use rand::rand_core::OsError;
38use thiserror::Error;
39
40/// Main error type for the seal-crypto-wrapper library.
41///
42/// seal-crypto-wrapper 库的主要错误类型。
43///
44/// This enum encompasses all possible errors that can occur during cryptographic
45/// operations. Each variant provides specific context about the failure mode.
46///
47/// 此枚举包含密码操作期间可能发生的所有错误。
48/// 每个变体都提供有关失败模式的特定上下文。
49#[derive(Error, Debug)]
50pub enum Error {
51    /// Errors from the underlying cryptographic library.
52    ///
53    /// 来自底层密码库的错误。
54    ///
55    /// These include algorithm-specific failures such as:
56    /// - Key generation failures
57    /// - Encryption/decryption errors
58    /// - Signature verification failures
59    /// - Invalid algorithm parameters
60    ///
61    /// 这些包括算法特定的失败,例如:
62    /// - 密钥生成失败
63    /// - 加密/解密错误
64    /// - 签名验证失败
65    /// - 无效的算法参数
66    #[error("Cryptographic operation failed: {0}")]
67    CryptoError(#[from] seal_crypto::errors::Error),
68
69    /// Operating system related errors.
70    ///
71    /// 操作系统相关错误。
72    ///
73    /// Typically occurs during:
74    /// - Random number generation
75    /// - System resource allocation
76    /// - Hardware security module access
77    ///
78    /// 通常发生在:
79    /// - 随机数生成
80    /// - 系统资源分配
81    /// - 硬件安全模块访问
82    #[error("Operating system error: {0}")]
83    OsError(#[from] OsError),
84
85    /// Data format and serialization errors.
86    ///
87    /// 数据格式和序列化错误。
88    ///
89    /// Covers issues with:
90    /// - Key serialization/deserialization
91    /// - Ciphertext format validation
92    /// - Algorithm parameter encoding
93    ///
94    /// 涵盖以下问题:
95    /// - 密钥序列化/反序列化
96    /// - 密文格式验证
97    /// - 算法参数编码
98    #[error("Data format error: {0}")]
99    FormatError(#[from] FormatError),
100}
101
102/// Convenient Result type alias for this library.
103///
104/// 此库的便捷 Result 类型别名。
105///
106/// This type alias reduces boilerplate when working with functions that
107/// return results from this library. Use this instead of `std::result::Result<T, Error>`.
108///
109/// 此类型别名在使用返回此库结果的函数时减少样板代码。
110/// 使用此类型而不是 `std::result::Result<T, Error>`。
111///
112/// # Examples | 示例
113///
114/// ```rust
115/// use seal_crypto_wrapper::error::Result;
116///
117/// fn encrypt_data(data: &[u8]) -> Result<Vec<u8>> {
118///     // ... encryption logic
119///     Ok(vec![])
120/// }
121/// ```
122pub type Result<T> = std::result::Result<T, Error>;
123
124/// Errors related to data formatting, serialization, and structure validation.
125///
126/// 与数据格式、序列化和结构验证相关的错误。
127///
128/// ## Overview | 概述
129///
130/// These errors occur when data doesn't conform to expected formats or when
131/// serialization/deserialization operations fail. They typically indicate
132/// either corrupted data or version incompatibilities.
133///
134/// 当数据不符合预期格式或序列化/反序列化操作失败时会发生这些错误。
135/// 它们通常表示数据损坏或版本不兼容。
136///
137/// ## Common Causes | 常见原因
138///
139/// - Corrupted or truncated data
140/// - Version mismatches between serialization formats
141/// - Invalid key material or algorithm parameters
142/// - Malformed ciphertext or signature data
143///
144/// - 损坏或截断的数据
145/// - 序列化格式之间的版本不匹配
146/// - 无效的密钥材料或算法参数
147/// - 格式错误的密文或签名数据
148#[derive(Debug, Error)]
149pub enum FormatError {
150    /// Binary serialization or deserialization failure.
151    ///
152    /// 二进制序列化或反序列化失败。
153    ///
154    /// This error occurs when `bincode` cannot serialize or deserialize data,
155    /// typically due to:
156    /// - Incompatible data structure versions
157    /// - Corrupted serialized data
158    /// - Insufficient buffer space
159    ///
160    /// 当 `bincode` 无法序列化或反序列化数据时发生此错误,通常由于:
161    /// - 不兼容的数据结构版本
162    /// - 损坏的序列化数据
163    /// - 缓冲区空间不足
164    ///
165    /// # Recovery | 恢复
166    ///
167    /// - Verify data integrity
168    /// - Check version compatibility
169    /// - Ensure sufficient buffer space
170    ///
171    /// - 验证数据完整性
172    /// - 检查版本兼容性
173    /// - 确保足够的缓冲区空间
174    #[error("Serialization/deserialization failed: {0}")]
175    Serialization(#[from] BincodeError),
176
177    /// Invalid or corrupted ciphertext format.
178    ///
179    /// 无效或损坏的密文格式。
180    ///
181    /// This error indicates that the ciphertext data is malformed, incomplete,
182    /// or has been corrupted. Common causes include:
183    /// - Data truncation during transmission or storage
184    /// - Bit flips due to hardware errors
185    /// - Incorrect data handling or parsing
186    ///
187    /// 此错误表示密文数据格式错误、不完整或已损坏。常见原因包括:
188    /// - 传输或存储期间的数据截断
189    /// - 硬件错误导致的位翻转
190    /// - 不正确的数据处理或解析
191    ///
192    /// # Security Implications | 安全影响
193    ///
194    /// This error should be treated as a potential security issue.
195    /// Never attempt to process malformed ciphertext.
196    ///
197    /// 此错误应被视为潜在的安全问题。
198    /// 永远不要尝试处理格式错误的密文。
199    #[error("Invalid or corrupted ciphertext format")]
200    InvalidCiphertext,
201
202    /// Unsupported or invalid key type.
203    ///
204    /// 不支持或无效的密钥类型。
205    ///
206    /// This error occurs when:
207    /// - A key is used with an incompatible algorithm
208    /// - The key type is not supported by the current configuration
209    /// - Key metadata is corrupted or missing
210    ///
211    /// 在以下情况下发生此错误:
212    /// - 密钥与不兼容的算法一起使用
213    /// - 当前配置不支持密钥类型
214    /// - 密钥元数据损坏或丢失
215    #[error("Invalid or unsupported key type")]
216    InvalidKeyType,
217
218    /// Invalid key material or structure.
219    ///
220    /// 无效的密钥材料或结构。
221    ///
222    /// This error indicates that the key data itself is invalid:
223    /// - Incorrect key length for the algorithm
224    /// - Invalid key format or encoding
225    /// - Corrupted key material
226    /// - Missing required key components
227    ///
228    /// 此错误表示密钥数据本身无效:
229    /// - 算法的密钥长度不正确
230    /// - 无效的密钥格式或编码
231    /// - 损坏的密钥材料
232    /// - 缺少必需的密钥组件
233    ///
234    /// # Security Note | 安全注意
235    ///
236    /// Invalid keys should never be used for cryptographic operations.
237    /// Always validate key material before use.
238    ///
239    /// 无效密钥永远不应用于密码操作。
240    /// 使用前始终验证密钥材料。
241    #[error("Invalid key material or structure")]
242    InvalidKey,
243}
244
245/// Wrapper for `bincode` serialization and deserialization errors.
246///
247/// `bincode` 序列化和反序列化错误的包装器。
248///
249/// ## Purpose | 目的
250///
251/// This wrapper provides a consistent error handling interface for `bincode`
252/// operations within the library. It abstracts the underlying `bincode` error
253/// types while preserving error information and source chains.
254///
255/// 此包装器为库内的 `bincode` 操作提供一致的错误处理接口。
256/// 它抽象了底层的 `bincode` 错误类型,同时保留错误信息和源链。
257///
258/// ## Usage Context | 使用上下文
259///
260/// These errors typically occur during:
261/// - Key serialization for storage or transmission
262/// - Key deserialization from stored or received data
263/// - Algorithm parameter encoding/decoding
264/// - Ciphertext metadata serialization
265///
266/// 这些错误通常发生在:
267/// - 用于存储或传输的密钥序列化
268/// - 从存储或接收的数据进行密钥反序列化
269/// - 算法参数编码/解码
270/// - 密文元数据序列化
271#[derive(Error, Debug)]
272pub enum BincodeError {
273    /// Serialization (encoding) operation failed.
274    ///
275    /// 序列化(编码)操作失败。
276    ///
277    /// This occurs when converting Rust data structures to binary format fails.
278    /// Common causes include:
279    /// - Insufficient output buffer space
280    /// - Unsupported data types
281    /// - Memory allocation failures
282    ///
283    /// 当将 Rust 数据结构转换为二进制格式失败时发生。
284    /// 常见原因包括:
285    /// - 输出缓冲区空间不足
286    /// - 不支持的数据类型
287    /// - 内存分配失败
288    #[error("Binary encoding failed: {0}")]
289    Enc(#[source] Box<bincode::error::EncodeError>),
290
291    /// Deserialization (decoding) operation failed.
292    ///
293    /// 反序列化(解码)操作失败。
294    ///
295    /// This occurs when converting binary data back to Rust structures fails.
296    /// Common causes include:
297    /// - Corrupted or truncated input data
298    /// - Version incompatibilities
299    /// - Invalid data format
300    /// - Insufficient input data
301    ///
302    /// 当将二进制数据转换回 Rust 结构失败时发生。
303    /// 常见原因包括:
304    /// - 损坏或截断的输入数据
305    /// - 版本不兼容
306    /// - 无效的数据格式
307    /// - 输入数据不足
308    #[error("Binary decoding failed: {0}")]
309    Dec(#[source] Box<bincode::error::DecodeError>),
310}
311
312impl From<bincode::error::EncodeError> for BincodeError {
313    /// Converts a `bincode` encoding error into our wrapper type.
314    ///
315    /// 将 `bincode` 编码错误转换为我们的包装器类型。
316    fn from(err: bincode::error::EncodeError) -> Self {
317        BincodeError::Enc(Box::from(err))
318    }
319}
320
321impl From<bincode::error::DecodeError> for BincodeError {
322    /// Converts a `bincode` decoding error into our wrapper type.
323    ///
324    /// 将 `bincode` 解码错误转换为我们的包装器类型。
325    fn from(err: bincode::error::DecodeError) -> Self {
326        BincodeError::Dec(Box::from(err))
327    }
328}