一、操作流程
-
在springboot项目中引入jasypt的staters
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
-
springboot配置文件中添加如下配置:
# xxx为加密密钥 jasypt.encryptor.password=xxxx
-
编写单元测试,完成敏感数据加密
@RunWith(SpringRunner.class) @SpringBootTest(classes = JasyptApplication.class) public class JasyptApplicationTests { @Autowired private StringEncryptor encryptor; @Test public void contextLoads() { } /** * 数据加密 */ @Test public void testEncrypt(){ String username = encryptor.encrypt("root"); String password = encryptor.encrypt("root"); String url = encryptor.encrypt("jdbc:mysql://localhost:3306/dtabase"); String redis = encryptor.encrypt("localhost"); System.out.println("username:" +username); System.out.println("password:" +password); System.out.println("url:" +url); System.out.println("redis:" +redis); } /** * 数据解密 */ @Test public void testDecrypt(){ String username = encryptor.decrypt("BFqR8ccKjXnxV1vVp7nOFg=="); String password = encryptor.decrypt("X720Oc+o5bZ+eGN3tr81dA=="); String url = encryptor.decrypt("iSVNDs1fnQL9DXJSK/7whm2O17IiG2l9ae90mjT"); String redis = encryptor.decrypt("IGrDzDuenxK+HK1dA8PH56Kvde0o+qbt"); System.out.println("username:" +username); System.out.println("password:" +password); System.out.println("url:" +url); System.out.println("redis:" +redis); } }
-
替换敏感数据(
ENC(
和)
为默认前缀、后缀,可替换 )
-
密钥隐藏
方式一:推荐使用
-
将密钥添加到环境变量(环境变量名与配置文件
${}
中的命名一致)-
windows环境变量配置
-
linux环境变量配置(未测试)
#1. 打开/etc/profile文件 vim /etc/profile #2. 文件末尾插入 export JASYPT_PASSWORD = G0CvDz7oJn6 #3. 编译 source /etc/profile
-
-
修改springboot配置文件
jasypt.encryptor.password
属性jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}
-
java -jar xxx.jar
启动应用
方式二:
-
删除springboot配置文件
jasypt.encryptor.password
属性 -
启动应用
java -jar xxx.jar --jasypt.encryptor.password=xxx 或 java -Djasypt.encryptor.password=xxx -jar xxx.jar
-
二、应用启动备注
-
添加环境变量后且未配置
jasypt.encryptor.password
属性还可以通过如下方式启动应用1.1 命令行启动:
java -jar xxx.jar --jasypt.encryptor.password=${ENCRYPTOR_PASSWORD} # 或 java -jar -Djasypt.encryptor.password=${ENCRYPTOR_PASSWORD} xxx.jar
1.2 idea启动:
# 添加Environmental variables JASYPT_PASSWORD=xxx
-
未添加环境变量且未配置
jasypt.encryptor.password
属性2.1 命令行启动:
java -jar xxx.jar --jasypt.encryptor.password=xxx # 或 java -Djasypt.encryptor.password=xxx -jar xxx.jar
2.2 idea启动:
# 方式一:添加VM options -Djasypt.encryptor.password=password # 方式二:添加Program arguments --jasypt.encryptor.password=password