OpenMined/TenSEAL (Save/Load Key & Encrypted Data @ BFV)#
[1]:
!pip install tenseal
Requirement already satisfied: tenseal in /home/hsiangjenli/miniconda3/lib/python3.12/site-packages (0.3.15)
[2]:
import tenseal as ts
from tenseal.enc_context import Context
context = Context(scheme=ts.SCHEME_TYPE.BFV, poly_modulus_degree=4096, plain_modulus=1032193)
[3]:
import base64
def save(file_name, data):
with open(file_name, "wb") as f:
data = base64.b64encode(data)
f.write(data)
def load(file_name):
with open(file_name, "rb") as f:
data = f.read()
data = base64.b64decode(data)
return data
Save Key & Encrypted Data#
[4]:
s_sk = context.serialize(save_secret_key=True)
save("secret.key", s_sk)
context.make_context_public() # Remove secret key from context
s_pk = context.serialize(save_public_key=True)
save("public.key", s_pk)
[5]:
from tenseal.tensors import BFVVector
vector = [1, 2, 3, 4, 5]
encrypted_vector = BFVVector(context, vector).data
save("encrypted_vector.data", encrypted_vector.serialize())
Load Key & Encrypted Data#
[6]:
load_sk_value = load("secret.key")
load_pk_value = load("public.key")
load_encrypted_vector_value = load("encrypted_vector.data")
[7]:
# Transform the loaded data back into context and bfvvector
load_sk_context = ts.context_from(load_sk_value)
load_pk_context = ts.context_from(load_pk_value)
load_encrypted_vector_context = ts.BFVVector.load(load_pk_context, load_encrypted_vector_value)
load_sk = load_sk_context.secret_key().data
load_pk = load_pk_context.public_key().data
load_encrypted_vector = load_encrypted_vector_context.data
[8]:
load_encrypted_vector.decrypt(load_sk)
[8]:
[1, 2, 3, 4, 5]
[9]:
(load_encrypted_vector+[1, 1, 1, 1, 1]).decrypt(load_sk)
[9]:
[2, 3, 4, 5, 6]
[10]:
load_pk_context.secret_key().data # Public Context should not contain the secret key.
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Cell In[10], line 1
----> 1 load_pk_context.secret_key().data # Public Context should not contain the secret key.
File ~/miniconda3/lib/python3.12/site-packages/tenseal/enc_context.py:262, in Context.secret_key(self)
261 def secret_key(self) -> SecretKey:
--> 262 return SecretKey(self.data.secret_key())
ValueError: the current context is public, it doesn't hold a Secret key