MyBatisプロファイルユーザーパスワード暗号化ストレージ

14466 ワード

propertiesプロファイル
一般的にはpropertiesを使用してプロファイルの内容を保存し、mybatisプロファイルでresourceファイルの下にdbを新規作成する.propertiesファイルの内容は以下の通りです.
#        
driver = com.mysql.cj.jdbc.Driver
url = jdbc:mysql://  /mybatis
username =  
password =   

次に、ソースパッケージにファイルを入れるmybatis-configを構成する.xmlファイル



	
	
	
	
		
	
	
	
	
		
	
	
	
		
			
			
			
			
				
				
				
				
			
		
	
	
	
		
	


ディレクトリ構造は次のとおりです.
データベースパスワードの暗号化
生产环境のデータベースのパスワードはすべて暗号化のパスワードで、使う时、暗号化のパスワードを解読して明文になって先にデータベースのパスワードのクラスを作成する必要があります
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);
    }
}


このクラスには3つの方法があり、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();
    }
}

現在のディレクトリ構造
ユニットテストを実行すると、ユニットテストがコンソールから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文が正常に実行されたことがわかります.