使用jasypt把配置文件密码加密
1.引入pom坐标
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
2.新增jasypt配置
2.1使用yml配置文件进行配置
jasypt:
encryptor:
password: fast_boot_security
2.2使用System进行配置(适用于代码扫描比较严格的场景,把jasypt的密码放入jvm启动参数)
#在启动类中添加配置
public static void main(String[] args) {
System.setProperty("jasypt.encryptor.password",System.getProperty("jasypt.publicKey"));
ConfigurableApplicationContext run = SpringApplication.run(FastBootApplication.class, args);
System.out.println("run = " + run);
}
在jvm启动参数中添加-D参数:"-Djasypt.publicKey=fast_boot_security"。
3.新增加解密测试类
@RestController
@Api(tags = "ypt测试工具类")
@RequestMapping("ypt")
public class YptTestController extends BaseController {
@Resource
private StringEncryptor stringEncryptor;
@ApiOperation(value = "加密")
@PostMapping("/encrypt")
public R<String> encrypt(String encryptStr) {
return select(this.stringEncryptor.encrypt(encryptStr));
}
@ApiOperation(value = "解密")
@GetMapping("decrypt")
public R<String> decrypt(String decryptStr) {
return select(this.stringEncryptor.decrypt(decryptStr));
}
}
4.替换配置文件中的明文密码
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3307/home-finance?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8
username: root
password: ENC(iKcnV0M2Ro4gEGmegC62bO2vb7y4wo955bpkFmn9mEKQSU63P1UtwvQKN+7MhJmywkrEauRDOAmc5ZKEZy+cg==)