MySQL 数据存储加密和解密(附代码)

原表里面的数据没有加密,创建了一张加密表,循环原表里面的数据,加密后插入到加密表。最后创建一个触发器,在原表里面插入了数据,自动触发在加密表里面插入相同的数据。

使用mysql的aes_encrypt加密数据
使用Mysql的aes_decrypt解密数据
因为加密后的数据比较难看,所以使用to_base64转码数据和from_base64解码数据
所以实际保存的数据是加密后又转码的数据
查看数据是先解码数据在解密数据
脚本如下

# _*_ 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()

猜你喜欢

转载自blog.csdn.net/m0_50654102/article/details/114940234