Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Tomcat数据库连接池数据库密码加密

1、加密工具类

package com.vajra.security.encrypt;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;

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

public class CipherEncrypter {
	Cipher ecipher;
	Cipher dcipher;
	byte[] salt = { -87, -101, -56, 50, 86, 53, -29, 3 };

	int iterationCount = 19;
	private static CipherEncrypter cipherEncrypter;

	private CipherEncrypter(String passPhrase) {
		try {
			PBEKeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray());
			SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES")
					.generateSecret(keySpec);
			this.ecipher = Cipher.getInstance(key.getAlgorithm());
			this.dcipher = Cipher.getInstance(key.getAlgorithm());

			AlgorithmParameterSpec paramSpec = new PBEParameterSpec(this.salt,
					this.iterationCount);

			this.ecipher.init(1, key, paramSpec);
			this.dcipher.init(2, key, paramSpec);
		} catch (InvalidAlgorithmParameterException localInvalidAlgorithmParameterException) {
		} catch (InvalidKeySpecException localInvalidKeySpecException) {
		} catch (NoSuchPaddingException localNoSuchPaddingException) {
		} catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
		} catch (InvalidKeyException localInvalidKeyException) {
		}
	}

	private CipherEncrypter() {
		this("sfpay");
	}

	public static CipherEncrypter getInstance() {
		if (cipherEncrypter == null) {
			cipherEncrypter = new CipherEncrypter();
		}
		return cipherEncrypter;
	}

	public static String encrypt(String str) {
		try {
			byte[] utf8 = str.getBytes("UTF8");
			byte[] enc = getInstance().ecipher.doFinal(utf8);
			return new BASE64Encoder().encode(enc);
		} catch (BadPaddingException localBadPaddingException) {
		} catch (IllegalBlockSizeException localIllegalBlockSizeException) {
		} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
		} catch (Exception localException) {
		}
		return null;
	}

	public static String decrypt(String str) {
		try {
			byte[] dec = new BASE64Decoder().decodeBuffer(str);

			byte[] utf8 = getInstance().dcipher.doFinal(dec);

			return new String(utf8, "UTF8");
		} catch (BadPaddingException localBadPaddingException) {
		} catch (IllegalBlockSizeException localIllegalBlockSizeException) {
		} catch (UnsupportedEncodingException localUnsupportedEncodingException) {
		} catch (IOException localIOException) {
		}
		return null;
	}

	public static void main(String[] args) {
		if (args.length != 1)
			return;
		System.out.println("encrypted string:" + encrypt(args[0]));
	}
}

2、Factory中实现数据库密码解密
package com.vajra.security.datasource;

import java.io.ByteArrayInputStream;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import java.util.StringTokenizer;

import javax.naming.Context;
import javax.naming.Name;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;
import org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory;

import com.vajra.security.encrypt.CipherEncrypter;

@SuppressWarnings("rawtypes")
public class VajraBasicDataSourceFactory extends BasicDataSourceFactory {

	protected static final String PROP_DEFAULTAUTOCOMMIT = "defaultAutoCommit";
	protected static final String PROP_DEFAULTREADONLY = "defaultReadOnly";
	protected static final String PROP_DEFAULTTRANSACTIONISOLATION = "defaultTransactionIsolation";
	protected static final String PROP_DEFAULTCATALOG = "defaultCatalog";
	protected static final String PROP_DRIVERCLASSNAME = "driverClassName";
	protected static final String PROP_MAXACTIVE = "maxActive";
	protected static final String PROP_MAXIDLE = "maxIdle";
	protected static final String PROP_MINIDLE = "minIdle";
	protected static final String PROP_INITIALSIZE = "initialSize";
	protected static final String PROP_MAXWAIT = "maxWait";
	protected static final String PROP_TESTONBORROW = "testOnBorrow";
	protected static final String PROP_TESTONRETURN = "testOnReturn";
	protected static final String PROP_TIMEBETWEENEVICTIONRUNSMILLIS = "timeBetweenEvictionRunsMillis";
	protected static final String PROP_NUMTESTSPEREVICTIONRUN = "numTestsPerEvictionRun";
	protected static final String PROP_MINEVICTABLEIDLETIMEMILLIS = "minEvictableIdleTimeMillis";
	protected static final String PROP_TESTWHILEIDLE = "testWhileIdle";
	protected static final String PROP_PASSWORD = "password";
	protected static final String PROP_URL = "url";
	protected static final String PROP_USERNAME = "username";
	protected static final String PROP_VALIDATIONQUERY = "validationQuery";
	protected static final String PROP_VALIDATIONQUERY_TIMEOUT = "validationQueryTimeout";
	protected static final String PROP_INITCONNECTIONSQLS = "initConnectionSqls";
	protected static final String PROP_ACCESSTOUNDERLYINGCONNECTIONALLOWED = "accessToUnderlyingConnectionAllowed";
	protected static final String PROP_REMOVEABANDONED = "removeAbandoned";
	protected static final String PROP_REMOVEABANDONEDTIMEOUT = "removeAbandonedTimeout";
	protected static final String PROP_LOGABANDONED = "logAbandoned";
	protected static final String PROP_POOLPREPAREDSTATEMENTS = "poolPreparedStatements";
	protected static final String PROP_MAXOPENPREPAREDSTATEMENTS = "maxOpenPreparedStatements";
	protected static final String PROP_CONNECTIONPROPERTIES = "connectionProperties";
	protected static final String[] ALL_PROPERTIES = { "defaultAutoCommit",
			"defaultReadOnly", "defaultTransactionIsolation", "defaultCatalog",
			"driverClassName", "maxActive", "maxIdle", "minIdle",
			"initialSize", "maxWait", "testOnBorrow", "testOnReturn",
			"timeBetweenEvictionRunsMillis", "numTestsPerEvictionRun",
			"minEvictableIdleTimeMillis", "testWhileIdle", "password", "url",
			"username", "validationQuery", "validationQueryTimeout",
			"initConnectionSqls", "accessToUnderlyingConnectionAllowed",
			"removeAbandoned", "removeAbandonedTimeout", "logAbandoned",
			"poolPreparedStatements", "maxOpenPreparedStatements",
			"connectionProperties" };

	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable environment) throws Exception {
		if ((obj == null) || (!(obj instanceof Reference))) {
			return null;
		}
		Reference ref = (Reference) obj;
		if (!"javax.sql.DataSource".equals(ref.getClassName())) {
			return null;
		}

		Properties properties = new Properties();
		for (int i = 0; i  0) {
			dataSource.getLogWriter();
		}

		Runtime.getRuntime().addShutdownHook(new Thread() {
			public void run() {
				try {
					dataSource.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		});

		return dataSource;
	}

	protected static Properties getProperties(String propText) throws Exception {
		Properties p = new Properties();
		if (propText != null) {
			p.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes()));
		}
		return p;
	}

}

3、将以上两个类打包(vajra-dbsecure.jar),并指定Main入口类
D:\>java -jar vajra-dbsecure.jar 1234567
encrypted string :L9+rt2kMEHo=

4、tomcat全局数据源中使用加密后的数据库密码


已有 0 人发表留言,猛击->> 这里

ITeye推荐
  • —软件人才免语言低担保 赴美带薪读研!—





This post first appeared on IT瘾 | IT社区推荐资讯, please read the originial post: here

Share the post

Tomcat数据库连接池数据库密码加密

×

Subscribe to It瘾 | It社区推荐资讯

Get updates delivered right to your inbox!

Thank you for your subscription

×