使用spring从tomcat server.xml解码加密的密码

时间:2015-06-10 09:53:04

标签: java spring

我的弹簧应用程序中有以下配置

--main-context.xml
<bean class="com.crisil.ram.hdfc.util.SpringContextUtil" />   
<import resource="DataSource.xml"/>

--DataSource.xml
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>WEB-INF/database.properties</value>
    </property>
</bean>

<!--<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiName" value="${jdbc.jndiName}"/>
</bean>-->

而不是上面的bean定义我使用了以下定义

<bean id="dataSource" class="my.app.util.EncryptedDataSource">
    <property name="jndiName" value="${jdbc.jndiName}"/>
</bean>

--database.properties

jdbc.jndiName=java:comp/env/jdbc/MYAPPDB

--server.xml
<Context crossContext="true" debug="0" docBase="D:/apache-tomcat-7.0.32/webapps/MyApp" path="/MyApp" reloadable="true">
<Resource auth="Container" driverClassName="oracle.jdbc.driver.OracleDriver" logAbandoned="true" maxActive="20" maxIdle="40" 
 maxWait="60000" name="jdbc/MYAPPDB" removeAbandoned="true" removeAbandonedTimeout="60" type="javax.sql.DataSource" 
 url="jdbc:oracle:thin:@MYDESK:1521:u11g4777" username="user" password="cGFzc3dvcmQ="/><!--password-->
</Context>

这是我用于解密密码的EncryptedDataSource类,它扩展了JndiObjectFactoryBean

package my.app.util;

import java.io.IOException;

import javax.naming.NamingException;

import org.apache.commons.configuration.JNDIConfiguration;
import org.springframework.jndi.JndiObjectFactoryBean;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class EncryptedDataSource extends JndiObjectFactoryBean{

    /*@Override
    public String getPassword() {
        String password = super.getPassword();
        password = decode(password);
        return password;
    }*/

    private String decode(String decode) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            decode = new String(decoder.decodeBuffer(decode));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return decode;
    }

    private String encode(String encode) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        encode = new String(encoder.encodeBuffer(encode.getBytes()));
        return encode;
    }

    public static void main(String[] args) throws IllegalArgumentException, NamingException {

        EncryptedDataSource ed = new EncryptedDataSource();

        try {
            String password = ed.encode("password");
            System.out.println("password = "+password);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

这里我使用了加密格式的密码,我想在连接池时解密。 请帮忙。

0 个答案:

没有答案