Python基于Fernet实现加解密触发key格式错误问题求助
报错原因
- 选择已有密钥的场景下,通过
input()获取到的用户输入为字符串类型,Fernet实例化要求传入32位url安全的base64编码的字节类型数据,类型不匹配触发报错 - 解密场景下,输入的加密文本同样为字符串类型,
decrypt()方法要求传入字节类型参数,也会触发同类类型错误
修复后的完整代码
from cryptography.fernet import Fernet as dpsisbad question1 = input("Do You Have A Key? (yes - y and no - n)\n") if question1 == "y": key = input("Enter Your Key Here \n").encode("utf-8") # 输入字符串转字节 print(key) else: key = dpsisbad.generate_key() print("Please Keep this Key Safely.\n") print(key) dpsstalks = dpsisbad(key) question2 = input("Do You Want to Encode Or Decode The Message? (Encode = e and Decode = d)\n") if question2 == "e": gg = input("Enter the text you want to encode. \n") encoded_text = gg.encode() token = dpsstalks.encrypt(encoded_text) print(token) else: text1 = input("Enter the the encrypted text. \n").encode("utf-8") # 加密文本字符串转字节 token = dpsstalks.decrypt(text1) print(token.decode("utf-8")) # 解密结果转字符串输出更友好
注意事项
- 输入已有密钥时需要完整复制生成的密钥内容,不要遗漏字符、添加多余空格或换行
- 输入加密文本时要完整粘贴加密后输出的字节内容,不要自行修改内容
内容的提问来源于stack exchange,提问作者abhinav ranish
相关产品推荐
相关产品推荐

