尝试在将信息添加到腌制的字典之前对其进行加密。

huangapple go评论62阅读模式
英文:

Attempting to encrypt information before adding it to a pickled dictionary

问题

I am currently attempting to save encrypted information in a dictionary in a pickle file, that can then be accessed, decrypted and searched through later on in the code.

I have created a function to encrypt, and then dump the information in a dictionary in my pickle file. But I am getting errors saying that the argument must be a string instead of bytes. I have tried to convert it, but I continue to get the error message regardless of what I have tried.

Any help would be appreciated!

password_dictionary = {}
pickle.dump(password_dictionary, open("dictionary.pkl", 'wb'))
dictionary = "dictionary.pkl"

def encrypt_and_dump(username, password):
    f=Fernet(key)
    user_pass = (username + password)
    b_user_pass = user_pass.encode()
    encrypted_user_pass = f.encrypt(b_user_pass)
    d_encrypted_user_pass = str(encrypted_user_pass)
    with open(dictionary, 'a+') as f:
        a = {site:[d_encrypted_user_pass]}
        pickle.dump(a,f)

The error message:
尝试在将信息添加到腌制的字典之前对其进行加密。

英文:

I am currently attempting to save encrypted information in a dictionary in a pickle file, that can then be accessed, decrypted and searched through later on in the code.

I have created a function to encrypt, and then dump the information in a dictionary in my pickle file. But I am getting errors saying that the argument must be a string instead of bytes. I have tried to convert it, but I continue to get the error message regardless of what I have tried.
Any help would be appreciated!

password_dictionary = {}
pickle.dump(password_dictionary, open("dictionary.pkl", 'wb'))
dictionary = "dictionary.pkl"

def encrypt_and_dump(username, password):
    f=Fernet(key)
    user_pass = (username + password)
    b_user_pass = user_pass.encode()
    encrypted_user_pass = f.encrypt(b_user_pass)
    d_encrypted_user_pass = str(encrypted_user_pass)
    with open(dictionary, 'a+') as f:
        a = {site:[d_encrypted_user_pass]}
        pickle.dump(a,f)

The error message

尝试在将信息添加到腌制的字典之前对其进行加密。

答案1

得分: 1

你以文本模式"a+"打开文件。Pickle想要写入字节,但write()接受str

所以如果你以二进制模式"ab+"打开文件,一切应该正常工作:

with open(dictionary, 'ab+') as f:
    a = {site:[d_encrypted_user_pass]}
    pickle.dump(a,f)
英文:

You open the file in text mode "a+". Pickle wants to write bytes, but write() accepts str.

So if you open the file with binary mode "ab+", everything should work:

with open(dictionary, 'ab+') as f:
        a = {site:[d_encrypted_user_pass]}
        pickle.dump(a,f)

huangapple
  • 本文由 发表于 2023年4月17日 14:09:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032127.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定