High-performance, memory-safe Rust implementation of the Chaum-Pedersen Zero-Knowledge Proof authentication system.
- Memory Safety: Rust's ownership system prevents memory bugs
- Concurrency: Safe concurrent access with Arc and Mutex
- Performance: Comparable to C++ with added safety guarantees
- Type Safety: Strong type system catches errors at compile time
- Zero-Cost Abstractions: High-level code compiles to efficient machine code
- Modern Async: Actix-web for high-performance HTTP server
# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Verify installation
rustc --version
cargo --version# Ubuntu/Debian (for SQLite)
sudo apt-get install libsqlite3-dev
# macOS (usually pre-installed)
# No additional dependencies needed# Navigate to rust directory
cd rust
# Build in release mode (optimized)
cargo build --release
# Executables will be in target/release/
# - zkp-server
# - zkp-client# Build in debug mode (faster compilation, includes debug symbols)
cargo build
# Executables will be in target/debug/# Run with default settings (port 8080, users.db)
cargo run --release --bin zkp-server
# Or run the compiled binary
./target/release/zkp-server
# Custom port and database
cargo run --release --bin zkp-server -- --port 9000 --db custom.db
# 4096-bit parameters (generation mode)
cargo run --release --bin zkp-server -- --bits 4096 --params-mode generate
# Show help
cargo run --release --bin zkp-server -- --help# Register a user
cargo run --release --bin zkp-client -- register alice password123
# Login
cargo run --release --bin zkp-client -- login alice password123
# Verify token
cargo run --release --bin zkp-client -- verify <token>
# Connect to custom server
cargo run --release --bin zkp-client -- --host 192.168.1.100 --port 9000 register alice password
# Using compiled binary
./target/release/zkp-client register alice password123# Run all tests
cargo test
# Run with output
cargo test -- --nocapture
# Run specific test
cargo test test_zkp_valid_proof
# Run tests with threading
cargo test --releaserust/
├── Cargo.toml # Dependencies and project config
├── src/
│ ├── lib.rs # Library root
│ ├── zkp/
│ │ └── mod.rs # ZKP implementation
│ ├── db/
│ │ └── mod.rs # Database layer
│ ├── server/
│ │ └── mod.rs # Actix-web server
│ ├── client/
│ │ └── mod.rs # HTTP client
│ └── bin/
│ ├── server.rs # Server binary
│ └── client.rs # Client binary
└── tests/
└── integration_tests.rs # Integration tests
- num-bigint: Arbitrary precision integers for cryptography
- num-traits: Numeric trait abstractions
- rand: Cryptographically secure random number generation
- sha2: SHA-256 hashing
- hex: Hexadecimal encoding/decoding
- rusqlite: SQLite database (bundled, no system SQLite needed)
- actix-web: Async HTTP server framework
- reqwest: HTTP client
- serde: Serialization framework
- serde_json: JSON support
- clap: Command-line argument parsing
- Parameter Generation: ~2-5 seconds (2048-bit primes, one-time startup)
- Registration: ~0.1 seconds per user
- Authentication: ~0.1 seconds per request
- Throughput: ~800-1000 requests/second (async server)
- Memory: ~15 MB resident
-
Always use --release:
cargo build --release
-
Profile-guided optimization (advanced):
RUSTFLAGS="-C target-cpu=native" cargo build --release -
Link-time optimization (slower build, faster runtime): Add to Cargo.toml:
[profile.release] lto = true codegen-units = 1
Rust prevents:
- Use after free
- Double free
- Buffer overflows
- Data races
All at compile time, with zero runtime cost!
// Automatic cleanup when variables go out of scope
{
let zkp = ChaumPedersenZKP::new();
// Use zkp...
} // zkp automatically cleaned up here// Arc for shared ownership, Mutex for synchronization
let db = Arc::new(Mutex::new(UserDatabase::new("users.db")?));
// Thread-safe access
let db_clone = Arc::clone(&db);
std::thread::spawn(move || {
let db = db_clone.lock().unwrap();
// Use database safely
});// Result type for explicit error handling
pub fn register_user(&self, username: &str, password: &str)
-> Result<UserPublicKey, String> {
if username.len() < 3 {
return Err("Username too short".to_string());
}
// ...
}Same as other implementations:
GET /params- Group parameters (hex)POST /register- Register with client-computedy1, y2, saltPOST /challenge- Request a one-timenoncePOST /authenticate- Submit ZKP{a1, a2, s, nonce}GET /verify- Verify session token
See ../docs/API.md for complete documentation.
All the same security features as C++ and Python implementations:
- 2048-bit Safe Primes: p = 2q + 1
- Cryptographically Secure RNG:
rand::thread_rng() - SHA-256 Hashing: For password derivation and challenges
- Timestamp Validation: 5-minute window
- Session Management: 1-hour expiry
- Zero-Knowledge: Server never learns passwords
Plus Rust-specific guarantees:
- Memory safety without garbage collection
- Thread safety enforced by the compiler
- No null pointer dereferences
- No data races
# Format code
cargo fmt
# Check formatting
cargo fmt -- --check# Run Clippy (Rust linter)
cargo clippy
# Fix automatically when possible
cargo clippy --fix# Generate and open documentation
cargo doc --open
# Document private items too
cargo doc --document-private-items --open| Feature | C++ | Python | Rust |
|---|---|---|---|
| Memory Safety | Manual | GC | Automatic (compile-time) |
| Performance | Excellent | Good | Excellent |
| Concurrency | Manual (threads) | GIL limited | Safe (fearless) |
| Compilation | Required | Not required | Required |
| Type Safety | Strong | Dynamic | Strongest |
| Learning Curve | Medium | Easy | Steep |
| Error Handling | Exceptions | Exceptions | Result types |
| Package Manager | None (external) | pip | cargo (built-in) |
✅ Use Rust when:
- You need C++ level performance with safety
- Building concurrent systems
- Memory safety is critical
- Long-term maintainability matters
- You want modern tooling (cargo, rustfmt, clippy)
❌ Use another language when:
- Rapid prototyping (use Python)
- Team unfamiliar with Rust (use C++ or Python)
- Very simple scripts (use Python)
Problem: error: linker 'cc' not found
# Ubuntu/Debian
sudo apt-get install build-essential
# macOS
xcode-select --installProblem: Long compilation times
# Use cargo check instead of cargo build for fast feedback
cargo check
# Enable incremental compilation (usually on by default)
export CARGO_INCREMENTAL=1Problem: "Database is locked"
- SQLite doesn't support high concurrency writes
- Consider using PostgreSQL for production
- Or use a connection pool
Problem: Server not binding to port
# Check if port is in use
lsof -i :8080
# Use a different port
cargo run --release --bin zkp-server -- --port 9000Modify src/zkp/mod.rs:
fn generate_parameters(&mut self) {
let bits = 4096; // Use 4096-bit primes for higher security
// ...
}For production, consider using r2d2 for connection pooling:
[dependencies]
r2d2 = "0.8"
r2d2_sqlite = "0.22"Add middleware to Actix-web server:
use actix_web::middleware::Logger;
HttpServer::new(move || {
App::new()
.wrap(Logger::default())
// ... routes
})- Main Documentation:
../README.md - ZKP Theory:
../docs/ZKP_THEORY.md - Protocol Details:
../docs/CHAUM_PEDERSEN.md - API Reference:
../docs/API.md - C++ Implementation:
../cpp/README.md - Python Implementation:
../python/README.md
When contributing to the Rust implementation:
- Run tests:
cargo test - Format code:
cargo fmt - Check with Clippy:
cargo clippy - Update documentation
- Keep in sync with C++ and Python APIs
This project was developed as POC for research purposes.
- Rust Book: https://doc.rust-lang.org/book/
- Actix-web: https://actix.rs/
- num-bigint: https://docs.rs/num-bigint/
- Chaum-Pedersen Protocol: See
../docs/CHAUM_PEDERSEN.md