SpringBoot配置文件中的內容通常情況下是明文顯示,安全性就比較低一些。打開application.properties或application.yml,比如mysql登陸密碼,redis登陸密碼以及第三方的密鑰等等一覽無餘。
1.
這裏介紹一個加解密組件,提高一些屬性配置的安全性。
jasypt是一個Springboot下的工具包
以數據庫用戶名和數據庫密碼加密爲例
步驟如下:
(1)引入maven依賴
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
(2)application.properties配置文件中增加如下內容(加解密時使用)
#jasypt加密的密匙
jasypt.encryptor.password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7
(3)在測試用例中生成加密後的祕鑰
package com.ljq.house.web;
import org.jasypt.encryption.StringEncryptor;
import org.junit.Assert;
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;
import org.springframework.test.context.web.WebAppConfiguration;
/**
* @Author: ljq
* @Date: 18-12-28 下午9:04
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class JasyptTest {
@Autowired
StringEncryptor encryptor;
@Test
public void getResult() {
String url = encryptor.encrypt("jdbc:mysql://127.0.0.1:3306/houses?useSSL=true&characterEncoding=utf-8" +
"&zeroDateTimeBehavior=convertToNull&useUnicode=true");
String name = encryptor.encrypt("root");
String password = encryptor.encrypt("root");
System.out.println(url);
System.out.println(name);
System.out.println(password);
Assert.assertTrue(name.length() > 0);
Assert.assertTrue(password.length() > 0);
}
}
下面是第一次加密後的輸出結果
BA9uZ35umFic6NbuaLdGzZBodw/wSqvztMt9UGdlOtxxs/fr/W5kf8Bs6GzzHklNfkcU30g8aQ/XdihsZtqRz1J34zNIQxuH3BCG1kknFayp13G8RhkeF4ptBfx6i6nqnP4Uc0UKpjcsxxfTZImHBVvcTY0RDANk26IGBPZvQry7qKuna/RTMQ==
kyMvAncHqzcvGAildsK67w==
7QCSL5/HKjxFQRPLGgGH7kAElrmf/mgQ
每次加密的結果還不同,更加增加了可靠性。
(4)將上面生成的url,name和password替換配置文件中的url,數據庫賬戶和密碼,替換後如下:
spring.datasource.url=ENC(BA9uZ35umFic6NbuaLdGzZBodw/wSqvztMt9UGdlOtxxs/fr/W5kf8Bs6GzzHklNfkcU30g8aQ/XdihsZtqRz1J34zNIQxuH3BCG1kknFayp13G8RhkeF4ptBfx6i6nqnP4Uc0UKpjcsxxfTZImHBVvcTY0RDANk26IGBPZvQry7qKuna/RTMQ==)
spring.datasource.username=ENC(kyMvAncHqzcvGAildsK67w==)
spring.datasource.password=ENC(7QCSL5/HKjxFQRPLGgGH7kAElrmf/mgQ)
ENC( )是固定寫法,( )裏面是加密後的信息。
springboot配置文件裏的敏感信息加密的第一種方法就是這樣。