1. 程式人生 > >使用SSM 或者 springboot +mybatis時,對資料庫的認證資訊(使用者名稱,密碼)進行加密。

使用SSM 或者 springboot +mybatis時,對資料庫的認證資訊(使用者名稱,密碼)進行加密。


通常情況下,為了提高安全性,我們需要對資料庫的認證資訊進行加密操作,然後在啟動專案的時候,會自動解密來核對資訊是否正確。下面介紹在SSM和springboot專案中分別是怎樣實現的。


無論是使用SSM還是springboot,首先我們需要一個加密工具,這裡我採用的是AES 高階加密演算法。

import javax.crypto.Cipher;  
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;  
import sun.misc.BASE64Decoder;
import 
sun.misc.BASE64Encoder; /** * AES 高階加密演算法,本專案中用於對資料庫的驗證資訊進行加密 */ public class AESUtil { private static String key="111"; /** * 加密 * @param content * @param strKey * @return * @throws Exception */ public static byte[] encrypt(String content,String strKey ) throws
Exception { SecretKeySpec skeySpec = getKey(strKey); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv); byte[] encrypted = cipher.doFinal(content.getBytes()); return
encrypted; } /** * 解密 * @param strKey * @param content * @return * @throws Exception */ public static String decrypt(byte[] content,String strKey ) throws Exception { SecretKeySpec skeySpec = getKey(strKey); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec("0102030405060708".getBytes()); cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv); byte[] original = cipher.doFinal(content); String originalString = new String(original); return originalString; } private static SecretKeySpec getKey(String strKey) throws Exception { byte[] arrBTmp = strKey.getBytes(); byte[] arrB = new byte[16]; // 建立一個空的16位位元組陣列(預設值為0) for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES"); return skeySpec; } /** * base 64 encode * @param bytes 待編碼的byte[] * @return 編碼後的base 64 code */ public static String base64Encode(byte[] bytes){ return new BASE64Encoder().encode(bytes); } /** * base 64 decode * @param base64Code 待解碼的base 64 code * @return 解碼後的byte[] * @throws Exception */ public static byte[] base64Decode(String base64Code) throws Exception{ return base64Code.isEmpty() ? null : new BASE64Decoder().decodeBuffer(base64Code); } /** * AES加密為base 64 code * @param content 待加密的內容 * @param encryptKey 加密金鑰 * @return 加密後的base 64 code * @throws Exception //加密傳String型別,返回String型別 */ public static String aesEncrypt(String content) throws Exception { return base64Encode(encrypt(content, key)); } /** * 將base 64 code AES解密 * @param encryptStr 待解密的base 64 code * @param decryptKey 解密金鑰 * @return 解密後的string //解密傳String型別,返回String型別 * @throws Exception */ public static String aesDecrypt(String encryptStr) throws Exception { return encryptStr.isEmpty() ? null : decrypt(base64Decode(encryptStr), key); } public static void main(String[] args) throws Exception { String encrypt = aesEncrypt("123456"); System.out.println(encrypt); // String decrypt = aesDecrypt("+hf8qB4LhS7L7BzBy83bLg=="); // System.out.println(decrypt); } }

一、SSM專案對資料庫認證資訊進行加密


1.首先我們需要自定義一個類,繼承 PropertyPlaceholderConfigurer。編寫程式碼,達到啟動伺服器時判斷哪些欄位需要解密,並將解密後的值返回出去

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
   // 需要加密的欄位陣列 。這裡需要和db.properties中一致
   private String[] encryptPropNames = { "db.username", "db.password"};
   
   
   //解密
   protected String convertProperty(String propertyName,String propertyValue) {
      if(judgeEncryptOrNot(propertyName)) {
         try {
            
            String realPropertyValue = AESUtil.aesDecrypt(propertyValue);
            return  realPropertyValue;//返回解密後的值
         } catch (Exception e) {
            e.printStackTrace();
         }
         
      }
      return propertyValue;
   }

   //判斷是否需要加密
   public boolean judgeEncryptOrNot(String propertyName) {
      
      for(String encryptPropName : encryptPropNames ) {
         if(encryptPropName.equals(propertyName)) {
            return true;
         }
      }
      return false;
   }
   
}

 

 

 
2.此時,我們的db.properties中的資訊
就可以填寫為我們在AES.util類中資料庫認證資訊進行加密之後的字串了。


 

 



3.最後,在配置檔案中(applicationContext-dao.xml)中定義這個bean即可




 

二、springboot專案對資料庫認證資訊進行加密

1.首先我們需要自定義一個類,繼承 PropertyPlaceholderConfigurer。編寫程式碼,達到啟動伺服器時判斷哪些欄位需要解密,並將解密後的值返回出去

package net.cqwu.collegeo2o.util;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

//繼承該類之後在spring-dao 中引入 可以實現加解密

public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
    // 需要加密的欄位陣列 。這裡需要和db.properties中一致
    private String[] encryptPropNames = { "jdbc.username", "jdbc.password"};


    //解密
    protected String convertProperty(String propertyName,String propertyValue) {
        if(judgeEncryptOrNot(propertyName)) {
            try {

                String realPropertyValue = AESUtil.aesDecrypt(propertyValue);
                return  realPropertyValue;//返回解密後的值
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return propertyValue;
    }


    //判斷是否需要加密
    public boolean judgeEncryptOrNot(String propertyName) {

        for(String encryptPropName : encryptPropNames ) {
            if(encryptPropName.equals(propertyName)) {
                return true;
            }
        }

        return false;
    }


}

 

2.此時,我們的application.yml或application.properties中的資訊
就可以填寫為我們在AES.util類中資料庫認證資訊進行加密之後的字串了。


 

 


3.建立一個類,對應於SSM中的applicationContext-dao.xml

package net.cqwu.collegeo2o.config.dao;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import net.cqwu.collegeo2o.util.AESUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * 對應spring 的 application-dao.xml
 */


@Configuration  //表示該配置是需要寫入spring的IOC容器中
@MapperScan("net.cqwu.collegeo2o.dao") //指定mapper介面所在的包,進行自動掃描(配置mybatismapper的掃描路徑)
public class DataSourceConfiguration {
    //定義資料庫的基本資訊屬性
    @Value("${jdbc.driver}")
    private String jdbcDriver;
    @Value("${jdbc.url}")
    private String jdbcUrl;
    @Value("${jdbc.username}")
    private String jdbcUsername;
    @Value("${jdbc.password}")
    private String jdbcPassword;


    //建立一個dataSource物件
    @Bean(name = "dataSource")

    public ComboPooledDataSource createDataSourceBean() throws Exception {
        //建立dataSource物件 並設定屬性
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(jdbcDriver);
        dataSource.setJdbcUrl(jdbcUrl);
        dataSource.setUser(AESUtil.aesDecrypt(jdbcUsername));  //需要先進行解密工作
        dataSource.setPassword(AESUtil.aesDecrypt(jdbcPassword));
        return dataSource;
    }
}


=========================================================================================================

至此,我們就成功實現了在SSM 和springboot中對資料庫認證資訊進行加密。