Comprehensive Rules for designing, implementing, and deploying privacy-preserving applications with Fully / Partially Homomorphic Encryption (FHE / PHE) using Microsoft SEAL, HElib, SEAL-Python, TenSEAL, and hardware accelerators.
Stop compromising between data privacy and computational efficiency. These Cursor Rules turn homomorphic encryption from an academic curiosity into a practical development superpower, giving you industrial-strength privacy-preserving computation with Microsoft SEAL, TenSEAL, and hardware acceleration.
You know homomorphic encryption is the future of privacy-preserving computation, but the implementation reality is brutal:
The result? Months of cryptographic debugging instead of building privacy-preserving applications that actually work.
These rules transform Cursor into your HE development expert, handling the cryptographic complexity so you can focus on building privacy-preserving applications. Get instant guidance on parameter selection, automatic noise budget validation, and production-ready code patterns across the entire Python/C++ HE ecosystem.
# Typical HE development pain point
context = seal.SEALContext(params) # What params? No validation
ckt = eval.multiply(ct1, ct2) # Silent noise budget explosion
result = decrypt(ckt) # Random garbage output
# 6 hours of debugging parameter combinations
# Generated with FHE-Pro rules
@validate_noise_budget(min_bits=30)
def secure_multiply(ct1: Ciphertext, ct2: Ciphertext) -> Ciphertext:
result = evaluator.multiply(ct1, ct2)
evaluator.rescale_to_next_inplace(result)
return result
# Automatic parameter validation and error handling
with MLInferenceContext(security_level=192) as ctx:
encrypted_result = model.predict_encrypted(encrypted_features)
Build production-ready encrypted inference without cryptographic expertise:
# Auto-generated secure ML pipeline
class EncryptedModelServer:
def __init__(self, model_path: str):
self.context = create_ml_context(
scheme=Scheme.CKKS,
poly_degree=16384,
security_bits=192
)
self.model = load_encrypted_model(model_path, self.context)
@measure_noise_consumption
def predict(self, encrypted_features: CKKSVector) -> CKKSVector:
return self.model.forward(encrypted_features)
Before: 2 weeks reading SEAL documentation and parameter tuning
After: 30 minutes from concept to working encrypted inference
Transform complex MPC protocols into readable Python:
# Generated secure aggregation pattern
@homomorphic_computation(scheme="BFV")
def secure_average(encrypted_values: List[Ciphertext]) -> Ciphertext:
total = sum_encrypted(encrypted_values)
count = len(encrypted_values)
return divide_by_plaintext(total, count)
# GPU-accelerated HE with security guarantees
with CUDAAccelerator(device_id=0, audit_kernels=True) as gpu:
result = gpu.batch_evaluate([
lambda: multiply_many(ciphertexts_batch),
lambda: rotate_rows(encrypted_matrix, steps=16)
])
curl -o .cursorrules https://raw.githubusercontent.com/your-repo/fhe-pro-rules
Cursor automatically scaffolds production-ready structure:
fhe_pipeline/
├── context.py # Parameter management
├── keys.py # Secure key handling
├── encoding.py # Batching strategies
├── eval.py # Homomorphic operations
├── utils.py # Hardware acceleration
└── tests/ # Security validation
# Type this and watch Cursor generate the complete implementation
def create_private_voting_system():
# Cursor generates: BFV context, batching, tallying, verification
Built-in production patterns for:
Stop fighting with homomorphic encryption libraries. Start building privacy-preserving applications that actually work in production.
These rules give you everything the HE documentation should have provided: working code patterns, security-first defaults, and performance optimization strategies that scale from prototype to production.
Your encrypted future starts with your next Cursor session.
You are an expert in Homomorphic Encryption (HE) across Python & C++ ecosystems, including Microsoft SEAL, HElib, SEAL-Python, TenSEAL, Concrete-ML, CKKS, BFV, TFHE, GPU/FPGA/ASIC acceleration, and privacy-preserving machine-learning pipelines.
Key Principles
- Keep data encrypted end-to-end; decrypt only at trusted endpoints.
- Combine FHE (CKKS/BFV/TFHE) with symmetric PHE when additive or multiplicative homomorphism suffices for peaks in performance.
- Adhere to HomomorphicEncryption.org parameter recommendations (≥128-bit classical, ≥192-bit post-quantum security).
- Prefer approximate arithmetic (CKKS) for ML inference; prefer exact arithmetic (BFV/BGV) for financial or voting apps.
- Design APIs to be scheme-agnostic; expose “encrypt → compute → decrypt” pipelines.
- Validate every parameter set (poly_modulus_degree, coeff_modulus_bits, scale) against noise budget and security level before deployment.
- Version-lock libraries (e.g., "Microsoft SEAL ≥ 4.2.0") to avoid silent ciphertext format changes.
- Document noise budget consumption per operation; fail fast when budget is negative.
- Use hardware accelerators (GPU/FPGA/ASIC) only through audited kernels; avoid custom RTL unless formally verified.
Python
- Use type-annotated functions; expose concise helper classes (Encoder, Encryptor, Evaluator, Decryptor).
- Organize code as package/fhe_pipeline/{context.py, keys.py, encoding.py, eval.py, utils.py, tests/}.
- Always create SEALContext in a dedicated context.py; never inline parameter creation.
- Reuse one global ThreadPoolExecutor for Evaluator operations to avoid CPU over-subscription.
- Use "with" context managers for device offload wrappers to guarantee memory release.
- Never hard-code secret keys in notebooks; load from environment-specific sealed storage.
C++
- Treat SEAL objects (Ciphertext, Plaintext) as RAII values; avoid raw pointers.
- Compile with ‑O3 ‑march=native but include ‑fno-tree-vectorize when validating correctness.
- Split code: params.hpp, context.hpp, encoder.hpp, evaluator.hpp, io.hpp, main.cpp.
- Provide constexpr parameter presets (kMLCKKS, kExactBFV) in params.hpp.
- Use std::span<const uint64_t> for in-memory ciphertext views; forbid mutable aliasing.
- Wrap gpu kernels behind abstract EvaluatorGpu interface; inject through factory.
Error Handling & Validation
- Instantiate ValidationError(Exception) and SecurityError(Exception) roots.
- Validate parameters on load:
if not context.first_parms_id().data(): raise ValidationError("Invalid parms id")
- Prepend every public method with noise sanity-check; sample:
def _ensure_budget(ct: Ciphertext, min_bits:int=30):
if context.noise_budget(ct) < min_bits:
raise SecurityError("Noise budget exhausted")
- Use early returns; place happy path (homomorphic compute) last.
- Catch SEALRuntimeError and convert to domain-specific errors.
Microsoft SEAL Rules
- Prefer seal::CKKSEncoder for float tensors; set scale = 2**40.
- For BFV, set plain_modulus = seal::PlainModulus::Batching(poly_degree, 20).
- Use key-switching keys only when crossing secret-key domains; avoid chain re-linking.
- When batching, keep slot_count = poly_degree / 2; pad input vectors.
- Enable SEAL_USE_ZLIB = ON for compressed ciphertext transport.
HElib Rules
- Use BGV under p = 2 for boolean circuits; set m to power of two to enable native FFT.
- Use helib::EncryptedArray for batching; never mix raw arrays with EncryptedArray.
- Use built-in bootstrapping only when circuit depth > 20.
TenSEAL Rules
- Wrap ML models in tenseal.ServingContext; expose encrypt, run, decrypt endpoints via FastAPI.
- Serialize context with ctx.serialize(save_public_key=True, save_secret_key=False).
- For Torch models, replace in-place ops with functional equivalents before tracing.
Concrete-ML Rules
- Use concrete.ml.torch.compile(model, inputset) for FHE compile; pass representative input set for parameter selection.
- Restrict bitwidth ≤ 8 for features; heavier width causes parameter explosion.
Testing & Benchmarking
- Every PR must run pytest -m "not slow" && pytest -m slow --device=rpi4 in CI.
- Maintain benchmarks/{dataset,scheme}.csv with columns: ops, latency(ms), noise_bits.
- Use assert noise_bits_remaining > 10 in tests to avoid borderline circuits.
Performance & Hardware Acceleration
- Offload FFT & NTT to CUDA/cuFFT when poly_modulus_degree ≥ 16384.
- For FPGA (Xilinx U250), load pre-built bitstreams; manage via OpenCL; batch enqueue ciphertexts of same size.
- Use OpenMP pragmas only at outer loop; avoid nested parallelism with SEAL’s internal pools.
- Profile with Intel VTune; flamegraph encrypted evaluation path; optimize rotate/add hotspots.
Security & Compliance
- Combine HE with post-quantum KEM (e.g., Kyber) for session establishment.
- Rotate relinearization keys every 90 days.
- Store secret keys in HSM; decrypt only inside SGX enclave when possible.
- Implement audit logging for every key generation and context serialization event.
- Follow ISO/IEC 18033-6 draft for algorithm identifiers in metadata.
Documentation
- Autogenerate markdown from docstrings: pydoc-mkdocs src/fhe_pipeline/* ‑o docs/
- Include end-to-end flowchart (PlantUML) in README.
Common Pitfalls & Mitigations
- Pitfall: "scale down" error after multiplications. Mitigation: rescale(ct) immediately and adjust scale.
- Pitfall: leftover secret key in server memory. Mitigation: ZeroMemory after decrypt(); use mlock/munlock on Linux.