Skip to content

robby1012/RBY-RUST-ZKP

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Zero-Knowledge Proof Authentication using Chaum-Pedersen Protocol

Rust License: MIT gRPC

A robust implementation of the Chaum-Pedersen zero-knowledge proof protocol in Rust, providing cryptographically secure authentication without revealing user secrets. This project demonstrates how users can prove knowledge of a secret to a server without ever transmitting that secret.

πŸš€ Features

  • Zero-Knowledge Authentication: Prove secret knowledge without revealing the secret
  • Chaum-Pedersen Protocol: Industry-standard discrete logarithm equality proof
  • gRPC Interface: Modern, efficient client-server communication
  • RFC 5114 Compliance: Uses standardized 2048-bit cryptographic parameters
  • Multiple Storage Backends: In-memory and Redis-backed implementations
  • Production Ready: Comprehensive error handling and security considerations

πŸ“– Table of Contents

πŸ”¬ Mathematical Background

The Chaum-Pedersen protocol allows a prover to demonstrate knowledge of a discrete logarithm x such that:

y1 = Ξ±^x (mod p)
y2 = Ξ²^x (mod p)

Where:

  • Ξ± and Ξ² are generators of a prime-order subgroup
  • p is a large prime modulus
  • q is the prime order of the subgroup
  • x is the secret known only to the prover

Security Properties

  • Completeness: Honest provers can always convince honest verifiers
  • Soundness: Malicious provers cannot convince verifiers without knowing the secret
  • Zero-Knowledge: Verifiers learn nothing about the secret beyond its existence

πŸ”„ Protocol Overview

The authentication process consists of three phases:

1. Registration Phase

Client β†’ Server: username, y1 = Ξ±^x mod p, y2 = Ξ²^x mod p

2. Challenge Phase

Client β†’ Server: r1 = Ξ±^k mod p, r2 = Ξ²^k mod p (where k is random)
Server β†’ Client: challenge c, auth_id

3. Verification Phase

Client β†’ Server: s = k - cΒ·x mod q
Server β†’ Client: session_id (if verification succeeds)

The server verifies by checking:

r1 β‰Ÿ Ξ±^s Β· y1^c mod p
r2 β‰Ÿ Ξ²^s Β· y2^c mod p

πŸ›  Installation

Prerequisites

  • Rust (1.70 or later): Install Rust
  • Protocol Buffers Compiler: Required for gRPC code generation
    # macOS
    brew install protobuf
    
    # Ubuntu/Debian
    sudo apt install protobuf-compiler
    
    # Arch Linux
    sudo pacman -S protobuf

Building from Source

# Clone the repository
git clone https://github.com/robby1012/RBY-RUST-ZKP.git
cd RBY-RUST-ZKP

# Build the project
cargo build --release

# Run tests
cargo test

Optional: Redis Setup

For the Redis-backed server:

# Install Redis
brew install redis  # macOS
sudo apt install redis-server  # Ubuntu/Debian

# Start Redis
redis-server

πŸš€ Quick Start

Option 1: Native Execution

  1. Start the server:

    cargo run --bin server
  2. Run the client (in a new terminal):

    cargo run --bin client
  3. Follow the interactive prompts to register and authenticate.

Option 2: Docker

# Build and start services
docker-compose up -d --build

# Access the container
docker exec -it zkp-server bash
cd /zkp-server/target/release

# Run the client
./client

πŸ’‘ Usage Examples

Basic Client Usage

use zkp_chaum_pedersen::ZKP;
use num_bigint::BigUint;

// Initialize cryptographic parameters
let (alpha, beta, p, q) = ZKP::get_constants();
let zkp = ZKP { alpha, beta, p, q: q.clone() };

// Generate a secret
let secret = ZKP::generate_random_number_below(&q);

// Registration: compute public values
let (y1, y2) = zkp.compute_pair(&secret);

// Authentication: generate commitment
let k = ZKP::generate_random_number_below(&q);
let (r1, r2) = zkp.compute_pair(&k);

// Receive challenge 'c' from server, then compute response
let response = zkp.solve(&k, &challenge, &secret);

// Server verifies the proof
let is_valid = zkp.verify(&r1, &r2, &y1, &y2, &challenge, &response);

gRPC Client Example

use zkp_auth::auth_client::AuthClient;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut client = AuthClient::connect("http://localhost:50051").await?;
    
    // Registration
    let request = RegisterRequest {
        user: "alice".to_string(),
        y1: y1.to_bytes_be(),
        y2: y2.to_bytes_be(),
    };
    client.register(request).await?;
    
    // Authentication challenge
    let request = AuthenticationChallengeRequest {
        user: "alice".to_string(),
        r1: r1.to_bytes_be(),
        r2: r2.to_bytes_be(),
    };
    let response = client.create_authentication_challenge(request).await?;
    
    // Submit proof
    let request = AuthenticationAnswerRequest {
        auth_id: response.auth_id,
        s: s.to_bytes_be(),
    };
    let session = client.verify_authentication(request).await?;
    
    println!("Session ID: {}", session.session_id);
    Ok(())
}

πŸ“š API Documentation

Core ZKP Functions

Function Description Usage
ZKP::get_constants() Returns RFC 5114 standardized parameters Initialization
zkp.compute_pair(exp) Computes (Ξ±^exp mod p, Ξ²^exp mod p) Registration & Challenge
zkp.solve(k, c, x) Computes s = k - cΒ·x mod q Response generation
zkp.verify(...) Verifies zero-knowledge proof Server-side verification
ZKP::generate_random_number_below(bound) Secure random generation Nonce & challenge creation

gRPC Service Methods

Method Phase Purpose
Register Registration Store user's public commitment values
CreateAuthenticationChallenge Challenge Generate and return cryptographic challenge
VerifyAuthentication Verification Verify proof and return session ID

Available Binaries

Binary Purpose Use Case
server In-memory authentication server Development, testing
server_redis Redis-backed authentication server Production, scalability
client Complete registration + login flow New user onboarding
login Authentication-only client Existing user login
client_debug Detailed protocol debugging Development, troubleshooting

πŸ”’ Security Considerations

Cryptographic Strength

  • Parameters: RFC 5114 standardized 2048-bit MODP group
  • Security Level: ~112 bits (resistant to current computational capabilities)
  • Random Generation: Cryptographically secure randomness for all nonces and challenges

Implementation Security

  • Memory Safety: Rust's ownership system prevents buffer overflows and memory corruption
  • Side-Channel Resistance: Uses constant-time operations where possible
  • Network Security: gRPC provides TLS encryption (configure for production)

Production Deployment

  • TLS Termination: Always use TLS in production environments
  • Rate Limiting: Implement authentication attempt rate limiting
  • Audit Logging: Log all authentication attempts for security monitoring
  • Key Rotation: Consider periodic rotation of system parameters

Known Limitations

  • Quantum Resistance: Not quantum-secure (like all discrete log systems)
  • Forward Secrecy: Sessions don't provide forward secrecy
  • Replay Protection: Implement timestamp-based replay protection for production

🐳 Docker Support

Development Environment

# Start all services
docker-compose up -d --build

# View logs
docker-compose logs -f

# Stop services
docker-compose down

Docker Configuration

The docker-compose.yaml includes:

  • ZKP authentication server
  • Redis instance (for server_redis variant)
  • Configured networking between services

Container Access

# Access the main container
docker exec -it zkp-server bash

# Navigate to built binaries
cd /zkp-server/target/release

# Run any client
./client        # Full registration + login
./login         # Login only
./client_debug  # Debug client

πŸ§ͺ Testing

Unit Tests

# Run all tests
cargo test

# Run tests with output
cargo test -- --nocapture

# Run specific test
cargo test test_toy_example

Integration Testing

# Start server
cargo run --bin server &

# Test with client
cargo run --bin client

# Clean up
pkill server

Test Coverage

The test suite includes:

  • βœ… Toy examples with small parameters
  • βœ… RFC 5114 parameter validation
  • βœ… Random number generation
  • βœ… Complete protocol flows
  • βœ… Error case handling

πŸ›‘ gRPC Tools & Development

gRPC Client Tools

Use gRPC Clicker VS Code extension:

  1. Install the extension
  2. Open proto/zkp_auth.proto
  3. Set server URL to localhost:50051
  4. Test all three RPC methods interactively

Protocol Buffer Schema

The service definition in proto/zkp_auth.proto includes:

  • Request/response message definitions
  • Service method signatures
  • Comprehensive documentation comments

πŸ“ˆ Performance Characteristics

Computational Complexity

Operation Time Complexity Description
Registration O(log p) Two modular exponentiations
Challenge Generation O(log p) Two modular exponentiations
Response Computation O(log q) Modular arithmetic
Verification O(log p) Four modular exponentiations

Benchmarks

On modern hardware (2023 MacBook Pro M2):

  • Registration: ~2ms
  • Challenge: ~2ms
  • Verification: ~4ms
  • Memory usage: ~50MB (server)

🀝 Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Development Setup

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Make your changes and add tests
  4. Run the test suite: cargo test
  5. Run the linter: cargo clippy
  6. Format code: cargo fmt
  7. Commit your changes: git commit -m 'Add amazing feature'
  8. Push to the branch: git push origin feature/amazing-feature
  9. Open a Pull Request

Code Style

  • Follow Rust standard formatting (cargo fmt)
  • Add comprehensive documentation for public APIs
  • Include unit tests for new functionality
  • Use meaningful commit messages

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“š References

🎯 Roadmap

  • Quantum-resistant protocol variants
  • Batch verification support
  • Mobile client libraries
  • Hardware security module (HSM) integration
  • Formal security proofs
  • Performance optimizations

Disclaimer: This implementation is for educational and research purposes. For production use, please conduct thorough security audits and consider professional cryptographic review.

About

ZKP Chaum-Pedersen Protocol Implementation using Rust

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published