Marian
Marian

Reputation: 5

The sum does not get decrypted

Hello I am trying to implement a program that will generate a csv file with bank transactions and will compute the total addition of the sum and then it will also compute it using homomorphic encryption but my output when doing homomorphic encryption is always encrypted. Here is the code:

import tkinter as tk
from tkinter import filedialog
import csv
import random
import time
from lightphe import LightPHE

def generate_and_write_transactions(filename, num_transactions):
    transactions = []
    for _ in range(num_transactions):
        amount_received = round(random.uniform(10, 500), 2)  
        transactions.append(("Deposit", amount_received))
    
    with open(filename, "w", newline="") as csvfile:
        csvwriter = csv.writer(csvfile)
        csvwriter.writerow(["Transaction Type", "Amount"])
        csvwriter.writerows(transactions)

def compute_total_amount():
    try:
        start_time = time.time()
        filename = "transaction_history.csv"
        total_amount = 0
        
        with open(filename, 'r') as file:
            reader = csv.reader(file)
            next(reader)  # Skip header row
            for row in reader:
                if row[0] == 'Deposit':
                    total_amount += float(row[1])
        
        end_time = time.time()
        result_label.config(text=f"Total amount (traditional computation): ${total_amount:.2f}\nTime taken: {end_time - start_time:.6f} seconds")
    except Exception as e:
        result_label.config(text="Error: " + str(e))

def compute_total_amount_homomorphic():
    try:
        start_time = time.time()
        filename = "transaction_history.csv"

        cs = LightPHE(algorithm_name="Paillier")
        
        encrypted_values = []  

        with open(filename, 'r') as file:
            reader = csv.reader(file)
            next(reader)  
            for row in reader:
                if row[0] == 'Deposit':
                    encrypted_amount = cs.encrypt(plaintext=float(row[1]))
                    encrypted_values.append(encrypted_amount)
        
        # Homomorphically add all encrypted values together
        total_encrypted_sum = encrypted_values[0]
        for encrypted_amount in encrypted_values[1:]:
            total_encrypted_sum += encrypted_amount
        
        # Decrypt the total sum
        total_sum_decrypted = cs.decrypt(total_encrypted_sum)
        
        total_sum_str = str(total_sum_decrypted)  # Represent the decrypted sum as a string
        
        end_time = time.time()
        
        result_text = f"Total amount (homomorphic encryption): {total_sum_str}\nTime taken: {end_time - start_time:.6f} seconds"
        result_label.config(text=result_text)
    except Exception as e:
        result_label.config(text="Error: " + str(e))

generate_and_write_transactions("transaction_history.csv", 10)

root = tk.Tk()
root.title("Bank Account testing")

root.geometry("400x300") 

compute_button = tk.Button(root, text="Compute Total Amount (Traditional)", command=compute_total_amount)
compute_button.pack(pady=5)

compute_homomorphic_button = tk.Button(root, text="Compute Total Amount (Homomorphic)", command=compute_total_amount_homomorphic)
compute_homomorphic_button.pack(pady=5)

result_label = tk.Label(root, text="")
result_label.pack()

root.mainloop()

Upvotes: 0

Views: 60

Answers (1)

sefiks
sefiks

Reputation: 1630

Float numbers are not invalid in LightPHE. They are converted to integers for that module. In that way, we are able to increase a ciphertext with a constant percentage.

from lightphe import LightPHE
cs = LightPHE(algorithm_name = "Paillier")

m1 = 17
c1 = cs.encrypt(m1)

# increasing something 5%
k = 1.05

# scalar multiplication - private key is not required!
c4 = k * c1

# proof of work
assert cs.decrypt(c4) == k * m1

Besides, if you set your plaintext as tensor, then you are able to restore that float number. You can skip the integer convertion with this approach.

from lightphe import LightPHE
cs = LightPHE(algorithm_name = "Paillier")

m = 1.5
c = cs.encrypt(plaintext = [m])
p = cs.decrypt(c)
assert p[0] == m

Upvotes: 0

Related Questions