如何解决在 PostgreSQL 数据库中存储字节类型对象
因此,我需要将敏感数据存储在数据库中,以便日后检索。简单地以明文形式存储它是一个坏主意,这就是为什么我决定在 python 中使用 AES 对其进行加密。
当我在本地进行加密和解密时,加密和解密工作正常,但问题是我需要将加密数据存储在数据库中。
问题是加密数据采用字节格式,到目前为止我还没有找到一种方法:
a)。将加密数据解码为UTF-8格式
或
b)。将加密数据的字节版本插入数据库。
有谁知道如何解决这个问题?将不胜感激。
加密/解密代码如下:
import hashlib
import math
import os
import codecs #bytes -> utf string
import chardet
from Crypto.Cipher import AES
#.env variables
import os
from os.path import join,dirname
from dotenv import load_dotenv
dotenv_path = "./.env"
load_dotenv(dotenv_path)
class encrypter():
def __init__(self):
self.IV_SIZE = 16 # 128 bit,fixed for the AES algorithm
self.KEY_SIZE = 32 # 256 bit meaning AES-256,can also be 128 or 192 bits
self.SALT_SIZE = 16 # This size is arbitrary
def encrypt(self,_input,_key):
'''
IN:
_input <str> - String/text to encrypt
_key <str> - Key that is used to encrypt/decrypt
OUT:
<str> - encrypted version of _input
'''
#Convert input and key into byte strings
_input,_key = bytes(_input,"utf-8"),bytes(_key,"utf-8")
salt = os.urandom(self.SALT_SIZE)
derived = hashlib.pbkdf2_hmac('sha256',_key,salt,100000,dklen=self.IV_SIZE + self.KEY_SIZE)
iv = derived[:self.IV_SIZE]
derived_key = derived[self.IV_SIZE:]
result = salt + AES.new(derived_key,AES.MODE_CFB,iv).encrypt(_input)
return result #Change bytes object into string
def decrypt(self,_encrypted_text,_key):
'''
IN:
_encrypted_text <str> - Encrypted text to decrypt
_key <str> - Key that is used to encrypt/decrypt
OUT:
<str> - Decrypted version of _encrypted_text
'''
# encrypted = bytes(_encrypted_text,"utf-8")
encryption_key = bytes(_key,"utf-8")
# encrypted = bytes(_encrypted_text,"utf-8")
encrypted = _encrypted_text
salt = encrypted[:self.SALT_SIZE]
derived = hashlib.pbkdf2_hmac('sha256',encryption_key,dklen=self.IV_SIZE + self.KEY_SIZE)
iv = derived[0:self.IV_SIZE]
derived_key = derived[self.IV_SIZE:]
result = AES.new(derived_key,iv).decrypt(encrypted[self.SALT_SIZE:])
return str(result)[2:-1] #Change bytes object into string
a = encrypter()
text = "C9ZVBLWvyo9vTnZDBs" #Plaintext to encrypt
encryption_key = "encryption key" #This is the 'password' to encrypt/decrypt
#Encrypt data
encrypted = a.encrypt(text,encryption_key)
print("Encrypted data: ",Encrypted)
#Decrypt data
decrypted = a.decrypt(encrypted,encryption_key)
print(decrypted)
print(text == decrypted) #Check so decrypted version matches original
解决方法
我想到了两种解决方案:
-
使用 postgres bytea 字段类型。详情请见:How to read and insert bytea columns using psycopg2?
-
Base64 对加密数据进行编码。这实际上是一种很常见的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。