jasypt是一个用来加密配置文件中的信息的工具包。使用如下所示
一、引入依赖(版本好根据自己项目自行修改)
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
二、配置加解密的密钥
#jasypt加密的密匙
jasypt:
encryptor:
password: 123qweasefz
为了演示我是将密钥写进了application.yml配置文件,但是在生产环境中,为了防止密钥泄露,反解出密码,一般是在项目部署的时候使用命令传入密钥值。
java -jar xxx.jar -Djasypt.encryptor.password=123qweasefz
三、根据密钥生成加密后的密钥
import org.jasypt.encryption.StringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
public class DatabaseTest {
private StringEncryptor encryptor;
public void getPass(){
String url = encryptor.encrypt("jdbc:mysql://117.66.84.31:3306/sharding-jdbc-db?useUnicode=true&useSSL=false&serverTimezone=Asia/Shanghai");
String name = encryptor.encrypt("root");
String password = encryptor.encrypt("123456");
System.out.println("url:"+url);
System.out.println("name:"+name);
System.out.println("password:"+password);
}
}
四、配置文件application.yml中将加密后的字符串替换原明文
server:
port: 8080
spring:
# 数据库相关配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# 这里加上后缀用来防止mysql乱码,serverTimezone=GMT%2b8设置时区
url: ENC(w7pPKpjHdHIchfu35aE9pw2efpiLAWimekC9wa6ZuEMzgIfzVv9ynymu+gA3ApFJbt7racIb60rbU0LCrDDBLgxFfcnOJVKn/n6pHNmcqBEsoNe5KMSBw2HtWqeWeU02anjJCBu/se1gDOMs0TTY3x7cTF1fxhFRg/ft4f/rsu65PwnBRFK4dVnQ8F2lsIDE)
username: ENC(7Ioe3toofVFqB1x0ML2sIrDjnieGHk743SdgrnXGSX6CAEzdFOkqBtFGeVUAnnLQ)
password: ENC(zmibGREZXVX4hl8mVytEmqQgXVInfxtEr6vg6oZV2Xlv6J9Y2GEimuDtmFCsNXbt)
# jasypt加密的密匙
jasypt:
encryptor:
password: Y6M9fAJQdU7jNp5MW
注意:上面的ENC()是固定的写法