1、DB查询手机号,若未加密,批量更新回填
2、查询加密的手机号,解密显示。
import pymysql
from Crypto.Util.Padding import pad
from Crypto.Cipher import AES
import base64
key = "0123456789abcdef0123456789abcdef"
def AES_Encrypt(key, aes_str):
aes = AES.new(key.encode('utf-8'), AES.MODE_ECB)
pad_pkcs7 = pad(aes_str.encode('utf-8'), AES.block_size, style='pkcs7') # 选择pkcs7补全
encrypt_aes = aes.encrypt(pad_pkcs7)
encrypted_text = str(base64.encodebytes(encrypt_aes), encoding='utf-8')
encrypted_text_str = encrypted_text.replace("\n", "")
return encrypted_text_str
def AES_Decrypt(key, text):
aes = AES.new(str.encode(key), AES.MODE_ECB)
base64_decrypted = base64.decodebytes(text.encode(encoding='utf-8'))
decrypted_text = str(aes.decrypt(base64_decrypted), encoding='utf-8').replace('\0', '')
return decrypted_text
db = pymysql.connect(user='root', password='123456', database='demos', host='127.0.0.1', port=3306, charset='utf8mb4')
cursor = db.cursor()
cursor.execute("select userId, phone from users")
data = cursor.fetchall()
val_list = []
for d in data:
if len(d[1]) <= 14:
val_list.append([AES_Encrypt(key, d[1]), d[0]])
else:
print(AES_Decrypt(key ,d[1]))
continue
print(val_list)
with db.cursor() as cursor:
try:
sql = "UPDATE users SET phone=(%s) WHERE userId=(%s)"
cursor.executemany(sql, val_list)
db.commit()
except:
db.rollback()
db.close()
if __name__ == '__main__':
print("done")
var mysql = require('mysql2');
const CryptoJS = require('crypto-js');
const crypto = require('crypto');
const secretKey = '0123456789abcdef0123456789abcdef';
const iv = '0123456789abcdef';
function aes256Decrypt(key, data, crypto) {
if (key.length !== 32) throw onerror
const cipher = crypto.createDecipheriv('aes-256-ecb', key, '');
let c = cipher.update(data, 'base64', 'utf8');
c += cipher.final('utf8');
return c;
}
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '123456',
port: '3306',
database: 'demos'
});
connection.connect();
var phones_aes = [];
var m = new Map();
connection.query('select userId, phone from users',function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
return;
}
for (const re of result) {
if (re.phone.length > 14) {
re.phone = aes256Decrypt(secretKey, re.phone, crypto);
}
console.log(re);
}
console.log('------------------------------------------------------------\n\n');
});
connection.end()
var mysql = require('mysql2');
const CryptoJS = require('crypto-js');
const crypto = require('crypto');
const secretKey = '0123456789abcdef0123456789abcdef';
const iv = '0123456789abcdef';
function aesEncrypt(content) {
const key = CryptoJS.enc.Utf8.parse(secretKey);
let srcs = CryptoJS.enc.Utf8.parse(content);
const ivs = CryptoJS.enc.Utf8.parse(iv);
let encrypted = CryptoJS.AES.encrypt(srcs, key, {
iv: ivs,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.toString();
}
function aesDecrypt(content) {
let key = CryptoJS.enc.Utf8.parse(secretKey);
const ivs = CryptoJS.enc.Utf8.parse(iv);
let decrypt = CryptoJS.AES.decrypt(content, key, {
iv: ivs,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
-- 加密:aes加密之后base64
select to_base64(AES_ENCRYPT(phone, '8G5M4Ff9hel8fUA9'))
-- 解密:base64反编译之后aes解密
select AES_DECRYPT(from_base64('giSZmBtx0y1OdggamClBOQ=='),'8G5M4Ff9hel8fUA9')
-- AES加密
SELECT AES_ENCRYPT('1234567890123456','abcdefgh');
-- AES解密
SELECT AES_DECRYPT(AES_ENCRYPT('1234567890123456','abcdefgh') ,'abcdefgh') ;
-- AES加密后进行转成16进制
SELECT HEX(AES_ENCRYPT('1234567890123456','abcdefgh'));
-- AES加密后进行转成16进制,再转二进制进行解密
SELECT AES_DECRYPT(UNHEX(HEX(AES_ENCRYPT('1234567890123456','abcdefgh'))),'abcdefgh');
-- 设置参数
mysql> SET block_encryption_mode = 'aes-256-cbc';
mysql> SET @key_str = SHA2('My secret passphrase',512);
mysql> SET @init_vector = RANDOM_BYTES(16);
mysql> SET @crypt_str = AES_ENCRYPT('text',@key_str,@init_vector);
mysql> SELECT AES_DECRYPT(@crypt_str,@key_str,@init_vector);
+-----------------------------------------------+
| AES_DECRYPT(@crypt_str,@key_str,@init_vector) |
+-----------------------------------------------+
| text |
+-----------------------------------------------+
https://www.mklab.cn/utils/aes
https://www.jpwz.vip/tool/hextobase64.html
1、不同语言,不同库AES加解密有差异, 注意不要踩坑
2、MySQL 中只有基于unix系统才可以调AES_DECRYPT,AES_DECRYPT,不同版本需要注意