1、引入依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
2、对信息加密 —以mysql数据库密码为例
写一个main方法或者测试方法:
- 设置随机盐及加密算法
- 对mysql数据库密码加密
- 得到加密后的密文,并记录
public static void main(String[] args) {
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
SimpleStringPBEConfig config = new SimpleStringPBEConfig();
// 设置密钥/随机盐
config.setPassword("123456");
// 设置加密方法
config.setAlgorithm("PBEWithMD5AndDES");
encryptor.setConfig(config);
// 加密数据
String encryptStr = encryptor.encrypt("mysql数据库密码");
//每次执行得到加密结果不同,但解密结果都一样
System.out.println(encryptStr);
// 解密
System.out.println(encryptor.decrypt(encryptStr));
}
3、修改配置文件
spring.datasource.password以密文形式进行配置:ENC(密文数据)
spring:
datasource:
username: root
password: ENC(OS40I92MLgDJy3d4A7905wyzrFPI5v4Vt5Zr7RwxsvQ=) //上一步得到的密文密码
url: jdbc:mysql://127.0.0.1:3306/table?serverTimezone=GMT%2B8
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES //上一步用的加密算法
password: 123456 //上一步用的随机盐,这里(自测时)先写上,项目正式部署时去掉
4、启动项目查看数据库是否正常访问
上来一个ERROR。。。
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to bind properties under 'spring.datasource.password' to java.lang.String:
Reason: Failed to bind properties under 'spring.datasource.password' to java.lang.String
Action:
Update your application's configuration
原因是:引入的jasypt依赖3.0.4版本问题,新版本加密算法升级,需加入iv-generator-classname: org.jasypt.iv.NoIvGenerator
,或者退回3.0.0以下版本
重新启动正常运行,数据库正常访问
5、启动传参形式加入随机盐
经过上述测试后,就可以把jasypt.encryptor.password: 123456配置项去掉了。因为随机盐是不能暴露在配置文件中的,否则加密就无意义了。注释掉该项配置,然后项目启动时传入相应参数。
mvn命令启动项目时加入jasypt.encryptor.password=123456随机盐配置:mvn spring-boot:run -Dspring-boot.run.arguments=--jasypt.encryptor.password=123456
(pom中需spring-boot-maven-plugin插件)
启动成功,数据库正常访问!