MySQL data storage encryption and decryption (code attached)

The data in the original table is not encrypted, an encrypted table is created, the data in the original table is recycled, and the encrypted data is inserted into the encrypted table. Finally, create a trigger, insert data in the original table, and automatically trigger the insertion of the same data in the encrypted table.

Use MySQL's aes_encrypt to encrypt data
Use Mysql's aes_decrypt to decrypt data.
Because the encrypted data is ugly, use to_base64 to transcode the data and from_base64 to decode the data.
So the actual saved data is encrypted and then transcoded.
View the data by decoding the data first. The decrypted data
script is as follows

# _*_ coding: utf-8 _*_
__author__ = 'Louislee'
__date__ = '2019/08/19 09:22'

添加触发器
CREATE TRIGGER auth_enc_trigger
AFTER INSERT on auth
FOR EACH ROW
INSERT into auth_enc (id, real_name, id_number) VALUES (NEW.id,to_base64(aes_encrypt(NEW.real_name, “slwh-dfh”)),to_base64(aes_encrypt(NEW.id_number, “slwh-dfh”)));
查询加密后的表
select id,aes_decrypt(from_base64(real_name),‘slwh-dfh’),aes_decrypt(from_base64(id_number),‘slwh-dfh’) from auth_enc;
import MySQLdb

db = MySQLdb.connect(host=‘localhost’, port=3306, user=‘root’, passwd=‘mypassword’, db=‘my_db’,
charset=‘utf8’)
cursor = db.cursor() # 创建一个游标对象
cursor.execute(“select * from auth;)
lines = cursor.fetchall()
print(“一共获取数据%s条”) % (len(lines))
for data in lines:
id, real_name, id_number = data
sql = ‘insert into auth_enc (id, real_name, id_number) VALUE (%d,to_base64(aes_encrypt("%s",“slwh-dfh”)),to_base64(aes_encrypt("%s", “slwh-dfh”)));% (
id, real_name, id_number)
print(sql)
try:
cursor.execute(sql)
db.commit()
except Exception, e:
db.rollback()
print(e)

cursor.close()

Guess you like

Origin blog.csdn.net/m0_50654102/article/details/114940234