在我们的服务中不可避免的需要使用到一些密码(数据库、redis等)
开发和测试环境还好,但生产环境如果采用明文配置讲会有安全问题,jasypt是一个通用的加解密库,我们可以使用它。
1. 修改maven配置文件pom.xml
加入依赖
<!-- Jasypt加密 -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
2. 在配置文件中对盐进行配置
# 配置文件加密key
jasypt:
encryptor:
password: thisissalt
3. 创建工具类
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
/**
* 数据库密码加密工具
**/
public class JasyptUtils {
public static void main(String[] args) {
//加密工具
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
//加密配置
EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
//加密方式,默认PBEWithMD5AndDES,可改PBEWithMD5AndTripleDES,加密方式不可随意修改
config.setAlgorithm("PBEWithMD5AndDES");
//加密所需的salt(盐)
config.setPassword("thisissalt");
//应用配置
encryptor.setConfig(config);
//加密
encrypt(encryptor, "root****1234");
//解密
decrypt(encryptor, "CDwEmbi*******Zz39Lg=");
}
/**
* Jasypt加密 结果
* @param encryptor 加密工具
* @param plaintext 需要加密字符串
*/
public static void encrypt(StandardPBEStringEncryptor encryptor, String plaintext){
//加密
String ciphertext=encryptor.encrypt(plaintext);
System.out.println("加密结果: " + ciphertext);
}
/**
* Jasypt解密 结果
* @param encryptor 解密工具
* @param ciphertext 需要解密字符串
*/
public static void decrypt(StandardPBEStringEncryptor encryptor, String ciphertext){
//解密
String plaintext=encryptor.decrypt(ciphertext);
System.out.println("解密结果: " + plaintext);
}
}
4. 修改配置文件中的密码
此时就可以把在上一步中生成的密码在配置文件中进行配置了,配置成ENC(CDwEmbi*******Zz39Lg=)
,如下,是对数据库密码进行加密的配置:
spring:
datasource:
name: saas_****
url: jdbc:mysql://127.0.0.1:3306/saas_****?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true
username: **** #安全起见,此处也可进行加密
password: ENC(CDwEmbi*******Zz39Lg=)
driver-class-name: com.mysql.cj.jdbc.Driver
评论区