python - 加密文本文件中的消息,然后在 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'
编辑:犯了一个错误,意味着在最后一行解密而不是解码
解决方案
你的代码没有意义。您当然可以使用从您的密码派生的密钥来加密您的密码。但是,要解密它,您需要再次输入原始密码。如果您有此密码,则无需再次解密。您迫切需要阅读 PBKDF2 以及如何将其用于密码散列。
然后你存储加密的密码,并尝试解码它,就好像它是一个编码的字节字符串,即bytes
或bytearray
。这是没有意义的,字符编码是从字符串转换为字节,而字符解码是从字节转换为字符串(使用特定的字符集)。阅读字符编码。
错误的根源可能是您将 Fernet 实例替换为 variable 中的文件f
。使用不同命名的变量。
推荐阅读
- design-patterns - 使访问解析器树的访问者更易于维护
- html - 为什么span元素的上半部分覆盖了文字而下半部分不覆盖
- wso2 - 连接到 Azure SSO 后,在发布者 UI 中测试 API 时,API 调用不起作用
- zsh - 如何缩短powerlevel9k左提示?
- javascript - 数据表服务器端设置为真不起作用
- java - 打开文件时文件显示以只读方式打开
- wcf - .NET5 中的 WCF - 使用 IsReference=true 反序列化 DataContract 会导致空属性
- perl - 如何理解 Perl 脚本
- javascript - 两台机器之间的 UTC 日期时间不匹配
- javascript - 使用vite+vue3构建项目并导入roslibjs后报错