目标:对数据库密码进行加密
-
源码获取
GitHub:https://github.com/291685399/springboot-learning/tree/master/springboot-jasypt01 -
pom.xml文件添加依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.14</version>
</dependency>
- 在application.properties文件添加jasypt加密秘钥
jasypt.encryptor.password=944ec5b7-148f-4db6-ae0e-612a5106507b
秘钥可以为一串UUID,可以使用UUID生成:
@Test
public void passwordTest() {
System.out.println(UUID.randomUUID());
}
- 对密码进行加密
@Autowired
private StringEncryptor stringEncryptor;
@Test
public void contextLoads() {
System.out.println(stringEncryptor.encrypt("root"));
}
将加密后的密码用“ENC()”括起来,最后spring.datasource.password=ENC(RWswJhLElfDXz04czUWwYg==)
- 对密码进行解密
首先一定要知道密码,即前面配置jasypt.encryptor.password=944ec5b7-148f-4db6-ae0e-612a5106507b,然后配置在Application.properties文件中
@Autowired
private StringEncryptor stringEncryptor;
@Test
public void contextLoads() {
System.out.println(stringEncryptor.decrypt("RWswJhLElfDXz04czUWwYg=="));
}
- 总结
这样就出现了一个问题,如果别人知道你的秘钥(没加密之前的)和加密后的字符串,就可以调用上面的方法进行解密,所以,秘钥还有其他的配置方式:将秘钥添加到启动参数中
java -jar springboot-jasypt01.jar jasypt.encryptor.password=944ec5b7-148f-4db6-ae0e-612a5106507b