### Configure log4j2.xml
Source: https://github.com/houbb/sensitive/blob/master/README.md
Example configuration for using SensitivePatternLayout in log4j2.
```xml
%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
UTF-8
```
--------------------------------
### Example Log Output with Sensitive Data Masking
Source: https://github.com/houbb/sensitive/blob/master/README.md
Demonstrates the typical output format after applying sensitive data masking rules to log messages. Notice how phone numbers, bank cards, and email addresses are masked.
```log
01:42:32.579 [main] INFO c.g.h.sensitive.test2.LogbackMain - mobile:130****7777|9FC4D36D63D2B6DC5AE1297544FBC5A2; bankCard:6217***********5024|444F49289B30944AB8C6C856AEA21180, email:mahu*****@qq.com|897915594C94D981BA86C9E83ADD449C, amount:123.00, " + "IdNo:340110199801016666, name1:李明, name2:李晓明, name3:李泽明天, name4:山东小栗旬" + ", birthday:20220517, GPS:120.882222, IPV4:127.0.0.1, address:中国上海市徐******|821A601949B1BD18DCBAAE27F2E27147;
```
--------------------------------
### Creating Custom Masking Strategy
Source: https://context7.com/houbb/sensitive/llms.txt
Implement the IStrategy interface to define custom data masking logic. This example creates a strategy that masks all but the first and last two characters of a string.
```java
import com.github.houbb.sensitive.api.IStrategy;
import com.github.houbb.sensitive.api.IContext;
import com.github.houbb.sensitive.annotation.Sensitive;
// 自定义策略:只保留前后各2位
public class CustomMaskStrategy implements IStrategy {
@Override
public Object des(Object original, IContext context) {
if (original == null) {
return null;
}
String str = original.toString();
if (str.length() <= 4) {
return "****";
}
int maskLen = str.length() - 4;
StringBuilder sb = new StringBuilder();
sb.append(str.substring(0, 2));
for (int i = 0; i < maskLen; i++) {
sb.append("*");
}
sb.append(str.substring(str.length() - 2));
return sb.toString();
}
}
```
```java
// 使用自定义策略
public class Order {
@Sensitive(strategy = CustomMaskStrategy.class)
private String orderNo;
private double amount;
// getter/setter 略...
}
Order order = new Order();
order.setOrderNo("ORD20231225001234");
order.setAmount(999.99);
Order result = SensitiveUtil.desCopy(order);
System.out.println(result.getOrderNo()); // OR************34
```
--------------------------------
### Implement Custom Condition for Sensitive Data Masking
Source: https://context7.com/houbb/sensitive/llms.txt
Implement the ICondition interface to define custom logic for when sensitive data masking should be applied. This example masks passwords only if they are not the default '123456'. Requires the 'sensitive-core' dependency.
```java
import com.github.houbb.sensitive.api.ICondition;
import com.github.houbb.sensitive.api.IContext;
import com.github.houbb.sensitive.annotation.Sensitive;
import com.github.houbb.sensitive.core.api.strategory.StrategyPassword;
import java.lang.reflect.Field;
// 条件:密码不是默认密码时才脱敏
public class NonDefaultPasswordCondition implements ICondition {
@Override
public boolean valid(IContext context) {
try {
Field field = context.getCurrentField();
Object currentObj = context.getCurrentObject();
String password = (String) field.get(currentObj);
// 默认密码 123456 不脱敏,其他密码脱敏
return !"123456".equals(password);
} catch (IllegalAccessException e) {
return true;
}
}
}
// 使用条件控制
public class UserAccount {
private String username;
@Sensitive(condition = NonDefaultPasswordCondition.class, strategy = StrategyPassword.class)
private String password;
// getter/setter 略...
}
// 测试
UserAccount user1 = new UserAccount();
user1.setUsername("user1");
user1.setPassword("123456"); // 默认密码
UserAccount user2 = new UserAccount();
user2.setUsername("user2");
user2.setPassword("mySecret"); // 非默认密码
System.out.println(SensitiveUtil.desCopy(user1).getPassword()); // 123456 (不脱敏)
System.out.println(SensitiveUtil.desCopy(user2).getPassword()); // null (脱敏)
```
--------------------------------
### Test Log Masking
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/03-log4j2-plugins.md
Example of logging sensitive data that will be automatically masked by the configured policy.
```java
private static final String TEST_LOG = "mobile:13088887777; bankCard:6217004470007335024, email:mahuateng@qq.com, amount:123.00, " +
"IdNo:340110199801016666, name1:李明, name2:李晓明, name3:李泽明天, name4:山东小栗旬" +
", birthday:20220517, GPS:120.882222, IPV4:127.0.0.1, address:中国上海市徐汇区888号;";
logger.info(TEST_LOG);
```
--------------------------------
### Applying @Sensitive Annotation to Fields
Source: https://context7.com/houbb/sensitive/llms.txt
Use the @Sensitive annotation on fields to specify the masking strategy class. This example shows various strategies for different data types.
```java
import com.github.houbb.sensitive.annotation.Sensitive;
import com.github.houbb.sensitive.core.api.strategory.*;
public class Account {
@Sensitive(strategy = StrategyChineseName.class)
private String name;
@Sensitive(strategy = StrategyPhone.class)
private String mobile;
@Sensitive(strategy = StrategyEmail.class)
private String email;
@Sensitive(strategy = StrategyCardId.class)
private String cardNo;
@Sensitive(strategy = StrategyIdNo.class)
private String idCard;
@Sensitive(strategy = StrategyPassword.class)
private String password;
@Sensitive(strategy = StrategyAddress.class)
private String address;
@Sensitive(strategy = StrategyBirthday.class)
private String birthday;
@Sensitive(strategy = StrategyGps.class)
private String gps;
@Sensitive(strategy = StrategyIp.class)
private String ip;
@Sensitive(strategy = StrategyPassport.class)
private String passport;
@Sensitive(strategy = StrategyMaskAll.class)
private String secretData;
@Sensitive(strategy = StrategyMaskHalf.class)
private String partialData;
// getter/setter 略...
}
```
```java
// 使用示例
Account account = new Account();
account.setName("王小明");
account.setMobile("13912345678");
account.setEmail("xiaoming@company.com");
account.setAddress("北京市朝阳区建国路100号");
account.setIp("192.168.1.100");
account.setSecretData("绝密信息不能泄露");
account.setPartialData("部分隐藏即可");
Account result = SensitiveUtil.desCopy(account);
System.out.println(result.getName()); // 王*明 (保留首尾)
System.out.println(result.getAddress()); // 北京市朝阳********0号
System.out.println(result.getIp()); // 192***1.100
System.out.println(result.getSecretData()); // *********
System.out.println(result.getPartialData());// 部分隐藏***
```
--------------------------------
### Create and Checkout New Branch
Source: https://github.com/houbb/sensitive/blob/master/doc/发布流程.md
Commands to create a new release branch and switch to it.
```bash
git branch release_XXX
git checkout release_XXX
```
--------------------------------
### 配置 logback 日志脱敏
Source: https://context7.com/houbb/sensitive/llms.txt
在 Maven 中添加依赖,并在 logback.xml 中通过 conversionRule 或 layout 配置脱敏规则。
```xml
com.github.houbb
sensitive-logback
1.7.0
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %sensitive%n
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
```
--------------------------------
### Prepare Test Data
Source: https://github.com/houbb/sensitive/blob/master/README.md
Initialize a bean instance with sample data to test the masking functionality.
```java
UserAnnotationBean bean = new UserAnnotationBean();
bean.setUsername("张三");
bean.setPassword("123456");
bean.setPassport("CN1234567");
bean.setPhone("13066668888");
bean.setAddress("中国上海市浦东新区外滩18号");
bean.setEmail("whatanice@code.com");
bean.setBirthday("20220831");
bean.setGps("66.888888");
bean.setIp("127.0.0.1");
bean.setMaskAll("可恶啊我会被全部掩盖");
bean.setMaskHalf("还好我只会被掩盖一半");
bean.setMaskRange("我比较灵活指定掩盖范围");
bean.setBandCardId("666123456789066");
bean.setIdNo("360123202306018888");
```
--------------------------------
### Push to Maven Central
Source: https://github.com/houbb/sensitive/blob/master/doc/发布流程.md
Use this command to deploy artifacts to the Maven central repository.
```bash
mvn clean deploy -P release
```
--------------------------------
### Implement Custom Strategy and Condition Logic
Source: https://github.com/houbb/sensitive/blob/master/README.md
Provide the implementation classes for custom strategies and conditions.
```java
public class CustomPasswordStrategy implements IStrategy {
@Override
public Object des(Object original, IContext context) {
return "**********************";
}
}
```
```java
/**
* 让这些 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);
}
}
}
```
--------------------------------
### Logback Integration
Source: https://github.com/houbb/sensitive/blob/master/README.md
Instructions for integrating the sensitive data masking library with Logback.
```APIDOC
## Logback Masking Plugin
### Description
Supports logback plugin mode starting from v1.6.0 for easier user integration.
### Getting Started
#### Maven Dependency
Add the core masking package:
```xml
com.github.houbb
sensitive-logback
1.7.0
```
Add the logback dependency:
```xml
ch.qos.logback
logback-classic
${logback.version}
```
#### Specify logback.xml Configuration
Configure `logback.xml` using either `converter` or `layout` mode.
**Using Converter:**
```xml
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %sensitive%n
```
**Using Layout:**
```xml
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
```
It is recommended to use `SensitiveLogbackConverter` for masking log content.
### Log Effect Example
```
01:42:32.579 [main] INFO c.g.h.sensitive.test2.LogbackMain - mobile:130****7777|9FC4D36D63D2B6DC5AE1297544FBC5A2; bankCard:6217***********5024|444F49289B30944AB8C6C856AEA21180, email:mahu*****@qq.com|897915594C94D981BA86C9E83ADD449C, amount:123.00, " + "IdNo:340110199801016666, name1:李明, name2:李晓明, name3:李泽明天, name4:山东小栗旬" + ", birthday:20220517, GPS:120.882222, IPV4:127.0.0.1, address:中国上海市徐******|821A601949B1BD18DCBAAE27F2E27147;
```
### Configuration Properties
Same as log4j2, not repeated here.
```
--------------------------------
### Configure Hashing Strategy with SensitiveBs
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/02-hash.md
Initialize SensitiveBs and specify the hashing algorithm, such as MD5, for anonymization.
```java
SensitiveBs sensitiveBs = SensitiveBs.newInstance()
.hash(Hashes.md5());
```
--------------------------------
### Java 服务日志脱敏示例
Source: https://context7.com/houbb/sensitive/llms.txt
在业务代码中使用 SLF4J 记录日志,配置后日志输出将自动触发脱敏。
```java
// Java 代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class UserService {
private static final Logger logger = LoggerFactory.getLogger(UserService.class);
public void registerUser(String name, String phone, String idNo, String address) {
logger.info("User registration - name:{}, phone:{}, idNo:{}, address:{}",
name, phone, idNo, address);
}
}
// 调用
userService.registerUser("张三", "13800138000", "110101199001011234", "上海市浦东新区世纪大道100号");
// 日志输出(自动脱敏):
// 10:15:30.456 [main] INFO UserService - User registration - name:张*, phone:138****8000, idNo:1****************4, address:上海市浦东********00号
```
--------------------------------
### Encrypt Coveralls Token for Travis-CI
Source: https://github.com/houbb/sensitive/blob/master/doc/CI集成.md
Generates an encrypted token for use with Coveralls in a Travis-CI environment.
```shell
travis encrypt COVERALLS_TOKEN=${your_repo_token}
```
--------------------------------
### 内置脱敏注解列表
Source: https://context7.com/houbb/sensitive/llms.txt
框架提供的 13 种内置脱敏注解,用于处理不同类型的敏感数据。
```java
// 脱敏注解与效果对照
@SensitiveStrategyChineseName // 张三 -> 张*
@SensitiveStrategyPhone // 13066668888 -> 1306****888
@SensitiveStrategyEmail // test@example.com -> te************.com
@SensitiveStrategyIdNo // 360123202306018888 -> 3****************8
@SensitiveStrategyCardId // 6217004470007335024 -> 621700*******5024
@SensitiveStrategyPassword // mypassword -> null
@SensitiveStrategyAddress // 上海市浦东新区外滩18号 -> 上海市浦********8号
@SensitiveStrategyBirthday // 20220831 -> 20*****1
@SensitiveStrategyGps // 121.473701 -> 121****01
@SensitiveStrategyIp // 192.168.1.1 -> 192***1.1
@SensitiveStrategyPassport // CN1234567 -> CN*****67
@SensitiveStrategyMaskAll // 任意文本 -> ******
@SensitiveStrategyMaskHalf // 任意文本 -> 任意***
@SensitiveStrategyMaskRange // 任意文本 -> *****本
```
--------------------------------
### Commit to GitHub
Source: https://github.com/houbb/sensitive/blob/master/doc/发布流程.md
Standard command to push local commits to the remote GitHub repository.
```bash
git push
```
--------------------------------
### Configure SensitivePatternLayout Properties
Source: https://github.com/houbb/sensitive/blob/master/README.md
Default properties for customizing the scanning and replacement behavior of the layout.
```properties
chars.scan.prefix=::,,'"‘“=| +()()
chars.scan.scanList=1,2,3,4,9
chars.scan.replaceList=1,2,3,4,9
chars.scan.defaultReplace=12
chars.scan.replaceHash=md5
chars.scan.whiteList=""
```
--------------------------------
### Define Custom Annotations
Source: https://github.com/houbb/sensitive/blob/master/README.md
Create custom strategy and condition annotations using meta-annotations.
```java
/**
* 自定义密码脱敏策略
* @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 {
}
```
```java
/**
* 自定义密码脱敏策略生效条件
* @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{
}
```
--------------------------------
### Add Encrypted Token to Travis Configuration
Source: https://github.com/houbb/sensitive/blob/master/doc/CI集成.md
Automatically appends the encrypted Coveralls token to the .travis.yml file.
```shell
travis encrypt COVERALLS_TOKEN=${your_repo_token} --add
```
--------------------------------
### Configure SensitiveBs Bootstrap
Source: https://github.com/houbb/sensitive/blob/master/README.md
Initializes and uses the SensitiveBs bootstrap class for flexible masking configuration.
```java
SensitiveBs.newInstance()
.deepCopy(FastJsonDeepCopy.getInstance())
.hash(Hashes.empty())
```
```java
SensitiveBs.newInstance().desCopy(user);
```
--------------------------------
### Performance Benchmarks
Source: https://github.com/houbb/sensitive/blob/master/README.md
Performance comparison of different methods for sensitive data masking.
```APIDOC
# Performance Timings
## Annotations
1 million operations timing:
| Method | Time (ms) | Description |
|---|---|---|
| Original utility method | 122 | Best performance, but most cumbersome. Worst extensibility. |
| JSON.toJSONString(user) | 304 | Good performance, decent extensibility. Dependency on fastjson is a drawback. |
| SensitiveUtil.desJson(user) | 1541 | Poor performance, best extensibility, very flexible. |
```
--------------------------------
### Add Maven Dependencies
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/03-log4j2-plugins.md
Include the core sensitive-log4j2 library and the required log4j2 dependencies in your project.
```xml
com.github.houbb
sensitive-log4j2
1.2.1
```
```xml
org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
```
--------------------------------
### Maven Dependency for Logback Classic
Source: https://github.com/houbb/sensitive/blob/master/README.md
Ensure you have the logback-classic dependency included in your project.
```xml
ch.qos.logback
logback-classic
${logback.version}
```
--------------------------------
### Configure Deep Copy Implementation
Source: https://github.com/houbb/sensitive/blob/master/README.md
Specifies a custom deep copy implementation for object processing.
```java
SensitiveBs.newInstance()
.deepCopy(FastJsonDeepCopy.getInstance())
.desJson(user);
```
--------------------------------
### Configure Hashing Strategy
Source: https://github.com/houbb/sensitive/blob/master/README.md
Sets a hashing strategy for sensitive data using the SensitiveBs builder.
```java
// 指定哈希策略
final SensitiveBs sensitiveBs = SensitiveBs.newInstance().hash(Hashes.md5());
```
--------------------------------
### Roadmap
Source: https://github.com/houbb/sensitive/blob/master/README.md
Future development plans for the sensitive data masking library.
```APIDOC
# ROAD-MAP
- [ ] Abstraction of configuration
- [x] Add a unified utility method for standalone use
Prefer overriding toString(), or special scenarios
- [x] Consider adding support for MAP masking
- [x] Default masking strategy for ID cards
- [x] Masking strategies for log components like log4j2
Enhance extensibility
- [x] Masking strategy corresponding to log4j2 layout
- [x] Optimize code implementation, inherit directly from patternLayout
- [x] Add specific configuration file for log4j2 masking configuration, instead of in pattern
- [ ] Log plugin masking benchmark performance report
```
--------------------------------
### Logback Configuration with SensitiveLogbackConverter
Source: https://github.com/houbb/sensitive/blob/master/README.md
Configure Logback to use the SensitiveLogbackConverter for masking sensitive data directly within the log pattern. This is the recommended approach for masking log content.
```xml
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %sensitive%n
%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
```
--------------------------------
### Advanced Sensitive Data Masking with SensitiveBs and Hashing
Source: https://context7.com/houbb/sensitive/llms.txt
Configure advanced sensitive data masking using the SensitiveBs builder, including specifying hash strategies like MD5. This allows for masking sensitive data while appending a hash of the original value. Requires 'sensitive-core' and 'sensitive-hash' dependencies.
```java
import com.github.houbb.sensitive.core.bs.SensitiveBs;
import com.github.houbb.hash.core.core.hash.Hashes;
UserInfo user = new UserInfo();
user.setUsername("脱敏君");
user.setPhone("18888888888");
user.setEmail("test@example.com");
user.setIdNo("123456190001011234");
// 配置 MD5 哈希,脱敏值后附加原值的 MD5 哈希
SensitiveBs sensitiveBs = SensitiveBs.newInstance()
.hash(Hashes.md5());
// 使用引导类脱敏
UserInfo result = sensitiveBs.desCopy(user);
String json = sensitiveBs.desJson(user);
System.out.println(result.getUsername());
// 输出: 脱**|00871641C1724BB717DD01E7E5F7D98A
System.out.println(result.getPhone());
// 输出: 1888****888|5425DE6EC14A0722EC09A6C2E72AAE18
System.out.println(json);
// 输出: {"email":"te************.com|..MD5..","idNo":"1****************4|..MD5..","phone":"1888****888|..MD5..","username":"脱**|..MD5.."}
```
--------------------------------
### Configure log4j2.xml
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/03-log4j2-plugins.md
Register the SensitiveRewritePolicy in your log4j2 configuration to enable automatic log masking.
```xml
```
--------------------------------
### Add Maven Dependencies
Source: https://github.com/houbb/sensitive/blob/master/README.md
Required dependencies for log4j2 sensitive data masking.
```xml
com.github.houbb
sensitive-log4j2
1.7.0
```
```xml
org.apache.logging.log4j
log4j-api
${log4j2.version}
org.apache.logging.log4j
log4j-core
${log4j2.version}
```
--------------------------------
### Anonymize User Object and JSON Output
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/02-hash.md
Demonstrates anonymizing a User object and converting it to a sensitive JSON string. Asserts that the original and anonymized string representations are as expected, and the JSON output matches the expected format.
```java
final SensitiveBs sensitiveBs = SensitiveBs.newInstance()
.hash(Hashes.md5());
User sensitiveUser = sensitiveBs.desCopy(user);
String sensitiveJson = sensitiveBs.desJson(user);
Assert.assertEquals(sensitiveStr, sensitiveUser.toString());
Assert.assertEquals(originalStr, user.toString());
Assert.assertEquals(expectJson, sensitiveJson);
```
--------------------------------
### Object Deep Copy Masking with SensitiveUtil.desCopy
Source: https://context7.com/houbb/sensitive/llms.txt
Use desCopy to create a deep copy of an object and apply masking. The original object remains unchanged, making it suitable for scenarios where both original and masked data are needed, such as logging.
```java
import com.github.houbb.sensitive.annotation.strategy.*;
import com.github.houbb.sensitive.core.api.SensitiveUtil;
// 定义带脱敏注解的用户类
public class UserInfo {
@SensitiveStrategyChineseName
private String username;
@SensitiveStrategyPhone
private String phone;
@SensitiveStrategyEmail
private String email;
@SensitiveStrategyIdNo
private String idNo;
@SensitiveStrategyCardId
private String bankCard;
@SensitiveStrategyPassword
private String password;
// getter/setter 略...
}
// 使用示例
UserInfo user = new UserInfo();
user.setUsername("张三");
user.setPhone("13066668888");
user.setEmail("zhangsan@example.com");
user.setIdNo("360123202306018888");
user.setBankCard("6217004470007335024");
user.setPassword("mySecret123");
// 执行脱敏,返回新对象
UserInfo sensitiveUser = SensitiveUtil.desCopy(user);
// 输出结果
System.out.println(sensitiveUser.getUsername()); // 张*
System.out.println(sensitiveUser.getPhone()); // 1306****888
System.out.println(sensitiveUser.getEmail()); // zh************.com
System.out.println(sensitiveUser.getIdNo()); // 3****************8
System.out.println(sensitiveUser.getBankCard()); // 621700*******5024
System.out.println(sensitiveUser.getPassword()); // null
// 原始对象不受影响
System.out.println(user.getPhone()); // 13066668888
```
--------------------------------
### Execute Masking Tests
Source: https://github.com/houbb/sensitive/blob/master/README.md
Use SensitiveUtil to perform object-level masking or JSON-level masking and verify the results.
```java
final String originalStr = "UserAnnotationBean{username='张三', password='123456', passport='CN1234567', idNo='360123202306018888', bandCardId='666123456789066', phone='13066668888', email='whatanice@code.com', address='中国上海市浦东新区外滩18号', birthday='20220831', gps='66.888888', ip='127.0.0.1', maskAll='可恶啊我会被全部掩盖', maskHalf='还好我只会被掩盖一半', maskRange='我比较灵活指定掩盖范围'}";
final String sensitiveStr = "UserAnnotationBean{username='张*', password='null', passport='CN*****67', idNo='3****************8', bandCardId='666123*******66', phone='1306****888', email='wh************.com', address='中国上海********8号', birthday='20*****1', gps='66*****88', ip='127***0.1', maskAll='**********', maskHalf='还好我只会*****', maskRange='我*********围'}";
final String expectSensitiveJson = "{\"address\":\"中国上海********8号\",\"bandCardId\":\"666123*******66\",\"birthday\":\"20*****1\",\"email\":\"wh************.com\",\"gps\":\"66*****88\",\"idNo\":\"3****************8\",\"ip\":\"127***0.1\",\"maskAll\":\"**********\",\"maskHalf\":\"还好我只会*****\",\"maskRange\":\"我*********围\",\"passport\":\"CN*****67\",\"phone\":\"1306****888\",\"username\":\"张*\"}";
UserAnnotationBean sensitiveUser = SensitiveUtil.desCopy(bean);
Assert.assertEquals(sensitiveStr, sensitiveUser.toString());
Assert.assertEquals(originalStr, bean.toString());
String sensitiveJson = SensitiveUtil.desJson(bean);
Assert.assertEquals(expectSensitiveJson, sensitiveJson);
```
--------------------------------
### Java Code for Log4j2 Automatic Log Masking
Source: https://context7.com/houbb/sensitive/llms.txt
Demonstrates how to log sensitive information directly in Java code without modification, relying on the configured log4j2 SensitivePatternLayout to automatically mask data like mobile numbers, bank cards, and emails. Ensure the 'sensitive-log4j2' dependency and log4j2 configuration are in place.
```java
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class PaymentService {
private static final Logger logger = LogManager.getLogger(PaymentService.class);
public void processPayment(String mobile, String bankCard, String email) {
// 直接打印敏感信息,插件自动脱敏
logger.info("Processing payment - mobile:{}, bankCard:{}, email:{}",
mobile, bankCard, email);
}
}
// 调用
service.processPayment("13088887777", "6217004470007335024", "user@example.com");
// 日志输出(自动脱敏):
// 14:30:25.123 [main] INFO PaymentService - Processing payment - mobile:130****7777, bankCard:6217***********5024, email:us***********.com
```
--------------------------------
### Modify Project Version with Maven
Source: https://github.com/houbb/sensitive/blob/master/doc/发布流程.md
Commands to update the project version using the Maven versions plugin. This includes setting a new version, updating child modules, and committing the changes.
```bash
mvn versions:set -DgroupId=com.github.houbb -DartifactId=paradise* -DoldVersion=1.1.2 -DnewVersion=1.1.3-SNAPSHOT
mvn -N versions:update-child-modules
mvn versions:commit
```
--------------------------------
### Use Custom Annotations in Model
Source: https://github.com/houbb/sensitive/blob/master/README.md
Apply the custom annotations to fields in a model class.
```java
public class CustomPasswordModel {
@SensitiveCustomPasswordCondition
@SensitiveCustomPasswordStrategy
private String password;
@SensitiveCustomPasswordCondition
@SensitiveStrategyPassword
private String fooPassword;
//其他方法
}
```
--------------------------------
### SensitiveBs Bootstrap API
Source: https://github.com/houbb/sensitive/blob/master/README.md
Flexible configuration and execution of masking operations using the SensitiveBs bootstrap class.
```APIDOC
## POST /SensitiveBs/execute
### Description
Provides a fluent API to configure and execute masking operations, allowing for custom deep copy strategies and hash configurations.
### Method
POST
### Parameters
#### Request Body
- **object** (Object) - Required - The target object to process.
### Response
#### Success Response (200)
- **result** (Object/String) - The masked result based on the chosen method (desCopy or desJson).
```
--------------------------------
### Conditional Masking Implementation
Source: https://github.com/houbb/sensitive/blob/master/README.md
Define custom conditions to control when masking should occur.
```java
@Sensitive(condition = ConditionFooPassword.class, strategy = StrategyPassword.class)
private String password;
```
```java
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);
}
}
}
```
--------------------------------
### Merge Branch into Master
Source: https://github.com/houbb/sensitive/blob/master/doc/发布流程.md
Steps to merge a feature branch into the master branch, including rebasing and resolving conflicts.
```bash
git checkout master
git pull
git checkout branch
git rebase master (用rebase合并主干的修改,如果有冲突在此时解决)
git checkout master
git merge branch
git push
```
--------------------------------
### Customize SensitiveRewritePolicy
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/03-log4j2-plugins.md
Override default settings for the masking policy within the log4j2 configuration.
```xml
```
--------------------------------
### Custom Log4j2 Sensitive Data Scanning Configuration
Source: https://context7.com/houbb/sensitive/llms.txt
Define custom sensitive data masking rules for log4j2 by creating a 'resources/chars-scan-config.properties' file. This allows specifying character prefixes, scan lists (e.g., phone, ID, email), replacement strategies, and hash policies.
```properties
# 敏感信息匹配前缀字符
chars.scan.prefix=::,,'"'"'=| +()()
# 扫描策略: 1-手机号 2-身份证 3-银行卡 4-邮箱 5-中国人名 6-生日 7-GPS 8-IPv4 9-地址 10-护照
chars.scan.scanList=1,2,3,4,9
# 替换策略
chars.scan.replaceList=1,2,3,4,9
# 默认替换策略: 12-半掩盖
chars.scan.defaultReplace=12
# 哈希策略: md5 或 none
chars.scan.replaceHash=md5
# 白名单(不脱敏的信息)
chars.scan.whiteList=""
```
--------------------------------
### Log4j2 Sensitive Data Masking Plugin Configuration
Source: https://context7.com/houbb/sensitive/llms.txt
Integrate sensitive data masking into log4j2 by using the SensitivePatternLayout. This requires adding the 'sensitive-log4j2' Maven dependency and configuring log4j2.xml to use the custom layout. Sensitive data in logs will be automatically masked.
```xml
com.github.houbb
sensitive-log4j2
1.7.0
%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n
```
--------------------------------
### SensitivePatternLayout Properties
Source: https://github.com/houbb/sensitive/blob/master/README.md
Properties for configuring the SensitivePatternLayout strategy for data masking.
```APIDOC
## SensitivePatternLayout Properties
Properties for configuring the SensitivePatternLayout strategy.
| Property | Description | Default Value | Notes |
|---|---|---|---|
| prefix | Matching prefix for sensitive information | `::,,'"‘“= +()()` and English vertical bar | Reduces false positives |
| replaceHash | Hashing strategy mode | `md5` | Supports md5/none modes |
| scanList | Sensitive scan strategy list | `1,2,3,4` | Built-in 10 sensitive information scanning strategies (1-10), separated by commas |
| replaceList | Sensitive replacement strategy list | `1,2,3,4` | Built-in 10 sensitive information replacement strategies (1-10), separated by commas |
| defaultReplace | Default sensitive replacement strategy | `12` | Built-in 13 sensitive information replacement strategies (1-13), specify one. Used when no list matches |
| whiteList | Whitelist | `` | Information to be skipped during processing |
Built-in strategies (1-13):
| Strategy ID | Description |
|---|---|
| 1 | Mobile phone |
| 2 | ID card |
| 3 | Bank card |
| 4 | Email |
| 5 | Chinese name |
| 6 | Date of birth |
| 7 | GPS |
| 8 | IPv4 |
| 9 | Address |
| 10 | Passport |
| 11 | Match any non-masked |
| 12 | Match any partially masked |
| 13 | Match any fully masked |
| m1 | Numeric merge operation (m1:1&2&3) better performance |
| m3 | Extended merge operation (m3:4&5&9) better performance |
```
--------------------------------
### Maven Dependency for Sensitive Logback
Source: https://github.com/houbb/sensitive/blob/master/README.md
Include this dependency in your pom.xml to add the sensitive-logback core functionality.
```xml
com.github.houbb
sensitive-logback
1.7.0
```
--------------------------------
### SensitiveUtil.desCopy(Object)
Source: https://github.com/houbb/sensitive/blob/master/README.md
Creates a deep copy of an object with sensitive fields masked.
```APIDOC
## POST /SensitiveUtil/desCopy
### Description
Performs a deep copy of the provided object and applies masking to sensitive fields. The original object remains unchanged.
### Method
POST
### Parameters
#### Request Body
- **object** (Object) - Required - The target object to be deep-copied and masked.
### Response
#### Success Response (200)
- **object** (Object) - A new instance of the object with masked values.
```
--------------------------------
### Maven Dependency for Sensitive Core
Source: https://github.com/houbb/sensitive/blob/master/doc/issues/02-hash.md
Include this dependency in your pom.xml to use the sensitive core functionalities.
```xml
com.github.houbb
sensitive-core
1.1.0
```
--------------------------------
### Maven Dependency for Sensitive Core
Source: https://context7.com/houbb/sensitive/llms.txt
Include this dependency to enable annotation-based object masking functionality.
```xml
com.github.houbb
sensitive-core
1.7.0
```
--------------------------------
### Batch Collection Masking with SensitiveUtil.desCopyCollection
Source: https://context7.com/houbb/sensitive/llms.txt
Utilize desCopyCollection to mask each object within a collection, returning a new list of masked objects. desJsonCollection can be used to generate a list of masked JSON strings.
```java
import com.github.houbb.sensitive.core.api.SensitiveUtil;
import java.util.*;
List userList = new ArrayList<>();
userList.add(createUser("张三", "13011112222"));
userList.add(createUser("李四", "13033334444"));
userList.add(createUser("王五", "13055556666"));
// 批量脱敏
List sensitiveList = SensitiveUtil.desCopyCollection(userList);
for (UserInfo u : sensitiveList) {
System.out.println(u.getUsername() + ": " + u.getPhone());
}
// 输出:
// 张*: 1301****222
// 李*: 1303****444
// 王*: 1305****666
// 批量生成脱敏 JSON
List jsonList = SensitiveUtil.desJsonCollection(userList);
jsonList.forEach(System.out::println);
```
--------------------------------
### Direct Masked JSON Generation with SensitiveUtil.desJson
Source: https://context7.com/houbb/sensitive/llms.txt
Use desJson to directly generate a masked JSON string from an object, bypassing intermediate object creation for better performance. This is ideal for logging purposes.
```java
import com.github.houbb.sensitive.core.api.SensitiveUtil;
UserInfo user = new UserInfo();
user.setUsername("李四");
user.setPhone("18888888888");
user.setEmail("lisi@qq.com");
user.setIdNo("110101199003077890");
user.setBankCard("6222021234567890123");
user.setPassword("password123");
// 直接生成脱敏 JSON
String sensitiveJson = SensitiveUtil.desJson(user);
System.out.println(sensitiveJson);
// 输出: {"bankCard":"622202*******0123","email":"li*******.com","idNo":"1****************0","phone":"1888****888","username":"李*"}
// 原始对象依然完整
System.out.println(user.getPhone()); // 18888888888
```
--------------------------------
### Test Custom Annotation Masking
Source: https://github.com/houbb/sensitive/blob/master/README.md
Verifies that custom annotations correctly mask sensitive fields without modifying the original object.
```java
/**
* 自定义注解测试
*/
@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());
}
```
```java
/**
* 构建自定义密码对象
* @return 对象
*/
private CustomPasswordModel buildCustomPasswordModel(){
CustomPasswordModel model = new CustomPasswordModel();
model.setPassword("hello");
model.setFooPassword("123456");
return model;
}
```