-
-
Notifications
You must be signed in to change notification settings - Fork 64
/
7_serialization.py
73 lines (55 loc) · 1.92 KB
/
7_serialization.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
from seal import *
import pickle
import time
def get_seal():
parms = EncryptionParameters(scheme_type.ckks)
poly_modulus_degree = 8192
parms.set_poly_modulus_degree(poly_modulus_degree)
parms.set_coeff_modulus(CoeffModulus.Create(poly_modulus_degree, [60, 40, 40, 60]))
scale = 2.0 ** 40
context = SEALContext(parms)
ckks_encoder = CKKSEncoder(context)
slot_count = ckks_encoder.slot_count()
keygen = KeyGenerator(context)
public_key = keygen.create_public_key()
secret_key = keygen.secret_key()
encryptor = Encryptor(context, public_key)
# evaluator = Evaluator(context)
decryptor = Decryptor(context, secret_key)
data = [3.1415926] * slot_count
plain = ckks_encoder.encode(data, scale)
cipher = encryptor.encrypt(plain)
return cipher, context, ckks_encoder, decryptor
def serialization_example():
print('serialization example')
print('-' * 70)
cipher2, context2, ckks_encoder2, decryptor2 = get_seal()
cipher2.save('cipher2.bin')
print('save cipher2 data success')
time.sleep(.5)
cipher3 = Ciphertext()
cipher3.load(context2, 'cipher2.bin')
print('load cipher2 data success')
plain3 = decryptor2.decrypt(cipher3)
data3 = ckks_encoder2.decode(plain3)
print(data3)
print('-' * 70)
def pickle_example():
print('pickle example')
print('-' * 70)
cipher1, context1, ckks_encoder1, decryptor1 = get_seal()
with open('cipher1.bin', 'wb') as f:
pickle.dump(cipher1.to_string(), f)
print('write cipher1 data success')
time.sleep(.5)
with open('cipher1.bin', 'rb') as f:
temp = pickle.load(f)
cipher2 = context1.from_cipher_str(temp)
plain2 = decryptor1.decrypt(cipher2)
data = ckks_encoder1.decode(plain2)
print('read cipher1 data success')
print(data)
print('-' * 70)
if __name__ == "__main__":
serialization_example()
pickle_example()