敏感信息(姓名、身份证)存入数据库时应当需要加密,防止被恶意访问数据库时暴露信息。
解决方案由于项目数据库中间件使用的是Mybatis,所以使用Mybatis中的baseTypeHandler的一个类型处理器,对数据进行AES加密存入数据
加密方法
package com.cdyl.utils;
import org.apache.commons.lang.StringUtils;
import sun.misc.base64Decoder;
import sun.misc.base64Encoder;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class DataDesensitizationUtils {
private static final String OTHER_LOGIN_KEY = "8ce87b8ec346ff4c80635f667d1592ae";
public static String encrypt(String text) {
try {
byte[] plaintext = text.getBytes();
IvParameterSpec ivspec = new IvParameterSpec(OTHER_LOGIN_KEY.substring(16).getBytes());
SecretKeySpec keyspec = new SecretKeySpec(OTHER_LOGIN_KEY.substring(0, 16).getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
byte[] encrypted = cipher.doFinal(plaintext);
return new base64Encoder().encode(encrypted).trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decrypt(String text) {
try {
byte[] encrypted1 = new base64Decoder().decodeBuffer(text);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keyspec = new SecretKeySpec(OTHER_LOGIN_KEY.substring(0, 16).getBytes(), "AES");
IvParameterSpec ivspec = new IvParameterSpec(OTHER_LOGIN_KEY.substring(16).getBytes());
cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] original = cipher.doFinal(encrypted1);
String originalString = new String(original);
return originalString.trim();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
// 手机号码前三后四脱敏
public static String mobileEncrypt(String mobile) {
if (StringUtils.isEmpty(mobile) || (mobile.length() != 11)) {
return mobile;
}
return mobile.replaceAll("(\d{3})\d{4}(\d{4})", "$1****$2");
}
}
实现baseTypeHandler
package com.cdyl.utils; import org.apache.commons.lang.StringUtils; import org.apache.ibatis.type.baseTypeHandler; import org.apache.ibatis.type.JdbcType; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class AESTypeHandler extends baseTypeHandlerMapper中使用
结果insert into info real_name, #{realName,jdbcType=VARCHAR,typeHandler=com.jmx.utils.AESTypeHandler},



