为什么我的加密python程序不起作用



我正在尝试编写一个程序来加密和解密消息。以下是回溯:追踪(最近一次通话(:文件";C: \Users\notelling\OneDrive \Desktop\pyprojects\crypto.py",第15行,inf=套圈(键(名称错误:名称"密钥"未定义

这是我的代码:

from cryptography.fernet import Fernet
import os
if os.path.isfile("encryption.key"):
file = open("encryption.key", "rb")
filec = file.read().decode()
else:
key = Fernet.generate_key()
file = open('encryption.key', 'wb')
file.write(key.encode()) # The key is type bytes still
file.close()
print("Key generated.")
mode = input("Please enter mode (e/d):")
if mode == 'e':
message = input("What is your message to encrypt?").encode()
f = Fernet(key)
encrypted = f.encrypt(message)
passkey = open("encryptedmsg.txt", "wb")
passkey.write(encrypted)
passkey.close()
elif mode == 'd':
passread = open("encryptedmsg.txt", "rb")
contents = passread.read()
f = Fernet(key)
decrypted = f.decrypt(encrypted).decode()
print("Decrypted message is ", decrypted)
input()

这与密码学无关,而是纯粹的Python特定错误。

变量键分配在第一个'else'块的第7行。

除非特别定义,否则此变量在该块之外不可用。

更多参考:

https://docs.python.org/3.8/tutorial/classes.html#class-和实例变量

https://docs.python.org/3.8/tutorial/classes.html#private-变量

最新更新