Mybatis使用typeHandler加密的实现
作者:hcpter
本文详细介绍了如何在Mybatis中使用typeHandler对特定字段进行加密处理,涵盖了从引入依赖、配置Mybatis,到实现typeHandler继承类和配置mapper层的详细步骤,为需要在项目中实现字段加密的开发者提供了参考和借鉴
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加密内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!