seal_crypto/traits/
asymmetric.rs

1//! Defines traits for asymmetric cryptographic operations.
2//!
3//! 定义了非对称加密操作的 trait。
4
5use crate::errors::Error;
6use crate::traits::key::Key;
7use crate::traits::key::AsymmetricKeySet;
8#[cfg(feature = "std")]
9use thiserror::Error;
10use zeroize::Zeroizing;
11
12// --- Key Generator ---
13/// A trait for schemes that can generate a new cryptographic key pair.
14///
15/// 用于可生成新加密密钥对的方案的 trait。
16pub trait KeyGenerator: AsymmetricKeySet {
17    /// Generates a new key pair (public and private key).
18    ///
19    /// # Returns
20    /// A result containing the key pair, or an error if generation fails.
21    ///
22    /// 生成一个新的密钥对(公钥和私钥)。
23    ///
24    /// # 返回
25    /// 一个包含密钥对的 `Result`,如果生成失败则返回错误。
26    fn generate_keypair() -> Result<(Self::PublicKey, Self::PrivateKey), Error>;
27}
28
29// --- Signer / Verifier ---
30/// Represents a digital signature, wrapping a byte vector for type safety.
31///
32/// 代表一个数字签名,为增强类型安全而包装了一个字节向量。
33pub type Signature = Vec<u8>;
34
35
36/// Defines the errors that can occur during signing and verification.
37///
38/// 定义了在签名和验证过程中可能发生的错误。
39#[cfg_attr(feature = "std", derive(Error))]
40#[derive(Debug, PartialEq, Eq)]
41pub enum SignatureError {
42    /// Failed to create a digital signature.
43    ///
44    /// 创建数字签名失败。
45    #[cfg_attr(feature = "std", error("Signing failed"))]
46    Signing,
47
48    /// Signature verification failed, indicating that the signature is invalid,
49    /// the data has been tampered with, or the wrong key was used.
50    ///
51    /// 签名验证失败,表明签名无效、数据被篡改或使用了错误的密钥。
52    #[cfg_attr(feature = "std", error("Verification failed"))]
53    Verification,
54
55    /// The provided signature is malformed or has an invalid length.
56    ///
57    /// 提供的签名格式错误或长度无效。
58    #[cfg_attr(feature = "std", error("Invalid signature format"))]
59    InvalidSignature,
60}
61
62/// A trait for cryptographic schemes that can create digital signatures.
63///
64/// 用于能够创建数字签名的加密方案的 trait。
65pub trait Signer: AsymmetricKeySet {
66    /// Creates a digital signature for a given message digest.
67    ///
68    /// 为给定的消息摘要创建一个数字签名。
69    fn sign(private_key: &Self::PrivateKey, message: &[u8]) -> Result<Signature, Error>;
70}
71
72/// A trait for cryptographic schemes that can verify digital signatures.
73///
74/// 用于能够验证数字签名的加密方案的 trait。
75pub trait Verifier: AsymmetricKeySet {
76    /// Verifies a digital signature for a given message digest.
77    ///
78    /// # Returns
79    /// `Ok(())` if the signature is valid, otherwise an `Err`.
80    ///
81    /// 验证给定消息摘要的数字签名。
82    ///
83    /// # 返回
84    /// 如果签名有效,则返回 `Ok(())`,否则返回 `Err`。
85    fn verify(
86        public_key: &Self::PublicKey,
87        message: &[u8],
88        signature: &Signature,
89    ) -> Result<(), Error>;
90}
91
92/// A unified trait for a complete signature scheme.
93///
94/// It combines key generation, signing, and verification capabilities.
95/// This is the primary trait that should be implemented by a signature algorithm.
96///
97/// 一个完整的签名方案的统一 trait。
98///
99/// 它结合了密钥生成、签名和验证的能力。
100/// 这是签名算法应该实现的主要 trait。
101pub trait SignatureScheme: KeyGenerator + Signer + Verifier {}
102
103impl<T: KeyGenerator + Signer + Verifier> SignatureScheme for T {}
104
105// --- KEM ---
106/// A secret value, derived from a KEM, suitable for use as a symmetric key.
107/// It is wrapped in `Zeroizing` to ensure it's wiped from memory when dropped.
108///
109/// 一个从 KEM 派生的秘密值,适合用作对称密钥。
110/// 它被包装在 `Zeroizing` 中,以确保在被丢弃时从内存中清除。
111#[allow(dead_code)]
112pub type SharedSecret = Zeroizing<Vec<u8>>;
113
114/// The encapsulated key (ciphertext) produced by a KEM.
115///
116/// KEM 生成的封装密钥(密文)。
117#[allow(dead_code)]
118pub type EncapsulatedKey = Vec<u8>;
119
120impl Key for EncapsulatedKey {
121    fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
122        Ok(bytes.to_vec())
123    }
124
125    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
126        Ok(self.to_vec())
127    }
128}
129
130/// Defines the errors that can occur during KEM operations.
131///
132/// 定义 KEM 操作期间可能发生的错误。
133#[cfg_attr(feature = "std", derive(Error))]
134#[derive(Debug, PartialEq, Eq)]
135pub enum KemError {
136    /// Failed to encapsulate a shared secret.
137    ///
138    /// 封装共享密钥失败。
139    #[cfg_attr(feature = "std", error("Key encapsulation failed"))]
140    Encapsulation,
141
142    /// Failed to decapsulate a shared secret, often due to an invalid
143    /// or tampered encapsulated key.
144    ///
145    /// 解封装共享密钥失败,通常是由于无效或被篡改的封装密钥。
146    #[cfg_attr(feature = "std", error("Key decapsulation failed"))]
147    Decapsulation,
148
149    /// The provided public key is invalid for the operation.
150    ///
151    /// 提供的公钥对于该操作无效。
152    #[cfg_attr(feature = "std", error("Invalid public key"))]
153    InvalidPublicKey,
154
155    /// The provided private key is invalid for the operation.
156    ///
157    /// 提供的私钥对于该操作无效。
158    #[cfg_attr(feature = "std", error("Invalid private key"))]
159    InvalidPrivateKey,
160
161    /// The provided encapsulated key (ciphertext) is invalid.
162    ///
163    /// 提供的封装密钥(密文)无效。
164    #[cfg_attr(feature = "std", error("Invalid encapsulated key"))]
165    InvalidEncapsulatedKey,
166}
167
168/// A trait for a Key Encapsulation Mechanism (KEM).
169///
170/// KEMs are a class of public-key cryptosystems designed for securely
171/// establishing shared secrets.
172///
173/// 密钥封装机制 (KEM) 的 trait。
174///
175/// KEM 是一类用于安全建立共享密钥的公钥密码系统。
176pub trait Kem: AsymmetricKeySet {
177    type EncapsulatedKey: Key;
178
179    /// Generates and encapsulates a shared secret using the recipient's public key.
180    ///
181    /// # Returns
182    /// A tuple containing the `(SharedSecret, EncapsulatedKey)`.
183    /// The `SharedSecret` is for the sender to use, and the `EncapsulatedKey`
184    /// is to be sent to the recipient.
185    ///
186    /// 使用接收者的公钥生成并封装一个共享密钥。
187    ///
188    /// # 返回
189    /// 一个包含 `(SharedSecret, EncapsulatedKey)` 的元组。
190    /// `SharedSecret` 供发送方使用,`EncapsulatedKey` 用于发送给接收方。
191    fn encapsulate(
192        public_key: &Self::PublicKey,
193    ) -> Result<(SharedSecret, Self::EncapsulatedKey), Error>;
194
195    /// Decapsulates an encapsulated key using the recipient's private key to
196    /// recover the shared secret.
197    ///
198    /// # Returns
199    /// The `SharedSecret` that matches the one generated by the sender.
200    ///
201    /// 使用接收者的私钥解封装一个封装密钥,以恢复共享密钥。
202    ///
203    /// # 返回
204    /// 与发送方生成的 `SharedSecret` 相匹配的共享密钥。
205    fn decapsulate(
206        private_key: &Self::PrivateKey,
207        encapsulated_key: &Self::EncapsulatedKey,
208    ) -> Result<SharedSecret, Error>;
209}
210
211// --- Key Agreement ---
212
213/// Defines the errors that can occur during key agreement.
214///
215/// 定义密钥协商期间可能发生的错误。
216#[cfg_attr(feature = "std", derive(Error))]
217#[derive(Debug, PartialEq, Eq)]
218pub enum KeyAgreementError {
219    /// Failed to derive the shared secret.
220    ///
221    /// 派生共享密钥失败。
222    #[cfg_attr(feature = "std", error("Key agreement failed"))]
223    AgreementFailed,
224
225    /// The peer's public key is invalid for this operation.
226    ///
227    /// 对方的公钥对于此操作无效。
228    #[cfg_attr(feature = "std", error("Invalid peer public key"))]
229    InvalidPeerPublicKey,
230}
231
232/// A trait for a Key Agreement scheme.
233///
234/// Key Agreement 方案的 trait。
235pub trait KeyAgreement: AsymmetricKeySet {
236    /// Derives a shared secret from one's own private key and a peer's public key.
237    ///
238    /// # Returns
239    /// The derived `SharedSecret`.
240    ///
241    /// 从自己的私钥和对方的公钥派生一个共享密钥。
242    ///
243    /// # 返回
244    /// 派生出的 `SharedSecret`。
245    fn agree(
246        private_key: &Self::PrivateKey,
247        public_key: &Self::PublicKey,
248    ) -> Result<SharedSecret, Error>;
249}