本地测试环境中,我们如果使用SpringMVC构建项目时,数据库的“用户名、密码、连接地址”都直接明文写在配置文件中。而一旦项目构建在运行环境的服务器时,对“用户名、密码、连接地址”连接信息进行必要的隐藏,这样更加安全一些,那么如何来做隐式jdbc连接信息呢?
SpringMVC在构建jdbc连接信息时,一般是在“applicationContext.xml”文件中有如下信息提供给项目的JdbcConnection。
<!-- 引入jdbc配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>file:C:/properties/hcmanage.properties</value>
</property>
</bean>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driver}"></property>
<property name="url" value="${url}?useUnicode=true&characterEncoding=utf8&"></property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<property name="testOnBorrow" value="true" />
<property name="validationQuery">
<value>select 1 from DUAL</value>
</property>
</bean>
然后我们在hcmanage.properties文件中配置“用户名、密码、连接地址”的明文信息。
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc
username=root
password=root
这种原始的做法很直接的就暴露了我们的“用户名、密码、连接地址”等关键信息,那么如何来规避这些关键信息呢?最好的做法是在hcmanage.properties文件中我们只提供如下信息显示:
driver=com.mysql.jdbc.Driver
url=
username=
password=
我们把“用户名、密码、连接地址”真实信息保存在相对安全的位置,比如说我们自己的数据库,该数据库不在生产环境上,这样做的话,别人要想知道生产环境上的“用户名、密码、连接地址”,就必须先破解我们自己的服务器,然后破解该服务器上的数据库,相对来说增加了不少难度。
那么想要实现这种安全的效果,我们该怎么做呢?
关键位置就在“PropertyPlaceholderConfigurer”类上!
<!-- 引入jdbc配置文件 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>file:C:/properties/hcmanage.properties</value>
</property>
</bean>
没错,我们新建一个自定义的PropertyPlaceholderConfigurer类,继承”org.springframework.beans.factory.config.PropertyPlaceholderConfigurer”。
EncryptPropertyPlaceholderConfigurer.java
public class EncryptPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {
@Override
protected String convertProperty(String propertyName, String propertyValue) {
if (isEncryptProperty(propertyName)) {
return Constants.databaseMap.get(propertyName);
}
return super.convertProperty(propertyName, propertyValue);
}
private boolean isEncryptProperty(String pname) {
for (String name : Constants.DATABASE_PROPERTY_NAMES) {
if (name.equals(pname)) {
return true;
}
}
return false;
}
}
ps:注意关键方法
protected String convertProperty(String propertyName, String propertyValue)
该方法会根据配置文件中提供的propertyName,按照我们自己的意愿进行转换,返回对应的propertyValue。
也就是说,我们可以将
driver=com.mysql.jdbc.Driver
url=
username=
password=
通过一定的转换法则,转换为
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/jdbc
username=root
password=root
而这个过程是不透明的,也就是所谓的隐式转换!
如何建立webservice通信连接,你可以参照第二篇。
如何在通信过程中进行非对称加密,你可以参照第一篇。
由于之前写过类似博客,我这里就不再赘述,重要的是提供SpringMVC使用隐式jdbc连接信息的解决方案!
感谢您阅读【沉默王二的博客】,如果王二的博客给您带来一丝帮助或感动,我(也就是王二)将不甚荣幸。
如果您碰巧喜欢,可以留言或者私信我,这将是我鼓捣更多优秀文章的最强动力。
原文:http://blog.csdn.net/qing_gee/article/details/50754383