0

I ma writing a simple "write_csv-row' and "read_csv_row" functions that encrypts part of the row and then uses the un-encrypted part (email) to identify the row, decrypt it and check in password is correct.

The "write" function works, but it appears I cannot decode it. I thought it is because my "read" function regenerate the key, but it seems that it uses the same one that is stored?

still getting a "cryptography.fernet.InvalidToken" error.

Here's the code:

import csv
import os
import base64
from cryptography.fernet import Fernet

# Generate a random secret key
secret_key = Fernet.generate_key()

# Write a function to encrypt data using the secret key
def encrypt_data(data):
  fernet = Fernet(secret_key)
  encrypted_data = fernet.encrypt(bytes(data, 'utf-8'))
  return encrypted_data

def write_csv_row(data):
  # Open the CSV file in append mode
  with open('user_data.csv', 'a', newline='') as csv_file:
    writer = csv.writer(csv_file)
    # Write the first two rows (Name and Email Address) unencrypted
    unencrypted_data = [data[0], data[1]]
    # Encrypt the remaining rows and write them to the file
    encrypted_data = [encrypt_data(str(item)) for item in data[2:]]
   # Combine the unencrypted and encrypted data into a single row
    combined_data = unencrypted_data + encrypted_data
    # Write the combined data to the file
    writer.writerow(combined_data)

# Write a function to read a row of data from the CSV file based on email and password
def read_csv_row(email, password):
  # Open the CSV file in read mode
  with open('user_data.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    # Read each row from the file
    for row in reader:
      # Check if the email address in the second column matches the specified email
      if row[1] == email:
        # Decrypt the password using the secret key
        fernet = Fernet(secret_key)
        decrypted_password = fernet.decrypt(row[2]).decode('utf-8')
        # Check if the decrypted password matches the specified password
        if decrypted_password == password:
          # Decrypt the rest of the row using the secret key
          decrypted_row = [row[0], row[1]] + [fernet.decrypt(item).decode('utf-8') for item in row[3:]]
          return decrypted_row

# Write some example data to the CSV file
write_csv_row(['Alice', 'alice@example.com', 'password123', 'Pro', '1234 5678 9012 3456', '01/23', '123', '123 Main St', '', 'New York', 'NY', '12345', 'USA', 'high', 'active', 'diversified', 'Exchange A', 'public_key_123', 'private_key_456'])

# Read the first row of data from the CSV file
row = read_csv_row('alice@example.com', 'password123')
print(row)

Looked on here for answers but it didn't help.

  • `secret_key = Fernet.generate_key()` --- For decryption you must use the exact same key as you used to encrypt. You can't generate a new random and use it for decryption. – President James K. Polk Jan 10 '23 at 02:17

0 Answers0