使用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中对数据库认证信息进行加密。



 

 

 

posted @ 2018-06-19 17:56  宇宙间的星河集  阅读(2301)  评论(2编辑  收藏  举报