Skip to content

Instantly share code, notes, and snippets.

View youben11's full-sized avatar
🏠
Working from home

Ayoub Benaissa youben11

🏠
Working from home
View GitHub Profile
@youben11
youben11 / rlwe_he_scheme.py
Last active April 22, 2024 09:07
Implementation of an homomorphic encryption scheme with numpy based on the ring learning with error problem
"""A basic homomorphic encryption scheme inspired from BFV https://eprint.iacr.org/2012/144.pdf
You can read my blog post explaining the implementation details here: https://www.ayoub-benaissa.com/blog/build-he-scheme-from-scratch-python/
Disclaimer: This implementation doesn’t neither claim to be secure nor does it follow software engineering best practices,
it is designed as simple as possible for the reader to understand the concepts behind homomorphic encryption schemes.
"""
import numpy as np
from numpy.polynomial import polynomial as poly
import hnumpy as hnp
import numpy as np
weights = np.array([0.1, 0.2, 0.3, 0.4, 0.5])
bias = np.array([0.1])
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def func(x):
return sigmoid(np.dot(x, weights) + bias)
h = hnp.compile_fhe(
func,
{
'x': hnp.encrypted_ndarray(bounds=(-1, 1), shape=(5,)),
}
)
x = np.random.uniform(-1, 1, 5)
print(f"Simulation result: {h.simulate(x)}")
print(f"Plain NumPy result: {func(x)}")
ctx = h.create_context()
keys = ctx.keygen()
print(f"Encrypted computation result: {h.encrypt_and_run(keys, x)}")
x_enc= keys.encrypt(x)
res = h.run(keys.public_keys, x_enc)
print(f"Encrypted computation result: {keys.decrypt(res)}")
HIDDEN_SIZE = 100
class Model(torch.nn.Module):
def __init__(self):
super().__init__()
self.lstm = torch.nn.LSTM(input_size=300, hidden_size=HIDDEN_SIZE)
self.fc = torch.nn.Linear(HIDDEN_SIZE, 1)
self.sigmoid = torch.nn.Sigmoid()