0

我想在 sqlite3 中向数据库添加值,它们需要加密。当我想检索值时,它们需要被解密。现在我收到了这个错误TypeError: token must be bytes。以下是错误的完整列表:Traceback (most recent call last): File "C:\Users\d\OneDrive\Bureaublad\Assignment8\CDMS.py", line 75, in <module> get_clients() File "C:\Users\d\OneDrive\Bureaublad\Assignment8\CDMS.py", line 68, in get_clients new += fernet.decrypt(i).decode() + " " File "C:\Users\d\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\fernet.py", line 75, in decrypt timestamp, data = Fernet._get_unverified_token_data(token) File "C:\Users\d\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\fernet.py", line 100, in _get_unverified_token_data utils._check_bytes("token", token) File "C:\Users\d\AppData\Local\Programs\Python\Python38\lib\site-packages\cryptography\utils.py", line 29, in _check_bytes raise TypeError("{} must be bytes".format(name)) TypeError: token must be bytes

这是我的代码:

from Classes import Client
from cryptography.fernet import Fernet
import sqlite3


key = Fernet.generate_key()

fernet = Fernet(key)
conn = sqlite3.connect('database.db')
c = conn.cursor()

def insert_client(client):
    fullname = fernet.encrypt(client.fullname.encode())
    fullname1 = fullname.decode()
    adress = fernet.encrypt(client.adress.encode())
    adress1 = adress.decode()
    zipcode = fernet.encrypt(client.zipcode.encode())
    zipcode1 = zipcode.decode()
    city = fernet.encrypt(client.city.encode())
    city1 = city.decode()
    email = fernet.encrypt(client.email.encode())
    email1 = email.decode()
    mphone = fernet.encrypt(client.mphone.encode())
    mphone1 = mphone.decode()
    
    with conn:
        c.execute("INSERT INTO client VALUES (:fullname, :adress, :zipcode, :city, :email, :mphone)",
          {'fullname': fullname1, 'adress': adress1, 'zipcode': zipcode1,
           'city': city1, 'email': email1, 'mphone': mphone1})

client1 = Client('Name1', 'Street1', 'Zipcode', 'NewYork', '123@gmail.com', '12345678')

def get_clients():
    arr = []
    new = ""
    c.execute("SELECT * FROM client")
    arr = c.fetchall()
    for i in arr:
        new += fernet.decrypt(i).decode() + " "
    return new
        


insert_client(client1)
get_clients()


conn.close()

第一个函数用于添加客户端,通过一个名为 Client 的类对象。第二个功能是检索所有解密的值。

4

1 回答 1

0

fetchall返回一个可迭代的(最常见的是元组)。如果您只想处理一条记录,则应改为使用fetchone

...
arr = c.fetchone()
for i in arr:
    new += fernet.decrypt(i).decode() + " "
...

或者,您可以迭代光标并返回一个列表:

def get_clients():
    arr = []
    c.execute("SELECT * FROM client")
    for row in c:
        new = ""
        for i in row:
            new += fernet.decrypt(i).decode() + " "
        arr.append(new)
    return arr

Pythonic的方式是使用推导:

def get_clients():
    c.execute("SELECT * FROM client")
    return [' '.join(fernet.decrypt(i).decode() for i in row)
            for row in c]

稍微短一点,不是吗?

于 2021-07-06T12:29:24.133 回答