用 cryptography.fernet 解密消息不起作用

Decrypt message with cryptography.fernet do not work

我刚刚尝试加密和解密数据。我首先生成一个密钥,然后用它加密数据并将其保存到 XML 文件中。现在该数据已读取,应该再次解密。

但现在我收到错误消息“cryptography.fernet.InvalidToken”。

import xml.etree.cElementTree as ET
from cryptography.fernet import Fernet
from pathlib import Path

def load_key():
    """
    Load the previously generated key
    """
    return open("../login/secret.key", "rb").read()

def generate_key():
    """
    Generates a key and save it into a file
    """
    key = Fernet.generate_key()
    with open("../login/secret.key", "wb") as key_file:
        key_file.write(key)

def decrypt_message(encrypted_message):
    """
    Decrypts an encrypted message
    """
    key = load_key()
    f = Fernet(key)
    message = encrypted_message.encode('utf-8')
    decrypted_message = f.decrypt(message)

    return(decrypted_message)

def decryptMessage(StringToDecrypt):
    decryptedMessage = decrypt_message(StringToDecrypt)
    return decryptedMessage

def loginToRoster(chrome):
    credentials = readXML()
    user = decryptMessage(credentials[0])
    pw = decryptMessage(credentials[1])

    userName = chrome.find_element_by_id('UserName')
    userName.send_keys(user)
    password = chrome.find_element_by_id('Password')
    password.send_keys(pw)

在元组“credentials”中有 2 个加密字符串。

请帮忙 - 已经尝试了所有更改格式的方法,但没有机会。

编辑:

错误信息:

Traceback (most recent call last):
  File "C:/Users/r/Documents/GitHub/ServiceEvaluationRK/source/main.py", line 27, in <module>
    login.loginToRoster(chrome)
  File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 106, in loginToRoster
    user = decryptMessage(credentials[0])
  File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 49, in decryptMessage
    decryptedMessage = decrypt_message(StringToDecrypt)
  File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\source\login.py", line 43, in decrypt_message
    decrypted_message = f.decrypt(message)
  File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\venv\lib\site-packages\cryptography\fernet.py", line 75, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "C:\Users\r\Documents\GitHub\ServiceEvaluationRK\venv\lib\site-packages\cryptography\fernet.py", line 107, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

你在decrypt_message函数的什么地方定义了load_key()。它不是一种方法,它只是一个未定义的函数。您可能会收到该错误,因为密钥无效,因为您没有获得您保存的密钥。

我找到了问题的答案:

我拿了 ASCII 而不是 utf-8。我在函数“loginToRoster”处向变量 'user' 和 'pw'

添加了一个 .decode('ASCII')

现在加解密正常了

因此,'loginToRoster' 函数看起来像:

def loginToRoster(chrome):
    credentials = readXML()
    user = decryptMessage(credentials[0]).decode('ASCII')
    pw = decryptMessage(credentials[1]).decode('ASCII')

    userName = chrome.find_element_by_id('UserName')
    userName.send_keys(user)
    password = chrome.find_element_by_id('Password')
    password.send_keys(pw)