测试程序如下:
#!/usr/bin/python# coding=utf-8from Crypto.Cipher import AESimport pymysql as mdbfrom binascii import b2a_hex, a2b_heximport syssor_conn = mdb.connect(host='127.0.0.1',port=3306,user='root',passwd='Root@Py123') sor_cur = sor_conn.cursor()class PyDbString():def __init__(self): self.key = 'pythonkey2020320' self.mode = AES.MODE_CBCdef addString(self, text): cryptor = AES.new(self.key, self.mode, self.key) length = 32 count = len(text) add = length - (count % length) text = text + ('\0' * add) self.ciphertext = cryptor.encrypt(text)return b2a_hex(self.ciphertext)def desString(self, text): cryptor = AES.new(self.key, self.mode, self.key) plain_text = cryptor.decrypt(a2b_hex(text))return plain_text.rstrip('\0') v_strpass = PyDbString() v_sql = "selectname,tel,pwd frombak_db.f_user"result_tb = sor_cur.execute(v_sql) t = sor_cur.fetchall()for col in t: v_name = col[0] v_tel = col[1] v_pwd = col[2]print(v_pwd) v_pwd = v_strpass.addString(v_pwd) # 加密 v_sql_insert = "insert intobak_db.f_user_p(name,tel,pwd) values('%s','%s','%s');" %(v_name,v_tel,v_pwd) sor_cur.execute(v_sql_insert) sor_conn.commit() sor_conn.close()查看数据如下:
解密的方法可以将上例中的addstring 改为desString即可。
上面通过三种方式进行数据的加密、解密,个人推荐第三种方式,从应用层自定义加密。另外,此方法只是加密,实际应用中可能要用加密、混淆等脱敏方法来保障数据安全,另外,很多情况下没有解密方式,即不可逆,有兴趣的可以多多沟通,感谢!