爲了保證用戶的信息安全,敏感信息須要脫敏。 項目開發過程當中,每次處理敏感信息的日誌問題感受很麻煩,大部分都是用工具類單獨處理,不利於之後統一管理,很不優雅。 因而,就寫了一個基於 java 註解的日誌脫敏工具。java
日誌脫敏是常見的安全需求。普通的基於工具類方法的方式,對代碼的入侵性太強。編寫起來又特別麻煩。github
本項目提供基於註解的方式,而且內置了常見的脫敏方式,便於開發。編程
用戶也能夠基於本身的實際須要,自定義註解。安全
變動日誌bash
爲了金融交易的安全性,國家強制規定對於如下信息是要日誌脫敏的:框架
用戶名maven
手機號ide
郵箱工具
銀行卡號
密碼
存儲的時候上面的信息都須要加密,密碼爲不可逆加密,其餘爲可逆加密。
相似的功能有不少。不在本系統的解決範圍內。
基於註解的日誌脫敏
能夠自定義策略實現,策略生效條件
常見的脫敏內置方案
<dependency>
<groupId>com.github.houbb</groupId>
<artifactId>sensitive-core</artifactId>
<version>0.0.1</version>
</dependency>
複製代碼
咱們對 password 使用脫敏,指定脫敏策略爲 StrategyPassword。(直接返回 null)
public class User {
@Sensitive(strategy = StrategyChineseName.class)
private String username;
@Sensitive(strategy = StrategyCardId.class)
private String idCard;
@Sensitive(strategy = StrategyPassword.class)
private String password;
@Sensitive(strategy = StrategyEmail.class)
private String email;
@Sensitive(strategy = StrategyPhone.class)
private String phone;
//Getter & Setter
//toString()
}
複製代碼
@Test
public void UserSensitiveTest() {
User user = buildUser();
System.out.println("脫敏前原始: " + user);
User sensitiveUser = SensitiveUtil.desCopy(user);
System.out.println("脫敏對象: " + sensitiveUser);
System.out.println("脫敏後原始: " + user);
}
private User buildUser() {
User user = new User();
user.setUsername("脫敏君");
user.setPassword("123456");
user.setEmail("12345@qq.com");
user.setIdCard("123456190001011234");
user.setPhone("18888888888");
return user;
}
複製代碼
脫敏前原始: User{username='脫敏君', idCard='123456190001011234', password='1234567', email='12345@qq.com', phone='18888888888'}
脫敏對象: User{username='脫*君', idCard='123456**********34', password='null', email='123**@qq.com', phone='188****8888'}
脫敏後原始: User{username='脫敏君', idCard='123456190001011234', password='1234567', email='12345@qq.com', phone='18888888888'}
複製代碼
咱們能夠直接利用 sensitiveUser
去打印日誌信息,而這個對象對於代碼其餘流程不影響,咱們依然可使用原來的 user
對象。
默認狀況下,咱們指定的場景都是生效的。
可是你可能須要有些狀況下不進行脫敏,好比有些用戶密碼爲 123456,你以爲這種用戶不脫敏也罷。
@Sensitive(condition = ConditionFooPassword.class, strategy = StrategyPassword.class)
private String password;
複製代碼
其餘保持不變,咱們指定了一個 condition,實現以下:
public class ConditionFooPassword implements ICondition {
@Override
public boolean valid(IContext context) {
try {
Field field = context.getCurrentField();
final Object currentObj = context.getCurrentObject();
final String password = (String) field.get(currentObj);
return !password.equals("123456");
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
複製代碼
也就是隻有當密碼不是 123456 時密碼脫敏策略纔會生效。
上面的例子是基於註解式的編程,若是你只是單個字段。好比
@Test
public void singleSensitiveTest() {
final String email = "123456@qq.com";
IStrategy strategy = new StrategyEmail();
final String emailSensitive = (String) strategy.des(email, null);
System.out.println("脫敏後的郵箱:" + emailSensitive);
}
複製代碼
脫敏後的郵箱:123***@qq.com
複製代碼
這種方式爲了不修改原始對象,建立了一個全新的對象,有點點浪費,能夠優化。
能夠基於 log4j2/logback 等轉換器進行敏感信息的脫敏,可是不具備不一樣的 log 框架的可移植性。