0

我正在尝试加密某些列的值,但所有单元格的加密值都相同!

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)

但是,当我独立尝试这种方法时,只是为了检查代码是否错误,加密有效!

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())

我无法理解出了什么问题。谁能帮我看看我错过了什么?

4

1 回答 1

0

我猜想与您的部分代码有关

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

相反,我正在使用

key = Fernet.generate_key()

那么加密的值是唯一的。

于 2020-06-16T14:00:05.667 回答