如何保护 SpringBoot 配置文件中的敏感信息
逆锋起笔
共 3069字,需浏览 7分钟
·
2021-11-05 15:00
来源:blog.csdn.net/jeikerxiao/article/details/96480136
说明
application.properties
或application.yml
,比如 MySql登陆密码,Redis登陆密码以及第三方的密钥等等一览无余,这里介绍一个加解密组件,提高一些属性配置的安全性。https://github.com/jeikerxiao/spring-boot2/tree/master/spring-boot-encrypt
数据用户名和数据库密码加密为例
1. 引入包
https://github.com/ulisesbocchio/jasypt-spring-boot
<dependency>
<groupId>com.github.ulisesbocchiogroupId>
<artifactId>jasypt-spring-boot-starterartifactId>
<version>2.1.0version>
dependency>
2. 配置加/解的密码
# jasypt加密的密匙
jasypt:
encryptor:
password: Y6M9fAJQdU7jNp5MW
3. 测试用例中生成加密后的秘钥
@RunWith(SpringRunner.class)
@SpringBootTest
public class DatabaseTest {
@Autowired
private StringEncryptor encryptor;
@Test
public void getPass() {
String url = encryptor.encrypt("jdbc:mysql://localhost:3306/mydb?autoReconnect=true&serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8");
String name = encryptor.encrypt("root");
String password = encryptor.encrypt("123456");
System.out.println("database url: " + url);
System.out.println("database name: " + name);
System.out.println("database password: " + password);
Assert.assertTrue(url.length() > 0);
Assert.assertTrue(name.length() > 0);
Assert.assertTrue(password.length() > 0);
}
}
database url: 6Ut7iADnHS18cManoFJuNRQ5QEDfcho/F96SOhsHZdXlHYCa5PSrz6rk48I9eHB7qPp5AxDFBk9xi0I1hi6BJ0DSPYA9443gBAk5JDUxDufjUKsdh6knZJLNELmFJzYrDvCu4S0x22MYdZqJDLbyDUU2JcoezCvs156vmsPgU4A=
database name: fmai72yGYKGlP6vTtX77EQ==
database password: GPMG7FGV+EA9iGkC27u67A==
4. 将加密后的字符串替换原明文
server:
port: 8080
spring:
# 数据库相关配置
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
# 这里加上后缀用来防止mysql乱码,serverTimezone=GMT%2b8设置时区
url: ENC(h20YiPrvNnuuTGjlrE1RVpudMuIQAS6ZPSVo1SPiYVyLen7/TWI5rXVRkStA3MDcoVHQCmLa70wYU6Qo8wwtnsmaXa5jykD3MNhAp5SGJxHsTG5u7tflPdnNmOufyhdsYPxBGWAgibYs9R7yBfrvtwBTRbe096APd3bnG3++Yro=)
username: ENC(sT6BztXbJEa71eg3pPGYMQ==)
password: ENC(MpSZFJ9ftq+3+VUANZjr0Q==)
jpa:
hibernate:
ddl-auto: update
show-sql: true
# 返回的api接口的配置,全局有效
jackson:
# 如果某一个字段为null,就不再返回这个字段
default-property-inclusion: non_null
date-format: yyyy-MM-dd HH:mm:ss
serialization:
write-dates-as-timestamps: false
time-zone: GMT+8
# jasypt加密的密匙
jasypt:
encryptor:
password: Y6M9fAJQdU7jNp5MW
注意: 上面的 ENC()
是固定写法.
附言
部署时配置salt(盐)值
java -jar xxx.jar -Djasypt.encryptor.password=Y6M9fAJQdU7jNp5MW
/etc/profile
文件vim /etc/profile
export JASYPT_PASSWORD = Y6M9fAJQdU7jNp5MW
source /etc/profile
java -jar -Djasypt.encryptor.password=${JASYPT_PASSWORD} xxx.jar
END
逆锋起笔
是一个专注于程序员圈子的技术平台,你可以收获最新技术动态
、最新内测资格
、BAT等大厂的经验
、精品学习资料
、职业路线
、副业思维
,微信搜索逆锋起笔
关注!
评论