一般我们都会把数据库用户名,密码,redis
用户名,密码等敏感信息写在property文件中,但是明文配置很不安全,那么我们就需要对明文进行加密,我们可以使用jasypt
对敏感信息加密。
第一步,导入依赖的包
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>1.8</version>
</dependency>
那这个包肯定支持加密解密,先看一下直接使用该类库如何加密解密:
import org.jasypt.util.text.BasicTextEncryptor;
public class JasyptTest {
private static BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
private static String salt = "welcome";// 加密的密钥
static {
textEncryptor.setPassword(salt);
}
public static String encrypt(final String password) {
return textEncryptor.encrypt(password);// 需要加密的密码
}
public static String decrypt(final String password) {
return textEncryptor.decrypt(password);
}
public static void main(final String[] args) {
String password = "123456";
String encrypt = encrypt(password);
System.out.println(encrypt);
System.out.println(decrypt(encrypt));
}
}
这样我们就可以把要加密的密文放到property文件中
server.port=8081
server.context-path=/app
spring.redis.host=localhost
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=ENC(Hwpma7vHGZDeZlvWB00qSg==)
那接下来我们在程序中如何解密该密码然后连接到redis
呢?
我们只需要在配置文件property中把密钥配置进去,jasypt
就会根据密钥自动解密。具体原理可以看这篇文章。
server.port=8081
server.context-path=/app
#jasypt加密密钥
jasypt.encryptor.password=welcome
spring.redis.host=localhost
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=ENC(Hwpma7vHGZDeZlvWB00qSg==)
但是密钥和密文都放在一起,这不是掩耳盗铃吗?我们可以用之前介绍的 外部文件配置
我们可以在启动项目时候使用命令行参数配置jasypt
密钥 --jasypt.encryptor.password=welcome
或者使用环境变量来配置密钥。