在SpringBoot項目的配置文件中, 至少會有數據庫用戶名和密碼,或其他敏感信息的配置。 通常都是用明文顯示的, 對於比較敏感的信息, 則可對其內容加密。
這里使用jasypt進行加密,步驟如下:
1)pom導入依賴:
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>3.0.4</version> </dependency>
2)在配置文件配置加/解密的秘鑰
jasypt.encryptor.password=5177251cc96740fdae33893599768b9e
秘鑰是自定義的,也不能太簡單。
3)測試加密與解密
package com.zys.example; import org.jasypt.encryption.StringEncryptor; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringbootTestExampleApplicationTests { @Autowired private StringEncryptor stringEncryptor; @Test public void test() { String username = stringEncryptor.encrypt("root"); System.out.println("加密的值:" + username); System.out.println("解密的值:" +stringEncryptor.decrypt(username)); String password = stringEncryptor.encrypt("zys123456"); System.out.println("加密的值:" + password); } }
打印結果如下:
加密的值:hewlv1rHszR5pR9ZgbEqw6kf+UUqkRSiYquLjOzAltEgzphROOLH6INDaT3KieJ8
解密的值:root
加密的值:b35mhYQ0vx5PlswtJYKXFVUHU4KfcuTPr6LXf8xCDdH7zvO2xeS0MdJMtITPiKIb
4)將加密后的字符串替換原明文
在替換時,需要使用ENC()標識加密,括號里面放加密的值。配置文件中只要配置了ENC開頭的內容, jasypt都會在用到值的時候進行PBE解密。如果值沒有以ENC開頭, 則不進行解密。
原始配置:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/db2020?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=root spring.datasource.password=zys123456
加密后的配置:
jasypt.encryptor.password=5177251cc96740fdae33893599768b9e spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://localhost:3306/db2020?serverTimezone=Hongkong&useUnicode=true&characterEncoding=utf8&useSSL=false spring.datasource.username=ENC(hewlv1rHszR5pR9ZgbEqw6kf+UUqkRSiYquLjOzAltEgzphROOLH6INDaT3KieJ8) spring.datasource.password=ENC(b35mhYQ0vx5PlswtJYKXFVUHU4KfcuTPr6LXf8xCDdH7zvO2xeS0MdJMtITPiKIb)
配置后也可正常訪問數據庫,對敏感信息進行了加密。
5)額外說明:
若把加/解密的秘鑰直接放在配置文件中,則可輕松解密出原文。那么更好的做法是不在配置文件中指定,而是將明文加密后,在啟動項目時通過啟動參數來攜帶秘鑰從而保證信息更加安全。
首先刪除配置文件中秘鑰的配置,然后見下面三種情況:
A.當使用IDEA進行測試時指定參數:
-Djasypt.encryptor.password=5177251cc96740fdae33893599768b9e
B.當項目是war時,在tomcat中設置參數后再啟動:
在Windows中,打開tomcat的bin/catalina.bat文件,找到setlocal,后面加上參數:
set "JAVA_OPTS=-Djasypt.encryptor.password=5177251cc96740fdae33893599768b9e"
截圖如下:
在Linux中,打開tomcat的bin/catalina.sh文件,找到setlocal,后面加上參數: