MyBatis-Plus如何實(shí)現(xiàn)自動(dòng)加密解密
MyBatis-Plus 自動(dòng)加密解密
通過(guò)使用MyBatis的typeHandler功能,對(duì)入?yún)⒑统鰠⑦M(jìn)行處理,實(shí)現(xiàn)無(wú)縫加密解密(將明文加密后保存至數(shù)據(jù)庫(kù);從數(shù)據(jù)庫(kù)讀取時(shí),自動(dòng)將密文解密成明文)
實(shí)現(xiàn)TypeHandler
@Slf4j public class UserTypeHandler extends BaseTypeHandler<Object> { /** * 非空字段加密 * @param preparedStatement * @param i * @param parameter * @param jdbcType * @throws SQLException */ @Override public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object parameter, JdbcType jdbcType) { try { if (StrUtil.isBlank((String) parameter)) { return; } // todo 加密操作 String encrypt = ""; preparedStatement.setString(i, encrypt); } catch (Exception e) { log.error("typeHandler加密異常:" + e); } } /** * 非空字段解密 * @param resultSet * @param columnName * @return * @throws SQLException */ @Override public Object getNullableResult(ResultSet resultSet, String columnName) throws SQLException { String col = resultSet.getString(columnName); try { if (StrUtil.isBlank(col)) { return col; } // todo 對(duì)結(jié)果col進(jìn)行解密操作 return ""; } catch (Exception e) { log.error("typeHandler解密異常:" + e); } return col; } /** * 可空字段加密 * @param resultSet * @param columnIndex * @return * @throws SQLException */ @Override public Object getNullableResult(ResultSet resultSet, int columnIndex) throws SQLException { String col = resultSet.getString(columnIndex); try { if (StrUtil.isBlank(col)) { return col; } // todo 對(duì)結(jié)果col進(jìn)行解密操作 return ""; } catch (Exception e) { log.error("typeHandler解密異常:" + e); } return col; } /** * 可空字段解密 * @param callableStatement * @param columnIndex * @return * @throws SQLException */ @Override public Object getNullableResult(CallableStatement callableStatement, int columnIndex) throws SQLException { String col = callableStatement.getString(columnIndex); try { if (StrUtil.isBlank(col)) { return col; } // todo 對(duì)結(jié)果col進(jìn)行解密操作 return ""; } catch (Exception e) { log.error("typeHandler解密異常:" + e); } return col; } }
添加注解
在對(duì)應(yīng)的實(shí)體類中
- 在 @TableName 注解中,設(shè)置 autoResultMap 參數(shù)為true
- 在需要加解密的字段上,添加注解 @TableField(typeHandler = UserTypeHandler.class)
@Data @TableName(value = "t_user", autoResultMap = true) public class UserEntity { /** * 主鍵自增 */ @TableId(type = IdType.AUTO) private Integer id; private String name; private Integer age; @TableField(typeHandler = UserTypeHandler.class) private String password; private String role; }
查詢加密字段
MyBatis-Plus的QueryWrapper在查詢加密字段時(shí),并不會(huì)進(jìn)入TypeHandler,需要手寫(xiě)sql,指定字段進(jìn)行TypeHandler中的流程。
注解方式
@Results(id= "resultMap", value = { @Result(column = "password", property = "password", typeHandler = UserTypeHandler.class) }) @Select("select * from t_user where password = #{password, typeHandler=com.mybatisdemo.config.UserTypeHandler}") List<UserEntity> list(UserQuery userQuery);
XML方式
<resultMap id="userMap" type="com.mybatisdemo.entity.UserEntity"> <result column="password" property="password" typeHandler="com.mybatisdemo.config.UserTypeHandler" /> </resultMap> <select id="list" resultMap="userMap"> select * from t_user where password = #{password,typeHandler=com.mybatisdemo.config.UserTypeHandler} </select>
MyBatis-Plus 敏感數(shù)據(jù)的加密
最近在做項(xiàng)目,需要實(shí)現(xiàn)對(duì)身份證,密碼等敏感數(shù)據(jù)的加密,即不能以明文存儲(chǔ)密碼到數(shù)據(jù)庫(kù)。
上網(wǎng)查了一下資料,解決辦法如下:
寫(xiě)加密解密的工具類
import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AES { // 密鑰 public static String key = "AD42F6697B035B7580E4FEF93BE20BAD"; private static String charset = "utf-8"; // 偏移量 private static int offset = 16; private static String transformation = "AES/CBC/PKCS5Padding"; private static String algorithm = "AES"; /** * 加密 * * @param content * @return */ public static String encrypt(String content) { return encrypt(content, key); } /** * 解密 * * @param content * @return */ public static String decrypt(String content) { return decrypt(content, key); } /** * 加密 * * @param content 需要加密的內(nèi)容 * @param key 加密密碼 * @return */ public static String encrypt(String content, String key) { try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm); IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset); Cipher cipher = Cipher.getInstance(transformation); byte[] byteContent = content.getBytes(charset); cipher.init(Cipher.ENCRYPT_MODE, skey, iv);// 初始化 byte[] result = cipher.doFinal(byteContent); return new Base64().encodeToString(result); // 加密 } catch (Exception e) { // LogUtil.exception(e); } return null; } /** * AES(256)解密 * * @param content 待解密內(nèi)容 * @param key 解密密鑰 * @return 解密之后 * @throws Exception */ public static String decrypt(String content, String key) { try { SecretKeySpec skey = new SecretKeySpec(key.getBytes(), algorithm); IvParameterSpec iv = new IvParameterSpec(key.getBytes(), 0, offset); Cipher cipher = Cipher.getInstance(transformation); cipher.init(Cipher.DECRYPT_MODE, skey, iv);// 初始化 byte[] result = cipher.doFinal(new Base64().decode(content)); return new String(result); // 解密 } catch (Exception e) { //LogUtil.exception(e); } return null; } public static void main(String[] args) throws Exception { String s = "hello world"; // 加密 System.out.println("加密前:" + s); String encryptResultStr = encrypt(s); System.out.println("加密后:" + encryptResultStr); // 解密 System.out.println("解密后:" + decrypt(encryptResultStr)); } }
繼承BaseTypeHandler ,實(shí)現(xiàn)對(duì)數(shù)據(jù)的轉(zhuǎn)換
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 starmark * @date 19-12-17 下午8:38 */ public class AESEncryptHandler extends BaseTypeHandler { @Override public void setNonNullParameter(PreparedStatement ps, int i, Object parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, AES.encrypt((String)parameter)); } @Override public String getNullableResult(ResultSet rs, String columnName) throws SQLException { String columnValue = rs.getString(columnName); return AES.decrypt(columnValue); } @Override public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String columnValue = rs.getString(columnIndex); return AES.decrypt(columnValue); } @Override public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String columnValue = cs.getString(columnIndex); return AES.decrypt(columnValue); } }
有po類中,實(shí)現(xiàn)相關(guān)類型注解
/** * 用戶管理 */ @Data @EqualsAndHashCode(callSuper = false) @TableName(autoResultMap = true) public class SysOrgUser extends BaseUpdateModel { /** * 登陸帳戶 */ private String loginName; /** * 密碼 */ @TableField(typeHandler = AESEncryptHandler.class) private String password;
至此,密碼等敏感信息已處理好。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限項(xiàng)目實(shí)踐
本文主要介紹了mybatis攔截器實(shí)現(xiàn)數(shù)據(jù)權(quán)限項(xiàng)目實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-06-06java子線程解決獲取主線程的request對(duì)象問(wèn)題
這篇文章主要介紹了java子線程解決獲取主線程的request對(duì)象問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08springboot實(shí)現(xiàn)極驗(yàn)校驗(yàn)的項(xiàng)目實(shí)踐
在系統(tǒng)業(yè)務(wù)中,需要想客戶發(fā)送手機(jī)驗(yàn)證碼,進(jìn)行驗(yàn)證后,才能提交,本文主要介紹了springboot實(shí)現(xiàn)極驗(yàn)校驗(yàn)的項(xiàng)目實(shí)踐,具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09關(guān)于maven install報(bào)錯(cuò)原因揭秘:parent.relativePath指向錯(cuò)誤的本地POM文件
在使用Maven進(jìn)行項(xiàng)目構(gòu)建時(shí),如果遇到'parent.relativePath'指向錯(cuò)誤的本地POM文件的問(wèn)題,可能會(huì)導(dǎo)致構(gòu)建失敗,這通常是由于父項(xiàng)目POM文件的相對(duì)路徑設(shè)置錯(cuò)誤、本地POM文件與父項(xiàng)目POM文件版本或內(nèi)容不一致所致,解決方法包括檢查并修正父項(xiàng)目POM文件中的相對(duì)路徑設(shè)置2024-09-09三步輕松實(shí)現(xiàn)Java的SM2前端加密后端解密
SM2算法和RSA算法都是公鑰密碼算法,SM2算法是一種更先進(jìn)安全的算法,在我們國(guó)家商用密碼體系中被用來(lái)替換RSA算法,這篇文章主要給大家介紹了關(guān)于如何通過(guò)三步輕松實(shí)現(xiàn)Java的SM2前端加密后端解密的相關(guān)資料,需要的朋友可以參考下2024-01-01mybatis報(bào)Query?was?Empty異常的問(wèn)題
這篇文章主要介紹了mybatis報(bào)Query?was?Empty異常的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03Springboot 如何關(guān)閉自動(dòng)配置
這篇文章主要介紹了Springboot 如何關(guān)閉自動(dòng)配置的操作,具有很好的開(kāi)車價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09SpringBoot項(xiàng)目中使用Groovy腳本的示例代碼
本文主要介紹了SpringBoot項(xiàng)目中使用Groovy腳本的示例代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08