Python 密码学 Fernet:解密时出错
Python Cryptography Fernet : Error during decryption
密钥以以下格式生成并保存在 env 文件中:
SECRET_KEY = KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
def encrypt_message(message):
key = app.config['SECRET_KEY']
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
def decrypt_message(encrypted_message):
key = app.config['SECRET_KEY']
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
print(decrypted_message.decode())
加密工作正常,没有错误。但是,在解密过程中出现以下错误:
当 Key 持久化为 byteString 时:
b'KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI='
ValueError: Fernet key must be 32 url-safe base64-encoded bytes
当 Key 持久化为字符串时
KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
TypeError: token must be bytes
解决方案:对密钥和消息进行编码
def decrypt_message(encrypted_message):
key = app.config['SECRET_KEY'] # KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
f = Fernet(key.encode()) #Encode key
decrypted_message = f.decrypt(encrypted_message.encode()) #Encode Message
print(decrypted_message.decode())
密钥以以下格式生成并保存在 env 文件中:
SECRET_KEY = KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
def encrypt_message(message):
key = app.config['SECRET_KEY']
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
def decrypt_message(encrypted_message):
key = app.config['SECRET_KEY']
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
print(decrypted_message.decode())
加密工作正常,没有错误。但是,在解密过程中出现以下错误:
当 Key 持久化为 byteString 时:
b'KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI='
ValueError: Fernet key must be 32 url-safe base64-encoded bytes
当 Key 持久化为字符串时
KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
TypeError: token must be bytes
解决方案:对密钥和消息进行编码
def decrypt_message(encrypted_message):
key = app.config['SECRET_KEY'] # KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=
f = Fernet(key.encode()) #Encode key
decrypted_message = f.decrypt(encrypted_message.encode()) #Encode Message
print(decrypted_message.decode())