使用過SpringBoot配置文件的朋友都知道,資源文件中的內容通常情況下是明文顯示,安全性就比較低一些。打開application.properties或application.yml,比如mysql登陸密碼,redis登陸密碼以及第三方的密鑰等等一覽無餘,這裏介紹一個加解密組件,提高一些屬性配置的安全性。
jasypt由一個國外大神寫了一個springboot下的工具包,
下面直接看代碼:
這裏以數據用戶名和數據庫密碼加密爲例
一,首先引入maven
<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
2.1.0版本是我用的時候最新版本。查看最新版本可以到
https://github.com/ulisesbocchio/jasypt-spring-boot 查看
二,application.yml配置文件中增加如下內容(加解密時使用)
#jasypt加密的密匙
jasypt:
encryptor:
password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ7
三,在測試用例中生成加密後的祕鑰:
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class testTest {
@Autowired
StringEncryptor encryptor;
@Test
public void getPass() {
String url = encryptor.encrypt("jdbc:mysql://47.97.192.116:3306/sell?characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2b8");
String name = encryptor.encrypt("你的數據庫名");
String password = encryptor.encrypt("你的數據庫密碼");
System.out.println(url+"----------------");
System.out.println(name+"----------------");
System.out.println(password+"----------------");
Assert.assertTrue(name.length() > 0);
Assert.assertTrue(password.length() > 0);
}
}
四,將上面生成的name和password替換配置文件中的數據庫賬戶和密碼,替換後如下
spring:
#數據庫相關配置
datasource:
driver-class-name: com.mysql.jdbc.Driver
#這裏加上後綴用來防止mysql亂碼,serverTimezone=GMT%2b8設置時區
url: ENC(i87lLC0ceVq1vK91R+Y6M9fAJQdU7jNp5MW+ndLgacRvPDj42HR8mUE33uFwpWqjOSuDX0d1dd2NilrnW7yJbZmoxuJ3HmOmjwY5+Vhu+e3We4QPDVCr/s/RHsQgYOiWrSQ92Mjammnody/jWI5aaw==)
username: ENC(3OW8RQaoiHu1DXfDny4FDP0W5KOSVcWN5yWNxQ6Q4UE=)
password: ENC(ITE8wJryM8hVnofDKQodFzPZuPpTaMtX71YDoOTdh0A=)
jpa:
hibernate:
ddl-auto: update
show-sql: true
#返回的api接口的配置,全局有效
jackson:
default-property-inclusion: non_null #如果某一個字段爲null,就不再返回這個字段
#url相關配置,這裏配置url的基本url
server:
port: 8888
#jasypt加密的密匙
jasypt:
encryptor:
password: EbfYkitulv73I2p0mXI50JMXoaxZTKJ7
注意上面的 ENC()是固定寫法,()裏面是加密後的信息。