hibernate c3p0数据源用户名密码加密

spring2 配置文件
Java代码 复制代码  收藏代码
<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
	<!--  数据源配置 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
		<property name="driverClass">
			<value>oracle.jdbc.driver.OracleDriver</value>
		</property>
		<property name="jdbcUrl" value="jdbc:oracle:thin:@IP:端口:SID" />
		<property name="acquireIncrement" value="1"/>
		<property name="idleConnectionTestPeriod" value="300"/>
		<property name="maxPoolSize" value="5"/>
		<property name="minPoolSize" value="1"/>
		<property name="initialPoolSize" value="1" />
		<property name="numHelperThreads" value="3"/>
		<property name="maxIdleTime" value="1200" />
		<property name="acquireRetryAttempts" value="2"/>
		<property name="preferredTestQuery" value=" select 1 from dual "/>
		<property name="testConnectionOnCheckin" value="true"/>
		<property name="properties" ref="dataSourceProperties"/>
	</bean>
	
	<bean id="dataSourceProperties" class="PropertiesEncryptFactoryBean">
		<property name="properties">
			<props>
				<prop key="user">xxxx加密后</prop>
				<prop key="password">xxxxxxx加密后</prop>
			</props>
		</property>
	</bean>


2.PropertiesEncryptFactoryBean(加密类)
Java代码 复制代码  收藏代码

  

import java.util.Properties;

import org.springframework.beans.factory.FactoryBean;

public class PropertiesEncryptFactoryBean implements FactoryBean {

	private Properties properties;
	
	public Object getObject() throws Exception {
		return getProperties();
	}

	public Class getObjectType() {
		return java.util.Properties.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties inProperties) {
		this.properties = inProperties;
		String originalUsername = properties.getProperty("user");
		String originalPassword = properties.getProperty("password");
		if (originalUsername != null){
			String newUsername = deEncryptUsername(originalUsername);
			properties.put("user", newUsername);
		}
		if (originalPassword != null){
			String newPassword = deEncryptPassword(originalPassword);
			properties.put("password", newPassword);
		}
	}
	
	private String deEncryptUsername(String originalUsername){
		return deEncryptString(originalUsername);
	}
	
	private String deEncryptPassword(String originalPassword){
		return deEncryptString(originalPassword);
	}
	//简单加密
	private String deEncryptString(String originalString){
		StringBuilder newString = new StringBuilder();
		for (int i = 0; i < originalString.length(); i++) {
			char eachChar= originalString.charAt(i);
			char newChar = (char)(eachChar + i);
			newString.append(newChar);
		}
		return newString.toString();
	}

}



ComboPooledDataSource的properties属性可被注入user,password
只有user,password两个属性是可配置,其他属性不存也不是取自properties(具体可看C3P0源码)

你可能感兴趣的:(Hibernate)