首页 > 解决方案 > 加密文本文件中的消息,然后在 python 中解密?

问题描述

我正在尝试加密密码,将该密码存储在一个文本文件中,然后我将检索该加密密码并在 python 中解密它。我已经使加密工作,并将其存储在文本文件中,但是当再次尝试解密时,它说:

AttributeError:“str”对象没有属性“decode”。我将我认为以字节为单位的加密消息复制并粘贴到文本文件中,所以我不确定如何解密它。

salt = b'salt123'
kdf = PBKDF2HMAC(
    algorithm=hashes.SHA256(),
    length=32,
    salt=salt,
    iterations=100000,
    backend=default_backend()
)

test_password = 'test123'.encode()
key = base64.urlsafe_b64encode(kdf.derive(test_password))
f = Fernet(key)
encrypted = f.encrypt(test_password) #This is the encrypted password which I copy and pasted into the text file

password = []
f = open("Passwords.txt", "r")
if f.mode == 'r':
    for line in f:
        password.append(line)
f.close()

#password[2] is the encrypted password 
decrypted_pass = f.decrypt(password[2]) #Error AttributeError: 'str' object has no attribute 'decode'

编辑:犯了一个错误,意味着在最后一行解密而不是解码

标签: pythonfileencryption

解决方案


你的代码没有意义。您当然可以使用从您的密码派生的密钥来加密您的密码。但是,要解密它,您需要再次输入原始密码。如果您有此密码,则无需再次解密。您迫切需要阅读 PBKDF2 以及如何将其用于密码散列。

然后你存储加密的密码,并尝试解码它,就好像它是一个编码的字节字符串,即bytesbytearray。这是没有意义的,字符编码是从字符串转换为字节,而字符解码是从字节转换为字符串(使用特定的字符集)。阅读字符编码。

错误的根源可能是您将 Fernet 实例替换为 variable 中的文件f。使用不同命名的变量。


推荐阅读