0

I am trying to encrypt values of some columns, but the encrypted values are coming out to be identical for all cells!

from cryptography.fernet import Fernet
import pandas as pd 

# already generated the key using Fernet method in a separate file. Retrieving now
file = open ("key.key", "rb")
key = file.read()
file.close ()

record = pd.read_excel("test.xlsx")

#list of columns whose values are to be encrypted 
encrypt_cols = ["IPFP APPLICATION ID","NAME OF IPFP FELLOW", "CNIC", "DATE OF BIRTH", 
                "AGE", "PRIMARY EMAIL", "PRIMARY CONTACT", "CURRENT MAILING ADDRESS", "Ticket No."]


#go inside each column
for i in range (len(encrypt_cols)):
    #go inside each row of the current column  
    for j in range (len(record)): 
        f = Fernet (key)
        #convert to string as some columns have integer based values 
        message = str(record.iloc[j, record.columns.get_loc(encrypt_cols[i])]) 
        #encrpyt the cell value after encoding it to bytes 
        encrpyted = f.encrypt (message.encode())
        #why is every encrypted message identical?
        print (encrypted)

However, when I try this method independently, just to check if the code is wrong, the encryption works!

for i in encrypt_cols: 
    f = Fernet (key)
    temp = f.encrypt (str(i).encode()) #different encryption for each string! 
    res = f.decrypt (temp) #recovers original message successfully! 
    print (res.decode())

I am unable to understand what's not going right. Can anyone help me see what I have missed?

Osaama Shehzad
  • 147
  • 1
  • 2
  • 12

1 Answers1

0

Something to do with following part of your code I guess

file = open ("key.key", "rb")
key = file.read()
file.close ()

Instead I was using

key = Fernet.generate_key()

then the encrypted values are unique.

ck22
  • 264
  • 3
  • 16
  • Oh sorry, I did not include that in the code here. I already generated the key using Fernet and stored it in a separate ```.key``` file. I am just retrieving the key back now. – Osaama Shehzad Jun 16 '20 at 14:06
  • I use Jupyter Notebook (Anaconda). Do you think Jupyter cache is messing with results? – Osaama Shehzad Jun 16 '20 at 15:00