Repository navigation
Releases
v0.2.0
zig-tfhe v0.2.0 Release Notes
Asymmetric Proxy Reencryption
Release Date: November 3, 2025
Version: 0.2.0
Breaking Changes: None
Overview
This release adds LWE-based asymmetric proxy reencryption to zig-tfhe, enabling secure delegation of encrypted data access without requiring secret key sharing. This is a major feature addition that opens up new use cases for homomorphic encryption in multi-party scenarios.
What's New in One Sentence
You can now securely transform ciphertexts from one encryption key to another without decryption, and without the recipient sharing their secret key.
New Features
1. Public Key Encryption
zig-tfhe now supports LWE-based public key encryption:
const secret_key = tfhe.key.SecretKey.new();
var public_key = try tfhe.proxy_reenc.PublicKeyLv0.new(allocator, &secret_key.key_lv0);
defer public_key.deinit(allocator);
// Anyone can encrypt with the public key
const ct = try public_key.encryptBool(true, tfhe.params.implementation.tlwe_lv0.ALPHA);
// Only the secret key owner can decrypt
const plaintext = ct.decryptBool(&secret_key.key_lv0);Performance: ~1.6ms to generate public key
2. Asymmetric Proxy Reencryption (Recommended)
Generate reencryption keys without requiring the recipient to share their secret key:
// Bob publishes his public key (safe to share)
var bob_public_key = try tfhe.proxy_reenc.PublicKeyLv0.new(allocator, &bob_key.key_lv0);
defer bob_public_key.deinit(allocator);
// Alice generates reencryption key using ONLY Bob's public key
var reenc_key = try tfhe.proxy_reenc.ProxyReencryptionKey.newAsymmetric(
allocator,
&alice_key.key_lv0,
&bob_public_key
);
defer reenc_key.deinit(allocator);
// Proxy transforms ciphertext (learns nothing about plaintext)
const bob_ct = tfhe.proxy_reenc.reencryptTLWELv0(&alice_ct, &reenc_key);Performance: ~1.7s key generation, ~1.1ms reencryption
3. Symmetric Proxy Reencryption (Fast Mode)
For trusted scenarios like single-party key rotation:
// Requires both secret keys (trusted scenario only)
var reenc_key = try tfhe.proxy_reenc.ProxyReencryptionKey.newSymmetric(
allocator,
&old_key.key_lv0,
&new_key.key_lv0
);
defer reenc_key.deinit(allocator);Performance: ~20ms key generation, ~1.1ms reencryption
4. Example Program
Run the comprehensive demonstration:
zig build proxy_reenc_demoFeatures:
- Basic asymmetric workflow
- Multi-hop chain (Alice → Bob → Carol)
- Performance measurements
- Security property demonstrations
- 100% accuracy verification
API Reference
New Module: proxy_reenc
Access via:
const proxy_reenc = @import("main").proxy_reenc;Types
PublicKeyLv0
pub const PublicKeyLv0 = struct {
pub fn new(allocator: std.mem.Allocator, secret_key: *const key.SecretKeyLv0) !PublicKeyLv0
pub fn newWithParams(allocator: std.mem.Allocator, secret_key: *const key.SecretKeyLv0, size: usize, alpha: f64) !PublicKeyLv0
pub fn encryptF64(self: *const Self, plaintext: f64, alpha: f64) !tlwe.TLWELv0
pub fn encryptBool(self: *const Self, plaintext: bool, alpha: f64) !tlwe.TLWELv0
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void
};ProxyReencryptionKey
pub const ProxyReencryptionKey = struct {
pub fn newAsymmetric(allocator: std.mem.Allocator, key_from: *const key.SecretKeyLv0, public_key_to: *const PublicKeyLv0) !ProxyReencryptionKey
pub fn newAsymmetricWithParams(allocator: std.mem.Allocator, key_from: *const key.SecretKeyLv0, public_key_to: *const PublicKeyLv0, alpha: f64, basebit: usize, t: usize) !ProxyReencryptionKey
pub fn newSymmetric(allocator: std.mem.Allocator, key_from: *const key.SecretKeyLv0, key_to: *const key.SecretKeyLv0) !ProxyReencryptionKey
pub fn newSymmetricWithParams(allocator: std.mem.Allocator, key_from: *const key.SecretKeyLv0, key_to: *const key.SecretKeyLv0, alpha: f64, basebit: usize, t: usize) !ProxyReencryptionKey
pub fn deinit(self: *Self, allocator: std.mem.Allocator) void
};Functions
pub fn reencryptTLWELv0(ct_from: *const tlwe.TLWELv0, reenc_key: *const ProxyReencryptionKey) tlwe.TLWELv0Use Cases
Enabled by This Release
-
Secure Data Sharing
- Share encrypted medical records between providers
- Delegate access to encrypted financial data
- Controlled document sharing in legal systems
-
Cloud Storage with Delegation
- Store encrypted data in cloud
- Delegate access to specific users without re-encryption
- Revoke access by rotating keys
-
Key Rotation
- Migrate encrypted data to new keys without decryption
- Update security parameters seamlessly
- Maintain encrypted backups under multiple keys
-
Multi-party Computation
- Enable collaborative work on encrypted data
- Share intermediate results securely
- Build complex encrypted workflows
-
Access Control Systems
- Implement granular access policies on encrypted data
- Time-based or conditional access delegation
- Audit trails without decryption
Performance Benchmarks
Measured on Apple Silicon (M-series):
| Operation | Time | Notes |
|---|---|---|
| Public key generation | ~1.6ms | One-time per user |
| Asymmetric key gen | ~1.7s | Use for secure delegation |
| Symmetric key gen | ~20ms | Use for key rotation |
| Reencryption | ~1.1ms | Per ciphertext transformation |
| Multi-hop (3 hops) | ~3.3ms | Without bootstrapping |
| Accuracy | 100% | Verified over 100+ iterations |
Comparison to Rust Implementation
| Operation | Rust | Zig | Zig Advantage |
|---|---|---|---|
| Public key gen | ~7ms | ~1.6ms | 4.4x faster |
| Asymmetric keygen | ~7.6s | ~1.7s | 4.5x faster |
| Symmetric keygen | ~91ms | ~20ms | 4.5x faster |
| Reencryption | ~2.5ms | ~1.1ms | 2.3x faster |
Zig's native code generation and compile-time optimizations provide significant performance advantages!
Security Properties
128-bit Post-Quantum Security
- Based on: Learning With Errors (LWE) problem
- Parameters: N=700, α=2.0e-5 (same as library default)
- Quantum resistance: Secure against known quantum algorithms
- Standard assumptions: Decision-LWE hardness
Proxy Obliviousness
The proxy can reencrypt ciphertexts without learning:
- The plaintext message
- Alice's secret key
- Bob's secret key (asymmetric mode)
Unidirectional Delegation
- Alice→Bob reencryption key ≠ Bob→Alice key
- One-way transformation only
- Prevents reverse reencryption attacks
No Secret Key Exposure (Asymmetric Mode)
- Bob only publishes public key
- Alice generates reencryption key without Bob's secret
- True non-interactive delegation
Migration Guide
Adding Proxy Reencryption to Your Project
No breaking changes - purely additive feature.
Import the Module
const tfhe = @import("main");
const proxy_reenc = tfhe.proxy_reenc;Basic Pattern
pub fn delegateAccess(
allocator: std.mem.Allocator,
alice_ct: *const tfhe.tlwe.TLWELv0,
alice_key: *const tfhe.key.SecretKey,
bob_public_key: *const proxy_reenc.PublicKeyLv0,
) !tfhe.tlwe.TLWELv0 {
// Generate reencryption key
var reenc_key = try proxy_reenc.ProxyReencryptionKey.newAsymmetric(
allocator,
&alice_key.key_lv0,
bob_public_key
);
defer reenc_key.deinit(allocator);
// Transform ciphertext
return proxy_reenc.reencryptTLWELv0(alice_ct, &reenc_key);
}Memory Management
All new types require explicit deinitialization:
var public_key = try PublicKeyLv0.new(allocator, &secret_key.key_lv0);
defer public_key.deinit(allocator); // Required!
var reenc_key = try ProxyReencryptionKey.newAsymmetric(...);
defer reenc_key.deinit(allocator); // Required!Testing
Run Proxy Reencryption Tests
# All tests
zig build test
# Proxy reencryption module only
zig test src/proxy_reenc.zig
# With summary
zig build test --summary allTest Coverage
New Tests (6 tests):
- ✅
test "public key encryption" - ✅
test "public key encryption multiple" - ✅
test "proxy reencryption asymmetric" - ✅
test "proxy reencryption symmetric" - ✅
test "proxy reencryption asymmetric multiple" - ✅
test "proxy reencryption chain asymmetric"
Results: All 86/86 tests passing (including library tests)
Example Output
Running zig build proxy_reenc_demo:
=== LWE Proxy Reencryption Demo ===
1. Setting up keys for Alice and Bob...
✓ Alice's secret key generated
✓ Bob's public key generated in 1.60ms
✓ Bob shares his public key (safe to publish)
2. Alice encrypts her data...
Messages encrypted by Alice:
- Message 1: true
- Message 2: false
- Message 3: true
- Message 4: true
- Message 5: false
3. Alice generates a proxy reencryption key (Alice -> Bob)...
Using ASYMMETRIC mode - Bob's secret key is NOT needed!
✓ Reencryption key generated in 1705.81ms
✓ Alice shares this key with the proxy
4. Proxy converts Alice's ciphertexts to Bob's ciphertexts...
✓ 5 ciphertexts reencrypted in 5.68ms
✓ Average time per reencryption: 1.14ms
5. Bob decrypts the reencrypted data...
Decrypted messages:
✓ Message 1: true (original: true)
✓ Message 2: false (original: false)
✓ Message 3: true (original: true)
✓ Message 4: true (original: true)
✓ Message 5: false (original: false)
=== Results ===
Accuracy: 5/5 ...
v0.1.1
Release Notes - v0.1.1
Release Date: October 24, 2025
Focus: Performance Optimization & Code Quality Improvements
Performance Improvements
SIMD Vectorization (+4.8% Performance)
Implemented comprehensive SIMD optimizations using Zig's @Vector type, targeting the most critical hot paths:
TLWE Operations
- Vectorized 6 core array operations:
add,sub,neg,mul,addMul,subMul - Used
Vec4<u32>for torus arithmetic operations - Impact: 2.6% overall performance improvement
TRGSW Operations
- Vectorized complex FMA (Fused Multiply-Add) in frequency domain
- Optimized
fmaInFd1024()withVec4<f64>for complex operations - Processes 4 complex numbers per iteration
FFT Operations
- Vectorized
ifft1024()twist loop (512 complex multiplications) - Vectorized
fft1024()untwist loop (512 complex conjugate multiplications) - Vectorized
poly_mul()complex multiplication - Impact: 2.3% overall performance improvement (on top of TLWE gains)
Benchmark Results
| Metric | Before | After | Improvement |
|---|---|---|---|
| Bootstrap time | 38.08 ms | 36.73 ms | 3.5% faster |
| Per-gate time | 39.20 ms | 37.31 ms | 4.8% faster |
| Full 80-gate test | 3107 ms | 2985 ms | 122 ms saved |
Gap vs Rust: Improved from 2.62x to 2.51x (4.2% closer to Rust performance)
Code Quality Improvements
Naming Conventions
- Renamed:
rayon_impl.zig→thread_pool.zig - Renamed:
RayonRailgun→ThreadPool - Rationale: "Rayon" is Rust-specific; "ThreadPool" is language-agnostic and more descriptive
Bug Fixes
- Fixed test memory deallocation errors in
trgsw.zig - Removed incorrect
defer free()calls on stack-allocated arrays - All tests now pass cleanly
Build System
- Removed temporary profiling tool (
bootstrap_profiler.zig) - Cleaned up build configuration
- Ensured optimization flags propagate correctly to all modules
Documentation
New Documentation Files
Performance Analysis
SIMD_OPTIMIZATION_RESULTS.md- Detailed TLWE & TRGSW SIMD resultsFFT_SIMD_OPTIMIZATION_RESULTS.md- Comprehensive FFT optimization analysisSIMD_VERIFICATION.md- Verification that@Vectoruses native NEON instructionsPROFILING_RESULTS.md- Initial profiling findingsPROFILING_SUMMARY.md- Executive summary
Each document includes:
- Performance metrics and benchmarks
- Code examples with before/after comparisons
- Technical analysis of optimizations
- Verification methodology
- Next steps and recommendations
Key Documentation Highlights
SIMD Verification:
- Confirmed Zig's
@Vectorcompiles to native ARM64 NEON instructions - Verified using assembly output analysis
- Explained optimal vector sizes for ARM64 (128-bit NEON registers)
Performance Analysis:
- Identified FFT as dominant bottleneck (90% of execution time)
- Documented memory profiling (zero allocations in hot path)
- Explained why gains are modest (memory bandwidth, not compute)
Technical Details
SIMD Implementation
The vectorization uses platform-agnostic Zig code that compiles to native SIMD:
const Vec4 = @Vector(4, f64);
// Process 4 elements at once
var i: usize = 0;
while (i + 4 <= array.len) : (i += 4) {
const a: Vec4 = array_a[i..][0..4].*;
const b: Vec4 = array_b[i..][0..4].*;
result[i..][0..4].* = a + b; // Compiles to NEON instructions
}Platform Support:
- ARM64: NEON instructions (verified on Apple M3)
- x86_64: SSE/AVX instructions (via LLVM backend)
- Fallback: Automatic scalar code on unsupported platforms
Optimization Strategy
- Profiled first - Used memory and time profiling to identify bottlenecks
- Targeted hot paths - Focused on FFT and TLWE operations (>95% of time)
- Maintained correctness - All optimizations verified with test suite
- Zero allocations - Confirmed no heap allocations in critical path
Testing & Verification
Test Coverage
- All existing tests pass
- Fixed 3 test memory management bugs
- Verified correctness of SIMD implementations
- Benchmark results reproducible
CI/CD
- Fixed formatting issues
- Fixed test compilation errors
- Build system cleaned up
- All checks passing
Comparison with Rust Implementation
| Implementation | Per Gate | Total (80 gates) | Relative |
|---|---|---|---|
| Rust (release) | 14.89 ms | 1191 ms | 1.0x |
| Zig v0.1.0 | 39.20 ms | 3107 ms | 2.62x |
| Zig v0.1.1 | 37.31 ms | 2985 ms | 2.51x |
Progress: Closed the gap by 4.2% (from 2.62x to 2.51x)
Future Optimization Opportunities
Based on our analysis, remaining performance gap is primarily due to:
-
FFT Algorithm (Highest Priority)
- Current: Simple radix-2 FFT
- Rust: Specialized algorithms (Split-Radix, Radix-4)
- Potential: 20-30% improvement
-
Butterfly Operations (High Priority)
- Vectorize core FFT butterfly operations
- Pre-compute twiddle factors
- Potential: 10-20% improvement
-
Cache Optimization (Medium Priority)
- Memory layout optimization
- Cache-aware blocking
- Potential: 5-10% improvement
See NEXT_STEPS.md for detailed optimization roadmap.
Breaking Changes
Renamed APIs
parallel.rayon_impl→parallel.thread_poolparallel.RayonRailgun→parallel.ThreadPoolparallel.rayonRailgun()→parallel.threadPool()
Migration: Simple find-and-replace if you're using the parallel API directly.
Build Changes
- Removed
zig build bootstrap-profilestep (temporary profiling tool) - All other build steps remain unchanged
Compatibility
- Zig Version: 0.14.0+ (tested on 0.15.1)
- Platforms: macOS (ARM64), Linux (x86_64, ARM64)
- Dependencies: No external dependencies (stdlib only)
Acknowledgments
This release focused on methodical performance optimization through:
- Careful profiling and measurement
- Evidence-based optimization decisions
- Comprehensive documentation of findings
- Maintaining code quality and correctness
The 4.8% performance improvement demonstrates that while SIMD helps, the remaining gap with Rust is primarily algorithmic - a solid foundation for future work.
Installation
# Clone the repository
git clone https://github.com/yourusername/zig-tfhe.git
cd zig-tfhe
# Build and test
zig build test
zig build add_two_numbers -Doptimize=ReleaseFastQuick Start
const tfhe = @import("main");
// Generate keys
const secret_key = tfhe.key.SecretKey.new();
var cloud_key = try tfhe.key.CloudKey.new(allocator, &secret_key);
defer cloud_key.deinit(allocator);
// Encrypt
const ct1 = try tfhe.utils.Ciphertext.encryptBool(true, alpha, &secret_key.key_lv0);
const ct2 = try tfhe.utils.Ciphertext.encryptBool(false, alpha, &secret_key.key_lv0);
// Compute homomorphically (now 4.8% faster!)
const result = try tfhe.gates.nand(&ct1, &ct2, &cloud_key);Full Changelog: https://github.com/yourusername/zig-tfhe/compare/v0.1.0...v0.1.1
What's Changed
Full Changelog: v0.1.0...v0.1.1
v0.1.0
zig-tfhe v0.1.0 Release Notes
Release Date: October 21, 2025
We're excited to announce the first official release of zig-tfhe, a high-performance Zig implementation of TFHE (Torus Fully Homomorphic Encryption)!
Overview
zig-tfhe is a comprehensive fully homomorphic encryption library that enables computation on encrypted data without decryption. This release represents a complete, production-ready port of the rs-tfhe library to Zig, bringing the power of FHE to the Zig ecosystem with performance, safety, and idiomatic Zig design.
What's New in v0.1.0
Core Cryptographic Primitives
- TLWE Encryption (Level 0): Basic torus learning with errors encryption for boolean values
- TRLWE Encryption (Level 1): Ring learning with errors over polynomial rings for higher dimensions
- TRGSW Encryption: Gadget switching keys enabling bootstrapping operations
- Bootstrapping: Noise reduction through homomorphic decryption with vanilla bootstrapping
Homomorphic Operations
Complete set of boolean logic gates:
AND,OR,NOT,XORNAND,NOR,XNORMUX(multiplexer)
All binary gates support bootstrapping to refresh noise and enable unlimited circuit depth.
Security Levels
Multiple security parameter sets to balance security and performance:
- 80-bit security - Optimized for development, testing, and performance-critical scenarios
- 110-bit security - Balanced security/performance (original TFHE reference parameters)
- 128-bit security - High security, quantum-resistant (default)
- Specialized Uint1-8 - Optimized parameter sets for multi-bit messages (1-8 bits)
Performance Optimizations
- Memory Safety: Zig's compile-time guarantees with comprehensive allocator tracking
- Native Parallelization: Ready for parallel batch operations (infrastructure in place)
Examples
- add_two_numbers: Complete demonstration of homomorphic integer addition
- Implements a 16-bit full adder circuit
- Adds two numbers (402 + 304 = 706) entirely in encrypted domain
- Uses 80 homomorphic gates (XOR, AND, OR)
- Showcases real-world FHE application
Build System & Tooling
- Clean
build.zigconfiguration with module system support - Comprehensive test suite covering all core modules
- Example executables with documented build commands
- Support for Zig 0.12.0+
Installation
git clone https://github.com/thedonutfactory/zig-tfhe
cd zig-tfhe
zig buildRequirements
- Zig 0.12.0 or later
- C compiler (for linking math libraries)
Quick Start
const std = @import("std");
const tfhe = @import("main");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const allocator = gpa.allocator();
// Generate keys
const secret_key = tfhe.key.SecretKey.new();
var cloud_key = try tfhe.key.CloudKey.new(allocator, &secret_key);
defer cloud_key.deinit(allocator);
// Encrypt
const ct_a = try tfhe.tlwe.TLWELv0.encryptBool(
true,
tfhe.params.implementation.tlwe_lv0.ALPHA,
&secret_key.key_lv0
);
const ct_b = try tfhe.tlwe.TLWELv0.encryptBool(
false,
tfhe.params.implementation.tlwe_lv0.ALPHA,
&secret_key.key_lv0
);
// Compute homomorphically
const gates_inst = tfhe.gates.Gates.new();
const result = try gates_inst.andGate(&ct_a, &ct_b, &cloud_key);
// Decrypt
const decrypted = result.decryptBool(&secret_key.key_lv0);
std.debug.print("true AND false = {}\n", .{decrypted});
}Performance Characteristics
Benchmarked on Apple M-series processors (~3-4 GHz):
| Operation | Time |
|---|---|
| Gate Operation (with bootstrap) | ~350-400ms |
| Cloud Key Generation | ~15-20 seconds |
| 16-bit Addition (80 gates) | ~30-35 seconds |
Note: Performance is dominated by bootstrapping operations, which are cryptographically necessary to maintain noise levels for continued computation.
API Modules
params- Security parameter selection and configurationkey- Secret key and cloud key generationtlwe- TLWE (Torus Learning With Errors) encryptiontrlwe- TRLWE (Ring Learning With Errors) encryptiontrgsw- TRGSW encryption for bootstrappinggates- Homomorphic logic gateslut- Programmable bootstrapping with lookup tablesfft- Fast Fourier Transform for polynomial operationsbootstrap- Noise refreshing operationsutils- Utility functions for torus operations and noise generationbit_utils- Bit manipulation and encryption helpersparallel- Parallel processing utilities
Testing
Run the full test suite:
zig build testRun specific module tests:
zig test src/gates.zig --test-filter "gates all"
zig test src/utils.zig
zig test src/key.zig --test-filter "secret key"Note: Full test suite includes cloud key generation (~30 seconds). Use test filters for faster iteration during development.
Known Limitations
- Performance: As an initial release, further FFT and bootstrapping optimizations are planned
- Parallel Operations: Batch gate infrastructure exists but not yet fully optimized
- Hardware Acceleration: SIMD optimizations (AVX, NEON) are planned for future releases
- Documentation: While all modules have inline documentation, comprehensive guides are in development
Architecture
TLWE (Level 0)
↓ (Bootstrap)
TRLWE (Level 1) ← Uses FFT for efficiency
↓
TRGSW (Gadget Decomposition)
↓
Homomorphic Gates
Key Components:
- TLWE - Basic torus LWE encryption (smaller dimension, boolean values)
- TRLWE - Ring-based LWE over polynomial rings (larger dimension, efficiency)
- TRGSW - Gadget switching keys enabling external products
- Bootstrap - Noise reduction through homomorphic decryption
Contributing
Contributions are welcome! This library is a port of rs-tfhe with Zig-specific optimizations.
Guidelines:
- Follow idiomatic Zig style (
zig fmt) - Add tests for new functionality
- Document public APIs with
///doc comments - Use proper memory management with allocators
License
MIT License - Copyright (c) 2025 The Donut Factory
See LICENSE for full details.
Acknowledgments
This library builds upon:
- TFHE - The original TFHE library and research papers
- rs-tfhe - Rust implementation that served as the reference for this port
- The broader FHE research community for advancing homomorphic encryption
Special thanks to the Zig community for excellent language design and tooling.
Related Projects
- rs-tfhe - Rust implementation with advanced optimizations
- go-tfhe - Go implementation for cloud-native deployments
- TFHE-rs - Zama's production TFHE library
Getting Help
- Issues: Report bugs or request features on GitHub Issues
- Discussions: Ask questions in GitHub Discussions
- Examples: Check the
examples/directory for working code
Changelog
v0.1.0 (October 21, 2025)
Added:
- Complete TFHE implementation with TLWE, TRLWE, TRGSW primitives
- All standard homomorphic logic gates (AND, OR, NOT, XOR, NAND, NOR, XNOR, MUX)
- Vanilla bootstrapping for noise refreshing
- Programmable bootstrapping with LUT support
- FFT implementation for efficient polynomial operations
- Multiple security levels (80-bit, 110-bit, 128-bit, Uint1-8)
- Comprehensive test suite covering all modules
add_two_numbersexample demonstrating 16-bit integer addition- Full API documentation in source files
- Build system with
build.zig - MIT license
- README with quick start guide
Infrastructure:
- Module-based architecture for clean imports
- Allocator-based memory management
- Parallel processing framework (ready for optimization)
- CI-ready structure
We're excited to see what you build with zig-tfhe! Happy encrypting! 🔐
What's Changed
New Contributors
Full Changelog: v0.0.1...v0.1.0
v0.0.1
Full Changelog: https://github.com/thedonutfactory/zig-tfhe/commits/v0.0.1