springboot项目中配置文件明文密码加密
springboot项目中配置文件明文密码
配置文件中采用明文存储密码,所有能够访问该文件的人都能访问该密码,将会降低系统安全性。
错误示范:
- application.yml文件中
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true&allowPublicKeyRetrieval=true
username: root
password: root
- application.properties文件中
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=root
解决方法:
- 在pom.xml中引入jasypt
<ulisesbocchio.version>3.0.3</ulisesbocchio.version>
<!--针对配置文件中数据库密码使用jasypt加密-->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>${ulisesbocchio.version}</version>
</dependency>
<!--针对配置文件中数据库密码使用jasypt加密-->
<plugin>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-maven-plugin</artifactId>
<version>${ulisesbocchio.version}</version>
</plugin>
- 在配置文件中加入加密算法
# application.yml文件中
# 配置文件中密码加密
jasypt:
encryptor:
algorithm: PBEWithMD5AndDES #算法-固定写法一般没人改
password: dy1255 #密钥
iv-generator-classname: org.jasypt.iv.NoIvGenerator #设置初始向量IV生成器的类名
# application.properties文件中
jasypt.encryptor.password=dy1255
jasypt.encryptor.algorithm=PBEWithMD5AndDES
jasypt.encryptor.iv-generator-classname=org.jasypt.iv.NoIvGenerator
- 随便找一个测试类,计算对应的密文(如果不能使用@Test,随便生成一个main函数运行即可)
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Test {
@Test
public void encry() {
//获取加密的password 3g8eMXCA6UwoB3bqtfY5cOjJQRymvc8b 在DB配置中替换*/
StandardPBEStringEncryptor standardPBEStringEncryptor =new StandardPBEStringEncryptor();
/*配置文件中algorithm对应的算法名:PBEWithMD5AndDES*/
standardPBEStringEncryptor.setAlgorithm("PBEWithMD5AndDES");
/*配置文件中password 对应的值(这个值自己随便定义)*/
standardPBEStringEncryptor.setPassword("dy1255");
/*获得name、password的加密文本*/
String name = standardPBEStringEncryptor.encrypt("root"); //账户
String password =standardPBEStringEncryptor.encrypt("root"); //密码
/*以下打印的就是在配置文件中需要配置的密文*/
System.out.println("name:"+name);
System.out.println("password:"+password);
}
}
- 将运行出来的账号密码加入配置文件,完成连接数据库
# application.yml文件中
spring:
datasource:
username: ENC(Dd4mk+UflElKI1ZqrOChdg==)
password: ENC(vcA2T6pLJm9s2lCFSCtbYg==)
# application.properties文件中
spring.datasource.username=ENC(9+2hEx6VRnfTjBQ3+9RfVg==)
spring.datasource.password=ENC(4dZoCidvk64ivm6peU8xLA==)
本文来自博客园,作者:芏筄,转载请注明原文链接:https://www.cnblogs.com/MiaoStudy/p/16638998.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)