日誌脫敏是常見的安全需求。普通的基於工具類方法的方式,對代碼的入侵性太強。編寫起來又特別麻煩。java
本項目提供基於註解的方式,而且內置了常見的脫敏方式,便於開發。git
<dependency> <groupId>com.github.houbb</groupId> <artifactId>sensitive-core</artifactId> <version>0.0.4</version> </dependency>
v0.0.4 新增功能。容許功能自定義條件註解和策略註解。github
/** * 自定義密碼脫敏策略 * @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
策略單獨使用的時候,默認是生效的。安全
若是有 @SensitiveCondition
註解,則只有當條件知足時,纔會執行脫敏策略。maven
@SensitiveCondition
只會對系統內置註解和自定義註解生效,由於 @Sensitive
有屬於本身的策略生效條件。ide
@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); } } }
定義一個使用自定義註解的對象。ui
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; }