Skip to main content

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.6.3 — self-contained C++ cryptographic core with Python bindings. Production builds use kctsb-native ASM on supported targets, CUDA/GPU Auto is enabled by default, and portable fallback paths are reserved for unsupported ABIs.
kctsb.crypto atomic primitives: AES-GCM (AES-NI), ChaCha20-Poly1305, SHA-256/512/3 (SHA-NI), HMAC, HKDF, constant-time CSPRNG, Ed25519, P-256 ECDH/ECIES, 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 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 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.bls BN254 BLS signatures with aggregate and batch verification for verifiable erasure receipts
kctsb.eft Erasure Fingerprint Tree (EFT): Merkle-based incremental erasure proofs and challenge-response audits
kctsb.abe Sahai-Waters threshold CP-ABE on BN254 with BLS-signed master-key erasure receipts
kctsb.watermark ChaCha20 fused logits bias (RFC 8439 PRF) and HMAC-SHA256 KDF for keyed tournament watermarks
kctsb.ml Encrypted ML inference (EncryptedTensor, neural network layers, pipeline)

Quick Start

pip install kctsb

Atomic Crypto Primitives

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

from kctsb.crypto import (
    AESGCM, ChaCha20Poly1305,
    Ed25519Keypair, P256Keypair,
    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)

# Ed25519 signatures and P-256 ECDH/ECIES
signer = Ed25519Keypair.generate()
signature = signer.sign(b"message")
assert Ed25519Keypair.verify(signer.public_key, b"message", signature)

alice = P256Keypair.generate()
bob = P256Keypair.generate()
assert alice.ecdh(bob.public_key) == bob.ecdh(alice.public_key)
sealed = P256Keypair.ecies_encrypt(bob.public_key, b"secret")
assert bob.ecies_decrypt(sealed) == b"secret"

Tournament watermark PRF

import numpy as np
from kctsb.watermark import chacha20_prf, fused_chacha20_logits_bias, hmac_sha256

key32 = hmac_sha256(b"master", b"layer-0")[:32]
nonce12 = b"\x00" * 12
stream = chacha20_prf(key32, nonce12, counter=0, outlen=64)
logits = np.zeros((1, 32), dtype=np.float32)
fused_chacha20_logits_bias(logits, key32, nonce12, counter_base=0, mix=0.5, device="auto")

Product Quantization Encoding

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}")

Unified Verifiable Erasure Framework (UVEF)

UVEF combines BLS aggregate signatures, Erasure Fingerprint Trees, and CP-ABE key erasure receipts. The notebook examples/unified_verifiable_erasure_demo.ipynb imports only this pip-installed package and does not require a source checkout.

import time
from kctsb import abe, bls, crypto, eft

# BLS receipt signature
sk = bls.keygen()
pk = bls.derive_pubkey(sk)
msg = b"block 7 erased"
sig = bls.sign(sk, msg)
assert bls.verify(pk, msg, sig)
assert not bls.verify(pk, b"block 8 erased", sig)

# EFT erasure proof
tree = eft.EFTTree.create(256)
tree.commit_block(7, crypto.sha256(b"sensitive block"), int(time.time()))
receipt = tree.erase_block(7, sk, signer_id="TEE-Node-A", scenario="deletion")
assert eft.EFTTree.verify_receipt(receipt, pk)

# CP-ABE threshold decrypt and master-key erasure receipt
pp, msk = abe.setup(["dept:engineering", "role:analyst", "clearance:l3"], threshold=2)
user_sk = abe.keygen(pp, msk, ["dept:engineering", "role:analyst"])
session = abe.encrypt(pp, ["dept:engineering", "role:analyst", "clearance:l3"], threshold=2)
ok, gt_bytes = abe.decrypt(pp, user_sk, session.ciphertext)
assert ok and crypto.sha3_256(gt_bytes) == session.key_bytes
key_receipt = abe.erase_master_key(msk, pp, sk, signer_id="Authority-A")
assert abe.verify_key_erasure_receipt(key_receipt, pk)

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 / macOS arm64 / Linux (x86_64, aarch64)

Platform wheels are built natively per platform — a wheel only contains its own platform's extension, so pip install kctsb never pulls in another OS's binary. If no wheel matches your platform, pip falls back to the sdist, which needs a C++20 toolchain (CMake 3.20+, Ninja).

Building a wheel (macOS / Linux)

scripts/publish_pypi.sh --wheel-only     # build this platform's wheel, verify contents
scripts/publish_pypi.sh                  # + upload (needs TWINE_PASSWORD or ~/.pypirc)

The platform tag must match the target (macosx_11_0_arm64, manylinux_2_35_*); a wrong tag produces a wheel nobody can install. The script asserts the wheel contains only this platform's binary before building/uploading, because a *.so glob otherwise happily matches another platform's extension.

On macOS the deployment target is pinned to 11.0 — without it the binary inherits the runner's SDK version and only runs on the newest macOS.

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

Release Notes

Current package version: v9.6.3. Version-specific changes are archived under ../docs/releases/; this PyPI README intentionally keeps installation, capabilities, and usage examples only.

License

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

Metadata

Release files for kctsb 9.6.5

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for kctsb 9.6.5
File Interpreter ABI Platform Actions
kctsb-9.6.5-cp314-cp314-macosx_11_0_arm64.whl CPython 3.14 CPython 3.14 macOS 11.0+ ARM64 Details for kctsb-9.6.5-cp314-cp314-macosx_11_0_arm64.whl
kctsb-9.6.5-cp312-cp312-manylinux_2_35_aarch64.manylinux_2_39_aarch64.whl CPython 3.12 CPython 3.12 Linux glibc 2.35+ ARM64, Linux glibc 2.39+ ARM64 Details for kctsb-9.6.5-cp312-cp312-manylinux_2_35_aarch64.manylinux_2_39_aarch64.whl
kctsb-9.6.5-cp312-cp312-macosx_11_0_arm64.whl CPython 3.12 CPython 3.12 macOS 11.0+ ARM64 Details for kctsb-9.6.5-cp312-cp312-macosx_11_0_arm64.whl

Total release size: 5.2 MB

Release files / kctsb-9.6.5-cp314-cp314-macosx_11_0_arm64.whl

Download URL kctsb-9.6.5-cp314-cp314-macosx_11_0_arm64.whl
Size 1.5 MB
Tags CPython 3.14 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
25370e9cc5edb799211594cc556fb72e583226c1296d05e204926cd62c83724a
BLAKE2b-256 checksum
How to use checksums
b38b3be5ea62923db5ab818b7f6a3fd3d68337a5fedc3a7a76e350fb637df18c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.9

Release files / kctsb-9.6.5-cp312-cp312-manylinux_2_35_aarch64.manylinux_2_39_aarch64.whl

Download URL kctsb-9.6.5-cp312-cp312-manylinux_2_35_aarch64.manylinux_2_39_aarch64.whl
Size 2.2 MB
Tags CPython 3.12 Linux glibc 2.35+ ARM64 Linux glibc 2.39+ ARM64
SHA-256 checksum
How to use checksums
fd008ed9d604d002043c33162e770d0c03106f468de5b224efb560954ec66d02
BLAKE2b-256 checksum
How to use checksums
39a754d4c2fc6861ec4ae74047ef3f740873fe8425aabfd3c4e93a43c08eef2a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.9

Release files / kctsb-9.6.5-cp312-cp312-macosx_11_0_arm64.whl

Download URL kctsb-9.6.5-cp312-cp312-macosx_11_0_arm64.whl
Size 1.5 MB
Tags CPython 3.12 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
3247d2e47a732b2514ce1b21c1045c2950295d937eebea43bdc6187b442acdfc
BLAKE2b-256 checksum
How to use checksums
1f07dd4e6a46298604b3a4c75a6efb8f1aa254220f8dcfcc983bf81dbd5c74b2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.14.9

Security for kctsb 9.6.5

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page