加密令牌对象引发异常,即使令牌相同也无法解密

时间:2017-10-13 18:24:33

标签: python json python-3.x encryption cryptography

代码概述:令牌是相同的,但在加密和解密之间,加密对象存储在模块级字典中 - 加密令牌仍然没有改变。

为什么这不起作用?我想在幕后有关加密对象的事情使其独一无二,但我认为它所需要的只是解密工作的正确密钥。

以下是最小相关代码:

import sys
from cryptography.fernet import Fernet
import json
import os

key = Fernet.generate_key()
f = Fernet(key)


with open("storage.json", "a+") as file:
    if os.stat("storage.json").st_size == 0:
        file.write("{}")
    file.seek(0)
    storage = json.load(file)


def write(data):
    with open("storage.json", "w") as file:
        json.dump(data, file)


def encrypt(pw):
    token = f.encrypt(bytes(pw, "utf-8"))
    return token


def decrypt(token):
    return f.decrypt(token)

if len(sys.argv) == 1:
    to_encrypt = input("A key to encrypt: ")
    storage[to_encrypt] = encrypt(to_encrypt).decode("utf-8")
    print("encrypted:", storage[to_encrypt])
    # print("storage:", storage)
    try:
        write(storage)
    except Exception as e:
        print("error:", e)

elif len(sys.argv) == 2:
    to_decrypt = input("Key to decrypt: ")
    # print(storage[to_d])
    print("decrypted:", f.decrypt(bytes(storage[to_decrypt], "utf-8")))

要使它工作:运行没有参数的程序 - 它将创建一个json文件,将你的字符串及其加密输入到文件中,然后退出。
然后,运行程序传递任何单个参数。尝试获取先前输入的相同字符串。

应该发生这种追溯:

Traceback (most recent call last):
  File "/Users/sjung/lib/python3.5/site-packages/cryptography/fernet.py", line 101, in decrypt
    h.verify(data[-32:])
  File "/Users/sjung/lib/python3.5/site-packages/cryptography/hazmat/primitives/hmac.py", line 69, in verify
    ctx.verify(signature)
  File "/Users/sjung/lib/python3.5/site-packages/cryptography/hazmat/backends/openssl/hmac.py", line 73, in verify
    raise InvalidSignature("Signature did not match digest.")
cryptography.exceptions.InvalidSignature: Signature did not match digest.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "test_a.py", line 43, in <module>
    print("decrypted:", f.decrypt(bytes(storage[to_decrypt], "utf-8")))
  File "/Users/sjung/lib/python3.5/site-packages/cryptography/fernet.py", line 103, in decrypt
    raise InvalidToken
cryptography.fernet.InvalidToken

编辑:注释掉elif行以在不退出系统的情况下进行尝试。 这确实有用

1 个答案:

答案 0 :(得分:2)

Fernet.generate_key()生成的密钥在解密时也必须是相同的密钥。我的示例代码每次都在创建一个新密钥。

https://github.com/pyca/cryptography/issues/3982