1. Introduce dependencies
<dependency> <groupId></groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId></groupId> <artifactId>hutool-crypto</artifactId> <version>5.7.16</version> </dependency> <dependency> <groupId></groupId> <artifactId>hutool-core</artifactId> <version>5.7.16</version> </dependency> <dependency> <groupId></groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.59</version> </dependency>
2. Configure mybatis
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-////DTD Config 3.0//EN" "/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"/> <!-- Printsql--> </settings> <typeHandlers> <package name=""/> </typeHandlers> <mappers> <package name=""/> </mappers> </configuration>
Configuration
mybatis: config-location: classpath:
4. Encryption tool class
package ; import ; import ; import ; import .SM4; import ; import ; import ; import ; public class SM4Util { private static final Charset ENCODING = StandardCharsets.UTF_8; public SM4Util() { } public static String generateKey() { return ((RandomUtil.BASE_CHAR_NUMBER, 16).getBytes()); } /** * @Description: Encryption */ public static String encryptEcb(String hexKey, String paramStr, Charset charset) throws Exception { String cipherText = ""; if (null != paramStr && !"".equals(paramStr)) { SM4 sm4 = new SM4((), Padding.(), (hexKey)); cipherText = (paramStr, charset); } return cipherText; } public static String encryptEcb(String key, String data) throws Exception { return encryptEcb(key, data, ENCODING); } /** * sm4 decryption * * @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((), Padding.(), (hexKey)); return (cipherText); } /** * sm4 decryption * * @param key * @param data Encrypted data * @return Decrypted data * @throws Exception */ public static String decryptEcb(String key, String data) throws Exception { return decryptEcb(key, data, ENCODING); } /** * @Description: Password verification */ public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception { boolean flag = false; byte[] keyData = (hexKey); byte[] cipherData = (cipherText); SM4 sm4 = new SM4((), Padding.(), keyData); byte[] decryptData = (cipherData); byte[] srcData = (ENCODING); flag = (decryptData, srcData); return flag; } }
Inheritance class
package ; import ; import ; import org.; import org.; import .SM4Util; import ; import ; import ; import ; /** * @Description typeHandler Encryption and decryption processor Encrypt or decrypt fields of type String */ public class SM4CryptoTypeHandler extends BaseTypeHandler<String> { // Please do not change the sm4 encryption key after it is launched private final static String PKEY = "912058752095k2948123c394ht868r0j"; private static final Logger log = (); /* * Processing ginseng */ @Override public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException { if (parameter != null) { //encryption String encryptHex = null; try { encryptHex = (PKEY,parameter); } catch (Exception e) { ("Database field encryption error",e); } ("{} ---Encrypted as---> {}", parameter, encryptHex); (i, encryptHex); } } /* * Get the return result according to the column name, and you can process the return value in this method */ @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { String originRes = (columnName); if (originRes != null) { String res = originRes; try { res = (PKEY,originRes); } catch (Exception e) { //(); ("database"+columnName+"Column field decryption error",e); } ("{} ---Decrypted as---> {}", originRes, res); return res; } ("The result is empty, no decryption is required"); return null; } /* * Get the return result according to the column subscript, and the return value can be processed in this method. */ @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String originRes = (columnIndex); if (originRes != null) { String res = originRes; try { res = (PKEY,originRes); } catch (Exception e) { //(); ("Database"+columnIndex+"Column field decryption error",e); } ("The[{}]List:{} ---Decrypted as---> {}",columnIndex, originRes, res); return res; } ("The result is empty, no decryption is required"); return null; } /* * Get the return result (storage procedure) according to the column subscript, and the return value can be processed in this method. */ @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String originRes = (columnIndex); if (originRes != null) { String res = originRes; try { res = (PKEY,originRes); } catch (Exception e) { //(); ("Database"+columnIndex+"Column field decryption error",e); } ("The[{}]List:{} ---Decrypted as---> {}",columnIndex, originRes, res); } ("The result is empty, no decryption is required"); return null; } }
Layer xml and interface
package ; import ; import ; public interface TestMapper { int insert(Test record); }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-////DTD Mapper 3.0//EN" "/dtd/"> <mapper namespace=""> <resultMap type=""> <result column="test" jdbcType="VARCHAR" property="test" typeHandler=".SM4CryptoTypeHandler"/> </resultMap> <insert parameterType=""> insert into t_test (test) values (#{test,jdbcType=VARCHAR,typeHandler=.SM4CryptoTypeHandler}) </insert> </mapper>
This is the end of this article about Mybatis's implementation of typeHandler encryption. For more related content related to Mybatis typeHandler encryption, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!