TenSEAL

0.3.16 · active · verified Fri Apr 17

TenSEAL (v0.3.16) is a Python library providing homomorphic encryption operations on tensors, built on Microsoft SEAL. It enables computations on encrypted data without decrypting it, enhancing privacy for machine learning and other applications. Releases are frequent, often incorporating updates from the underlying SEAL library and expanding Python version support.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up a TenSEAL context for the CKKS scheme, encrypting two vectors, performing homomorphic addition on them, and then decrypting the result. It highlights the critical steps of context initialization, key generation, and scale setting for encrypted computations.

import tenseal as ts

# 1. Setup TenSEAL Context for CKKS scheme
# These parameters are critical for security and functionality.
poly_mod_degree = 8192
coeff_mod_bit_sizes = [60, 40, 40, 60]

# Create a TenSEAL context
context = ts.context(
    ts.SCHEME_TYPE.CKKS,
    poly_mod_degree=poly_mod_degree,
    coeff_mod_bit_sizes=coeff_mod_bit_sizes
)

# Generate keys for homomorphic operations (e.g., rotations, relinearization for multiplication)
context.generate_galois_keys()
context.generate_relin_keys()

# Set the scale for CKKS scheme
# The scale defines the precision of computations.
scale = 2**40
context.global_scale = scale

# 2. Encrypt some data
vector1 = [0, 1, 2, 3, 4]
vector2 = [5, 6, 7, 8, 9]

encrypted_vector1 = ts.ckks_vector(context, vector1)
encrypted_vector2 = ts.ckks_vector(context, vector2)

# 3. Perform homomorphic operations (e.g., addition)
encrypted_sum = encrypted_vector1 + encrypted_vector2

# 4. Decrypt and verify
# The decryption operation uses the secret key from the context.
decrypted_sum = encrypted_sum.decrypt()

print(f"Original vector 1: {vector1}")
print(f"Original vector 2: {vector2}")
print(f"Encrypted sum (truncated): {decrypted_sum[:5]}") # Print first 5 elements

# Expected result: [5.0, 7.0, 9.0, 11.0, 13.0]

view raw JSON →