ciphern/
lib.rs

1#![feature(portable_simd)]
2// Copyright (c) 2025 Kirky.X
3//
4// Licensed under the MIT License
5// See LICENSE file in the project root for full license information.
6
7//! Ciphern 加密库
8//!
9//! 企业级、安全优先的 Rust 加密库。
10
11#[cfg(feature = "hash")]
12use hmac::Mac;
13
14pub(crate) mod audit;
15#[cfg(feature = "encrypt")]
16pub(crate) mod cipher;
17pub(crate) mod error;
18pub(crate) mod fips;
19#[cfg(feature = "encrypt")]
20pub mod hardware;
21#[cfg(feature = "encrypt")]
22pub(crate) mod hash;
23#[cfg(feature = "encrypt")]
24pub(crate) mod key;
25pub(crate) mod memory;
26
27#[cfg(feature = "simd")]
28pub mod simd;
29
30pub mod random;
31
32pub(crate) mod ffi;
33#[cfg(feature = "plugin")]
34pub mod plugin;
35#[cfg(feature = "encrypt")]
36pub(crate) mod side_channel;
37#[cfg(feature = "encrypt")]
38pub(crate) mod signer;
39pub(crate) mod types;
40
41#[cfg(feature = "i18n")]
42pub(crate) mod i18n;
43#[cfg(feature = "i18n")]
44pub(crate) mod service;
45#[cfg(feature = "i18n")]
46pub(crate) mod ui;
47
48// 重新导出 FIPS 相关类型
49pub use fips::{get_fips_approved_algorithms, is_fips_enabled, FipsContext, FipsError, FipsMode};
50
51pub use error::CryptoError;
52pub use error::Result;
53#[cfg(feature = "kdf")]
54pub use key::derivation::{Argon2id, Hkdf, Pbkdf2, Sm3Kdf};
55#[cfg(feature = "encrypt")]
56pub use key::manager::KeyManager;
57#[cfg(feature = "encrypt")]
58pub use key::{Key, KeyState};
59#[cfg(feature = "encrypt")]
60pub use random::{
61    detect_hardware_rng, hardware_fill_bytes, is_rdseed_available, rdseed_fill_bytes,
62    BulkHardwareRng, SeedGenerator,
63};
64pub use random::{is_hardware_rng_available, EntropySource, HardwareRng, SecureRandom};
65pub use types::Algorithm;
66
67#[cfg(feature = "simd")]
68pub use simd::{
69    is_simd_available, simd_combine_hashes, simd_process_blocks_sha256, simd_sha256_finalize,
70    simd_sm4_decrypt, simd_sm4_encrypt,
71};
72
73#[cfg(feature = "i18n")]
74pub use error::{get_localized_error, get_localized_message, get_localized_title, LocalizedError};
75#[cfg(feature = "i18n")]
76pub use i18n::{
77    get_locale, get_supported_locales, is_locale_supported, reset_for_testing, set_locale,
78    translate, translate_safe, translate_with_args, I18nError,
79};
80#[cfg(feature = "i18n")]
81pub use service::TranslationService;
82#[cfg(feature = "i18n")]
83pub use ui::{Button, FormField, Label, LocalizedMessage, MenuItem, Notification, UIElement};
84
85#[cfg(feature = "plugin")]
86pub use plugin::manager::PluginManager;
87#[cfg(feature = "plugin")]
88pub use plugin::{CipherPlugin, Plugin, PluginLoadError, PluginMetadata};
89
90/// Initialize the library (e.g., FIPS self-tests)
91///
92/// # Errors
93/// Returns `CryptoError` if FIPS self-tests fail or initialization fails
94pub fn init() -> Result<()> {
95    #[cfg(feature = "fips")]
96    {
97        fips::FipsContext::enable()?;
98        fips::init_fips_context()?;
99    }
100
101    // 初始化审计日志
102    audit::AuditLogger::init();
103
104    // 初始化 RNG 监控系统
105    let _rng_monitor_manager = random::get_rng_monitor_manager();
106
107    // Initialize CPU hardware acceleration features
108    #[cfg(feature = "encrypt")]
109    {
110        hardware::init_cpu_features();
111        random::detect_hardware_rng();
112    }
113
114    Ok(())
115}
116
117/// High-level Cipher API
118#[cfg(feature = "encrypt")]
119pub struct Cipher {
120    provider: std::sync::Arc<dyn cipher::provider::SymmetricCipher>,
121    algorithm: Algorithm,
122}
123
124#[cfg(feature = "encrypt")]
125impl Cipher {
126    /// Create a new cipher instance
127    ///
128    /// This method first checks for plugin-provided implementations,
129    /// then falls back to built-in providers.
130    ///
131    /// # Errors
132    /// Returns `CryptoError` if the algorithm is not supported or FIPS validation fails
133    pub fn new(algorithm: Algorithm) -> Result<Self> {
134        fips::validate_algorithm_fips(&algorithm)?;
135
136        let provider: std::sync::Arc<dyn cipher::provider::SymmetricCipher> = {
137            #[cfg(feature = "plugin")]
138            {
139                if let Some(plugin_provider) = plugin::PLUGIN_MANAGER.get_cipher_provider(algorithm)
140                {
141                    plugin_provider
142                } else {
143                    cipher::provider::REGISTRY.get_symmetric(algorithm)?
144                }
145            }
146            #[cfg(not(feature = "plugin"))]
147            {
148                cipher::provider::REGISTRY.get_symmetric(algorithm)?
149            }
150        };
151
152        Ok(Self {
153            provider,
154            algorithm,
155        })
156    }
157
158    /// Get the internal implementation provider
159    #[cfg(test)]
160    pub(crate) fn get_implementation(
161        &self,
162    ) -> std::sync::Arc<dyn cipher::provider::SymmetricCipher> {
163        self.provider.clone()
164    }
165
166    /// Encrypt data using the specified key
167    ///
168    /// # Errors
169    /// Returns `CryptoError` if encryption fails, key is not found, or FIPS validation fails
170    pub fn encrypt(
171        &self,
172        key_manager: &KeyManager,
173        key_id: &str,
174        plaintext: &[u8],
175    ) -> Result<Vec<u8>> {
176        let start = std::time::Instant::now();
177
178        // FIPS 条件自检
179        #[cfg(feature = "fips")]
180        {
181            if let Some(fips_context) = fips::get_fips_context() {
182                fips_context.run_conditional_self_test(self.algorithm)?;
183            }
184        }
185
186        let result =
187            key_manager.with_key(key_id, |key| self.provider.encrypt(key, plaintext, None));
188
189        // 将密钥相关的错误转换为通用错误,防止信息泄露
190        let result = result.map_err(|e| match e {
191            CryptoError::KeyNotFound(_) => CryptoError::EncryptionFailed("Operation failed".into()),
192            _ => e,
193        });
194
195        // Audit Log
196        let _duration = start.elapsed();
197
198        audit::AuditLogger::log(
199            "ENCRYPT",
200            Some(self.algorithm),
201            Some(key_id),
202            if result.is_ok() {
203                Ok(())
204            } else {
205                Err(CryptoError::EncryptionFailed(
206                    "Encryption operation failed".into(),
207                ))
208            },
209        );
210
211        result
212    }
213
214    /// Decrypt data using the specified key
215    ///
216    /// # Errors
217    /// Returns `CryptoError` if decryption fails, key is not found, or FIPS validation fails
218    pub fn decrypt(
219        &self,
220        key_manager: &KeyManager,
221        key_id: &str,
222        ciphertext: &[u8],
223    ) -> Result<Vec<u8>> {
224        let start = std::time::Instant::now();
225
226        // FIPS 条件自检
227        #[cfg(feature = "fips")]
228        {
229            if let Some(fips_context) = fips::get_fips_context() {
230                fips_context.run_conditional_self_test(self.algorithm)?;
231            }
232        }
233
234        let result =
235            key_manager.with_key(key_id, |key| self.provider.decrypt(key, ciphertext, None));
236
237        // 将密钥相关的错误转换为通用错误,防止信息泄露
238        let result = result.map_err(|e| match e {
239            CryptoError::KeyNotFound(_) => CryptoError::DecryptionFailed("Operation failed".into()),
240            _ => e,
241        });
242
243        // Audit Log
244        let _duration = start.elapsed();
245
246        audit::AuditLogger::log(
247            "DECRYPT",
248            Some(self.algorithm),
249            Some(key_id),
250            if result.is_ok() {
251                Ok(())
252            } else {
253                Err(CryptoError::DecryptionFailed(
254                    "Decryption operation failed".into(),
255                ))
256            },
257        );
258
259        result
260    }
261
262    /// Encrypt data with additional authenticated data (AAD)
263    ///
264    /// # Errors
265    /// Returns `CryptoError` if encryption fails
266    pub fn encrypt_aad(
267        &self,
268        key_manager: &KeyManager,
269        key_id: &str,
270        plaintext: &[u8],
271        aad: &[u8],
272    ) -> Result<Vec<u8>> {
273        key_manager.with_key(key_id, |key| {
274            self.provider.encrypt(key, plaintext, Some(aad))
275        })
276    }
277
278    /// Decrypt data with additional authenticated data (AAD)
279    ///
280    /// # Errors
281    /// Returns `CryptoError` if decryption fails or authentication fails
282    pub fn decrypt_aad(
283        &self,
284        key_manager: &KeyManager,
285        key_id: &str,
286        ciphertext: &[u8],
287        aad: &[u8],
288    ) -> Result<Vec<u8>> {
289        key_manager.with_key(key_id, |key| {
290            self.provider.decrypt(key, ciphertext, Some(aad))
291        })
292    }
293}
294
295#[cfg(feature = "encrypt")]
296impl Drop for Cipher {
297    fn drop(&mut self) {
298        audit::AuditLogger::log("CIPHER_DROP", Some(self.algorithm), None, Ok(()));
299    }
300}
301
302/// High-level Hashing API
303#[cfg(feature = "hash")]
304pub struct Hasher {
305    hash: hash::MultiHash,
306}
307
308#[cfg(feature = "hash")]
309impl Hasher {
310    pub fn new(algorithm: types::Algorithm) -> Result<Self> {
311        let algo_type = match algorithm {
312            types::Algorithm::SHA256 => hash::AlgorithmType::Sha256,
313            types::Algorithm::SHA384 => hash::AlgorithmType::Sha384,
314            types::Algorithm::SHA512 => hash::AlgorithmType::Sha512,
315            types::Algorithm::SM3 => hash::AlgorithmType::Sm3,
316            _ => {
317                return Err(CryptoError::UnsupportedAlgorithm(
318                    "Unsupported hash algorithm".into(),
319                ))
320            }
321        };
322        Ok(Self {
323            hash: hash::MultiHash::new(algo_type)?,
324        })
325    }
326
327    pub fn hash(&self, data: &[u8]) -> Vec<u8> {
328        let mut hasher = self.hash.clone();
329        hasher.update(data);
330        hasher.finalize()
331    }
332
333    #[cfg(feature = "encrypt")]
334    pub fn hash_large(&self, data: &[u8]) -> Result<Vec<u8>> {
335        if hardware::has_sha_ni() || hardware::has_avx2() {
336            let algorithm = match self.hash.algorithm() {
337                hash::AlgorithmType::Sha256 => Algorithm::SHA256,
338                hash::AlgorithmType::Sha384 => Algorithm::SHA384,
339                hash::AlgorithmType::Sha512 => Algorithm::SHA512,
340                hash::AlgorithmType::Sm3 => Algorithm::SM3,
341            };
342            hardware::accelerated_hash(data, algorithm)
343        } else {
344            Ok(self.hash(data))
345        }
346    }
347}
348
349/// High-level MAC API
350#[cfg(feature = "hash")]
351pub struct Hmac {
352    algorithm: types::Algorithm,
353}
354
355#[cfg(feature = "hash")]
356impl Hmac {
357    pub fn new(algorithm: types::Algorithm) -> Result<Self> {
358        Ok(Self { algorithm })
359    }
360
361    pub fn sign(&self, key: &[u8], data: &[u8]) -> Result<Vec<u8>> {
362        match self.algorithm {
363            types::Algorithm::SHA256 => {
364                let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(key)
365                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
366                mac.update(data);
367                Ok(mac.finalize().into_bytes().to_vec())
368            }
369            types::Algorithm::SHA384 => {
370                let mut mac = hmac::Hmac::<sha2::Sha384>::new_from_slice(key)
371                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
372                mac.update(data);
373                Ok(mac.finalize().into_bytes().to_vec())
374            }
375            types::Algorithm::SHA512 => {
376                let mut mac = hmac::Hmac::<sha2::Sha512>::new_from_slice(key)
377                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
378                mac.update(data);
379                Ok(mac.finalize().into_bytes().to_vec())
380            }
381            _ => Err(CryptoError::UnsupportedAlgorithm(
382                "Unsupported MAC algorithm".into(),
383            )),
384        }
385    }
386
387    pub fn verify(&self, key: &[u8], data: &[u8], signature: &[u8]) -> Result<bool> {
388        match self.algorithm {
389            types::Algorithm::SHA256 => {
390                let mut mac = hmac::Hmac::<sha2::Sha256>::new_from_slice(key)
391                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
392                mac.update(data);
393                Ok(mac.verify_slice(signature).is_ok())
394            }
395            types::Algorithm::SHA384 => {
396                let mut mac = hmac::Hmac::<sha2::Sha384>::new_from_slice(key)
397                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
398                mac.update(data);
399                Ok(mac.verify_slice(signature).is_ok())
400            }
401            types::Algorithm::SHA512 => {
402                let mut mac = hmac::Hmac::<sha2::Sha512>::new_from_slice(key)
403                    .map_err(|_| CryptoError::KeyError("Invalid HMAC key".into()))?;
404                mac.update(data);
405                Ok(mac.verify_slice(signature).is_ok())
406            }
407            _ => Err(CryptoError::UnsupportedAlgorithm(
408                "Unsupported MAC algorithm".into(),
409            )),
410        }
411    }
412}
413
414/// High-level Digital Signature API
415#[cfg(feature = "encrypt")]
416pub struct Signer {
417    algorithm: types::Algorithm,
418}
419
420#[cfg(feature = "encrypt")]
421impl Signer {
422    pub fn new(algorithm: types::Algorithm) -> Result<Self> {
423        Ok(Self { algorithm })
424    }
425
426    pub fn sign(&self, key_manager: &KeyManager, key_id: &str, data: &[u8]) -> Result<Vec<u8>> {
427        let signer = cipher::provider::REGISTRY.get_signer(self.algorithm)?;
428        key_manager.with_key(key_id, |key| signer.sign(key, data))
429    }
430
431    pub fn verify(
432        &self,
433        key_manager: &KeyManager,
434        key_id: &str,
435        data: &[u8],
436        signature: &[u8],
437    ) -> Result<bool> {
438        let signer = cipher::provider::REGISTRY.get_signer(self.algorithm)?;
439        key_manager.with_key(key_id, |key| signer.verify(key, data, signature))
440    }
441}
442
443/// Get the hardware acceleration status
444#[cfg(feature = "encrypt")]
445pub fn get_hardware_info() -> hardware::CpuFeatures {
446    hardware::CpuFeatures::detect()
447}
448
449/// Check if AES-NI is available
450#[cfg(feature = "encrypt")]
451pub fn has_aes_ni() -> bool {
452    hardware::has_aes_ni()
453}
454
455/// Check if AVX2 is available
456#[cfg(feature = "encrypt")]
457pub fn has_avx2() -> bool {
458    hardware::has_avx2()
459}
460
461/// Check if SHA-NI is available
462#[cfg(feature = "encrypt")]
463pub fn has_sha_ni() -> bool {
464    hardware::has_sha_ni()
465}
466
467#[cfg(feature = "encrypt")]
468pub fn is_hardware_acceleration_available() -> bool {
469    hardware::is_hardware_acceleration_available()
470}
471
472#[cfg(feature = "encrypt")]
473pub fn get_cpu_capabilities() -> hardware::cpu::CpuCapabilities {
474    hardware::get_cpu_capabilities()
475}
476
477#[cfg(feature = "encrypt")]
478pub fn accelerated_hash_cpu(data: &[u8], algorithm: types::Algorithm) -> error::Result<Vec<u8>> {
479    hardware::accelerated_hash_cpu(data, algorithm)
480}
481
482#[cfg(feature = "encrypt")]
483pub fn accelerated_batch_hash_cpu(
484    data_chunks: Vec<&[u8]>,
485    algorithm: types::Algorithm,
486) -> error::Result<Vec<Vec<u8>>> {
487    hardware::accelerated_batch_hash_cpu(data_chunks, algorithm)
488}
489
490#[cfg(feature = "encrypt")]
491pub fn accelerated_aes_encrypt_cpu(
492    key: &[u8],
493    plaintext: &[u8],
494    nonce: &[u8],
495) -> error::Result<Vec<u8>> {
496    hardware::accelerated_aes_encrypt_cpu(key, plaintext, nonce)
497}
498
499#[cfg(feature = "encrypt")]
500pub fn accelerated_aes_decrypt_cpu(
501    key: &[u8],
502    ciphertext: &[u8],
503    nonce: &[u8],
504) -> error::Result<Vec<u8>> {
505    hardware::accelerated_aes_decrypt_cpu(key, ciphertext, nonce)
506}
507
508#[cfg(feature = "encrypt")]
509pub fn accelerated_batch_aes_encrypt_cpu(
510    key: &[u8],
511    plaintexts: Vec<&[u8]>,
512    nonces: Vec<&[u8]>,
513) -> error::Result<Vec<Vec<u8>>> {
514    hardware::accelerated_batch_aes_encrypt_cpu(key, plaintexts, nonces)
515}
516
517#[cfg(feature = "encrypt")]
518pub fn accelerated_batch_aes_decrypt_cpu(
519    key: &[u8],
520    ciphertexts: Vec<Vec<u8>>,
521    nonces: Vec<&[u8]>,
522) -> error::Result<Vec<Vec<u8>>> {
523    hardware::accelerated_batch_aes_decrypt_cpu(key, ciphertexts, nonces)
524}
525
526#[cfg(feature = "encrypt")]
527pub fn accelerated_sm4_encrypt_cpu(key: &[u8], plaintext: &[u8]) -> error::Result<Vec<u8>> {
528    hardware::accelerated_sm4_encrypt_cpu(key, plaintext)
529}
530
531#[cfg(feature = "encrypt")]
532pub fn accelerated_sm4_decrypt_cpu(key: &[u8], ciphertext: &[u8]) -> error::Result<Vec<u8>> {
533    hardware::accelerated_sm4_decrypt_cpu(key, ciphertext)
534}
535
536#[cfg(feature = "encrypt")]
537pub fn accelerated_batch_sm4_cpu(
538    key: &[u8],
539    data_chunks: Vec<Vec<u8>>,
540    encrypt: bool,
541) -> error::Result<Vec<Vec<u8>>> {
542    hardware::accelerated_batch_sm4_cpu(key, data_chunks, encrypt)
543}