使用pymysql在Python中实现数据库的敏感数据加密
发布时间:2023-12-18 19:38:10
在Python中使用pymysql进行数据库连接和操作非常简单,并且可以通过使用其他加密库来实现数据库的敏感数据加密。下面是一个使用pymysql进行数据库加密的示例代码:
1. 安装依赖库
在开始之前,你需要安装pymysql库和其他一些加密库。
pip install pymysql pip install cryptography
2. 导入库
导入所需的库。
import pymysql from cryptography.fernet import Fernet
3. 生成加密密钥
生成一个加密密钥,用于加密和解密数据库中的敏感数据。
def generate_key():
key = Fernet.generate_key()
with open('key.key', 'wb') as key_file:
key_file.write(key)
4. 加密数据
使用生成的密钥对数据进行加密。
def encrypt_data(data):
with open('key.key', 'rb') as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
encrypted_data = cipher_suite.encrypt(data.encode())
return encrypted_data
5. 解密数据
使用相同的密钥对加密的数据进行解密。
def decrypt_data(encrypted_data):
with open('key.key', 'rb') as key_file:
key = key_file.read()
cipher_suite = Fernet(key)
decrypted_data = cipher_suite.decrypt(encrypted_data)
return decrypted_data.decode()
6. 连接到数据库
使用pymysql库来连接到数据库,并插入和读取加密的数据。
# 添加数据
def insert_data(data):
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='my_db')
encrypted_data = encrypt_data(data)
try:
with conn.cursor() as cursor:
sql = 'INSERT INTO my_table (data) VALUES (%s)'
cursor.execute(sql, encrypted_data)
conn.commit()
finally:
conn.close()
# 读取数据
def read_data():
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='my_db')
try:
with conn.cursor() as cursor:
sql = 'SELECT data FROM my_table'
cursor.execute(sql)
result = cursor.fetchall()
for row in result:
encrypted_data = row[0]
decrypted_data = decrypt_data(encrypted_data)
print(decrypted_data)
finally:
conn.close()
这是一个简单的示例代码,演示了如何使用pymysql和加密库在Python中进行数据库的敏感数据加密。你可以根据自己的需要进行修改和扩展。
