使用 Python 的加密库通过 GridDB 存储和检索加密的二进制数据

问题描述 投票:0回答:1

我正在使用 GridDB 设置,并希望通过实施后量子加密来使其免受未来量子计算威胁的影响。我首先使用加密数据存储与

cryptography
库和 GridDB 测试基本集成。这是我的代码:

from cryptography.fernet import Fernet
import griddb_python as griddb

# Generate encryption key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Sample data encryption
data = "Quantum Safe Data"
encrypted_data = cipher_suite.encrypt(data.encode())

# Initialize GridDB connection
factory = griddb.StoreFactory.get_instance()
try:
    gridstore = factory.get_store(
        host="localhost", port=10001, cluster_name="defaultCluster",
        username="admin", password="admin"
    )
    container_name = "quantum_test"
    conInfo = griddb.ContainerInfo(
        name=container_name,
        column_info_list=[["id", griddb.Type.INTEGER],
                          ["data", griddb.Type.STRING]],
        type=griddb.ContainerType.COLLECTION, row_key=True)
    
    container = gridstore.put_container(conInfo)
    container.set_auto_commit(False)

    # Storing encrypted data
    row = [1, encrypted_data]
    container.put_row(row)
    container.commit()

    # Retrieve and decrypt data
    query = container.query("select *")
    rs = query.fetch()
    while rs.has_next():
        row = rs.next()
        decrypted_data = cipher_suite.decrypt(row[1]).decode()
        print("Decrypted Data:", decrypted_data)

except griddb.GSException as e:
    print("GridDB Error:", e)

问题:

运行上述代码时,遇到以下错误:

Traceback (most recent call last):
  File "griddb_encryption_test.py", line 32, in <module>
    decrypted_data = cipher_suite.decrypt(row[1]).decode()
  File "/path/to/python/site-packages/cryptography/fernet.py", line 117, in decrypt
    timestamp, data = Fernet._get_unverified_token_data(token)
  File "/path/to/python/site-packages/cryptography/fernet.py", line 166, in _get_unverified_token_data
    raise TypeError("token must be bytes")
TypeError: expected bytes-like object, not str

GridDB 容器中应如何处理加密的二进制数据?我是否应该以不同的方式转换数据以进行存储/检索,以防止这些类型问题?

python griddb
1个回答
0
投票

这与后量子加密无关。问题是您已指定

data
列是字符串,但
Fernet.encrypt()
返回包含 Base64 编码数据的字节对象。然而,当您从数据库检索它时,它神奇地是一个字符串。我猜想 GridDB 以某种方式将字节对象“转换”为字符串。与其依赖一些自动转换,不如自己转换。从
encrypt
返回的值是一个包含base64编码数据的字节对象。这意味着它是 ASCII,在指定 UTF8 解码(这是 python 的默认设置)时可以正确解码,因此 TLDR 在插入时仅提供 UTF8 解码的字符串。检索时,在解密之前将字符串 UTF8 编码回字节,例如

# ...
# Storing encrypted data
    row = [1, encrypted_data.decode()]
# ...

然后稍后

# ...
row = rs.next()
decrypted_data = cipher_suite.decrypt(row[1].encode()).decode()
# ...
© www.soinside.com 2019 - 2024. All rights reserved.