Skip to main content

High-performance cryptographic library — HE (CKKS/BFV/BGV), DP, PSI/PIR, VOPRF, SSS, MPC, PQ encoding, and encrypted ML inference. C++ core with Python bindings.

Project description

kctsb — Knight's Cryptographic Trusted Security Base

High-performance cryptographic library with Python bindings for homomorphic encryption, differential privacy, private set intersection, PIR, MPC, Product Quantization (PQ) encoding, and encrypted ML inference.

C++ core + pybind11 bindings → native Python speed

Features

Module Description
kctsb v9.0.1 — production primitive completion and performance-stability release with real ZK/BN254, fixed-limb FHE CRT fallback, MPC, ML-DSA hardening, and SM3 batch dispatch on top of the v9.0.0 CSPRNG baseline
kctsb.crypto v8.6.9 — atomic primitives: AES-GCM (AES-NI), ChaCha20-Poly1305, SHA-256/512/3 (SHA-NI), HMAC, HKDF, constant-time CSPRNG, secure_compare, token_bytes, token_hex; hand-written PEP 561 type stubs for all public symbols
kctsb.ckks CKKS approximate homomorphic encryption (encode, encrypt, add, multiply, rotate)
kctsb.bfv BFV scale-invariant FHE for integer arithmetic
kctsb.bgv BGV leveled homomorphic encryption with Galois rotations
kctsb.dp Differential privacy (Laplace, Gaussian mechanisms, budget tracking)
kctsb.psi v9.0.1 — Private Set Intersection with domain-separated SHA-256 tokens, constant-time token equality, CSPRNG sampling, and PIR provider-unavailable paths that fail closed with security-policy errors instead of plaintext fallback
kctsb.pir Private Information Retrieval (FHE-based, BGV/BFV/CKKS)
kctsb.ecc_blind_sign Clause Blind Schnorr signatures (FPS20) — ROS-resistant unlinkable tokens, public verifiable, AGM+ROM secure
kctsb.voprf RFC 9497 VOPRF (P256-SHA256, OPRF/VOPRF/POPRF modes) — deterministic blinded PRF
kctsb.sss Shamir's Secret Sharing (GF(2^8), information-theoretic security)
kctsb.mpc Secure MPC primitives and benchmarks (Rep3 batch secret sharing, Half-Gates GC)
kctsb.encode v8.6.9 — Product Quantization training, encoding, decoding, ADC lookup, and ADC top-k for private vector query search (PVQS)
kctsb.hcc Homomorphic Confidential Computing (6 privacy scenarios)
kctsb.upsi Unbalanced PSI + Symmetric Searchable Encryption
kctsb.core Hardware acceleration detection (AVX2/AVX512/AES-NI/CUDA)
kctsb.ml Encrypted ML inference (EncryptedTensor, neural network layers, pipeline)

Quick Start

pip install kctsb

Atomic Crypto Primitives (v8.6.9)

Hardware-accelerated primitives (AES-NI / SHA-NI). Requires Python 3.10+.

from kctsb.crypto import (
    AESGCM, ChaCha20Poly1305,
    sha256, sha512, sha3_256,
    hmac_sha256, hmac_sha512, hkdf_sha256,
    random_bytes, random_uint32, random_uint64, random_range,
    secure_compare, token_bytes, token_hex,
)

# AES-256-GCM (AES-NI accelerated)
key = AESGCM.generate_key(256)     # bit length
nonce = random_bytes(12)
aead = AESGCM(key)
ct = aead.encrypt(nonce, b"hello", b"aad")
pt = aead.decrypt(nonce, ct, b"aad")

# SHA-NI accelerated hashing
digest = sha256(b"payload")         # 32-byte bytes
tag    = hmac_sha256(key, b"msg")   # 32-byte bytes

# Constant-time CSPRNG (platform RtlGenRandom / getrandom)
secret = token_bytes(32)
hexstr = token_hex(16)

# HKDF-SHA256
okm = hkdf_sha256(ikm=secret, salt=b"salt", info=b"context", length=64)

Product Quantization Encoding (v8.6.9)

Compress high-dimensional feature vectors into compact PQ codes and run ADC top-k search. This module is designed for PVQS-style private vector retrieval pipelines where the online private query only carries compact candidate/key handles.

import numpy as np
from kctsb import encode

vectors = np.random.default_rng(20260508).normal(size=(4096, 512)).astype(np.float32)
query = vectors[0]

codebooks = encode.train_pq(vectors, subquantizers=32, centroids=64, max_iterations=8)
codes = encode.encode_pq(vectors, codebooks)
lookup = encode.adc_lookup(query, codebooks)
indices, distances = encode.adc_topk(codes, lookup, top_k=10)

CKKS Homomorphic Encryption

from kctsb import CKKSContext

ctx = CKKSContext(poly_modulus_degree=8192, coeff_modulus_levels=5, scale_bits=40)
sk = ctx.keygen()
pk = ctx.public_key(sk)

pt = ctx.encode([1.0, 2.0, 3.0])
ct = ctx.encrypt(pk, pt)
ct_sum = ctx.add(ct, ct)
result = ctx.decrypt_decode(sk, ct_sum)
print(result[:3])  # [2.0, 4.0, 6.0]

Differential Privacy

from kctsb.dp import DPMechanism, DPBudget

noise = DPMechanism.laplace(sensitivity=1.0, epsilon=0.1)
noisy_data = DPMechanism.add_noise([1.0, 2.0, 3.0], sensitivity=1.0, epsilon=0.1)

budget = DPBudget(total_epsilon=1.0)
budget.consume(0.1)
print(f"Remaining ε: {budget.remaining_epsilon}")

Private Set Intersection

from kctsb._kctsb_core import psi

client_set = list(range(1, 101))
server_set = list(range(50, 151))
piano = psi.PianoPSI()
result = piano.compute(client_set, server_set)
print(f"Intersection size: {len(result.intersection)}")

Multi-Party Computation (MPC)

The Python package now exposes kctsb.mpc for secure MPC primitives and performance benchmarking. Use this module to access Rep3 batch secret sharing APIs and Half-Gates garbled-circuit benchmarks directly from Python.

Shamir's Secret Sharing

from kctsb._kctsb_core import sss

secret = b"my_secret_key_32bytes_long!!!!!"
shares = sss.ShamirSSS.split(secret, threshold=3, num_shares=5)
recovered = sss.ShamirSSS.reconstruct(shares[:3], len(secret))
assert recovered == secret

Hardware Detection

from kctsb._kctsb_core import core

hw = core.detect_hardware()
print(f"AVX2: {hw['avx2']}, AES-NI: {hw['aes_ni']}, CUDA: {hw['cuda']}")
core.print_status()

Building from Source

Developers with the full kctsb source tree can build locally:

# Windows (PowerShell)
cd kctsb
.\scripts\build_python.ps1

# Or manually:
$env:PATH = "C:\msys64\mingw64\bin;$env:PATH"
cmake -B build_release -G Ninja -DCMAKE_BUILD_TYPE=Release -DKCTSB_BUILD_PYTHON=ON
cmake --build build_release --parallel 16
pip install ./python

Requirements

  • Python 3.10+
  • NumPy >= 1.24
  • Windows x64 (pre-built), Linux/macOS (build from source)

Optional Dependencies

pip install kctsb[ml]   # + torch, transformers for encrypted ML
pip install kctsb[dev]  # + pytest, build, twine for development
pip install kctsb[all]  # Everything

Changelog

v9.0.1 (2026-05)

  • Completed production primitive hardening for Groth16/QAP, BN254 Fp2/G2/Fp12 paths, BFV/BGV CRT decryption, SPDZ2k 104-bit MACs, ML-DSA signing/verification, NTT cache synchronization, and CKKS real rescale benchmark paths.
  • Replaced BFV/BGV decrypt fallback dynamic big-integer reconstruction with fixed-limb CRT using the unified 128-bit arithmetic policy, while preserving the BEHZ RNS-native hot path.
  • Added public kctsb_sm3_batch() coverage through the C API and benchmark suite; GPU auto-dispatch uses a real loaded CUDA provider only, otherwise AVX2/CPU fallback remains deterministic.
  • PIR CUDA/preprocessing provider-unavailable paths now fail closed with security-policy semantics, because plaintext index fallback is unsafe.
  • Removed deterministic emergency ML-DSA signatures and local placeholder proof/circuit paths where a secure implementation is available.
  • Verified Release and Debug CTest suites: 469/469 tests passed in both configurations.

v9.0.0 (2026-05)

  • Hardened project-wide randomness paths to use kctsb platform CSPRNG for HCC blinding/DP noise, MPC MAC checks/triples/shares, ZK scalar sampling, SSE/OPE key and range sampling, and FHE C ABI RNG seeding.
  • Verified Debug and Release CMake presets with KCTSB_WARNINGS_AS_ERRORS=ON and synchronized C++/pybind11/PyPI version metadata.
  • Updated publishing validation for major-version release-note archives such as docs/releases/V9Release/v9.0.0-release.md.

v8.6.10 (2026-05)

  • Hardened PSI/PIR providers with domain-separated SHA-256 tokens and constant-time token/hash equality.
  • Replaced PSI sampling and OT seed generation paths with platform CSPRNG calls.
  • Removed plaintext CUDA/preprocessing PIR fallbacks; unavailable providers now fail closed.

v8.6.9 (2026-05)

  • Added kctsb.encode Product Quantization primitives for PVQS: PQ training, batch encode/decode, ADC lookup, and ADC top-k.
  • Added PEP 561 type hints for kctsb.encode and refreshed blind-signature stubs to match the P-256 pybind11 API.
  • Added PVQS notebook and protocol design documentation for low-communication private theme/resource retrieval.

v8.6.6 (2026-04)

  • Breaking: removed _hashlib / _hmac compat shim objects from kctsb.crypto. Use sha256, hmac_sha256, token_bytes etc. directly.
  • Added hand-written PEP 561 type stubs (*.pyi) for all public symbols in kctsb.crypto, kctsb.ckks, kctsb.dp, kctsb.sss and all _kctsb_core sub-modules.
  • Secure RAG demo: Phase 0 bootstrap and corpus loader extracted to standalone helper modules.

License

Apache-2.0 — Copyright (c) 2019-2026 knightc

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

kctsb-9.0.1-cp312-cp312-win_amd64.whl (2.3 MB view details)

Uploaded CPython 3.12Windows x86-64

File details

Details for the file kctsb-9.0.1-cp312-cp312-win_amd64.whl.

File metadata

  • Download URL: kctsb-9.0.1-cp312-cp312-win_amd64.whl
  • Upload date:
  • Size: 2.3 MB
  • Tags: CPython 3.12, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.4

File hashes

Hashes for kctsb-9.0.1-cp312-cp312-win_amd64.whl
Algorithm Hash digest
SHA256 7e45e018eadf63881f7df557336872db45a64451fa0287efb81144cb7524c72a
MD5 9e283c662936489f3ea5a8a037646eca
BLAKE2b-256 bd7310db30913d5084394b7df151213f4bee3457d41601f73ab5de47a34e2579

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page