1 场景
SpringBoot的项目发布时,线上配置文件
通常会采用spring.profiles.active
参数的形式指定。
这种方式,线上配置文件,需要配置到源码
中,密码等敏感信息
会暴露
出来。
虽然数据库可以限制访问的IP
来杜绝密码泄露出去后代码的非法访问问题。但是有些外部邮箱密码
、第三方访问接口
密钥等不可控的外部接口
,无法限制访问者的IP,仍然有安全问题。
2 加密方式
这里采用jasypt
对SpringBoot中的配置文件信息进行加密。
配置文件中的密码信息为加密后的字符串
,通过在启动时指定jasypt私钥
,来进行自动解密
。运维人员保管维护解密的私钥
。
加密步骤:
(1)配置jasypt密钥
,对密码进行加密
(2)将加密后的字符串以ENC(xxxx)
的格式配置在配置文件中
(3)启动jar后,在参数中加上--jasypt.encryptor.password
指定jasypt密钥
3 加密过程
3.1 maven依赖
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
3.2 配置加密密钥
这里设置加密密钥为:abcd_123
3.2.1 开发环境
开发环境可在配置文件yml
中配置
jasypt:
encryptor:
password: abcd_123
3.2.2 生产环境
生产环境采用启动参数
的形式传入:--jasypt.encryptor.password=abcd_123
如:
java -jar xxx.jar --jasypt.encryptor.password=abcd_123
3.3 加密
对字符串rootPwd进行加密:
@Autowired
private StringEncryptor encryptor;
@Test
public void encrypt(){
System.out.println(encryptor.encrypt("rootPwd"));
}
rootPwd加密后的内容如下:
yCu0xHHOTfl8evdE0bR1Fg==
3.4 配置密文
将密码加密后生成的密文
,以ENC(xxxx)
的形式配置在配置文件中。
如下:
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://xxx.xxx.xxx.xxx:xxx/xxx
username: root
password: ENC(yCu0xHHOTfl8evdE0bR1Fg==)
网友评论