因为客户要求,有时候,我们在tomcat里配置的数据库连接池,连接密码不能直接用明文,所以需要我们加密后,在配置上去,然后这就需要用到解密了。
我们需要写一个类继承org.apache.commons.dbcp.BasicDataSourceFactory,然后在tomcat的配置文件里指定 factory="*.EncryptedDataSourceFactory",
相关代码如下:
import java.util.Enumeration;
import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.StringRefAddr;
import org.apache.commons.dbcp.BasicDataSourceFactory;
/**
*
* @author wsa
*
*/
public class EncryptedDataSourceFactory extends BasicDataSourceFactory {
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment) throws Exception {
if (obj instanceof Reference) {
//用户名不需要加密,所以去掉解密
//setUsername((Reference) obj);
setPassword((Reference) obj);
}
return super.getObjectInstance(obj, name, nameCtx, environment);
}
private void setUsername(Reference ref) throws Exception {
findDecryptAndReplace("username", ref);
}
private void setPassword(Reference ref) throws Exception {
findDecryptAndReplace("password", ref);
}
private void findDecryptAndReplace(String refType, Reference ref)
throws Exception {
int idx = find(refType, ref);
String decrypted = decrypt(idx, ref);
replace(idx, refType, decrypted, ref);
}
/**
* 将解密后的字符串替换配置文件里的加密后的字符串
* @param idx
* @param refType
* @param newValue
* @param ref
* @throws Exception
*/
private void replace(int idx, String refType, String newValue, Reference ref)
throws Exception {
ref.remove(idx);
ref.add(idx, new StringRefAddr(refType, newValue));
}
/**
* 解密
* @param idx
* @param ref
* @return
* @throws Exception
*/
private String decrypt(int idx, Reference ref) throws Exception {
//解密方法
return G4Utils.decryptBasedDes(ref.get(idx).getContent().toString());
}
/**
* 找到需要解密的字符串的位置
* @param addrType
* @param ref
* @return
* @throws Exception
*/
private int find(String addrType, Reference ref) throws Exception {
Enumeration enu = ref.getAll();
for (int i = 0; enu.hasMoreElements(); i++) {
RefAddr addr = (RefAddr) enu.nextElement();
if (addr.getType().compareTo(addrType) == 0) {
return i;
}
}
throw new Exception("The \"" + addrType
+ "\" name/value pair was not found"
+ " in the Reference object. The reference Object is" + " "
+ ref.toString());
}
}
tomcat的配置如下(将password设置成加密后的密文,Factory设置为上面添加的类):
上述测试,tomcat启动没有问题。
原文转载自:https://my.oschina.net/cimu/blog/164757