Jasypt简介

Jasypt是一个用于对yml敏感数据进行加密的工具,在公司项目中学到的。

一段内容可以经过一个密钥进行加密,加密后的数据使用该密钥可进行解密

使用方式

添加依赖

1
2
3
4
5
6
<!--yml敏感信息加密工具-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>

使用工具类进行加密

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class JasyptUtil {
public static BasicTextEncryptor textEncryptor = new BasicTextEncryptor();

public static String encrypt(String message) {
return textEncryptor.encrypt(message);
}

public static String decrypt(String message) {
return textEncryptor.decrypt(message);
}

public static void main(String[] args) {
//加密所需的salt(盐)
textEncryptor.setPassword("planb123");
//要加密的数据(数据库的用户名或密码)
String password = encrypt("root");
System.out.println("加密结果:" + password);
password = decrypt(password);
System.out.println("解密结果:" + password);

}
}

修改yml敏感数据

例如数据库账户和密码

1
2
3
4
5
6
7
spring:
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/bookhub?serverTimezone=UTC
username: ENC(ojZbEkkRbUtDdJnNkMmR0w==)
password: ENC(uhJgAJ4GnWNyG/LuBpXZmw==)

启动形式

配置VM运行参数-Djasypt.encryptor.password=planb123

image-20240120194521598

或者打包成jar包后携带参数进行运行

1
java -jar xxx.jar --jasypt.encryptor.password=planb123