mysql對數據庫字段存儲的數據加密
阿新 • • 發佈:2018-06-13
mysql aes_encryupt 原表裏面的數據沒有加密,創建了一張加密表,循環原表裏面的數據,加密後插入到加密表。最後創建一個觸發器,在原表裏面插入了數據,自動觸發在加密表裏面插入相同的數據。
- 使用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()
mysql對數據庫字段存儲的數據加密