-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathservercalc.py
60 lines (52 loc) · 2.04 KB
/
servercalc.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
"""Server-side calculations for Homomorphic Encryption-based Salary Prediction."""
from linmodel import LinModel
import phe as paillier
import json
def getData():
"""
Load encrypted customer data from data.json.
Returns:
dict: Encrypted data containing public key and encrypted values.
"""
with open('data.json', 'r') as file:
d = json.load(file)
data = d # Changed from data = json.loads(d)
return data
def computeData():
"""
Compute the encrypted salary prediction using linear model coefficients.
Steps:
- Load encrypted data.
- Retrieve linear model coefficients.
- Initialize the Paillier public key.
- Encrypt each feature value.
- Compute the encrypted salary by summing the products of coefficients and encrypted features.
Returns:
tuple: (encrypted_salary, public_key)
"""
# Load the encrypted customer data
data = getData()
# Retrieve linear model coefficients
mycoef = LinModel().getCoef()
# Initialize the Paillier public key
pk = data['public_key']
pubkey = paillier.PaillierPublicKey(n=int(pk['n']))
# Reconstruct encrypted numbers from stored ciphertext and exponent
enc_nums_rec = [paillier.EncryptedNumber(pubkey, int(x[0]), int(x[1])) for x in data['values']]
# Compute the encrypted salary by summing the products of coefficients and encrypted features
results = sum([mycoef[i] * enc_nums_rec[i] for i in range(len(mycoef))])
return results, pubkey
def serializeDataCompany():
"""
Serialize the computed encrypted salary and public key for the company.
Returns:
dict: Serialized data containing public key and encrypted salary values.
"""
# Compute encrypted salary and retrieve public key
results, pubkey = computeData()
encrypted_data = {}
# Store public key
encrypted_data['pubkey'] = {'n': pubkey.n}
# Store encrypted salary as ciphertext and exponent
encrypted_data['values'] = (str(results.ciphertext()), results.exponent)
return encrypted_data