Skip to main content

flare_core/common/encryption/
registry.rs

1//! 加密器注册表
2//!
3//! 管理加密器的注册和查找,支持用户注册自定义加密器
4
5use super::algorithms::NoEncryptor;
6use super::traits::Encryptor;
7use std::collections::HashMap;
8use std::sync::Arc;
9use std::sync::RwLock;
10
11lazy_static::lazy_static! {
12    /// 全局加密器注册表
13    static ref ENCRYPTION_REGISTRY: EncryptionRegistry = {
14        let registry = EncryptionRegistry::new();
15        // 注册内置加密器
16        registry.register_defaults();
17        registry
18    };
19}
20
21/// 加密器注册表
22///
23/// 管理加密器的注册和查找
24pub struct EncryptionRegistry {
25    encryptors: Arc<RwLock<HashMap<String, Arc<dyn Encryptor>>>>,
26}
27
28impl Default for EncryptionRegistry {
29    fn default() -> Self {
30        Self {
31            encryptors: Arc::new(RwLock::new(HashMap::new())),
32        }
33    }
34}
35
36impl EncryptionRegistry {
37    /// 创建新的注册表
38    pub fn new() -> Self {
39        Self::default()
40    }
41
42    /// 注册内置加密器
43    pub fn register_defaults(&self) {
44        self.register("none", Arc::new(NoEncryptor));
45        // AES-256-GCM 需要密钥,不能直接注册,需要用户提供密钥后创建
46    }
47
48    /// 注册加密器
49    ///
50    /// # 参数
51    /// - `name`: 加密器名称(用于查找)
52    /// - `encryptor`: 加密器实例
53    ///
54    /// # 示例
55    ///
56    /// ```rust
57    /// use flare_core::common::encryption::{EncryptionRegistry, Encryptor};
58    /// use std::sync::Arc;
59    ///
60    /// struct MyEncryptor;
61    /// impl Encryptor for MyEncryptor { /* ... */ }
62    ///
63    /// let registry = EncryptionRegistry::new();
64    /// registry.register("my_custom", Arc::new(MyEncryptor));
65    /// ```
66    pub fn register(&self, name: &str, encryptor: Arc<dyn Encryptor>) {
67        if let Ok(mut encryptors) = self.encryptors.write() {
68            encryptors.insert(name.to_string(), encryptor);
69        }
70    }
71
72    /// 查找加密器
73    ///
74    /// # 参数
75    /// - `name`: 加密器名称
76    ///
77    /// # 返回
78    /// 找到的加密器,如果不存在则返回 None
79    pub fn find(&self, name: &str) -> Option<Arc<dyn Encryptor>> {
80        if let Ok(encryptors) = self.encryptors.read() {
81            encryptors.get(name).cloned()
82        } else {
83            None
84        }
85    }
86
87    /// 检查加密器是否已注册
88    ///
89    /// # 参数
90    /// - `name`: 加密器名称
91    ///
92    /// # 返回
93    /// 如果已注册返回 `true`,否则返回 `false`
94    pub fn is_registered(&self, name: &str) -> bool {
95        if let Ok(encryptors) = self.encryptors.read() {
96            encryptors.contains_key(name)
97        } else {
98            false
99        }
100    }
101
102    /// 获取所有已注册的加密器名称
103    ///
104    /// # 返回
105    /// 已注册的加密器名称列表
106    pub fn list_registered(&self) -> Vec<String> {
107        if let Ok(encryptors) = self.encryptors.read() {
108            encryptors.keys().cloned().collect()
109        } else {
110            Vec::new()
111        }
112    }
113}
114
115/// 全局加密器注册表访问器
116impl EncryptionRegistry {
117    /// 获取全局注册表实例
118    pub fn global() -> &'static EncryptionRegistry {
119        &ENCRYPTION_REGISTRY
120    }
121}
122
123/// 加密工具类
124///
125/// 提供便捷的全局加密器访问方法
126pub struct EncryptionUtil;
127
128impl EncryptionUtil {
129    /// 查找加密器(从全局注册表)
130    ///
131    /// # 参数
132    /// - `name`: 加密器名称
133    ///
134    /// # 返回
135    /// 找到的加密器,如果不存在则返回 None
136    ///
137    /// # 示例
138    ///
139    /// ```rust
140    /// use flare_core::common::encryption::EncryptionUtil;
141    ///
142    /// let encryptor = EncryptionUtil::find("none");
143    /// if let Some(enc) = encryptor {
144    ///     let encrypted = enc.encrypt(b"hello").unwrap();
145    ///     let decrypted = enc.decrypt(&encrypted).unwrap();
146    /// }
147    /// ```
148    pub fn find(name: &str) -> Option<Arc<dyn Encryptor>> {
149        EncryptionRegistry::global().find(name)
150    }
151
152    /// 检查加密器是否已注册
153    ///
154    /// # 参数
155    /// - `name`: 加密器名称
156    ///
157    /// # 返回
158    /// 如果已注册返回 `true`,否则返回 `false`
159    pub fn is_registered(name: &str) -> bool {
160        EncryptionRegistry::global().is_registered(name)
161    }
162
163    /// 注册自定义加密器(到全局注册表)
164    ///
165    /// # 参数
166    /// - `encryptor`: 加密器实例
167    ///
168    /// # 示例
169    ///
170    /// ```rust
171    /// use flare_core::common::encryption::{EncryptionUtil, Encryptor};
172    /// use std::sync::Arc;
173    ///
174    /// struct MyEncryptor;
175    /// impl Encryptor for MyEncryptor { /* ... */ }
176    ///
177    /// EncryptionUtil::register_custom(Arc::new(MyEncryptor));
178    /// ```
179    pub fn register_custom(encryptor: Arc<dyn Encryptor>) {
180        let name = encryptor.name();
181        // 如果已注册同名加密器,记录警告但不覆盖(避免密钥不一致问题)
182        if EncryptionUtil::is_registered(name) {
183            tracing::warn!(
184                "Encryptor '{}' is already registered. Skipping registration to avoid key mismatch.",
185                name
186            );
187            return;
188        }
189        EncryptionRegistry::global().register(name, encryptor);
190        tracing::debug!("Registered encryptor: {}", name);
191    }
192
193    /// 获取所有已注册的加密器名称列表
194    ///
195    /// # 返回
196    /// 已注册的加密器名称列表
197    pub fn list_registered() -> Vec<String> {
198        EncryptionRegistry::global().list_registered()
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn test_encryption_registry() {
208        let registry = EncryptionRegistry::new();
209        registry.register_defaults();
210
211        assert!(registry.find("none").is_some());
212        assert!(registry.find("unknown").is_none());
213    }
214
215    #[test]
216    fn test_no_encryptor() {
217        let encryptor = NoEncryptor;
218        let data = b"hello world";
219        let encrypted = encryptor.encrypt(data).unwrap();
220        let decrypted = encryptor.decrypt(&encrypted).unwrap();
221        assert_eq!(data, decrypted.as_slice());
222    }
223
224    #[test]
225    #[cfg(feature = "encryption-aes-gcm")]
226    fn test_aes256gcm_encryptor() {
227        use crate::common::encryption::Aes256GcmEncryptor;
228
229        // 创建测试密钥(32 字节)
230        let key = b"01234567890123456789012345678901"; // 32 bytes
231        let encryptor = Aes256GcmEncryptor::new(key).unwrap();
232
233        // 测试数据
234        let plaintext = b"Hello, World! This is a test message for AES-256-GCM encryption.";
235
236        // 加密
237        let ciphertext = encryptor.encrypt(plaintext).unwrap();
238
239        // 验证密文长度(应该包含 12 字节 nonce + 密文 + 16 字节认证标签)
240        // GCM 模式是流式加密,密文长度 = 明文长度 + 16 字节认证标签
241        assert!(ciphertext.len() >= plaintext.len() + 12 + 16); // nonce(12) + plaintext + tag(16)
242
243        // 解密
244        let decrypted = encryptor.decrypt(&ciphertext).unwrap();
245        assert_eq!(plaintext, decrypted.as_slice());
246
247        // 测试相同明文产生不同密文(由于随机 nonce)
248        let ciphertext2 = encryptor.encrypt(plaintext).unwrap();
249        assert_ne!(ciphertext, ciphertext2); // 应该不同
250
251        // 但解密后应该相同
252        let decrypted2 = encryptor.decrypt(&ciphertext2).unwrap();
253        assert_eq!(plaintext, decrypted2.as_slice());
254    }
255
256    #[test]
257    #[cfg(feature = "encryption-aes-gcm")]
258    fn test_aes256gcm_from_password() {
259        use crate::common::encryption::Aes256GcmEncryptor;
260
261        // 从密码派生密钥
262        let password = b"my_secret_password";
263        let salt = b"some_salt";
264        let encryptor = Aes256GcmEncryptor::from_password(password, Some(salt)).unwrap();
265
266        let plaintext = b"Test message";
267        let ciphertext = encryptor.encrypt(plaintext).unwrap();
268        let decrypted = encryptor.decrypt(&ciphertext).unwrap();
269        assert_eq!(plaintext, decrypted.as_slice());
270    }
271
272    #[test]
273    #[cfg(feature = "encryption-aes-gcm")]
274    fn test_aes256gcm_invalid_key_length() {
275        use crate::common::encryption::Aes256GcmEncryptor;
276
277        // 测试无效密钥长度
278        let short_key = b"short"; // 只有 5 字节
279        assert!(Aes256GcmEncryptor::new(short_key).is_err());
280
281        let long_key = b"0123456789012345678901234567890123456789"; // 超过 32 字节
282        assert!(Aes256GcmEncryptor::new(long_key).is_err());
283    }
284
285    #[test]
286    #[cfg(feature = "encryption-aes-gcm")]
287    fn test_aes256gcm_invalid_ciphertext() {
288        use crate::common::encryption::Aes256GcmEncryptor;
289
290        let key = b"01234567890123456789012345678901";
291        let encryptor = Aes256GcmEncryptor::new(key).unwrap();
292
293        // 测试太短的密文
294        let short_data = b"short";
295        assert!(encryptor.decrypt(short_data).is_err());
296
297        // 测试无效的密文
298        let invalid_data = vec![0u8; 20]; // 长度足够但内容无效
299        assert!(encryptor.decrypt(&invalid_data).is_err());
300    }
301
302    #[test]
303    #[cfg(not(feature = "encryption-aes-gcm"))]
304    fn test_aes256gcm_constructor_reports_disabled_feature() {
305        use crate::common::encryption::Aes256GcmEncryptor;
306        use crate::common::error::ErrorCode;
307
308        match Aes256GcmEncryptor::new(b"01234567890123456789012345678901") {
309            Ok(_) => panic!("AES-GCM should report disabled feature"),
310            Err(err) => assert_eq!(err.code(), Some(ErrorCode::OperationNotSupported)),
311        }
312    }
313}