无法将 'str' 对象转换为 RSA python 中的字节错误

Cannot convert 'str' object to bytes error in RSA python

我一直在使用 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

我应该如何解决这个错误

问题是加密密码的 CSV 文件“序列化”。 encpassbytes 类型,但 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)