MyBatis之Base64加密数据源

一般来讲,MyBatis的数据源都是通过这种形式直接配置的:
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>
	<environments default="development">
		<environment id="development">
			<transactionManager type="JDBC" />
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
				<property name="username" value="root" />
				<property name="password" value="11111111" />
			</dataSource>
		</environment>
	</environments>
</configuration>

显然,这样把数据库连接的所有信息,明文的这样展示出来是一件很危险的事情。

所以,我就去研究了一下,如果对数据源信息进行加密。

我采用的就是简单Base64对文件进行加密,当然,有人说java是可以反编译的,对,没错,我们只防君子,不能防小人。

所以,我要做的事情是Base64对MyBatis的数据源进行加密.

那么,整理下思路,我要做的工作,主要有以下3点:

1.将url,username,password,进行加密,获得密文

2.将密文配置到MyBatis中,并MyBatis的创建SqlSessionFactory之前,对密文进行解密,然后获得数据库连接

3.关联数据源


1.将url,username,password,进行加密,获得密文

/**
 * 工具类,将Sting字符串进行加密
 * 
 * @author robin
 *
 */
public class String2Coder {
	public static void main(String[] args) {
		if (args.length < 1)
			return;
		byte[] buffer = Base64.getEncoder().encode(args[0].getBytes());
		System.out.println(new String(buffer));
		try {
			System.out.println("press any key to exit.");
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

这个类很简单,就是使用Base64对字段进行加密。当然,出于方便,可以直接将args[0]换成我们需要加密的字符串。

但是,我这样做,是为了顺便做个Base64加密的工具,然后将这个类导出为可执行的jar包。

然后,打开cmd,执行jar包,注意最后的 >out.txt 是将输出结果重定向到out.txt


打开out.txt文件:

cm9iaW4就是robin加密后的密文啦。


2.将密文配置到MyBatis中

2.1  首先需要说明的是,MyBatis,是支持将数据源分离成jdbc.propertis,所以第一步是准备jdbc.properties

jdbc.properties:

driver=com.mysql.jdbc.Driver
url=******
username=******
password=******

2.2  通过代码获取jdbc.properties并将字段解密,创建SqlSessionFactory

package com.test.sql.session;

import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Properties;

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.log4j.Logger;

public class SqlSessionFactoryUtil {
	public static Logger logger = Logger.getLogger(SqlSessionFactoryUtil.class);

	private static SqlSessionFactory factory;

	public static Class<SqlSessionFactoryUtil> LOCK = SqlSessionFactoryUtil.class;

	public static SqlSession getSqlSession() {
		SqlSessionFactory sf = getFactory();
		return getFactory().openSession();
	}

	private static SqlSessionFactory getFactory() {
		if (factory != null)
			return factory;

		synchronized (LOCK) {
			if (factory == null) {
				InputStream inputStream = null;
				try {
					inputStream = Resources
							.getResourceAsStream("mybatis-config.xml");
					// read the encode jdbc.properties
					Properties prop = getJdbcPropertiesByDecode("jdbc.properties");
					factory = new SqlSessionFactoryBuilder().build(inputStream,
							prop);
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				} finally {
					if (inputStream != null)
						try {
							inputStream.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
				}
			}
		}
		return factory;
	}

	private static Properties getJdbcPropertiesByDecode(String string)
			throws IOException {
		Properties prop = Resources.getResourceAsProperties("jdbc.properties");
		// String driver = prop.getProperty("driver");
		String url = prop.getProperty("url");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");

		byte[] buffer = Base64.getDecoder().decode(url.getBytes());
		prop.setProperty("url", new String(buffer));
		buffer = Base64.getDecoder().decode(username.getBytes());
		prop.setProperty("username", new String(buffer));
		buffer = Base64.getDecoder().decode(password.getBytes());
		prop.setProperty("password", new String(buffer));
		return prop;
	}

	public static void main(String[] args) throws IOException {
		Properties prop = Resources.getResourceAsProperties("jdbc.properties");
		// String driver = prop.getProperty("driver");
		String url = prop.getProperty("url");
		String username = prop.getProperty("username");
		String password = prop.getProperty("password");

		byte[] buffer = Base64.getDecoder().decode(url.getBytes());
		prop.setProperty("url", new String(buffer));
		buffer = Base64.getDecoder().decode(username.getBytes());
		prop.setProperty("username", new String(buffer));
		buffer = Base64.getDecoder().decode(password.getBytes());
		prop.setProperty("password", new String(buffer));
		
		System.out.println(prop);
	}
}

注意看getJdbcPropertiesByDecode方法,解密过程;

注意看factory = new SqlSessionFactoryBuilder().build(inputStream,prop);很清晰吧。

main,是用来测试我加密的密文,解密之后是否正确。

but!!!!到这里并没有结束。

笔者第一次配置的时候,天真的把dataSource全部删除掉了,我猜大概这样可以了吧,但,你会发现,并不行。


3.关联数据源

为什么不行,可以思考下,虽然我们通过factory = new SqlSessionFactoryBuilder().build(inputStream,prop);中的prop把url,username,password注入了进去,但还是没有获取到数据源。从设计的角度来看,jdbc.properties里面,我完全可以将url写成urllllllll,username写成name,password写成pwd。这样MyBatis是无法识别,所以最后一步就是关联。

再来看下关联后的mybatis-config.xml

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>
	<environments default="development">
		<environment id="development">
			<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>
</configuration>


此处的$url对应的就是第二部 prop.set("url",url);中的"url"了。

到此,结束。


笔者突然想到一个问题,就是MyBatis如何配置多个数据源

其实很简单嘛,有几个数据源就配置几个mybatis-config.xml,也对应几个SqlSessionFactory。

完全没有任何问题。









發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章