springboot中配置項信息都是在配置文件中進行保存的,其中涉及了很多敏感信息,如數據庫賬號、密碼等。爲了保證系統的安全可靠,往往需要我們將這些明文信息進行加密處理。下面就以SpringBoot 結合 Jasypt 爲例,對敏感信息進行加密處理。
1. 首先在pom.xml中添加 Jasypt 依賴
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter -->
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
2. 在配置文件中爲Jasypt增加加密參數
#加密參數
jasypt:
encryptor:
password: test
3. 修改原來的明文信息爲加密後的信息
spring:
#數據源
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&nullCatalogMeansCurrent=true
username: root
password: ENC(nRV3L2PCDlDmUkXV6Cu/Bf99Dq13VO4Q)
如何獲取加密後的字符串呢?
1. 生成密鑰
找到你本地maven倉庫的jasypt的jar包,在該目錄下打開cmd命令窗口,如圖:
2. 執行
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI input="test" password=test algorithm=PBEWithMD5AndDES
其中input爲你的明文密碼,這裏我演示的是test,password爲你的私鑰,algorithm這個是一個規則,切勿更改!!!。執行後如圖:
簡單解釋一下,這裏的OUTPUT就是加密之後的密文(密碼)
3. 可以通過命令,對密碼進行解密
java -cp jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI input="nhyL4CzSQv/aPxoe7TzpOQ==" password=test algorithm=PBEWithMD5AndDES