seal_crypto/traits/
key.rs

1//! Defines traits for cryptographic keys.
2//!
3//! 定义了加密密钥的核心 trait。
4use crate::errors::Error;
5use crate::traits::algorithm::Algorithm;
6use zeroize::Zeroize;
7
8#[cfg(feature = "serde")]
9use serde::{Deserialize, Serialize};
10
11/// Defines errors that can occur during key operations.
12///
13/// 定义了在密钥操作期间可能发生的错误。
14#[derive(Debug, PartialEq, Eq)]
15#[cfg_attr(feature = "std", derive(thiserror::Error))]
16pub enum KeyError {
17    /// Failed to generate a key.
18    ///
19    /// 生成密钥失败。
20    #[cfg_attr(feature = "std", error("Key generation failed"))]
21    GenerationFailed,
22    /// The provided data is not a valid key encoding.
23    ///
24    /// 提供的密钥编码无效。
25    #[cfg_attr(feature = "std", error("Invalid key encoding"))]
26    InvalidEncoding,
27    /// The provided data is not a valid key encoding.
28    ///
29    /// 提供的密钥编码无效。
30    #[cfg_attr(feature = "std", error("Invalid key encoding"))]
31    InvalidLength,
32}
33
34#[cfg(feature = "serde")]
35/// A helper trait for conditionally adding serde support.
36///
37/// 当 `serde` feature 开启时,为密钥添加 serde 支持的辅助 trait。
38pub trait ConditionallySerde: Serialize + for<'de> Deserialize<'de> {}
39#[cfg(feature = "serde")]
40impl<T: Serialize + for<'de> Deserialize<'de>> ConditionallySerde for T {}
41
42#[cfg(not(feature = "serde"))]
43/// A helper trait for conditionally adding serde support.
44///
45/// 当 `serde` feature 关闭时,这是一个空的辅助 trait。
46pub trait ConditionallySerde {}
47#[cfg(not(feature = "serde"))]
48impl<T> ConditionallySerde for T {}
49
50/// A blanket trait for all key types, defining common properties and behaviors.
51///
52/// 适用于所有密钥类型的通用 trait,定义了通用的属性和行为。
53pub trait Key: Sized + Send + Sync + 'static + Clone + ConditionallySerde {
54    /// Deserializes a key from its byte representation.
55    ///
56    /// 从字节表示反序列化密钥。
57    fn from_bytes(bytes: &[u8]) -> Result<Self, Error>;
58
59    /// Serializes the key into its byte representation.
60    ///
61    /// 将密钥序列化为字节表示。
62    fn to_bytes(&self) -> Result<Vec<u8>, Error>;
63}
64
65/// A marker trait for public keys.
66///
67/// 公钥的标记 trait。
68pub trait PublicKey: Key + Clone + for<'a> From<&'a Self> {}
69
70/// A marker trait for private keys, generic over its corresponding public key type.
71///
72/// 私钥的标记 trait,它对其对应的公钥类型是通用的。
73pub trait PrivateKey<P: PublicKey>: Key + Zeroize {}
74
75/// Defines the set of keys used in an asymmetric cryptographic scheme.
76///
77/// 定义非对称加密方案中使用的密钥集。
78pub trait AsymmetricKeySet: Algorithm {
79    type PublicKey: PublicKey;
80    type PrivateKey: PrivateKey<Self::PublicKey>;
81}
82
83/// Defines the key used in a symmetric cryptographic scheme.
84///
85/// 定义对称加密方案中使用的密钥。
86pub trait SymmetricKeySet: Algorithm {
87    type Key: Key;
88}