# TenSEAL库：

TensSEAL是一个python的第三方库，是一个方便的同态加密库。他并不是一个原生库，而是Microsoft SEAL（一个C++库）的python接口。实现了BFV和CKKS两种同态加密算法，可以直接对tensor进行加密，隐藏了很多具体细节，可以很容易上手编写同态加密的代码。是一款新手友好性的同态加密库。

``pip install tenseal``

# 公钥与私钥

``````import tenseal as ts

ctx=ts.context(ts.SCHEME_TYPE.BFV,poly_modulus_degree=4096,plain_modulus=1032193)
if ctx.is_private():
print("This context is private!")
if ctx.is_public():
print("This context is public!")``````

TenSEAL中定义了一个context的对象用于封装加解密所需要的参数，里面包含了密钥。在导入tenseal包之后，就可以实例化一个context对象，输入需要的参数来生成公钥和私钥了。

``````sk=ctx.secret_key()
ctx.make_context_public()
if ctx.is_private():
print("This context is private!")
if ctx.is_public():
print("This context is public!")``````

# BFV加解密的简单演示

``````m1=[1,2,3,4,5]
m2=[5,4,3,2,1]

c1=ts.bfv_vector(ctx,m1)
c2=ts.bfv_vector(ctx,m2)

print("m1 is ",c1.decrypt(sk))
print("m2 is ",c2.decrypt(sk))``````

``````#homomorphic addition
c3=c1+c2
print("The sum is ",c3.decrypt(sk))

#homomorphic scale
c4=2*c1
print("2 times of m1 is ",c4.decrypt(sk))

#homomorphic multiplication
c5=c1*c2
print("The product is ",c5.decrypt(sk))``````

``````import tenseal as ts

ctx=ts.context(ts.SCHEME_TYPE.BFV,poly_modulus_degree=4096,plain_modulus=1032193)
if ctx.is_private():
print("This context is private!")
if ctx.is_public():
print("This context is public!")

sk=ctx.secret_key()
ctx.make_context_public()
if ctx.is_private():
print("This context is private!")
if ctx.is_public():
print("This context is public!")

m1=[1,2,3,4,5]
m2=[5,4,3,2,1]

c1=ts.bfv_vector(ctx,m1)
c2=ts.bfv_vector(ctx,m2)

print("m1 is ",c1.decrypt(sk))
print("m2 is ",c2.decrypt(sk))

c3=c1+c2
print("The sum is ",c3.decrypt(sk))

#homomorphic scale
c4=2*c1
print("2 times of m1 is ",c4.decrypt(sk))

#homomorphic multiplication
c5=c1*c2
print("The product is ",c5.decrypt(sk))
``````

THE END

)">