Cas*_*per 6 python encryption json cryptography python-3.x
代码概述:令牌是相同的,但是在加密和解密之间,加密的对象被存储到模块级字典中 - 尽管如此,加密令牌不会改变。
为什么这不起作用?我想加密对象背后有一些东西使它独一无二,但我认为它所需要的只是解密工作的正确密钥。
这是最少的相关代码:
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")))
Run Code Online (Sandbox Code Playgroud)
要使其工作:运行不带参数的程序 - 它将创建一个 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
Run Code Online (Sandbox Code Playgroud)
编辑:注释掉该elif行以在不退出系统的情况下尝试它。这确实有效。
生成的密钥Fernet.generate_key()也必须与解密时的密钥相同。我的示例代码每次都会创建一个新密钥。
https://github.com/pyca/cryptography/issues/3982
| 归档时间: |
|
| 查看次数: |
11089 次 |
| 最近记录: |