背景
原本项目中数据库和中间件账号密码都是直接用明文配置的,毕竟这样最方便开发,平时也没人在乎这个。
但是部署到实际项目中,甲方进行安全检查第一个就查到这个,要求我们整改,那只能整了。
网上找了一些资料,好像大都用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样式的数据把里面的密文解密出来给框架使用。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论