我一直在使用rsa python 庫來加密和解密資料,一切正常。但是,當我使用pandas將加密資料保存到 CSV 檔案時,如果嘗試通過從 CVS 檔案中提取保存的資料值來解密保存的資料值,則它不再起作用
下面是我的python代碼
import rsa
import pandas as pd
key = int(input("enter an interger key value : ")) #512
paasword = input("input pass : ")
publicKey, privateKey = rsa.newkeys(key)
encpass = rsa.encrypt(paasword.encode(),publicKey)
print("\noriginal string: ", paasword)
print("\nencrypted string: ", encpass)
# Save to New CSV file
data={'Name':['Jhon'], 'Password':[encpass], } #new dict
df = pd.DataFrame(data) # create new pandas DataFrame
df.to_csv('my_data.csv', index=False) # write a new csv file
# Extract form CSV file
df = pd.read_csv("my_data.csv",index_col = 0) #using 0th column (Name) as index
find_password = df['Password']['Jhon'] #column id , index of that row;
print(find_password)
decpass = rsa.decrypt(find_password, privateKey).decode()
print("\ndecrypted string: ", decMessage)
> enter an integer key value: 512
> input pass: abhijeetbyte123
> original string: abhijeetbyte123
> encrypted string: b',.\x89\xb8&"\xdc|\x97.................................
> error : TypeError: cannot convert 'str' object to bytes
我應該怎么做才能解決這個錯誤
uj5u.com熱心網友回復:
問題是加密密碼的 CSV 檔案的“序列化”。encpass是型別bytes,但 Pandas 將文字字串表示形式寫入 CSV 檔案。因此,Pandas 也會將其作為字串 ( "b'$\\xaa...'") 讀回,該字串看起來僅類似于位元組物件。
如果您想將密碼寫入檔案,我建議您使用 base64 對其進行編碼并創建一個 UTF-8 字串表示形式。單獨的 UTF-8 很可能會為(偽)隨機位元組流產生編碼錯誤。
import rsa
from base64 import b64encode, b64decode
import pandas as pd
key = int(input("enter an interger key value : ")) #512
paasword = input("input pass : ")
publicKey, privateKey = rsa.newkeys(key)
encpass = rsa.encrypt(paasword.encode(),publicKey)
print("\noriginal string: ", paasword)
print("\nencrypted string: ", encpass)
# Encode encrypted password to base64 and produce UTF-8 conform string
b64_enc_pass = b64encode(encpass).decode()
# Save to New CSV file
data={'Name':['Jhon'], 'Password':[b64_enc_pass], } #new dict
df = pd.DataFrame(data) # create new pandas DataFrame
df.to_csv('my_data.csv', index=False) # write a new csv file
# Extract form CSV file
df = pd.read_csv("my_data.csv",index_col = 0) #using 0th column (Name) as index
find_password = df['Password']['Jhon'] #column id , index of that row;
# Decode encrypted password from UTF-8 encoded string
find_password = b64decode(find_password.encode())
print(find_password)
decpass = rsa.decrypt(find_password, privateKey).decode()
print("\ndecrypted string: ", decpass)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/464386.html
