以下是常見的脫敏方法及實現步驟,涵蓋配置、日志和API響應等多個層面:
?1. 配置文件敏感信息脫敏?
(1) 使用加密庫(如Jasypt)
?步驟?:
-
添加依賴:
<dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.5</version> </dependency>
-
加密密碼:
BasicTextEncryptor encryptor = new BasicTextEncryptor(); encryptor.setPassword("your-secret-key"); // 加密密鑰 String encryptedPassword = encryptor.encrypt("your-real-password");
-
在配置文件中使用加密值(用
ENC()
包裹):spring:datasource:password: ENC(encryptedPassword)
-
啟動時指定密鑰:
java -jar your-app.jar --jasypt.encryptor.password=your-secret-key
(2) 自定義屬性源(實現PropertySource
)
public class MaskedPropertySource extends PropertySource<Map<String, Object>> {public MaskedPropertySource(String name, Map<String, Object> source) {super(name, source);}@Overridepublic Object getProperty(String name) {Object value = source.get(name);if (name.contains("password") && value != null) {return "?**?*?**?*"; // 返回脫敏值}return value;}
}
?2. 日志脫敏?
(1) 使用Logback的replace
功能
在logback-spring.xml
中配置脫敏規則:
<configuration><conversionRule conversionWord="maskedMsg" converterClass="com.example.MaskingPatternLayout"/><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{HH:mm:ss} [%thread] %-5level %logger{36} - %maskedMsg%n</pattern></encoder></appender><root level="info"><appender-ref ref="CONSOLE" /></root>
</configuration>
自定義轉換器:
public class MaskingPatternLayout extends PatternLayout {@Overridepublic String doLayout(ILoggingEvent event) {String message = super.doLayout(event);return message.replaceAll("password\":\"(.*?)\"", "password\":\"?**?*?**?*\"");}
}
?3. API響應脫敏?
(1) 使用Jackson注解忽略敏感字段
public class UserDTO {private String username;@JsonIgnore // 完全忽略該字段private String password;@JsonProperty(access = Access.WRITE_ONLY) // 僅允許寫入,響應時不序列化private String secretKey;
}
(2) 自定義序列化器
public class PasswordSerializer extends JsonSerializer<String> {@Overridepublic void serialize(String value, JsonGenerator gen, SerializerProvider provider) throws IOException {gen.writeString("?**?*?**?*"); // 返回固定脫敏值}
}// 在DTO字段上指定序列化器
public class UserResponse {@JsonSerialize(using = PasswordSerializer.class)private String password;
}
?4. 其他注意事項?
- ?環境變量?:優先使用環境變量傳遞敏感信息,而非明文配置文件:
export SPRING_DATASOURCE_PASSWORD=your_password
- ?安全存儲密鑰?:加密密鑰(如Jasypt的密鑰)應通過安全渠道(如KMS、Vault)管理,避免硬編碼。
- ?代碼審查?:避免在代碼中硬編碼密碼,使用
.gitignore
排除敏感配置文件。
?總結?
通過配置文件加密(如Jasypt)、日志脫敏(Logback替換)和API響應控制(Jackson注解),可全方位保護敏感信息。建議結合多種方案,確保密碼在存儲、傳輸和展示時均處于脫敏狀態。