SpringBoot配置文件脱敏
SpringBoot集成Jasypt配置很简单,只需引入依赖,然后配置Jasypt相关属性参数即可:
● Maven
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
1、使用默认加解密方式
● 生成密文
package com.example.jasptytest;
import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JasptyTestApplicationTests {
@Autowired
StringEncryptor stringEncryptor;
@Test
void contextLoads() {
final String url = stringEncryptor.encrypt("jdbc:mysql://172.16.156.158:3306/lucene?characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai");
final String u = stringEncryptor.encrypt("wq");
final String p = stringEncryptor.encrypt("qifeng");
System.out.println("url: " + url);
System.out.println("u: " + u);
System.out.println("p: " + p);
}
}
2、使用指定加解密方式
● 配置加解密bean
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES
bean: stringEncryptor
● 注册加解密bean
@Bean("stringEncryptor")
public StringEncryptor stringEncryptor(@Value("${jasypt.encryptor.password}") String password){
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword(password);
encryptor.setAlgorithm("PBEWithMD5AndDES");
return encryptor;
}
● 生成密文
public static void main(String[] args) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("sdas$%#^*GHJu");
encryptor.setAlgorithm("PBEWithMD5AndDES");
final String url = encryptor.encrypt("jdbc:mysql://172.16.156.158:3306/lucene?characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai");
final String u = encryptor.encrypt("wq");
final String p = encryptor.encrypt("qifeng");
System.out.println("url: " + url);
System.out.println("u: " + u);
System.out.println("p: " + p);
}
3、使用
● 配置文件加密
密文使用ENC()包裹
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
url: ENC(NjKtplPL9XmtxnUCz7ySOM8259+OH3mBf378s5bYNRoogK8hlltoSMOoalABVsRpp+6Q3b7ZsIm3aJERPjv5hSC0lOEJYegyzUNvv3m2Sq0hXZ5qdyLkugNtRhsF7w6seZN7eN/OdVW2QRWchvmCUG7ChLzlMP5NhbBk62/hSFPthLQDMUnHHJv8iT5EB1m8)
driver-class-name: com.mysql.cj.jdbc.Driver
username: ENC(4ZqAMYAkPXJmTyBptPa1osuHeD62D4LYtqO1iC70Htd+1ILWTui2ZXW2EDPWkGst)
password: ENC(b6YpA5JYiWImDqhz5uVeHYLM2K3eJihVbgGfgoaH0hMR3QOljes4Kb0ckvu+xk4s)
● 启动应用时,配置系统属性,idea配置VM选项
java -jar test.jar -Djasypt.encryptor.password=sdas$%#^*GHJu