Skip to content

Latest commit

 

History

History
433 lines (317 loc) · 9.47 KB

File metadata and controls

433 lines (317 loc) · 9.47 KB

ZKP Authentication System - Rust Implementation

High-performance, memory-safe Rust implementation of the Chaum-Pedersen Zero-Knowledge Proof authentication system.

Features

  • 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

Prerequisites

Rust Installation

# Install Rust (if not already installed)
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

# Verify installation
rustc --version
cargo --version

System Dependencies

# Ubuntu/Debian (for SQLite)
sudo apt-get install libsqlite3-dev

# macOS (usually pre-installed)
# No additional dependencies needed

Building

# Navigate to rust directory
cd rust

# Build in release mode (optimized)
cargo build --release

# Executables will be in target/release/
# - zkp-server
# - zkp-client

Development Build

# Build in debug mode (faster compilation, includes debug symbols)
cargo build

# Executables will be in target/debug/

Usage

Starting the Server

# 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

Using the Client

# 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

Running Tests

# 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 --release

Project Structure

rust/
├── 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

Dependencies

Core Dependencies

  • 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

Database

  • rusqlite: SQLite database (bundled, no system SQLite needed)

HTTP

  • actix-web: Async HTTP server framework
  • reqwest: HTTP client

Serialization

  • serde: Serialization framework
  • serde_json: JSON support

CLI

  • clap: Command-line argument parsing

Performance

Benchmarks (Approximate)

  • 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

Optimization Tips

  1. Always use --release:

    cargo build --release
  2. Profile-guided optimization (advanced):

    RUSTFLAGS="-C target-cpu=native" cargo build --release
  3. Link-time optimization (slower build, faster runtime): Add to Cargo.toml:

    [profile.release]
    lto = true
    codegen-units = 1

Rust-Specific Features

Memory Safety

Rust prevents:

  • Use after free
  • Double free
  • Buffer overflows
  • Data races

All at compile time, with zero runtime cost!

Ownership System

// Automatic cleanup when variables go out of scope
{
    let zkp = ChaumPedersenZKP::new();
    // Use zkp...
} // zkp automatically cleaned up here

Concurrent Safety

// 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
});

Error Handling

// 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());
    }
    // ...
}

API Endpoints

Same as other implementations:

  • GET /params - Group parameters (hex)
  • POST /register - Register with client-computed y1, y2, salt
  • POST /challenge - Request a one-time nonce
  • POST /authenticate - Submit ZKP {a1, a2, s, nonce}
  • GET /verify - Verify session token

See ../docs/API.md for complete documentation.

Security Features

All the same security features as C++ and Python implementations:

  1. 2048-bit Safe Primes: p = 2q + 1
  2. Cryptographically Secure RNG: rand::thread_rng()
  3. SHA-256 Hashing: For password derivation and challenges
  4. Timestamp Validation: 5-minute window
  5. Session Management: 1-hour expiry
  6. 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

Development

Code Formatting

# Format code
cargo fmt

# Check formatting
cargo fmt -- --check

Linting

# Run Clippy (Rust linter)
cargo clippy

# Fix automatically when possible
cargo clippy --fix

Documentation

# Generate and open documentation
cargo doc --open

# Document private items too
cargo doc --document-private-items --open

Comparison with Other Implementations

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)

When to Use Rust

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)

Troubleshooting

Build Errors

Problem: error: linker 'cc' not found

# Ubuntu/Debian
sudo apt-get install build-essential

# macOS
xcode-select --install

Problem: 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=1

Runtime Errors

Problem: "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 9000

Advanced Topics

Custom Crypto Parameters

Modify src/zkp/mod.rs:

fn generate_parameters(&mut self) {
    let bits = 4096;  // Use 4096-bit primes for higher security
    // ...
}

Database Connection Pooling

For production, consider using r2d2 for connection pooling:

[dependencies]
r2d2 = "0.8"
r2d2_sqlite = "0.22"

Custom Middleware

Add middleware to Actix-web server:

use actix_web::middleware::Logger;

HttpServer::new(move || {
    App::new()
        .wrap(Logger::default())
        // ... routes
})

See Also

  • 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

Contributing

When contributing to the Rust implementation:

  1. Run tests: cargo test
  2. Format code: cargo fmt
  3. Check with Clippy: cargo clippy
  4. Update documentation
  5. Keep in sync with C++ and Python APIs

License

This project was developed as POC for research purposes.

References