MyBatis-Plus如何實現(xiàn)自動加密解密
MyBatis-Plus 自動加密解密
通過使用MyBatis的typeHandler功能,對入?yún)⒑统鰠⑦M行處理,實現(xiàn)無縫加密解密(將明文加密后保存至數(shù)據(jù)庫;從數(shù)據(jù)庫讀取時,自動將密文解密成明文)
實現(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 對結(jié)果col進行解密操作
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 對結(jié)果col進行解密操作
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 對結(jié)果col進行解密操作
return "";
} catch (Exception e) {
log.error("typeHandler解密異常:" + e);
}
return col;
}
}
添加注解
在對應的實體類中
- 在 @TableName 注解中,設置 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在查詢加密字段時,并不會進入TypeHandler,需要手寫sql,指定字段進行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àn)對身份證,密碼等敏感數(shù)據(jù)的加密,即不能以明文存儲密碼到數(shù)據(jù)庫。
上網(wǎng)查了一下資料,解決辦法如下:
寫加密解密的工具類
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 ,實現(xiàn)對數(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類中,實現(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;
至此,密碼等敏感信息已處理好。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis攔截器實現(xiàn)數(shù)據(jù)權(quán)限項目實踐
本文主要介紹了mybatis攔截器實現(xiàn)數(shù)據(jù)權(quán)限項目實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-06-06
關(guān)于maven install報錯原因揭秘:parent.relativePath指向錯誤的本地POM文件
在使用Maven進行項目構(gòu)建時,如果遇到'parent.relativePath'指向錯誤的本地POM文件的問題,可能會導致構(gòu)建失敗,這通常是由于父項目POM文件的相對路徑設置錯誤、本地POM文件與父項目POM文件版本或內(nèi)容不一致所致,解決方法包括檢查并修正父項目POM文件中的相對路徑設置2024-09-09

