如何修复Python密码管理器中Fernet密钥格式不匹配错误?
解决Fernet密钥格式错误问题
你遇到的错误提示ValueError: Fernet key must be 32 url-safe base64-encoded bytes,本质是当前使用的密钥不符合Fernet的规范,结合你的脚本来看,问题出在两个地方:生成密钥的函数被注释且存在拼写错误,导致key.key里的密钥不是合法的Fernet密钥。
具体修正步骤:
- 修复并启用密钥生成函数
你注释的write_key函数里有拼写错误:key.file.write(key)应该改为key_file.write(key),取消注释后先运行一次生成合法密钥。 - 确保密钥加载正确
生成密钥后,load_key函数才能读取到符合要求的32字节URL安全Base64编码密钥。
修正后的完整脚本:
from cryptography.fernet import Fernet def write_key(): # 生成符合要求的Fernet密钥 key = Fernet.generate_key() with open("key.key", "wb") as key_file: key_file.write(key) # 修复原拼写错误 # 首次运行时取消下面的注释,生成密钥后可重新注释 # write_key() def load_key(): file = open("key.key", "rb") key = file.read() file.close() return key key = load_key() fer = Fernet(key) def view(): with open('passwords.txt', 'r') as f: for line in f.readlines(): data = line.rstrip() user, passw = data.split("|") print("User:", user, "| Password:", fer.decrypt(passw.encode()).decode()) def add(): name = input('Account Name: ') pwd = input("Password: ") # 修复文件名不一致问题:原脚本add函数写的是password.txt,view函数读的是passwords.txt with open('passwords.txt', 'a') as f: f.write(name + "|" + fer.encrypt(pwd.encode()).decode() + "\n") while True: mode = input("would you like to add a new password or view existing ones(view, add)? press q to quit").lower() if mode == "q": break if mode == "view": view() elif mode == "add": add() else: print("Invalid mode") continue
额外注意事项:
- 首次运行时必须先调用
write_key()生成密钥,之后不要重复调用,否则之前加密的密码会因为密钥变更无法解密。 - 原脚本中
add函数写入的文件名是password.txt,而view函数读取的是passwords.txt,已统一修正为passwords.txt,避免后续找不到密码记录。
内容的提问来源于stack exchange,提问作者etan
相关产品推荐
相关产品推荐

