日誌脫敏是常見的安全需求。普通的基於工具類方法的方式,對代碼的入侵性太強。編寫起來又特別麻煩。java
本項目提供基於註解的方式,而且內置了常見的脫敏方式,便於開發。git
基於註解的日誌脫敏。github
能夠自定義策略實現,策略生效條件。安全
常見的脫敏內置方案。maven
java 深拷貝,且原始對象不用實現任何接口。ide
支持用戶自定義註解。工具
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>sensitive-core</artifactId>
<version>0.0.4</version>
</dependency>
複製代碼
v0.0.4 新增功能。容許功能自定義條件註解和策略註解。測試
/** * 自定義密碼脫敏策略 * @author binbin.hou * date 2019/1/17 * @since 0.0.4 */
@Inherited
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@SensitiveStrategy(CustomPasswordStrategy.class)
public @interface SensitiveCustomPasswordStrategy {
}
複製代碼
/** * 自定義密碼脫敏策略生效條件 * @author binbin.hou * date 2019/1/17 * @since 0.0.4 */
@Inherited
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@SensitiveCondition(ConditionFooPassword.class)
public @interface SensitiveCustomPasswordCondition{
}
複製代碼
@SensitiveStrategy
策略單獨使用的時候,默認是生效的。ui
若是有 @SensitiveCondition
註解,則只有當條件知足時,纔會執行脫敏策略。spa
@SensitiveCondition
只會對系統內置註解和自定義註解生效,由於 @Sensitive
有屬於本身的策略生效條件。
@Sensitive
優先生效,而後是系統內置註解,最後是用戶自定義註解。
兩個元註解 @SensitiveStrategy
、@SensitiveCondition
分別指定了對應的實現。
public class CustomPasswordStrategy implements IStrategy {
@Override
public Object des(Object original, IContext context) {
return "**********************";
}
}
複製代碼
/** * 讓這些 123456 的密碼不進行脫敏 * @author binbin.hou * date 2019/1/2 * @since 0.0.1 */
public class ConditionFooPassword implements ICondition {
@Override
public boolean valid(IContext context) {
try {
Field field = context.getCurrentField();
final Object currentObj = context.getCurrentObject();
final String name = (String) field.get(currentObj);
return !name.equals("123456");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
複製代碼
定義一個使用自定義註解的對象。
public class CustomPasswordModel {
@SensitiveCustomPasswordCondition
@SensitiveCustomPasswordStrategy
private String password;
@SensitiveCustomPasswordCondition
@SensitiveStrategyPassword
private String fooPassword;
//其餘方法
}
複製代碼
/** * 自定義註解測試 */
@Test
public void customAnnotationTest() {
final String originalStr = "CustomPasswordModel{password='hello', fooPassword='123456'}";
final String sensitiveStr = "CustomPasswordModel{password='**********************', fooPassword='123456'}";
CustomPasswordModel model = buildCustomPasswordModel();
Assert.assertEquals(originalStr, model.toString());
CustomPasswordModel sensitive = SensitiveUtil.desCopy(model);
Assert.assertEquals(sensitiveStr, sensitive.toString());
Assert.assertEquals(originalStr, model.toString());
}
複製代碼
構建對象的方法以下:
/** * 構建自定義密碼對象 * @return 對象 */
private CustomPasswordModel buildCustomPasswordModel(){
CustomPasswordModel model = new CustomPasswordModel();
model.setPassword("hello");
model.setFooPassword("123456");
return model;
}
複製代碼