-
Notifications
You must be signed in to change notification settings - Fork 0
/
arithmatic-op-nufhe.py
74 lines (61 loc) · 2.03 KB
/
arithmatic-op-nufhe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import random
import nufhe
def fixSizeBoolList(decimal,size):
x = [int(x) for x in bin(decimal)[2:]]
x = list(map(bool, x))
x = [False]*(size - len(x)) + x
return x
# in subtraction, ciX have to be greater than ciY
def subtract(ciX, ciY):
for i in range(size):
ciXnotTemp = ciX
a = vm.gate_and(vm.gate_not(ciX), ciY)
ciX = vm.gate_xor(ciX, ciY)
aShiftTemp = a
aShiftTemp.roll(-1, axis=-1)
ciY = aShiftTemp
return ciX
def checkSubtract(sub1,sub2):
if sub1 > sub2:
return sub2
else :
return sub1
def add(ciX, ciY):
# fixed iteration since
for i in range(size):
a = vm.gate_and(ciX, ciY)
b = vm.gate_xor(ciX, ciY)
aShiftTemp = a
# using roll as a shift bit
aShiftTemp.roll(-1, axis=-1)
ciX = aShiftTemp
ciY = b
return b
def boolListToInt(bitlists):
out = 0
for bit in bitlists:
out = (out << 1) | bit
return out
### testing ###
ctx = nufhe.Context()
secret_key, cloud_key = ctx.make_key_pair()
# size even decimal only
size = 32
# test decimal number. bits lenght need to be less than size/2
deci_x = 3093
deci_y = 1999
x = fixSizeBoolList(deci_x,size)
print(x)
y = fixSizeBoolList(deci_y,size)
print(y)
ciX = ctx.encrypt(secret_key, x)
ciY = ctx.encrypt(secret_key, y)
vm = ctx.make_virtual_machine(cloud_key)
# subtraction have to be done twice since we don't know which one is grater than the other
subXthenY = ctx.decrypt(secret_key, subtract(ciX, ciY))
subYthenX = ctx.decrypt(secret_key, subtract(ciY, ciX))
# the Lesser subtraction result is the right one, this have to be done after decrypting themessage
plainSubtractNumber = checkSubtract(boolListToInt(subXthenY),boolListToInt(subYthenX))
print("reference subtract number is : ", (deci_x-deci_y) ,"/ nuFHE subtract number is : ", plainSubtractNumber)
plainAddNumber = ctx.decrypt(secret_key, add(ciX, ciY))
print("reference add number is : ", (deci_x+deci_y) ,"/ nuFHE subtract number is : ", boolListToInt(plainAddNumber))