SpringBoot實戰(二)——配置檔案內容加密jasypt
阿新 • • 發佈:2019-02-18
使用過SpringBoot配置檔案的朋友都知道,資原始檔中的內容通常情況下是明文顯示,安全性就比較低一些。開啟application.properties或application.yml,比如mysql登陸密碼,redis登陸密碼以及第三方的金鑰等等一覽無餘,這裡介紹一個加解密元件,提高一些屬性配置的安全性。
jasypt由一個國外大神寫了一個springboot下的工具包,下面直接看程式碼:
1、maven依賴引入:
<!-- https://mvnrepository.com/artifact/com.github.ulisesbocchio/jasypt-spring-boot-starter --> <dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>1.14</version> </dependency>
2、application.properties配置檔案中增加如下內容(加解密時使用):
jasypt.encryptor.password=EbfYkitulv73I2p0mXI50JMXoaxZTKJ7
3、裡面main方法或測試生成祕鑰:
//這是JUnit的註解,通過這個註解讓SpringJUnit4ClassRunner這個類提供Spring測試上下文。 @RunWith(SpringJUnit4ClassRunner.class) //這是Spring Boot註解,為了進行整合測試,需要通過這個註解載入和配置Spring應用上下 @SpringBootTest(classes = Application.class) @WebAppConfiguration public class EncryptorTest { @Autowired StringEncryptor encryptor; @Test public void getPass() { String name = encryptor.encrypt("DBusername"); String password = encryptor.encrypt("DBpassword"); System.out.println(name+"----------------"); System.out.println(password+"----------------"); Assert.assertTrue(name.length() > 0); Assert.assertTrue(password.length() > 0); } }
4、將上面生成的name和password替換配置檔案中的資料庫賬戶和密碼,替換後如下:
spring.datasource.driverClassName=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://1.1.1.1:3306/xxxx?characterEncoding=utf8&useSSL=true spring.datasource.username=ENC(zj4OUZ3/mmHV0JOgCdg8qQ==) spring.datasource.password=ENC(UBtTQGk1xbdmhff+UUoT6g==)
簡單四步完成加密操作。。。。。。。。。。。