使用mysql的aes_encrypt加密数据
使用Mysql的aes_decrypt解密数据
因为加密后的数据比较难看,所以使用to_base64转码数据和from_base64解码数据
所以实际保存的数据是加密后又转码的数据
查看数据是先解码数据在解密数据
脚本如下
# _*_ coding: utf-8 _*_
__author__ = ‘xiaoke‘
__date__ = ‘2018/6/12 18:25‘
"""
添加触发器
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()
原文:http://blog.51cto.com/kexiaoke/2128847