mysql數據庫中針對敏感信息字段加密處理問題

最近有這樣一個需求,針對系統中的敏感信息,如供應商的手機號碼,銀行賬號等需要做加密處理。比較常見的加密方式如md5,但是公司架構組的給出的方案是:統一在數據庫處理,使用mysql的加密函數AES_ENCRYPT(’‘明文,‘加密key’)和解密函數AES_DECRYPT(’'明文,‘加密key’),加密key可配置。

經過一天的更改測試完成,做個總結,記錄下此過程中遇到的問題及解決方法。

在原表中增加存儲加密信息的字段,如新增字段encrypt_mobile,encrypt_bank_num分別對應之前的mobile,bank_num

處理方案:

1、在常量類中添加靜態的常量:

package com.lyc.common.constant;
public class CommonConstant {
	public static final String MYSQL_ENTRYPT_KEY = "entryptkey";
}

2、mybatis的mapper.xml中新增數據的sql更改如下:

insert into table (encrypt_mobile,encrypt_bank_num) 
values(
AES_ENCRYPT(#{encryptMobile},'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}'),
AES_ENCRYPT(#{encryptBankNum},'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}')
);

3、查詢手機號、銀行賬號,在mybatis的mapper.xml中查詢sql更改如下:

select AES_DECRYPT(encrypt_mobile,'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}') as mobile,
AES_DECRYPT(encrypt_bank_num,'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}') as bank_num 
from table;

效果如圖:
在這裏插入圖片描述

數據成功加密並保存了,但是看起來像亂碼,而且解密返回的結果爲null,有問題。查資料發現mysql還有兩個函數,HEX()和UNHEX()。HEX()可以將一個字符串或數字轉換爲十六進制格式的字符串,UNHEX()把十六進制格式的字符串轉化爲原來的格式。

解決方案:

1、mybatis的mapper.xml中新增數據的sql更改如下:

insert into table (encrypt_mobile,encrypt_bank_num) 
values(
HEX(AES_ENCRYPT(#{encryptMobile},'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}')),
HEX(AES_ENCRYPT(#{encryptBankNum},'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}'))
);

2、查詢手機號、銀行賬號,在mybatis的mapper.xml中查詢sql更改如下:

select AES_DECRYPT(UNHEX(encrypt_mobile),'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}') as mobile,
AES_DECRYPT(UNHEX(encrypt_bank_num),'${@com.lyc.common.constant.CommonConstant@MYSQL_ENTRYPT_KEY}') as bank_num
from table;

效果如圖:
在這裏插入圖片描述

解決問題中參考的博客地址:
[1] https://blog.csdn.net/lwwl12/article/details/81502989
[2] http://blog.itpub.net/29773961/viewspace-2142305/
[3] https://blog.csdn.net/oppoppoppo/article/details/53407048

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章