ciphern 0.2.1

Enterprise-grade cryptographic library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
# Ciphern Crypto Library

[![Crates.io](https://img.shields.io/crates/v/ciphern.svg)](https://crates.io/crates/ciphern)
[![Documentation](https://docs.rs/ciphern/badge.svg)](https://docs.rs/ciphern)
[![License](https://img.shields.io/github/license/Kirky-X/ciphern)](LICENSE)
[![Build Status](https://github.com/Kirky-X/ciphern/actions/workflows/health-check.yml/badge.svg)](https://github.com/Kirky-X/ciphern/actions/workflows/health-check.yml)
[![Coverage](https://img.shields.io/codecov/c/github/Kirky-X/ciphern)](https://codecov.io/gh/Kirky-X/ciphern)
[![Security Audit](https://img.shields.io/badge/security-audited-success)](docs/SECURITY_AUDIT.md)

**Ciphern** is an enterprise-grade, security-first Rust cryptographic library providing cryptographic capabilities that comply with both Chinese National Standards (GuoMi) and international standards. Designed for data storage encryption, communication encryption, and key management.

[English]README.md | [中文文档]README_zh.md

---

## ✨ Core Features

### 🔒 Security First

- **Memory Protection**: Securely clear keys using `zeroize`, support for memory locking (mlock) and integrity verification
- **Side-channel Protection**: Provides constant-time operation implementation to prevent timing attacks
- **Compliance**: Compliant with Chinese National Standards (SM2/SM3/SM4) and FIPS 140-3 basic requirements
- **Audit Logs**: Full audit trail for cryptographic operations
- **Key Lifecycle**: Support for basic lifecycle management including key generation, activation, and destruction

### ⚡ High Performance

- **Zero-Copy Design**: Minimizes memory allocation and copying
- **Smart Caching**: Reuses keys and algorithm instances
- **Pure Rust Implementation**: No external dependencies, compile-time optimization

### 🔧 Easy Integration

- **Unified Interface**: Simple API that hides underlying complexity
- **Multi-language Support**: C FFI interface, basic Java JNI and Python PyO3 bindings
- **Pluggable Architecture**: Supports custom cryptographic algorithm plugins (basic framework)
- **Rich Testing**: Includes unit tests, integration tests, and performance tests
- **Internationalization (i18n)**: Full i18n support with English and Chinese locales, string interpolation with arguments

### 🌐 Standard Compatibility

- **International Standards**: AES-128/192/256-GCM, ECDSA-P256/P384/P521, RSA-2048/3072/4096, Ed25519
- **National Standards**: SM2, SM3, SM4-GCM
- **Hash Functions**: SHA-256/384/512, SHA3-256/384/512, SM3
- **Key Derivation**: HKDF, PBKDF2, Argon2id, Sm3Kdf

---

## 🚀 Quick Start

### Installation

**Rust (Cargo)**

```toml
[dependencies]
ciphern = "0.1"
```

**Java (Maven)**

Java JNI bindings have completed core functionality implementation, supporting encryption/decryption and key management:

```xml
<!-- Maven direct installation is not yet supported, requires compilation of the JNI library from source -->
```

**Python (pip)**

Python PyO3 bindings have completed core functionality implementation, supporting encryption/decryption, signature verification, and hash calculation:

```bash
# pip direct installation is not yet supported, requires compilation from source
# pip install ciphern  # Not available yet
```

### 5-Minute Examples

#### Basic Encryption/Decryption (Rust)

```rust
use ciphern::{Cipher, Algorithm, KeyManager};
#[cfg(feature = "hash")]
use ciphern::Hash;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the library
    ciphern::init()?;
    
    // Initialize KeyManager
    let km = KeyManager::new()?;
    
    // Generate a key
    let key_id = km.generate_key(Algorithm::AES256GCM)?;
    
    // Create a cipher
    let cipher = Cipher::new(Algorithm::AES256GCM)?;
    
    // Encrypt
    let plaintext = b"Hello, Ciphern!";
    let ciphertext = cipher.encrypt(&km, &key_id, plaintext)?;
    
    // Decrypt
    let decrypted = cipher.decrypt(&km, &key_id, &ciphertext)?;
    assert_eq!(plaintext, &decrypted[..]);
    
    println!("✅ Encryption and decryption successful!");
    Ok(())
}
```

#### Digital Signature (Rust)

```rust
use ciphern::{Cipher, Algorithm, KeyManager};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the library
    ciphern::init()?;
    
    // Initialize KeyManager
    let km = KeyManager::new()?;
    
    // Generate a key pair (using ECDSA-P256 as an example)
    let key_id = km.generate_key(Algorithm::ECDSAP256)?;
    
    // Create a cipher for signing
    let cipher = Cipher::new(Algorithm::ECDSAP256)?;
    
    // Sign
    let message = b"Important message";
    let signature = cipher.sign(&km, &key_id, message)?;
    
    // Verify
    let is_valid = cipher.verify(&km, &key_id, message, &signature)?;
    assert!(is_valid);
    
    println!("✅ Signature verified!");
    Ok(())
}
```

#### National Standard Algorithms (Rust)

```rust
use ciphern::{Cipher, Algorithm, KeyManager};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Initialize the library
    ciphern::init()?;
    
    let km = KeyManager::new()?;

    // SM4 Encryption
    let key_id = km.generate_key(Algorithm::SM4GCM)?;
    let cipher = Cipher::new(Algorithm::SM4GCM)?;
    let ciphertext = cipher.encrypt(&km, &key_id, b"GuoMi encryption test")?;
    
    // SM4 Decryption verification
    let decrypted = cipher.decrypt(&km, &key_id, &ciphertext)?;
    assert_eq!(b"GuoMi encryption test", &decrypted[..]);
    
    // SM3 Hash (requires "hash" feature)
    #[cfg(feature = "hash")]
    {
        let hash = Hash::sm3(b"Data integrity verification")?;
        println!("SM3 hash: {:?}", hash);
    }
    
    println!("✅ National standard algorithms executed successfully!");
    Ok(())
}
```

#### Java Example

Java JNI bindings have completed core functionality implementation:

```java
import com.ciphern.Ciphern;

public class Main {
    public static void main(String[] args) {
        // Initialize the library
        Ciphern.init();
        
        // Generate a key
        String keyId = Ciphern.generateKey("AES256GCM");
        
        // Encrypt
        byte[] plaintext = "Hello, Ciphern!".getBytes();
        byte[] ciphertext = Ciphern.encrypt(keyId, plaintext);
        
        // Decrypt
        byte[] decrypted = Ciphern.decrypt(keyId, ciphertext);
        
        System.out.println("Decrypted result: " + new String(decrypted));
    }
}
```

#### Python Example

Python PyO3 bindings have completed core functionality implementation:

```python
from ciphern_py import KeyManager, Ciphern

# Initialize KeyManager
km = KeyManager()

# Generate a key
key_id = km.generate_key("AES256GCM")

# Create cipher
cipher = Ciphern(km)

# Encrypt
plaintext = b"Hello, Ciphern!"
ciphertext = cipher.encrypt(key_id, plaintext)

# Decrypt
decrypted = cipher.decrypt(key_id, ciphertext)

print(f"Decrypted result: {decrypted.decode('utf-8')}")
```

---

## 📚 Documentation

### Core Documentation

- **[User Guide]docs/USER_GUIDE.md** - Detailed instructions and best practices
- **[API Reference]https://docs.rs/ciphern** - Complete API reference
- **[Examples]examples/** - Examples covering common scenarios

### Advanced Topics

- **[Architecture]docs/ARCHITECTURE.md** - System architecture and design decisions
- **[Performance Optimization]docs/PERFORMANCE.md** - SIMD, hardware acceleration, benchmark
- **[Security Guide]docs/SECURITY.md** - Threat model, security best practices
- **[Multi-Tenancy Guide]docs/MULTI_TENANT.md** - Key isolation and access control

### Developer Documentation

- **[Contributing Guide]CONTRIBUTING.md** - How to participate in development
- **[Plugin Development]docs/PLUGIN_DEVELOPMENT.md** - Implementing custom algorithms
- **[FFI Guide]docs/FFI_GUIDE.md** - C/Java/Python bindings

---

## 🎯 Use Cases

### Data Storage Encryption

Protect sensitive data in databases and file systems

```rust
use ciphern::{Cipher, KeyManager, Algorithm};

ciphern::init()?;
let km = KeyManager::new()?;
let key_id = km.generate_key_with_alias(Algorithm::AES256GCM, "database-encryption")?;
let cipher = Cipher::new(Algorithm::AES256GCM)?;

// Encrypt sensitive field
let encrypted_ssn = cipher.encrypt(&km, &key_id, user.ssn.as_bytes())?;
db.save_encrypted_field(user.id, "ssn", &encrypted_ssn)?;
```

### API Communication Encryption

Protect the confidentiality and integrity of API requests and responses

```rust
use ciphern::{Cipher, Algorithm, KeyManager};

ciphern::init()?;
let km = KeyManager::new()?;
let key_id = km.generate_key(Algorithm::ECDSAP384)?;
let cipher = Cipher::new(Algorithm::ECDSAP384)?;
let signature = cipher.sign(&km, &key_id, &request_body)?;

http_request
    .header("X-Signature", base64::encode(&signature))
    .body(request_body)
    .send()?;
```

### Key Management

Basic key lifecycle management

```rust
use ciphern::{KeyManager, Algorithm};

ciphern::init()?;
let km = KeyManager::new()?;

// Generate a key
let key_id = km.generate_key(Algorithm::AES256GCM)?;

// Manage keys using aliases
let alias_key_id = km.generate_key_with_alias(Algorithm::AES256GCM, "my-app-key")?;
```

---

## 🔧 Advanced Features

### FIPS 140-3 Compliance Mode

```toml
[dependencies]
ciphern = { version = "0.1", features = ["fips"] }
```

```rust
use ciphern::{is_fips_enabled, Algorithm, Cipher};

// Enable FIPS mode during initialization
ciphern::init()?;

// Check if FIPS mode is enabled
if is_fips_enabled() {
    println!("FIPS mode is enabled");
}

// In FIPS mode, non-approved algorithms will be rejected
let result = Cipher::new(Algorithm::SM4GCM);
assert!(result.is_err()); // CryptoError::FipsError
```

### Audit Logging and Monitoring

```rust
use ciphern::audit::AuditLogger;
use std::sync::Arc;

// Initialize the library
ciphern::init()?;

// Log an event
AuditLogger::log("ENCRYPT", Some(ciphern::Algorithm::Aes256Gcm), Some("key-123"), Ok(()))?;

// Get performance metrics
let metrics = audit_logger.get_performance_metrics()?;
println!("Throughput: {:.2} ops/sec", metrics.avg_throughput_ops_per_sec);
println!("Cache hit rate: {:.1}%", metrics.avg_cache_hit_rate * 100.0);
```

### Custom Algorithm Plugins

```rust
use ciphern::plugin::{Plugin, CipherPlugin};
// Extend algorithms by implementing Plugin and CipherPlugin traits
```

### Internationalization (i18n)

```toml
[dependencies]
ciphern = { version = "0.1", features = ["i18n"] }
```

```rust
use ciphern::i18n::{set_locale, tr, tr_with_args};

// Set locale to English or Chinese
set_locale("en"); // or "zh"

// Simple translation
let message = tr("common.ok")?;  // Returns "OK" in English

// Translation with arguments
let error_msg = tr_with_args("error.key_not_found_in_keyring", 
    &[("key_id", "my-key"), ("keyring", "main"), ("reason", "not found")])?;
// Returns: "Key my-key not found in keyring main: not found"

// Check supported locales
use ciphern::i18n::{is_locale_supported, get_supported_locales};
assert!(is_locale_supported("en"));
assert!(is_locale_supported("zh"));
let locales = get_supported_locales(); // Returns vec!["en", "zh"]
```

---

## 📊 Performance Metrics

### Performance Metrics

The current version is based on a pure Rust implementation. Performance data can be obtained through the audit system:

```rust
// Performance monitoring is handled internally by the audit system

// The current version collects performance metrics internally
// Performance data is available through internal monitoring systems
```

> Note: SIMD optimization and hardware acceleration features are under development. The current version provides a basic implementation of cryptographic functions.

Run benchmark:

```bash
cargo bench
```

---

## 🔐 Security

### Security Features

- **Automatic Memory Erasure**: Securely clear keys using `zeroize`
-**Memory Locking**: Uses `mlock` to prevent sensitive data from being swapped to disk
-**Integrity Verification**: Key integrity checks to prevent memory tampering
-**Constant-time Operations**: Side-channel protection to prevent timing attacks
-**FIPS 140-3 Basic Compliance**: Supports verification of FIPS-approved algorithms
-**Audit Logs**: Full audit trail for cryptographic operations
-**Algorithm Verification**: Built-in algorithm correctness self-checks
-**Error Handling**: Secure error state management

### Security Audit

Ciphern security features are based on the following implementations:

- ✅ Uses mature cryptographic libraries (`ring`, `libsm`) as the underlying implementation
- ✅ Built-in algorithm correctness verification
- ✅ FIPS 140-3 algorithm approval checks
- ✅ Comprehensive error handling and state management

> Note: NIST CAVP testing, Fuzzing, third-party security audits, etc., are planned.

### Vulnerability Reporting

If you find a security vulnerability, please report it in the GitHub Issues.

> Note: A dedicated security email and SECURITY.md documentation are being prepared.

---

## 🛠️ Development Environment

### Prerequisites

- Rust 1.75+ (stable)
- Standard C compiler (for FFI bindings)

### Build

```bash
# Clone the repository
git clone https://github.com/Kirky-X/ciphern.git
cd ciphern

# Default build
cargo build --release

# Enable all features
cargo build --release --all-features

# FIPS mode
cargo build --release --features fips
```

### Test

```bash
# Run all tests
cargo test --all-features

# Run benchmarks
cargo bench

# Check code quality
cargo clippy --all-features
```

### Cross-Compilation

```bash
# ARM64 Linux
cargo build --target aarch64-unknown-linux-gnu --release

# Windows
cargo build --target x86_64-pc-windows-msvc --release

# macOS ARM (Apple Silicon)
cargo build --target aarch64-apple-darwin --release
```

---

## 🗺️ Roadmap

### v0.1.0 - MVP (Completed) ✅

- [x] Core encryption (AES-128/192/256-GCM, SM4-GCM)
- [x] Digital signatures (ECDSA-P256/P384/P521, RSA-2048/3072/4096, Ed25519, SM2)
- [x] Hash functions (SHA-256/384/512, SHA3-256/384/512, SM3)
- [x] Key derivation (HKDF, PBKDF2, Argon2id, Sm3Kdf)
- [x] Basic key management
- [x] Rust API
- [x] Audit logging system
- [x] FIPS 140-3 basic support

### v0.2.0 - Multi-language Support (Completed) ✅

- [x] C FFI interface
- [x] Java JNI bindings (core functionality implemented)
- [x] Python PyO3 bindings (core functionality implemented)
- [x] Memory protection enhancements (mlock + integrity verification)
- [x] Side-channel protection (constant-time operations)
- [x] Plugin system improvements
- [x] Internationalization (i18n) with English and Chinese locale support

### v0.3.0 - Extensibility (Planned) 📋

- [ ] SIMD optimization
- [ ] WASM support
- [ ] HSM integration (PKCS#11)
- [ ] TEE support (Intel SGX, ARM TrustZone)

### v1.0.0 - Production Ready (Planned) 🎯

- [ ] Complete security audit
- [ ] FIPS 140-3 certification
- [ ] Performance optimization (SIMD, multi-core)
- [ ] Full documentation and examples

---

## 🤝 Contributing

We welcome all forms of contribution!

### How to Contribute

1. Fork this repository
2. Create a feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Create a Pull Request

> Note: CONTRIBUTING.md documentation is being prepared.

### Contributors

Thanks to all contributors!

[![Contributors](https://contrib.rocks/image?repo=Kirky-X/ciphern)](https://github.com/Kirky-X/ciphern/graphs/contributors)

---

## 📄 License

This project is dual-licensed:

- **MIT License** - see [LICENSE-MIT]LICENSE-MIT
- **Apache License 2.0** - see [LICENSE-APACHE]LICENSE-APACHE

You may choose either license for your use.

> Note: License files are being prepared. The current version follows standard Rust open-source protocols.

---

## 🙏 Acknowledgments

Ciphern is built upon these excellent open-source projects:

- [ring]https://github.com/briansmith/ring - High-performance cryptography library (v0.17)
- [libsm]https://github.com/citahub/libsm - GuoMi algorithm implementation (v0.6)
- [aes-gcm]https://github.com/RustCrypto/AEADs - AES-GCM implementation (v0.10)
- [argon2]https://github.com/RustCrypto/password-hashes - Argon2 key derivation (v0.5)
- [zeroize]https://github.com/RustCrypto/utils/tree/master/zeroize - Secure memory erasure (v1.7)

Special thanks to all security researchers who audited the code and provided feedback.

---

## 📞 Contact

- **Issues**: https://github.com/Kirky-X/ciphern/issues
- **Discussions**: https://github.com/Kirky-X/ciphern/discussions

> Note: Official website, documentation site, and dedicated support email are being prepared.

---

## ⭐ Star History

[![Star History Chart](https://api.star-history.com/svg?repos=Kirky-X/ciphern&type=Date)](https://star-history.com/#Kirky-X/ciphern&Date)

---

**Built with ❤️ by the Ciphern Team**

[⬆ Back to Top](#ciphern-crypto-library)