1. 引入依赖
<!--数据库加密解密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.14</version>
</dependency>
<!--数据库加密解密结束-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot</artifactId>
<version>1.14</version>
</dependency>
2. yml配置添加盐值
# jasypt
jasypt:
encryptor:
#加密的算法,这个算法是默认的
algorithm: PBEWithMD5AndDES
# jasypt加密的盐值
password: 123456
iv-generator-classname: org.jasypt.iv.NoIvGenerator
3.生成加密后的密匙
@Test
public void test() {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("123456");//yml文件里设置的key
String url = encryptor.encrypt("jdbc:mysql://localhost:3306/数据库名称?serverTimezone=UTC");
String name = encryptor.encrypt("数据库用户名");
String password = encryptor.encrypt("数据库密码");
String url1 = encryptor.decrypt(url);
String name1 = encryptor.decrypt(name);
String password1 = encryptor.decrypt(password);
System.out.println("url密文:"+url);
System.out.println("url明文:"+url1);
System.out.println("username密文:"+name);
System.out.println("username明文:"+name1);
System.out.println("password密文:"+password);
System.out.println("password明文:"+password1);
}
将测试用例中生成的密匙添加到application.yml配置中,数据库密文使用ENC进行标识
spring:
# 数据库配置
datasource:
druid:
driver-class-name: com.mysql.cj.jdbc.Driver
url: ENC(l02FrVAaBYPpTYJ/6eIyoqgoyBH/Ay1PwFcyFfQrkhOyUeh8X4/ipvMxMqSeTfdfxXUZpGnrbYDB8Lf913AgZEYRl4yFe0rZ)
username: ENC(9yyRfS8ljI2kh422XHra0g==)
password: ENC(nCZrXZJSahl2xkXbu9+C/Q==)