Skip to content

Instantly share code, notes, and snippets.

@phil8192
Created April 3, 2020 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phil8192/dbee55bfa1e67b75b410fd7fe6cbc99f to your computer and use it in GitHub Desktop.
Save phil8192/dbee55bfa1e67b75b410fd7fe6cbc99f to your computer and use it in GitHub Desktop.
import phe as paillier
def encrypt(pub_key, x):
"""encrypt a vector with pub_key"""
return np.array([pub_key.encrypt(v) for v in x.tolist()])
def decrypt(pri_key, x):
"""decypt a vector with pri_key"""
return np.array([pri_key.decrypt(v) for v in x])
# generate a private, public key-pair
pub_key, pri_key = paillier.generate_paillier_keypair(n_length=1024)
# add an encypted vector to clear-text number
# (result is an encypted vector)
# [101, 102, 103]
decrypt(pri_key, encrypt(pub_key, np.array([1, 2, 3])) + 100)
# multiply an ecypted vector with a clear-text number
# [100, 200, 300]
decrypt(pri_key, encrypt(pub_key, np.array([1, 2, 3])) * 100)
# add 2 encypted vectors together
# [2, 4, 6]
decrypt(pri_key, encrypt(pub_key, np.array([1, 2, 3])) + \
encrypt(pub_key, np.array([1, 2, 3])))
# perform matrix multiplcation on a clear-text vector x and encypted
# vector y. result is an encypted vector.
# [140, 100]
x = np.array([[1, 2, 3],[4, 5, 6]])
w = encrypt(pub_key, np.array([10, 20, 30]))
decrypt(pri_key, np.dot([[1, 2, 3], [3, 2, 1]], w))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment