1
코드 개요 : 토큰은 동일하지만 암호화와 암호 해독 사이에 암호화 된 개체가 모듈 수준의 사전에 저장됩니다. 암호화 토큰은 변경되지 않습니다.암호화 토큰 개체가 예외를 발생시키고 토큰이 동일해도 암호 해독 할 수 없음
왜 작동하지 않습니까? 나는 고유 한 암호화 된 객체와 관련하여 장면 뒤에 숨어있는 것들이 있다고 생각하지만, 필요한 모든 것이 복호화가 작동하기위한 올바른 키라고 가정했을 것입니다.
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
줄을 주석. 이 작업은입니다.
: 예'("해독", f.decrypt (바이트 (저장 [to_decrypt, "UTF-8"))) 인쇄 깊은 중첩 호출'디버깅하기 어려운 대신 사용 여러 단계 및 중간 변수. 그런 다음 디버거에서 실행을 추적하거나 중간 값에 대한 인쇄 명령문을 추가하십시오. 또한 오류 메시지의 행 번호는 실제 오류가 있다는 것을 더 잘 이해할 수 있습니다. – zaph