当前位置: 代码网 > it编程>编程语言>Java > Mybatis使用typeHandler加密的实现

Mybatis使用typeHandler加密的实现

2024年09月27日 Java 我要评论
1引入依赖 <dependency> <groupid>org.mybatis.spring.boot</groupid>

1引入依赖

        <dependency>
            <groupid>org.mybatis.spring.boot</groupid>
            <artifactid>mybatis-spring-boot-starter</artifactid>
        </dependency>
        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
        </dependency>
        <dependency>
            <groupid>cn.hutool</groupid>
            <artifactid>hutool-crypto</artifactid>
            <version>5.7.16</version>
        </dependency>

        <dependency>
            <groupid>cn.hutool</groupid>
            <artifactid>hutool-core</artifactid>
            <version>5.7.16</version>
        </dependency>
         <dependency>
            <groupid>org.bouncycastle</groupid>
            <artifactid>bcprov-jdk15on</artifactid>
            <version>1.59</version>
        </dependency>

2.配置mybatis

<?xml version="1.0" encoding="utf-8" ?>
<!doctype configuration
        public "-//mybatis.org//dtd config 3.0//en"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <setting name="logprefix" value="show_sql."/>
        <!--		<setting name="logimpl" value="stdout_logging" />-->
        <setting name="callsettersonnulls" value="true" />

        <setting name="cacheenabled" value="true" />

        <setting name="lazyloadingenabled" value="true" />

        <setting name="aggressivelazyloading" value="true" />

        <setting name="multipleresultsetsenabled" value="true" />

        <setting name="usecolumnlabel" value="true" />

        <setting name="usegeneratedkeys" value="false" />

        <setting name="automappingbehavior" value="partial" />

        <setting name="defaultexecutortype" value="simple" />

        <setting name="mapunderscoretocamelcase" value="true" />

        <setting name="localcachescope" value="session" />

        <setting name="jdbctypefornull" value="null" />

        <setting name="logimpl" value="log4j2"/> <!-- 打印sql-->
    </settings>
    <typehandlers>
        <package name="test.handler"/>
    </typehandlers>
    <mappers>
        <package name="test.mapper"/>
    </mappers>
</configuration>

3.yml配置

mybatis:
  config-location: classpath:mybatis-config.xml

4.加密工具类

package test.utils;


import cn.hutool.core.util.randomutil;
import cn.hutool.crypto.mode;
import cn.hutool.crypto.padding;
import cn.hutool.crypto.symmetric.sm4;
import org.bouncycastle.pqc.math.linearalgebra.byteutils;


import java.nio.charset.charset;
import java.nio.charset.standardcharsets;
import java.util.arrays;

public class sm4util {

    private static final charset encoding = standardcharsets.utf_8;

    public sm4util() {
    }


    public static string generatekey() {
        return byteutils.tohexstring(randomutil.randomstring(randomutil.base_char_number, 16).getbytes());
    }


    /**
     * @description:加密
     */
    public static string encryptecb(string hexkey, string paramstr, charset charset) throws exception {
        string ciphertext = "";
        if (null != paramstr && !"".equals(paramstr)) {
            sm4 sm4 = new sm4(mode.ecb.name(), padding.pkcs5padding.name(), byteutils.fromhexstring(hexkey));
            ciphertext = sm4.encrypthex(paramstr, charset);
        }
        return ciphertext;
    }

    public static string encryptecb(string key, string data) throws exception {
        return encryptecb(key, data, encoding);
    }

    /**
     * sm4解密
     *
     * @param hexkey
     * @param ciphertext
     * @param charset
     * @return
     * @throws exception
     */
    public static string decryptecb(string hexkey, string ciphertext, charset charset) throws exception {
        sm4 sm4 = new sm4(mode.ecb.name(), padding.pkcs5padding.name(), byteutils.fromhexstring(hexkey));
        return sm4.decryptstr(ciphertext);
    }

    /**
     * sm4解密
     *
     * @param key  密钥
     * @param data 加密的数据
     * @return 解密后的数据
     * @throws exception 异常
     */
    public static string decryptecb(string key, string data) throws exception {
        return decryptecb(key, data, encoding);
    }

    /**
     * @description:密码校验
     */
    public static boolean verifyecb(string hexkey, string ciphertext, string paramstr) throws exception {
        boolean flag = false;
        byte[] keydata = byteutils.fromhexstring(hexkey);
        byte[] cipherdata = byteutils.fromhexstring(ciphertext);
        sm4 sm4 = new sm4(mode.ecb.name(), padding.pkcs5padding.name(), keydata);
        byte[] decryptdata = sm4.decrypt(cipherdata);
        byte[] srcdata = paramstr.getbytes(encoding);
        flag = arrays.equals(decryptdata, srcdata);
        return flag;
    }


    

}

5.typehandler继承类

package test.handler;


import org.apache.ibatis.type.basetypehandler;
import org.apache.ibatis.type.jdbctype;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import test.utils.sm4util;

import java.sql.callablestatement;
import java.sql.preparedstatement;
import java.sql.resultset;
import java.sql.sqlexception;

/**
 * @description typehandler加解密处理器 将string类型的字段加密或解密
 */

public class sm4cryptotypehandler extends basetypehandler<string> {

    //sm4加密key上线后请勿更改
    private final static string pkey = "912058752095k2948123c394ht868r0j";

    private static final logger log = loggerfactory.getlogger(sm4cryptotypehandler.class);

    /*
     * 加工入参
     */
    @override
    public void setnonnullparameter(preparedstatement ps, int i, string parameter, jdbctype jdbctype) throws sqlexception {
        if (parameter != null) {
            //加密
            string encrypthex = null;
            try {
                encrypthex = sm4util.encryptecb(pkey,parameter);
            } catch (exception e) {
                log.error("数据库字段加密错误",e);
            }
            log.debug("{} ---加密为---> {}", parameter, encrypthex);
            ps.setstring(i, encrypthex);
        }
    }

    /*
     * 根据列名获取返回结果,可在此方法中加工返回值
     */
    @override
    public string getnullableresult(resultset rs, string columnname) throws sqlexception {
        string originres = rs.getstring(columnname);
        if (originres != null) {
            string res = originres;
            try {
                res = sm4util.decryptecb(pkey,originres);
            } catch (exception e) {
                //e.printstacktrace();
                log.error("数据库"+columnname+"列字段解密错误",e);
            }
            log.debug("{} ---解密为---> {}", originres, res);
            return res;
        }
        log.debug("结果为空,无需解密");
        return null;
    }

    /*
     * 根据列下标获取返回结果,可在此方法中加工返回值
     */
    @override
    public string getnullableresult(resultset rs, int columnindex) throws sqlexception {
        string originres = rs.getstring(columnindex);
        if (originres != null) {
            string res = originres;
            try {
                res = sm4util.decryptecb(pkey,originres);
            } catch (exception e) {
                //e.printstacktrace();
                log.error("数据库第"+columnindex+"列字段解密错误",e);
            }
            log.debug("第[{}]列:{} ---解密为---> {}",columnindex, originres, res);
            return res;
        }
        log.info("结果为空,无需解密");
        return null;
    }

    /*
     * 根据列下标获取返回结果(存储过程),可在此方法中加工返回值
     */
    @override
    public string getnullableresult(callablestatement cs, int columnindex) throws sqlexception {
        string originres = cs.getstring(columnindex);
        if (originres != null) {
            string res = originres;
            try {
                res = sm4util.decryptecb(pkey,originres);
            } catch (exception e) {
                //e.printstacktrace();
                log.error("数据库第"+columnindex+"列字段解密错误",e);
            }
            log.debug("第[{}]列:{} ---解密为---> {}",columnindex, originres, res);
        }
        log.debug("结果为空,无需解密");
        return null;
    }

}

6.mapper层xml和interface

package test.mapper;


import org.apache.ibatis.annotations.param;
import test.entry.test;

public interface testmapper {
    
    int insert(test record);
}
<?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="test.mapper.testmapper">
  <resultmap id="baseresultmap" type="test.entry.test">
    <result column="test" jdbctype="varchar" property="test" typehandler="test.handler.sm4cryptotypehandler"/> 
  </resultmap>
    <insert id="insert" parametertype="test.entry.test">
    insert into t_test (test)
    values (#{test,jdbctype=varchar,typehandler=test.handler.sm4cryptotypehandler})
  </insert>
</mapper>

到此这篇关于mybatis使用typehandler加密的实现的文章就介绍到这了,更多相关mybatis typehandler加密内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com