0

我刚刚尝试过加密和解密数据。我首先生成了一个密钥,然后用它加密数据并将其保存到一个 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)

在元组“凭据”中有 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
4

2 回答 2

1

我找到了我的问题的答案:

ASCII代替了utf-8. 我.decode('ASCII')在函数“loginToRoster”中添加了一个变量“user”和“pw”

现在加密和解密工作正常。

因此,“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)
于 2021-04-28T08:27:31.140 回答
0

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

于 2021-04-27T15:14:47.487 回答