使用Cryptography Fernet解密失败:Invalid Token错误求助
解密时"invalid token"错误的解决方案
问题出在加密内容的写入方式上:你把加密后的字节对象用str()转成字符串写入,这会给令牌套上b''的外壳(比如原本的b'gAAAAAB...'变成了"b'gAAAAAB...'")。读取时再encode,得到的是b"b'gAAAAAB...'",这根本不是合法的Fernet令牌,自然会报"invalid token"。
修正后的代码
from cryptography.fernet import Fernet key = b'Sw42CeEyZCyRyct0Ly2loEga9D4iv6tF0WRiTLKVdDA=' fkey = Fernet(key) def add(): app = input("enter app name ").upper() name = input("enter account name ") password = input("enter account password ") with open("passwords2.txt", 'a') as f: original = "{}: {} | {} ".format(app, name, password) inbytes = original.encode() originalencrypted = fkey.encrypt(inbytes) # 把加密后的字节解码成utf-8字符串写入,避免b''包裹 f.write(originalencrypted.decode('utf-8') + "\n") def read(): with open("passwords2.txt", 'r') as f: for line in f: # 直接把字符串转成字节后解密 print(fkey.decrypt(line.strip().encode('utf-8')).decode()) while True: operation = input("would you like to read, add, or quit (q) ") if operation == "read": read() elif operation == "add": add() elif operation == "q" or operation == "quit": quit() else: print("invalid input")
关键修改点
- 写入时:用
originalencrypted.decode('utf-8')替代str(originalencrypted),直接把加密后的字节转成可写入的字符串 - 读取时:不需要处理多余的字符,直接
line.strip().encode('utf-8')就能得到正确的加密字节令牌
内容的提问来源于stack exchange,提问作者manlearnscode
相关产品推荐
相关产品推荐

