Spring + MyBatis 数据库连接加密实现方式

近期因项目需要,客户要求数据库用户名和密码需加密实现连接。项目实现框架SSM,上网查阅一番资料后,发现有部分资料分享的不是很完善,在此写下随笔,以便大家采纳及提出建议。有写的不对的地方,欢迎给予指正。

以下来介绍我的实现方式

1、配置 jdbc.properties 配置文件,该文件可放置在src同级目录下,其中的SIT环境和PRD环境的参数我就给删掉了,可以根据自身项目实际情况,决定要配置几个参数。这里需要注意一点,配置文件中的用户名的KEY一定不能使用username,否则会带来不必要的麻烦,无法正确连接数据库,具体原因还请知道的同学回复分享下。

# 数据库连接密文配置
# AES加密方式

#driver
jdbc.driver = oracle.jdbc.driver.OracleDriver
#url
jdbc.url = jdbc:oracle:thin:@127.0.0.1:1521/orcl
#username 
jdbc.user = test
#password fms
jdbc.password = test
#SITurl 测试环境
jdbc.SITurl = 
#SITusername 
jdbc.SITuser = 
#SITpassword 
jdbc.SITpassword = 
#PRDurl 生产环境
jdbc.PRDurl = 
#PRDusername
jdbc.PRDuser = 
#PRDpassword 
jdbc.PRDpassword = 

##加密状态是否已加密 0-否 1-是
jdbc.isencoder = 0

2、修改 Spring 配置文件 applicationContext-config.xml中 数据源配置参数,如下,部分数据源配置就没有贴出来啦

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.user}" />
		<property name="password" value="${jdbc.password}" />
</bean>

并需要添加如下配置来读取配置文件,location="属性文件,多个之间逗号分隔",ignore-unresolvable是否忽略解析不到的属性,如果不忽略,找不到将抛出异常。

<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

3、创建自己的加密工具类,和参数重写工具类,加密工具类就百度一下有很对,加密方式可以自行百度了,这里我使用的是AES加密方式,下面我来贴一下我的配置文件参数重写的工具类

/**
 * 配置文件工具类 
 * 实现配置文件重写
 * 
 * @author Fyq
 *
 */
public class PropUtil {
	private static Logger logger = LoggerFactory.getLogger(PropUtil.class);

	private static Properties properties = new Properties();
	private static String filename;

	public static String getProperty(String key) {
		return properties.getProperty(key);
	}

	/**
	 * 配置文件参数重写
	 * 
	 * @param key
	 * @param value
	 */
	public static void setProperty(String key, String value) {
		try {
			FileInputStream inputStream = new FileInputStream(
					new File(Thread.currentThread().getContextClassLoader().getResource(filename).getPath()));
			Properties prop = new Properties();
			prop.load(inputStream);

			prop.setProperty(key, value);

			FileOutputStream outputStream = new FileOutputStream(
					new File(Thread.currentThread().getContextClassLoader().getResource(filename).getPath()));
			prop.store(outputStream, "Update '" + key + "' value");
			outputStream.flush();
			outputStream.close();
			properties.setProperty(key, value);
		} catch (FileNotFoundException e) {
			logger.error("load properties file error:" + e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("load properties file error:" + e);
			e.printStackTrace();
		}
	}

	/**
	 * 启动时加载properties配置文件
	 * 
	 * @param filePath
	 */
	public static void loadFile(String filePath) {
		try {
			properties.clear();
			filename = filePath;
			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath));
		} catch (IOException e) {
			logger.error("加载配置文件错误:" + e);
			e.printStackTrace();
		}
	}
}

4、接着需要重写 Spring容器的监听器 ContextLoaderListener


/**
 * 重写Spring容器的监听器
 * 实现配置文件属性加密
 * @author Fyq
 *
 */
public class JdbcSafetyListener extends ContextLoaderListener {
	protected final Logger logger = LoggerFactory.getLogger(JdbcSafetyListener.class);
	// 属性需与配置文件的KEY保持一致
	private String[] encryptPropNames = { "jdbc.user", "jdbc.password", "jdbc.SITuser", "jdbc.SITpassword",
			"jdbc.PRDuser", "jdbc.PRDpassword" };

	/**
	 * 初始化时加载properties配置文件
	 * 
	 * 重写properties配置文件,为key值加密
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		try {
			PropUtil.loadFile("jdbc.properties");
			// 配置文件为未加密状态
			if (PropUtil.getProperty("jdbc.isencoder").equals("0")) {
				for (String string : encryptPropNames) {
					// 获取需加密字符串
					String propertyValue = PropUtil.getProperty(string);
					// 加密密文
					String encryptValue = AESUtil.getEncryptString(propertyValue);
					log.info(string + "---->" + encryptValue);
					PropUtil.setProperty(string, encryptValue);
				}
				// 设置配置文件加密状态
				PropUtil.setProperty("jdbc.isencoder", "1");
			}
		} catch (Exception e) {
			log.error("参数加载失败");
			log.debug(e.getMessage(), e);
		}
	}

	/**
	 * 最后处理的事情
	 */
	@Override
	protected void finalize() throws Throwable {
		// 关闭自动运行批处理
		super.finalize();
		log.info("参数加载成功");
	}
}

监听器实现之后,在web.xml配置这个监听器,启动容器时,就会默认执行它实现的方法。

<listener>
	<listener-class>com.it.csdn.jdbcDecode.JdbcSafetyListener</listener-class>
</listener>

至此,我们的项目工程启动后,工作域路径\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\工程名\WEB-INF\classes\jdbc.properties中的属性就会被重写成密文

Linux环境下也在相关工程文件加下可以找到,这里就不贴出来给大家看了。

但是,我们还不能实现数据库连接,因为数据库user和密码都是密文,那么我们还需要实现用户名和密码的解密

5、实现数据库用户名和密码的解密方式,这个时候就用到了 Spring中提供着一个 PropertyPlaceholderConfigurer ,其作用就是我们系统初始化的时候,系统自动读取jdbc.properties配置文件中的key value(键值对),然后对我们系统进行定制的初始化。

/**
 * 数据库配置文件解密
 * 
 * @author Fyq
 *
 */
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
	protected final Logger logger = LoggerFactory.getLogger(EncryptPropertyPlaceholderConfigurer.class);
	// 属性需与配置文件的KEY保持一致
	private String[] encryptPropNames = { "jdbc.user", "jdbc.password", "jdbc.SITuser", "jdbc.SITpassword",
			"jdbc.PRDuser", "jdbc.PRDpassword" };

	@Override
	protected String convertProperty(String propertyName, String propertyValue) {
		// 如果在加密属性名单中发现该属性
		if (isEncryptProp(propertyName)) {
			logger.info(propertyName + "======>>" + propertyValue);
			String decryptValue = AESUtil.getDecryptString(propertyValue);
			System.out.println(decryptValue);
			return decryptValue;
		} else {
			return propertyValue;
		}

	}

	private boolean isEncryptProp(String propertyName) {
		for (String encryptName : encryptPropNames) {
			if (encryptName.equals(propertyName)) {
				return true;
			}
		}
		return false;
	}
}

PropertyPlaceholderConfigurer重写后,需要在applicationContext-config.xml下添加如下配置来加载该配置文件解密方式

<bean class="com.it.csdn.jdbcDecode.EncryptPropertyPlaceholderConfigurer" p:locations="classpath:jdbc.properties"></bean>

至此数据库明文配置,密文加载就已经实现。

另外说一下,还有一种实现方式,是在配置文件中直接配置密文的方式,可以不必使用上述步骤中的Spring容器的监听器去重写配置文件。个人感觉不是很方便,说一下其中缺点吧,,直接配置密文,不利于后面其他人员的维护,数据库用户名密码如果忘记就很尴尬,还有一点就是,windows 和 linux环境下  加密算法不一致,导致的密文也不一样,换环境的时候,需要来回修改配置文件中的密文参数非常的麻烦。

希望此篇文章可以帮助到那些急需数据库加密连接实现的人

备注:文章中部分技术实现是参考网络中一些资料。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值