通常狀況下,Spring項目中數據庫等配置文件都寫在配置文件中,因此存在必定的風險,可選的作法有:①重寫Spring讀取配置文件的機制;②在Java代碼中配置DataSource;這兩種方法均可以實現,第一種方法比較複雜可是更通用,第二種較爲簡單,可是將配置寫死在程序中顯然是不恰當的。因此使用一個開源的專門針對Spring配置文件加密的工具jasypt,其原理是重寫讀取配置文件的機制,在讀取到具備加密標識的前綴和後綴時進行解密,具體步驟以下:git
<dependency> <groupId>com.github.ulisesbocchio</groupId> <artifactId>jasypt-spring-boot-starter</artifactId> <version>2.1.1</version> </dependency>
jasypt: encryptor: password: 123456 #加密/解密密鑰
public static void main(String[] args) { BasicTextEncryptor encryptor = new BasicTextEncryptor(); //需和配置文件中jasypt.encryptor.password的值相同 encryptor.setPassword("123456"); //加密獲得密文 System.out.println(encryptor.encrypt("明文")); //解密 System.out.println(encryptor.decrypt("密文")); }
格式以下:
ENC(密文)
例如:github
spring: datasource: username: abc password: ENC(as/qrKIOWhfvweioclz)
自定義前綴/後綴:spring
jasypt: encryptor: property: prefix: "" suffix: ""
jasypt地址:https://github.com/ulisesbocchio/jasypt-spring-boot數據庫