MyBatis 配置文件 用戶密碼加密存儲


properties配置文件

一般是使用properties保存配置文件內容,然后在mybatis配置文件中進行讀取
在resource文件下新建db.properties文件
內容如下

# 數據庫配置文件
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://  /mybatis
username =  
password =   

然后,接着把文件放入源碼包中
配置mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
		"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<!-- 讀取數據庫配置文件 -->
	<properties resource="db.properties"/>
	<!-- 定義別名 -->
	<typeAliases>
		<typeAlias type="com.ming.Role" alias="role"/>
	</typeAliases>
	
	<!-- 自定義數據處理 -->
	<typeHandlers>
		<typeHandler handler="org.apache.ibatis.type.EnumOrdinalTypeHandler" javaType="com.ming.Sex"/>
	</typeHandlers>
	<!-- 定義數據庫信息 -->
	<environments default="development">
		<environment id="development">
			<!-- jdbc事物管理 -->
			<transactionManager type="JDBC"/>
			<!-- 數據庫鏈接信息 -->
			<dataSource type="POOLED">
				<property name="driver" value="${driver}"/>
				<property name="url" value="${url}"/>
				<property name="username" value="${username}"/>
				<property name="password" value="${password}"/>
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<mapper resource="RoleMapper.xml"/>
	</mappers>
</configuration>

目錄結構如下
2019-04-11-14-38-08----

數據庫密碼加密

生產環境的數據庫密碼都為加密密碼,需要在使用的時候,把加密密碼解密成為明文
先創建數據庫密碼類

package com.ming.Util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;

public class Decode {
    /**
     * 生成秘鑰
     * @param
     * @return
     */
    public static String generateDecode() throws UnsupportedEncodingException {
        KeyGenerator keyGen = null;//密鑰生成器
        try {
            keyGen = KeyGenerator.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyGen.init(56);//初始化密鑰生成器
        SecretKey secretKey = keyGen.generateKey();//生成密鑰
        byte[] key = secretKey.getEncoded();//密鑰字節數組
        // 進行base64編碼
        String encodedKey = Base64.getEncoder().encodeToString(key);
        return encodedKey;
    }

    /**
     * 進行加密
     * @param string
     * @param key
     * @return
     */
    public static String encryptionDecode(String string, String key){
        //System.out.println(System.getenv("KEYWORDES"));
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "DES");//恢復密鑰
        Cipher cipher = null;//Cipher完成加密或解密工作類
        try {
            cipher = Cipher.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);//對Cipher初始化,加密模式
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] cipherByte = null;
        try {
            cipherByte = cipher.doFinal(Base64.getDecoder().decode(string));//加密data
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(cipherByte);
    }

    public static String decryptDecode(String string, String key){
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "DES");//恢復密鑰
        Cipher cipher = null;//Cipher完成加密或解密工作類
        try {
            cipher = Cipher.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);//對Cipher初始化,解密模式
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] cipherByte = new byte[0];//解密data
        try {
            cipherByte = cipher.doFinal(Base64.getDecoder().decode(string));
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(cipherByte);
    }
}

該類有三個方法,為加密data,解密data,生成key
然后編輯操作系統環境變量
達到輸入

➜  ~ echo $KEYWORDES

可以輸出環境變量
接着再次修改SqlSessionFactoryUtil類

package com.ming.Util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

/**
 * @author ming
 * 構建SqlSessionFactory
 * 由於數據庫連接是寶貴的,需要對數據庫連接統一管理,所以使用單例進行管理
 * 這里的單利使用的雙重鎖
 * SqlSessionFactory為線程不安全類型需要加鎖,確保同一時刻,只有一個線程可以使用該對象
 */
public class SqlSessionFactoryUtil {

    /**
     * SqlSessionFactory對象
     */
    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 類線程鎖
     */
    private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;

    /**
     * 日志管理類
     */
    private static final Logger logger = LogManager.getLogger();
    /**
     * 單例
     */
    private SqlSessionFactoryUtil(){

    }

    /**
     * @return SqlSessionFactory
     * 初始化SqlSessionFactory對象
     */
    public static SqlSessionFactory initSqlSessionFactory(){
       // 獲得輸入流
       InputStream cfgStream = null;
       // 閱讀流
       Reader cfgReader = null;
       InputStream proStream = null;
       Reader proReader = null;
       // 持久化屬性集
       Properties properties = null;
       try{
           // 配置文件流
           cfgStream = Resources.getResourceAsStream("mybatis-config.xml");
           // 獲得閱讀流
           cfgReader = new InputStreamReader(cfgStream);
           // 讀入屬性文件
           proStream = Resources.getResourceAsStream("db.properties");
           proReader = new InputStreamReader(proStream);
           // 持久化屬性集
           properties = new Properties();
           // 流轉載進入屬性集合
           properties.load(proReader);
       }catch (Exception e){
           logger.error(e);
       }

       if(sqlSessionFactory == null){
           synchronized (CLASS_LOCK){
               sqlSessionFactory = new SqlSessionFactoryBuilder().build(cfgReader, properties);
           }
       }
       return sqlSessionFactory;
    }

    /**
     * 打開SqlSession
     * @return SqlSession
     */
    public static SqlSession openSqlSesion(){
        // 判空處理
        if(sqlSessionFactory == null){
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}

接着,再次對密碼進行加密,在讀取的時候,對閱讀流的結果集進行持久化設置
先對db.properties數據庫密碼進行加密
更改以后配置文件如下

# 數據庫配置文件
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://47.94.95.84:32786/mybatis
username = mybatis
password = 8GgwaJCtTXLGItiYF9c4mg==

接着再次更改Util類

package com.ming.Util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;


import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Properties;

/**
 * @author ming
 * 構建SqlSessionFactory
 * 由於數據庫連接是寶貴的,需要對數據庫連接統一管理,所以使用單例進行管理
 * 這里的單利使用的雙重鎖
 * SqlSessionFactory為線程不安全類型需要加鎖,確保同一時刻,只有一個線程可以使用該對象
 */
public class SqlSessionFactoryUtil {

    /**
     * SqlSessionFactory對象
     */
    private static SqlSessionFactory sqlSessionFactory = null;

    /**
     * 類線程鎖
     */
    private static final Class CLASS_LOCK = SqlSessionFactoryUtil.class;

    /**
     * 日志管理類
     */
    private static final Logger logger = LogManager.getLogger();
    /**
     * 單例
     */
    private SqlSessionFactoryUtil(){

    }

    /**
     * @return SqlSessionFactory
     * 初始化SqlSessionFactory對象
     */
    public static SqlSessionFactory initSqlSessionFactory(){
       // 獲得輸入流
       InputStream cfgStream = null;
       // 閱讀流
       Reader cfgReader = null;
       InputStream proStream = null;
       Reader proReader = null;
       // 持久化屬性集
       Properties properties = null;
       try{
           // 配置文件流
           cfgStream = Resources.getResourceAsStream("mybatis-config.xml");
           // 獲得閱讀流
           cfgReader = new InputStreamReader(cfgStream);
           // 讀入屬性文件
           proStream = Resources.getResourceAsStream("db.properties");
           proReader = new InputStreamReader(proStream);
           // 持久化屬性集
           properties = new Properties();
           // 流裝載進入屬性集合
           properties.load(proReader);
           // 獲取當前系統ENV
           String key = System.getenv("KEYWORDES");
           // 進行解密
           properties.setProperty("password", Decode.decryptDecode(properties.getProperty("password"), key));
       }catch (Exception e){
           logger.error(e);
       }

       if(sqlSessionFactory == null){
           synchronized (CLASS_LOCK){
               sqlSessionFactory = new SqlSessionFactoryBuilder().build(cfgReader, properties);
           }
       }
       return sqlSessionFactory;
    }

    /**
     * 打開SqlSession
     * @return SqlSession
     */
    public static SqlSession openSqlSesion(){
        // 判空處理
        if(sqlSessionFactory == null){
            initSqlSessionFactory();
        }
        return sqlSessionFactory.openSession();
    }
}

書寫單元測試

package com.ming.Util;

import org.junit.Test;

import static org.junit.Assert.*;

public class SqlSessionFactoryUtilTest {

    @Test
    public void initSqlSessionFactory() {
    }

    @Test
    public void openSqlSesion() {
        SqlSessionFactoryUtil.openSqlSesion();
    }
}

目前的目錄結構
2019-04-11-17-28-38----

此時執行單元測試,可以發現單元測試已經通過
控制台打印出log信息

2019-04-11 17:17:37.357 [DEBUG] org.apache.ibatis.logging.LogFactory.setImplementation(LogFactory.java:105) - Logging initialized using 'class org.apache.ibatis.logging.log4j2.Log4j2Impl' adapter.
2019-04-11 17:17:37.403 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:334) - PooledDataSource forcefully closed/removed all connections.
2019-04-11 17:17:37.403 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:334) - PooledDataSource forcefully closed/removed all connections.
2019-04-11 17:17:37.404 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:334) - PooledDataSource forcefully closed/removed all connections.
2019-04-11 17:17:37.404 [DEBUG] org.apache.ibatis.datasource.pooled.PooledDataSource.forceCloseAll(PooledDataSource.java:334) - PooledDataSource forcefully closed/removed all connections.

Process finished with exit code 0

發現錯誤,修改加密類

package com.ming.Util;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.util.Base64;

public class Decode {
    /**
     * 生成秘鑰
     * @param
     * @return
     */
    public static String generateDecode() throws UnsupportedEncodingException {
        KeyGenerator keyGen = null;//密鑰生成器
        try {
            keyGen = KeyGenerator.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyGen.init(56);//初始化密鑰生成器
        SecretKey secretKey = keyGen.generateKey();//生成密鑰
        byte[] key = secretKey.getEncoded();//密鑰字節數組
        // 進行base64編碼
        String encodedKey = Base64.getEncoder().encodeToString(key);
        return encodedKey;
    }

    /**
     * 進行加密
     * @param string
     * @param key
     * @return
     */
    public static String encryptionDecode(String string, String key){
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "DES");//恢復密鑰
        Cipher cipher = null;//Cipher完成加密或解密工作類
        try {
            cipher = Cipher.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);//對Cipher初始化,加密模式
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] cipherByte = null;
        try {
            cipherByte = cipher.doFinal(string.getBytes());//加密data
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return Base64.getEncoder().encodeToString(cipherByte);
    }

    /**
     * 進行解密
     * @param string
     * @param key
     * @return
     */
    public static String decryptDecode(String string, String key){
        SecretKey secretKey = new SecretKeySpec(Base64.getDecoder().decode(key), "DES");//恢復密鑰
        Cipher cipher = null;//Cipher完成加密或解密工作類
        try {
            cipher = Cipher.getInstance("DES");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }
        try {
            cipher.init(Cipher.DECRYPT_MODE, secretKey);//對Cipher初始化,解密模式
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        byte[] cipherByte = new byte[0];//解密data
        try {
            cipherByte = cipher.doFinal(Base64.getDecoder().decode(string));
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }
        return new String(cipherByte);
    }
}

再次運行,可以發現已經成功執行sql語句
1554124784598.remmina-2019-4-11-10-3-0.972575


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM