业务场景
敏感信息(姓名、身份证)存入数据库时应当需要加密,防止被恶意访问数据库时暴露信息。
解决方案
由于项目数据库中间件使用的是Mybatis,所以使用Mybatis中的BaseTypeHandler的一个类型处理器,对数据进行AES加密存入数据库
具体实现方式
import mons.lang3.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 BaseTypeHandler<Object> {/*** 非空字段加密*/@Overridepublic void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) {try {if (StringUtils.isBlank((String) parameter)) return;ps.setString(i, AesKit.encrypt((String) parameter, AesKey.SPECIAL_COLS_AES));} catch (Exception e) {system.out.println("mybatis字段加密异常");}}/*** 非空字段解密*/@Overridepublic Object getNullableResult(ResultSet rs, String columnName) throws SQLException {String col = rs.getString(columnName);try {if (StringUtils.isBlank(col)) return col;return AesKit.decrypt(col, AesKey.SPECIAL_COLS_AES);} catch (Exception e) {system.out.println("mybatis字段解密异常");}return col;}/*** 可空字段加密*/@Overridepublic Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {String col = rs.getString(columnIndex);try {if (StringUtils.isBlank(col)) return col;return AesKit.decrypt(col, AesKey.SPECIAL_COLS_AES);} catch (Exception e) {system.out.println("mybatis字段加密异常");}return col;}/*** 可空字段解密*/@Overridepublic Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {String col = cs.getString(columnIndex);try {if (StringUtils.isBlank(col)) return col;return AesKit.decrypt(col, AesKey.SPECIAL_COLS_AES);} catch (Exception e) {system.out.println("mybatis字段解密异常")}return col;}}
Mapper中使用
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.cx.merchant.data.mapper.sharding.MerchantDetailInfoMapper"><!--返回模型--><resultMap id="BaseResultMap" type="info"><result column="real_name" jdbcType="VARCHAR" property="realName" typeHandler="AESTypeHandler"/></resultMap><!--插入--><insert id="insertSelective" parameterType="info" useGeneratedKeys="true" keyProperty="id">insert into info<trim prefix="(" suffix=")" suffixOverrides=",">real_name,</trim><trim prefix="values (" suffix=")" suffixOverrides=","><if test="realName != null">#{realName,jdbcType=VARCHAR,typeHandler=AESTypeHandler},</if></trim></insert><!-- 查询 --><select id="selectByEntity" parameterType="info" resultMap="BaseResultMap">select<include refid="Base_Column_List" />from infowhere 1 = 1<if test="realName!= null" >and real_name= #{realName,jdbcType=VARCHAR,typeHandler=AESTypeHandler}</if>limit 1</select>
结果
数据库如下