Paillier Homomorphic Encryption Example

DISCLAIMER: This is a proof-of-concept implementation. It does not represent a remotely product ready implementation or follow proper conventions for security, convenience, or scalability. It is part of a broader proof-of-concept demonstrating the vision of the OpenMined project, its major moving parts, and how they might work together.


In [1]:
from syft.he.Paillier import KeyPair
import numpy as np

Basic Ops


In [2]:
pubkey,prikey = KeyPair().generate()

In [3]:
x = pubkey.encrypt(np.array([1.,2.,3.,4.,5.]))

In [4]:
prikey.decrypt(x)


Out[4]:
array([ 1.,  2.,  3.,  4.,  5.])

In [5]:
prikey.decrypt(x+x[0])


Out[5]:
array([ 2.,  3.,  4.,  5.,  6.])

In [6]:
prikey.decrypt(x*5)


Out[6]:
array([  5.,  10.,  15.,  20.,  25.])

In [7]:
prikey.decrypt(x+x/5)


Out[7]:
array([ 1.2,  2.4,  3.6,  4.8,  6. ])

Key SerDe


In [8]:
pubkey,prikey = KeyPair().generate()

In [9]:
x = pubkey.encrypt(np.array([1.,2.,3.,4.,5.]))

In [10]:
pubkey_str = pubkey.serialize()
prikey_str = prikey.serialize()

In [11]:
pubkey2,prikey2 = KeyPair().deserialize(pubkey_str,prikey_str)

In [12]:
prikey2.decrypt(x)


Out[12]:
array([ 1.,  2.,  3.,  4.,  5.])

In [13]:
y = pubkey2.encrypt(np.ones(5))/2

In [14]:
prikey.decrypt(y)


Out[14]:
array([ 0.5,  0.5,  0.5,  0.5,  0.5])

Value SerDe


In [15]:
import pickle

In [16]:
y_str = pickle.dumps(y)

In [17]:
y2 = pickle.loads(y_str)

In [18]:
prikey.decrypt(y)


Out[18]:
array([ 0.5,  0.5,  0.5,  0.5,  0.5])