1. 程式人生 > 程式設計 >SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

在Spring boot開發中,需要在application.yml檔案裡配置資料庫的連線資訊,或者在啟動時傳入資料庫密碼,如果不加密,傳明文,資料庫就直接暴露了,相當於"裸奔"了,因此需要進行加密處理才行。

使用@SpringBootApplication註解啟動的專案,只需增加maven依賴

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

我們對資訊加解密是使用這個jar包的:

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

編寫加解密測試類:

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("test");            // 加密的金鑰
    standardPBEStringEncryptor.setConfig(config);
    String plainText = "88888888";
    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("test");
    standardPBEStringEncryptor.setConfig(config);
    String encryptedText = "ip10XNIEfAMTGQLdqt87XnLRsshu0rf0";
    String plainText = standardPBEStringEncryptor.decrypt(encryptedText);
    System.out.println(plainText);
  }
}

加密串拿到了,現在來修改application.yml的配置:

我們把加密串放在ENC({加密串})即可。

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

啟動時需要配置 祕鑰

將祕鑰加入啟動引數

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

SpringBoot專案application.yml檔案資料庫配置密碼加密的方法

到此這篇關於SpringBoot專案application.yml檔案資料庫配置密碼加密的方法的文章就介紹到這了,更多相關SpringBoot application.yml資料庫加密內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!