0

密钥以以下格式生成并保存在 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())

加密工作正常,没有错误。但是,在解密过程中出现以下错误:

  1. 当 Key 持久化为 byteString 时:

    b'KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI='

    ValueError: Fernet key must be 32 url-safe base64-encoded bytes

  2. 当 Key 被持久化为 String

    KG0TUB0grHz1AngJUwcsN4jcRlujde5sbzbeJ8InZsI=

    TypeError: token must be bytes

4

1 回答 1

0

解决方案:对密钥和消息进行编码

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())
于 2021-03-16T07:08:01.420 回答