简单密码程序中的错误(cryptography.fernet.InvalidToken)

时间:2018-04-10 13:17:01

标签: python encryption

我正在用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 个答案:

答案 0 :(得分:0)

如果我的理解是正确的,那么您将向解密方法传递加密文本的编码值,该值不是要解密的有效令牌。

由于您将编码值传递给crypt,因此解密应该类似于

def decrypt(token):
    return base64.decode(cipher_suite.decrypt(token, encoding="ascii")