使用SSM 或者 springboot +mybatis时,对数据库的认证信息(用户名,密码)进行加密。

 

一般状况下,为了提升安全性,咱们须要对数据库的认证信息进行加密操做,而后在启动项目的时候,会自动解密来核对信息是否正确。下面介绍在SSM和springboot项目中分别是怎样实现的。java

 

不管是使用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); } } 

 

1、SSM项目对数据库认证信息进行加密spring

 

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便可数组

 

 

 
 

2、springboot项目对数据库认证信息进行加密安全

 

 

1.首先咱们须要自定义一个类,继承 PropertyPlaceholderConfigurer。编写代码,达到启动服务器时判断哪些字段须要解密,并将解密后的值返回出去springboot

 

 

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;
    }
}mybatis

 

=========================================================================================================app

至此,咱们就成功实现了在SSM 和springboot中对数据库认证信息进行加密。

相关文章
相关标签/搜索