使用 Flask 和密码术解密存储在 MySQL 数据库中的文件时出错

Error Decrypting file stored in a MySQL DB using Flask and Cryptography

我正在使用 Flask 和 Cryptography 包从用户那里接收一个 .csv 文件,加密它,将它存储在 MySQL 数据库中,然后检索和解密它。

收到用户上传的文件后,我将执行以下操作对其进行加密:

from cryptography.fernet import Fernet

# Read the file as bytes
# file_bytes is <class 'werkzeug.datastructures.FileStorage'>
file_bytes = file.stream.read()

# Get the main encrypter/decrypter
f = Fernet(app.config['CRYPTOGRAPHY_KEY'])

# Encrypt the bytes
# encrypted is <class 'bytes'> , This has 526156 Bytes
encrypted = f.encrypt(file_bytes)

# Convert the encrypted bytes to String
# encrypted_string it is <class 'str'>
encrypted_string = encrypted.decode() 

# Store the encrypted file into the MySQL DB in a BLOB field
# flask_mysqldb is being used here.
store_file(encrypted_string)

将其存储在数据库中后,我看到 BLOB 变量有 65535 字节。我可以使用 MySQL Workbench

来查看

当我从我收到的数据库中检索加密文件时

# encrypted_bytes_database it is <class 'bytes'> , This has 65535 Bytes
encrypted_bytes_database = retrieve_file_from_db(user_id)

当我尝试使用以下方法解密时:

f.decrypt(encrypted_bytes_database)

出现以下错误:

  File "MY_ENV/lib/python3.8/site-packages/cryptography/fernet.py", line 104, in _get_unverified_token_data
    raise InvalidToken
cryptography.fernet.InvalidToken

如果我解密 encrypted 变量它工作正常没有错误,但是当我尝试解密 encrypted_bytes_database 时我得到这个错误。知道这里出了什么问题吗?

我刚刚发现问题出在 MySQL 数据类型中。

  • BLOB:最多可处理 65,535 字节的数据。

  • MEDIUMBLOB:支持的最大长度为 16,777,215 字节。

在我的数据库中将数据类型更改为 MEDIUMBLOB 后一切正常。

这就是我解密 encrypted_bytes_database 并将此 .csv 文件作为 pandas df.

读取的方式
from cryptography.fernet import Fernet
import pandas as pd
import io

decrypted_db = f.decrypt(encrypted_bytes_database)
df = pd.read_csv(io.StringIO(decrypted_db.decode()))