我用python编写了2个函数,一个用于加密数据,另一个用于解密数据,如下所示。
from app.settings import DATA_KEY
import logging
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
import base64
cipher_suite = AESSIV(DATA_KEY)
error_logger = logging.getLogger("error_logger")
def encrypt_field(input_text):
try:
if isinstance(input_text, str):
input_text = input_text.encode()
enc_text = cipher_suite.encrypt(input_text, associated_data = None)
print(f"enc_text is {enc_text}")
enc_text_base_64 = base64.b64encode(enc_text)
print(f"encrypted_text is {enc_text_base_64}")
return enc_text_base_64
except Exception as e:
error_logger.error(f"exception in encrypt field {str(e)} on field {input_text}")
return input_text
def decrypt_field(input_text):
try:
print(f"input in decrypt field is {input_text} its type is {type(input_text)}")
enc_text = base64.b64decode(input_text)
print(f"enc text is {enc_text}")
decrypted_field = cipher_suite.decrypt(enc_text, associated_data = None)
print(f"decrypted_field is {decrypted_field}")
return decrypted_field.decode('utf-8')
except Exception as e:
print(e)
error_logger.error(f"exception in decrypt_field {e} on field {input_text}")
return input_text
我能够加密数据并将其存储在数据库中,但是在从数据库读取数据并尝试解密它时,我得到一个 utf-8 字节字符串,而不是原始的纯文本字符串。我在这里做错了什么? 我的Django版本是5.0,Python版本是3.10.11,数据库是PostgreSQ
我尝试将数据存储在 Django 模型的 BinaryField 和 TextField 中,但结果相同,但无济于事。我也尝试过将数据存储为不带 base64encde 的编码字节数据,但稍后无法解码并导致未定义的字符错误。
我认为你可以简单地简化你的实现:
import base64
from cryptography.hazmat.primitives.ciphers.aead import AESSIV
DATA_KEY = b"ABCDEFGH" * 4 # VERY SECRET!
cipher_suite = AESSIV(DATA_KEY)
def encrypt_text_to_base64(input_text: str) -> str:
if not isinstance(input_text, str):
raise TypeError("Input must be text")
enc_text = cipher_suite.encrypt(input_text.encode("utf-8"), associated_data=None)
return base64.b64encode(enc_text).decode("ascii")
def decode_base64_to_text(input_text: str | bytes) -> str:
return cipher_suite.decrypt(
base64.b64decode(input_text), associated_data=None
).decode("utf-8")
plain = "Hello, world!"
encrypted = encrypt_text_to_base64(plain)
encrypted_bytes = encrypted.encode("utf-8")
decrypted = decode_base64_to_text(encrypted)
decrypted_from_bytes = decode_base64_to_text(encrypted_bytes)
print(f"{plain=}")
print(f"{encrypted=}")
print(f"{encrypted_bytes=}")
print(f"{decrypted=}")
print(f"{decrypted_from_bytes=}")
打印出来
plain='Hello, world!'
encrypted='1mtatTQy3/GRFv0tUd3Mp66V8uDbeKDqn8rKytU='
encrypted_bytes=b'1mtatTQy3/GRFv0tUd3Mp66V8uDbeKDqn8rKytU='
decrypted='Hello, world!'
decrypted_from_bytes='Hello, world!'
因此您可以看到解密函数适用于 Base64-in-bytes 和 Base64-as-a-string。