前言
在 Spring Boot 项目开发中,资源配置文件的内容通常都是明文显示的,这样很不安全。经常有公司员工将带有明文密码的代码上传至 Github ,导致数据泄露的事件。因此,配置文件中的敏感数据(如密码)加密是有必要的。
本文使用到的加密工具是 jasypt-spring-boot-starter
,其 Github 地址为:ulisesbocchio/jasypt-spring-boot 。
示例代码已上传至 Github:spring-boot-config-file-encrypt。
使用
添加依赖
编辑 pom.xml
,添加以下依赖:
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>3.0.4</version>
</dependency>
配置加解密的Salt
编辑 application.yml
,添加以下内容:
jasypt:
encryptor:
# 加密使用的 salt
password: As12mda-02mdAadi123df
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator
编写工具类生成加密后的密码
编写工具类生成加密后的字符:
public class JasyptUtils {
public static void main(String[] args) {
StandardPBEStringEncryptor stringEncryptor = new StandardPBEStringEncryptor();
// salt
stringEncryptor.setPassword("As12mda-02mdAadi123df");
String userName = stringEncryptor.encrypt("root");
String password = stringEncryptor.encrypt("Aa123456.");
System.out.println("用户名:" + userName);
System.out.println("密码:" + password);
}
}
生成加密字符:
用户名:lDEBjN01BigteIWrpKA6ew==
密码:f3kS535Eu8fhA/jVvTgxx4xDVS7uAtuP
在配置文件中将生成的加密字符替换原明文字符
编辑配置文件 application.yml
,修改数据库连接参数:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db01?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai
username: ENC(lDEBjN01BigteIWrpKA6ew==)
password: ENC(f3kS535Eu8fhA/jVvTgxx4xDVS7uAtuP)
注:ENC()
是固定写法。
设置 jasypt.encryptor.password
开发环境
配置 IDEA,修改 jvm 启动参数,指定 jasypt.encryptor.password
的值:
参数:-Djasypt.encryptor.password=As12mda-02mdAadi123df
生产环境
- 可以在启动时指定启动参数:
java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=<SALT> -jar -Xmx512m xxxxxx.jar
- 也可以将密码(salt)设置成系统环境变量(如:
JASYPT_ENCRYPTOR_PASSWORD
):
vim /etc/profile
# 添加 salt 值
export JASYPT_ENCRYPTOR_PASSWORD = As12mda-02mdAadi123df
# 使配置生效
source /etc/profile
上述命令可修改为:
java -Dfile.encoding=UTF8 -Djasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD} -jar -Xmx512m xxxxxx.jar
重启项目测试
重启项目,访问编写好的 Controller,发现可正常访问到数据。
更多的使用方法,如自定义加密器、自定义属性检测/解析器请查看官方介绍:jasypt-spring-boot。
相关错误
1. Failed to bind properties under ‘spring.datasource.password’ to java.lang.String:
Description:
Failed to bind properties under 'spring.datasource.password' to java.lang.String:
Reason: org.springframework.boot.context.properties.bind.BindException: Failed to bind properties under 'spring.datasource.password' to java.lang.String
Action:
Update your application's configuration
解决方案:
方案一:更换版本为 2.1.0
;
方案二:在 application.yml
中添加以下配置:
jasypt:
encryptor:
# 加密使用的 salt
password: As12mda-02mdAadi123df
algorithm: PBEWithMD5AndDES
iv-generator-classname: org.jasypt.iv.NoIvGenerator