在Spring boot開發中,需要在application.yml文件里配置數據庫的連接信息,或者在啟動時傳入數據庫密碼,如果不加密,傳明文,數據庫就直接暴露了,相當於"裸奔"了,因此需要進行加密處理才行。
如果使用@SpringBootApplication注解啟動的項目,只需增加maven依賴,其他方式請參考如下GitHub地址的README信息:
---------------------
我們對信息加解密是使用這個jar包的:
編寫加解密測試類:
package cn.linjk.ehome; import org.jasypt.encryption.pbe.StandardPBEStringEncryptor; import org.jasypt.encryption.pbe.config.EnvironmentPBEConfig; import org.junit.Test; public class JasyptTest { @Test public void testEncrypt() throws Exception { StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); EnvironmentPBEConfig config = new EnvironmentPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); // 加密的算法,這個算法是默認的 config.setPassword("ljk"); // 加密的密鑰 standardPBEStringEncryptor.setConfig(config); String plainText = "linjingke"; String encryptedText = standardPBEStringEncryptor.encrypt(plainText); System.out.println(encryptedText); } @Test public void testDe() throws Exception { StandardPBEStringEncryptor standardPBEStringEncryptor = new StandardPBEStringEncryptor(); EnvironmentPBEConfig config = new EnvironmentPBEConfig(); config.setAlgorithm("PBEWithMD5AndDES"); config.setPassword("ljk"); standardPBEStringEncryptor.setConfig(config); String encryptedText = "aHsFtlQjatrOP2s8bfLGkUG55z53KLNi"; String plainText = standardPBEStringEncryptor.decrypt(encryptedText); System.out.println(plainText); } }
加密串拿到了,現在來修改application.yml的配置:
我們把加密串放在ENC({加密串})即可。
還要加這個密鑰的配置:
