0%

jasypt加密SpringBoot配置文件

文章字数:290,阅读全文大约需要1分钟

application.properties中经常会放账户密码数据库连接地址等敏感信息,可能会造成信息的泄露。使用jasypt可以加密解密配置文件。

引入

1
2
3
4
5
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.5</version>
</dependency>

使用

  1. 通过密钥生成密文
  • 下载jasypt-1.9.2.jar生成
1
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=G0CvDz7oJn6 algorithm=PBEWithMD5AndDES input=root

结果

1
2
3
4
5
6
7
8
9
10
----ENVIRONMENT-----------------
Runtime: Oracle Corporation Java HotSpot(TM) 64-Bit Server VM 25.171-b11

----ARGUMENTS-------------------
input: root
algorithm: PBEWithMD5AndDES
password: G0CvDz7oJn6

----OUTPUT----------------------
Gvkoz+sbFWiRe3ECtizV1A==
  • 代码生成
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import org.jasypt.util.text.BasicTextEncryptor;
import java.util.UUID;

public class testTest {

public static void main(String[] args) {
testTest t = new testTest();
t.getPass();
}

/**
* 加密解密
*/
public void getPass() {
BasicTextEncryptor stringEncryptor = new BasicTextEncryptor();
//设置密钥
stringEncryptor.setPassword("tfa46e505nh4565e5o8adjg4a8e01by");

//加密数据
String url = stringEncryptor.encrypt("url");
String name = stringEncryptor.encrypt("username");
String password = stringEncryptor.encrypt("pwd");
//结果
System.out.println("-----------------url------------------");
System.out.println("ENC("+url+")");
System.out.println("-----------------name------------------");
System.out.println("ENC("+name+")");
System.out.println("-----------------pwd------------------");
System.out.println("ENC("+password+")");

//手动密文解密
password = password.replace("ENC(","");
password = password.replace(")","");
String decrypted = stringEncryptor.decrypt(password);
System.out.println("-----------------decrypt------------------");
System.out.println(decrypted);

//自动生成密钥
String uuid = UUID.randomUUID().toString().replaceAll("-","");
System.out.println("-----------------uuid------------------");
System.out.println(uuid);
}
}
  1. 配置文件
1
2
3
4
5
# 加密所需的salt(盐),和生成密文时使用的要一样
jasypt.encryptor.password=tfa46e505nh4565e5o8adjg4a8e01by
# 加密后的密文,使用ENC(...)包裹
spring.datasource.username=ENC(6eaMh/RX5oXUVca9ignvtg==)
spring.datasource.password=ENC(6eaMh/RX5oXUVca9ignvtg==)
  1. 开启加密

项目里没有使用@SpringBootApplication或者@EnableAutoConfiguration,可以手动在Configuration类上添加注解@EnableEncryptableProperties,来在整个环境的属性启用属性加密。