MyBatis 配置文件 用户密码加密存储

栏目: 数据库 · 发布时间: 6年前

内容简介:一般是使用properties保存配置文件内容,然后在mybatis配置文件中进行读取在resource文件下新建db.properties文件内容如下

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>

目录结构如下

MyBatis 配置文件 用户密码加密存储

数据库密码加密

生产环境的数据库密码都为加密密码,需要在使用的时候,把加密密码解密成为明文

先创建数据库密码类

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();
    }
}

目前的目录结构

MyBatis 配置文件 用户密码加密存储

此时执行单元测试,可以发现单元测试已经通过

控制台打印出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 语句

MyBatis 配置文件 用户密码加密存储

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Creative Curve

The Creative Curve

Allen Gannett / Knopf Doubleday Publishing Group / 2018-6-12

Big data entrepreneur Allen Gannett overturns the mythology around creative genius, and reveals the science and secrets behind achieving breakout commercial success in any field. We have been s......一起来看看 《The Creative Curve》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码