Exemplo n.º 1
0
def my__mul__(self, other):
    """Multiply by an int, float, or EncodedNumber.
    If `other` is a scalar, it is first encoded to fixed-point precision of `self`"""
    if isinstance(other, paillier.EncryptedNumber):
        raise NotImplementedError('Good luck with that...')
    if isinstance(other, paillier.EncodedNumber):
        encoding = other
    else:
        int_rep = int(other * pow(paillier.EncodedNumber.BASE, -self.exponent))
        if abs(int_rep) > self.public_key.max_int:
            raise ValueError('Integer needs to be within +/- %d but got %d' %
                             (self.public_key.max_int, int_rep))
        # Wrap negative numbers by adding n
        encoding = paillier.EncodedNumber(self.public_key,
                                          int_rep % self.public_key.n,
                                          self.exponent)
    product = self._raw_mul(encoding.encoding)
    exponent = self.exponent + encoding.exponent
    unscaled_result = paillier.EncryptedNumber(self.public_key, product,
                                               exponent)
    # moving the decimal point to end up having the same number of digits to its right
    scaling_multiplier = invert(paillier.EncodedNumber.BASE**(-self.exponent),
                                self.public_key.n)
    scaled_product = unscaled_result._raw_mul(scaling_multiplier)
    return paillier.EncryptedNumber(self.public_key, scaled_product,
                                    self.exponent)
Exemplo n.º 2
0
def computeData():
    data = getData()
    mycoef = LinModel().getCoef()
    pk = data['public_key']
    pubkey = paillier.PaillierPublicKey(n=int(pk['n']))
    enc_nums_rec = [paillier.EncryptedNumber(pubkey, int(x[0], int(x[1]))) for x in data['values']]
    results = sum([mycoef[i] * enc_nums_rec[i] for i in range(len(mycoef))])
    return results, pubkey
Exemplo n.º 3
0
def load_encrypted_number(enc_number_file, pub):
    ciphertext_data = json.load(enc_number_file)
    assert 'v' in ciphertext_data
    assert 'e' in ciphertext_data

    enc = phe.EncryptedNumber(pub,
                              int(ciphertext_data['v']),
                              exponent=ciphertext_data['e'])
    return enc
Exemplo n.º 4
0
def loadAnswer():
    with open('answer.json', 'r') as file: 
    ans=json.load(file)
    answer=json.loads(ans)
    return answer

pub_key, priv_key = getKeys()
data = age, he, al, gen = [24,4,6,1]
serializeData(pub_key, data)
datafile=serializeData(pub_key, data)
with open('data.json', 'w') as file: 
    json.dump(datafile, file)

answer_file=loadAnswer()
answer_key=paillier.PaillierPublicKey(n=int(answer_file['pubkey']['n']))
answer = paillier.EncryptedNumber(answer_key, int(answer_file['values'][0]), int(answer_file['values'][1]))
if (answer_key==pub_key):
    print(priv_key.decrypt(answer))
	
Exemplo n.º 5
0
def main():

    linmodel.mainLinModel()
    servercalc.mainServerCalc()

    print(
        "Saisissez les donnees sous la forme a,b,c,d avec a,b,c et d 4 entiers"
    )
    input1 = input()

    pub_key, priv_key = cust.getKeys()
    data = []
    for i in range(4):
        print(
            input1.split(',')[i], " est chiffré par ",
            servercalc.getData().get('values')[i][0][0:12], '...')
        data.append(int(input1.split(',')[i]))
    cust.serializeData(pub_key, data)
    datafile = cust.serializeData(pub_key, data)
    with open('data.json', 'w') as file:
        json.dump(datafile, file)

    answer_file = cust.loadAnswer()
    answer_key = paillier.PaillierPublicKey(n=int(answer_file['pubkey']['n']))
    answer = paillier.EncryptedNumber(answer_key,
                                      int(answer_file['values'][0]),
                                      int(answer_file['values'][1]))
    print(priv_key.decrypt(answer))

    # Affichage

    window = Tk()
    window.title("Simulation")
    window.geometry("1920x1060")
    window.iconbitmap("hash.ico")
    window.config(background='grey')

    # premier texte

    label_title = Label(window,
                        text="Simulation",
                        font=("Courrier, 30"),
                        bg='Grey',
                        fg='white')
    label_title.grid(row=0, column=2)

    label_title = Label(window,
                        text="Chiffrement homomorphe",
                        font=("Courrier, 30"),
                        bg='Grey',
                        fg='white')
    label_title.grid(row=1, column=2)
    # second texte

    label_subtitle1 = Label(window,
                            text="① Utilisateur",
                            font=("Courrier, 25"),
                            bg='white',
                            fg='grey')
    label_subtitle1.grid(row=2, column=1)

    #troisieme texte

    label_subtitle3 = Label(
        window,
        text="Les données entrées par l'utilisateur sont :",
        font=("Courrier,25"),
        bg='grey',
        fg='white')
    label_subtitle3.grid(row=3, column=1)

    label_subtitle4 = Label(window,
                            text=data,
                            font=("Courrier,500"),
                            bg='grey',
                            fg='white')
    label_subtitle4.grid(row=4, column=1)

    label_subtitle3 = Label(window,
                            text="et sont chiffrées respectivement par :",
                            font=("Courrier,25"),
                            bg='grey',
                            fg='white')
    label_subtitle3.grid(row=5, column=1)

    label_subtitle5 = Label(
        window,
        text=servercalc.getData().get('values')[0][0][0:12] + "...",
        font=("Courrier, 25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=6, column=1)

    label_subtitle5 = Label(
        window,
        text=servercalc.getData().get('values')[1][0][0:12] + "...",
        font=("Courrier, 25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=7, column=1)

    label_subtitle5 = Label(
        window,
        text=servercalc.getData().get('values')[2][0][0:12] + "...",
        font=("Courrier, 25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=8, column=1)

    label_subtitle5 = Label(
        window,
        text=servercalc.getData().get('values')[3][0][0:12] + "...",
        font=("Courrier, 25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=9, column=1)

    label_subtitle2 = Label(window,
                            text="② Serveur externe (cloud)",
                            font=("Courrier, 25"),
                            bg='white',
                            fg='grey')
    label_subtitle2.grid(row=10, column=3)

    label_subtitle5 = Label(
        window,
        text=
        "Les coefficients donnés par l'algorithme de Machine Learning à appliqués aux données sont :",
        font=("Courrier,25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=11, column=3)

    label_subtitle5 = Label(window,
                            text=linmodel.LinModel().getCoef(),
                            font=("Courrier,25"),
                            bg='grey',
                            fg='white')
    label_subtitle5.grid(row=12, column=3)

    label_subtitle5 = Label(
        window,
        text=
        "L'opération \"coefficient i\" multiplié par  l'élément i des données chiffrées donne :",
        font=("Courrier,25"),
        bg='grey',
        fg='white')
    label_subtitle5.grid(row=13, column=3)

    label_subtitle6 = Label(window,
                            text=answer_file['values'][0][0:12] + "...",
                            font=("Courrier, 25"),
                            bg='grey',
                            fg='white')
    label_subtitle6.grid(row=14, column=3)
    #computeData()[0].ciphertext()

    label_subtitle1 = Label(window,
                            text="③ Utilisateur",
                            font=("Courrier, 25"),
                            bg='white',
                            fg='grey')
    label_subtitle1.grid(row=15, column=1)

    label_subtitle1 = Label(window,
                            text="Récupération du résultat chiffré",
                            font=("Courrier, 25"),
                            bg='grey',
                            fg='white')
    label_subtitle1.grid(row=16, column=1)

    label_subtitle1 = Label(window,
                            text="Après déchiffrement, on obtient :",
                            font=("Courrier, 25"),
                            bg='grey',
                            fg='white')
    label_subtitle1.grid(row=17, column=1)

    label_subtitle7 = Label(window,
                            text=priv_key.decrypt(answer),
                            font=("Courrier,35"),
                            bg='grey',
                            fg='white')
    label_subtitle7.grid(row=18, column=1)

    #    window.grid_rowconfigure(0, minsize=150)
    #    window.grid_rowconfigure(8, minsize=150)
    #    window.grid_rowconfigure(5, minsize=150)

    # afficher

    window.mainloop()
 def get_encrypted_number(self, pub_key, value):
     ciphertext, exponent = value["ciphertext"], value["exponent"]
     return paillier.EncryptedNumber(pub_key, int(ciphertext), int(exponent))
Exemplo n.º 7
0
    encrypted_data['values'] = [(str(x.ciphertext()), x.exponent)
                                for x in encrypted_data_list]
    serialized = json.dumps(encrypted_data)
    return serialized


def loadAnswer():
    '''This function is intended to load the encrypted data coming from the server.'''

    with open('answer.json', 'r') as file:
        ans = json.load(file)
        answer = json.loads(ans)
        return answer


pub_key, priv_key = getKeys()
data = age, he, al, gen = [24, 4, 6, 1]
serializeData(pub_key, data)
datafile = serializeData(pub_key, data)
with open('data.json', 'w') as file:
    json.dump(datafile, file)

answer_file = loadAnswer()
answer_key = paillier.PaillierPublicKey(n=int(answer_file['pubkey']['n']))
answer = paillier.EncryptedNumber(answer_key, int(answer_file['values'][0]),
                                  int(answer_file['values'][1]))

# Decrypted Result
if (answer_key == pub_key):
    print(priv_key.decrypt(answer))
Exemplo n.º 8
0
def query_pred(feature_vector):
    encrypted_vector = encrypt_vector(feature_vector)
    response = requests.post('http://hw7prediction:8000/prediction', json={'pub_key_n': pubkey.n, 'enc_feature_vector': encrypted_vector})
    prediction = paillier.EncryptedNumber(pubkey, response.json()['enc_prediction'], exponent=-8)
    decrypted_prediction = decrypt_value(prediction)
    return decrypted_prediction
Exemplo n.º 9
0
 def get_encrypted_number(self, public_key, value):
     ciphertext, exponent = value['ciphertext'], value['exponent']
     return paillier.EncryptedNumber(public_key, int(ciphertext),
                                     int(exponent))