背景:
原本项目中数据库和中间件账号密码都是直接用明文配置的,毕竟这样最方便开发,平时也没人在乎这个。但是部署到实际项目中,甲方进行安全检查第一个就查到这个,要求我们整改,那只能整了。
网上找了一些资料,好像大都用Jasypt加密工具操作,Jasypt官网看其他博客看了下,发现使用起来比较方便,直接简单记录下,
扩展:直接预研敏感数据加密技术,不只是对配置文件加密,对其他接口经过后台的敏感数据也进行了解,包括数据加密、加密后的技术怎么进行模糊查询等等,会在后续博客中进行编写。当然这都是后话,下面直接操作Jasypt进行配置文件账号密码加密。
实践Jasypt
1、引入依赖
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.5</version>
</dependency>
如果项目中启动类没有 @SpringBootApplication或@EnableAutoConfiguration注解,那么需要引入jasypt-spring-boot依赖且需要创建配置类并启用 @Configuration和@EnableEncryptableProperties,进行声明。
2、账号密码转成加密值
创建一个工具类把我们的账号密码进行加密
import org.jasypt.properties.PropertyValueEncryptionUtils;
import org.jasypt.util.text.BasicTextEncryptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Jasypt加密工具类
* @author ppp
* @date 2023/1/5
*/
public class JasyptUtil {
private static final Logger logger = LoggerFactory.getLogger(JasyptUtil.class);
/**
* 加密使用密钥,需要在和配置文件中的jasypt.encryptor.password保持一致
*/
private static final String PRIVATE_KEY = "demo";
/**
* BasicTextEncryptor对象初始化使用的算法就是"PBEWithMD5AndDES"
* 点击进源码构造方法中就可以看到下面的设置
* this.encryptor.setAlgorithm("PBEWithMD5AndDES");
*/
private static BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
static {
basicTextEncryptor.setPassword(PRIVATE_KEY);
}
/**
* 明文加密
*
* @param plaintext 明文
* @return String
*/
public static String encrypt(String plaintext) {
logger.info("明文字符串为:{}", plaintext);
String ciphertext = basicTextEncryptor.encrypt(plaintext);
logger.info("密文字符串为:{}", ciphertext);
return ciphertext;
}
/**
* 解密
*
* @param ciphertext 密文
* @return String
*/
public static String decrypt(String ciphertext) {
logger.info("密文字符串为:{}", ciphertext);
ciphertext = "ENC(" + ciphertext + ")";
if (PropertyValueEncryptionUtils.isEncryptedValue(ciphertext)) {
String plaintext = PropertyValueEncryptionUtils.decrypt(ciphertext, basicTextEncryptor);
logger.info("明文字符串为:{}", plaintext);
return plaintext;
}
logger.error("解密失败!");
return "";
}
public static void main(String[] args) {
String encrypt = encrypt("123456");
String test = decrypt(encrypt);
}
}
3、配置文件添加配置
application.yml中添加配置
jasypt:
encryptor:
# 指定加密密钥,生产环境请放到启动参数里面 -Djasypt.encryptor.password=加密密钥
password: demo
# 指定解密算法,需要和加密时使用的算法一致
algorithm: PBEWithMD5AndDES
# 指定initialization vector类型
iv-generator-classname: org.jasypt.iv.NoIvGenerator
4、替换账号密码
把application.yml中需要加密的账号密码都换成 ENC(密文) 格式即可,启用项目后他会检测配置文件中ENC样式的数据把里面的密文解密出来给框架使用。