代码之家  ›  专栏  ›  技术社区  ›  Abhijeet

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

  •  0
  • Abhijeet  · 技术社区  · 3 年前

    我一直在使用 rsa公司 python库对数据进行加密和解密,一切正常。 但是,当我使用将加密数据保存到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
    

    我应该如何修复此错误

    0 回复  |  直到 3 年前
        1
  •  3
  •   Marcel Gohsen    3 年前

    问题是加密密码的CSV文件的“序列化”。 encpass 属于类型 bytes 但是Pandas将文本字符串表示写入CSV文件。因此,熊猫也会将此作为字符串读回( "b'$\\xaa...'" )它看起来与bytes对象相似。

    如果您想将密码写入文件,我建议您使用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)