Java MyBatis typeHandler 敏感数据加密解密

业务场景

敏感信息(姓名、身份证)存入数据库时应当需要加密,防止被恶意访问数据库时暴露信息。

解决方案

由于项目数据库中间件使用的是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;

/**
 * @Author: jmx
 * @Description: 数据脱敏
 * @DateTime: 2021/11/15 16:25
 */
public class DataDesensitizationUtils {

    private static final String OTHER_LOGIN_KEY = "8ce87b8ec346ff4c80635f667d1592ae";

    /**
     * 加密
     * @param text
     * @return
     * @throws Exception
     */
    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;
        }
    }


    /**
     * 解密
     * @param text
     * @return
     */
    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;

/**
 * @Author: jmx
 * @Description:
 * @DateTime: 2021/11/16 14:59
 */
public class AESTypeHandler extends BaseTypeHandler<Object> {

    /**
     * 非空字段加密
     */
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) {
        try {
            if (StringUtils.isBlank((String) parameter)) return;

            ps.setString(i, DataDesensitizationUtils.encrypt((String) parameter));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 非空字段解密
     */
    @Override
    public Object getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String col = rs.getString(columnName);
        try {
            if (StringUtils.isBlank(col)) return col;

            return DataDesensitizationUtils.decrypt(col);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return col;
    }

    /**
     * 可空字段加密
     */
    @Override
    public Object getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String col = rs.getString(columnIndex);
        try {
            if (StringUtils.isBlank(col)) return col;
            return DataDesensitizationUtils.encrypt(col);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return col;
    }


    /**
     * 可空字段解密
     */
    @Override
    public Object getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String col = cs.getString(columnIndex);
        try {
            if (StringUtils.isBlank(col)) return col;
            return DataDesensitizationUtils.decrypt(col);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return col;
    }

}

Mapper中使用

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cx.merchant.data.mapper.sharding.MerchantDetailInfoMapper">
    <!--返回模型-->
    <resultMap id="BaseResultMap" type="com.jmx.entity.TestEntity">
    <result column="real_name" jdbcType="VARCHAR" property="realName"    typeHandler="AESTypeHandler"/>
    </resultMap>
    <!--插入-->
     <insert id="insertSelective" parameterType="com.jmx.entity.TestEntity" 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=com.jmx.utils.AESTypeHandler},
            </if>
        </trim>
    </insert>
   
    <!-- 查询 -->
    <select id="selectByEntity" parameterType="info" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from info
        where 1 = 1
        <if test="realName!= null" >
            and real_name= #{realName,jdbcType=VARCHAR,typeHandler=com.jmx.utils.AESTypeHandler}
        </if>
     
        limit 1
    </select>

结果

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值