我在用Python写一个简单的密码程序(Python新手,加密更新),用户帐户和密码保存在字典中的文件中。我用Fernet模块加密密码。添加用户工作正常,但当我试图解密密码时,我得到 cryptography.fernet.InvalidToken 错误,所以问题应该与密钥有关,虽然我看不出我做错了什么
代码片段:
def generate_master_key():
my_key_file = "/path/to/passwordfile"
if os.path.exists(my_key_file):
with open(my_key_file, 'rb') as myfile:
master_key = myfile.read()
else:
master_key = Fernet.generate_key()
with open(my_key_file, 'wb') as myfile:
myfile.write(master_key)
return master_key
del master_key
PASSWORDS = json.load(open('accounts'))
key = generate_master_key()
cipher_suite = Fernet(key)
def encrypt(s):
return cipher_suite.encrypt(base64.encodestring(bytes(s, encoding="ascii")))
def decrypt(token):
return cipher_suite.decrypt(base64.encodestring(bytes(token, encoding="ascii")))
def add_user():
print('What is the name of the account you would like to add?')
account = input()
print('What is the password of {}?'.format(account))
pw = getpass.getpass()
PASSWORDS[account] = encrypt(pw).decode('ascii')
json.dump(PASSWORDS, open('accounts', 'w'))
def get_password():
account = sys.argv[1]
if account in PASSWORDS:
pyperclip.copy(decrypt(PASSWORDS[account]))
print('Password for {} copied to clipboard'.format(account))
else:
print('There is no account named {}'.format(account))
字符串
1条答案
按热度按时间lztngnrs1#
如果我的理解是正确的,您正在向decrypt方法传递加密文本的编码值,这不是一个有效的令牌来解密。
因为你传递了一个编码的值给crypt,所以解密应该是这样的:
字符串