`
log_cd
  • 浏览: 1098415 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

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 < ALL_PROPERTIES.length; i++) {
			String propertyName = ALL_PROPERTIES[i];
			RefAddr ra = ref.get(propertyName);
			if (ra != null) {
				String propertyValue = ra.getContent().toString();
				properties.setProperty(propertyName, propertyValue);
			}
		}

		return createDataSource(properties);
	}

	public static DataSource createDataSource(Properties properties)
			throws Exception {
		final BasicDataSource dataSource = new BasicDataSource();
		String value = null;

		value = properties.getProperty("defaultAutoCommit");
		if (value != null) {
			dataSource.setDefaultAutoCommit(Boolean.valueOf(value)
					.booleanValue());
		}

		value = properties.getProperty("defaultReadOnly");
		if (value != null) {
			dataSource
					.setDefaultReadOnly(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("defaultTransactionIsolation");
		if (value != null) {
			int level = -1;
			if ("NONE".equalsIgnoreCase(value)) {
				level = 0;
			} else if ("READ_COMMITTED".equalsIgnoreCase(value)) {
				level = 2;
			} else if ("READ_UNCOMMITTED".equalsIgnoreCase(value)) {
				level = 1;
			} else if ("REPEATABLE_READ".equalsIgnoreCase(value)) {
				level = 4;
			} else if ("SERIALIZABLE".equalsIgnoreCase(value))
				level = 8;
			else {
				try {
					level = Integer.parseInt(value);
				} catch (NumberFormatException e) {
					System.err
							.println("Could not parse defaultTransactionIsolation: "
									+ value);
					System.err
							.println("WARNING: defaultTransactionIsolation not set");
					System.err
							.println("using default value of database driver");

					level = -1;
				}
			}
			dataSource.setDefaultTransactionIsolation(level);
		}

		value = properties.getProperty("defaultCatalog");
		if (value != null) {
			dataSource.setDefaultCatalog(value);
		}

		value = properties.getProperty("driverClassName");
		if (value != null) {
			dataSource.setDriverClassName(value);
		}

		value = properties.getProperty("maxActive");
		if (value != null) {
			dataSource.setMaxActive(Integer.parseInt(value));
		}

		value = properties.getProperty("maxIdle");
		if (value != null) {
			dataSource.setMaxIdle(Integer.parseInt(value));
		}

		value = properties.getProperty("minIdle");
		if (value != null) {
			dataSource.setMinIdle(Integer.parseInt(value));
		}

		value = properties.getProperty("initialSize");
		if (value != null) {
			dataSource.setInitialSize(Integer.parseInt(value));
		}

		value = properties.getProperty("maxWait");
		if (value != null) {
			dataSource.setMaxWait(Long.parseLong(value));
		}

		value = properties.getProperty("testOnBorrow");
		if (value != null) {
			dataSource.setTestOnBorrow(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("testOnReturn");
		if (value != null) {
			dataSource.setTestOnReturn(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("timeBetweenEvictionRunsMillis");
		if (value != null) {
			dataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(value));
		}

		value = properties.getProperty("numTestsPerEvictionRun");
		if (value != null) {
			dataSource.setNumTestsPerEvictionRun(Integer.parseInt(value));
		}

		value = properties.getProperty("minEvictableIdleTimeMillis");
		if (value != null) {
			dataSource.setMinEvictableIdleTimeMillis(Long.parseLong(value));
		}

		value = properties.getProperty("testWhileIdle");
		if (value != null) {
			dataSource.setTestWhileIdle(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("password");
		if (value != null) {
			dataSource.setPassword(CipherEncrypter.decrypt(value.trim()));
		}

		value = properties.getProperty("url");
		if (value != null) {
			dataSource.setUrl(value);
		}

		value = properties.getProperty("username");
		if (value != null) {
			dataSource.setUsername(value.trim());
		}

		value = properties.getProperty("validationQuery");
		if (value != null) {
			dataSource.setValidationQuery(value);
		}

		value = properties.getProperty("validationQueryTimeout");
		if (value != null) {
			dataSource.setValidationQueryTimeout(Integer.parseInt(value));
		}

		value = properties.getProperty("accessToUnderlyingConnectionAllowed");
		if (value != null) {
			dataSource.setAccessToUnderlyingConnectionAllowed(Boolean.valueOf(
					value).booleanValue());
		}

		value = properties.getProperty("removeAbandoned");
		if (value != null) {
			dataSource
					.setRemoveAbandoned(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("removeAbandonedTimeout");
		if (value != null) {
			dataSource.setRemoveAbandonedTimeout(Integer.parseInt(value));
		}

		value = properties.getProperty("logAbandoned");
		if (value != null) {
			dataSource.setLogAbandoned(Boolean.valueOf(value).booleanValue());
		}

		value = properties.getProperty("poolPreparedStatements");
		if (value != null) {
			dataSource.setPoolPreparedStatements(Boolean.valueOf(value)
					.booleanValue());
		}

		value = properties.getProperty("maxOpenPreparedStatements");
		if (value != null) {
			dataSource.setMaxOpenPreparedStatements(Integer.parseInt(value));
		}

		value = properties.getProperty("initConnectionSqls");
		if (value != null) {
			StringTokenizer tokenizer = new StringTokenizer(value, ";");
			dataSource.setConnectionInitSqls(Collections.list(tokenizer));
		}

		value = properties.getProperty("connectionProperties");
		if (value != null) {
			Properties p = getProperties(value);
			Enumeration e = p.propertyNames();
			while (e.hasMoreElements()) {
				String propertyName = (String) e.nextElement();
				dataSource.addConnectionProperty(propertyName,
						p.getProperty(propertyName));
			}

		}

		if (dataSource.getInitialSize() > 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全局数据源中使用加密后的数据库密码
<Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" maxActive="50" maxIdle="20" maxOpenPreparedStatements="100" maxWait="10000" name="jdbc/yxzxuserDS" password="L9+rt2kMEHo=" poolPreparedStatements="true" type="javax.sql.DataSource" url="jdbc:mysql://192.168.2.102:3306/testdb?autoReconnect=true&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;useSSL=false" username="appuser" validationQuery="SELECT 1" factory="com.vajra.security.datasource.VajraBasicDataSourceFactory"/>
分享到:
评论

相关推荐

    tomcat_连接池数据库密码加密解密方法

    ### Tomcat连接池数据库密码加密解密方法详解 在企业级应用中,数据库的安全性尤为重要。其中,数据库连接池作为应用程序与数据库之间的桥梁,扮演着关键角色。然而,当数据库的用户名和密码直接硬编码在配置文件...

    AES256 加密 解密 Tomcat连接池数据库密码加密_1

    使用AES256加密技术实现tomcat7对连接池数据库密码加密解密,资源中包含加密小程序,小程序实现加密,tomcat中实现解密,方便客户自己修改数据库密码且是密文!支持多操作系统如:linux mac os 文件太多分成两部分请...

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

    使用AES256加密技术实现tomcat7对连接池数据库密码加密解密,资源中包含加密小程序,小程序实现加密,tomcat中实现解密,方便客户自己修改数据库密码且是密文!

    使用Tomcat-5_5_20配置数据库连接池详细介绍

    ### 使用Tomcat-5_5_20配置数据库连接池详细介绍 #### 一、Tomcat基本概述 在本文档中,我们将详细介绍如何在Tomcat 5.5.20版本中配置数据库连接池。Tomcat作为一款开源轻量级Web应用服务器,在Java Web开发领域...

    高性能的分布式数据库连接池clearpool.zip

    clearpool有着良好的性能,因为它最大程度地复用了数据库连接池的连接。 clearpool的功能: 有效地管理分布式数据库。 支持分布式事务。 可以监控数据库池状态。  能够在数据库重启...

    早期写的数据库连接池

    总之,早期的数据库连接池设计为我们提供了高效、可靠的数据库连接管理手段,随着技术的发展,现代的连接池如HikariCP、Apache DBCP 2.x和Tomcat JDBC Pool等在性能和功能上都有了进一步的提升,但基本的连接池原理...

    tomcat数据源连接池配置

    4. **测试与调整**:启动Tomcat,运行应用并尝试获取数据库连接,观察日志确认连接池是否正常工作。如果出现问题,检查配置文件中的错误,或者调整连接池参数以优化性能。 **注意事项:** - 配置时要确保数据库驱动...

    MVC+数据库链接池功能实现

    在Tomcat中,数据库连接池的配置通常在`conf/server.xml`文件中。你需要将数据库连接池的配置添加到`&lt;GlobalNamingResources&gt;`或特定的`&lt;Context&gt;`元素内。配置通常包括数据源名称(DataSource)、驱动类名、URL、...

    Tomcat连接池

    【描述】:Tomcat连接池是Apache Tomcat服务器中的一个关键组件,它管理数据库连接资源,以提高应用程序的性能和效率。在高并发环境中,频繁地创建和销毁数据库连接会导致系统资源的大量消耗,而连接池可以预先配置...

    druid配置数据库连接使用密文密码

    Druid是由阿里巴巴开源的一个高性能的Java数据库连接池实现,它不仅提供数据库连接管理的功能,还提供了SQL执行监控、数据源代理等功能。Druid相比其他数据库连接池(如C3P0、DBCP等)具有更好的性能和稳定性,在...

    详解SpringBoot配置连接池

    总之,SpringBoot通过自动配置使得数据库连接池的配置变得简单,而Druid作为一款强大的连接池组件,提供了丰富的监控和扩展功能,是很多开发者的选择。通过合理配置,我们可以有效管理和优化数据库连接,提高应用的...

    详解springboot 使用c3p0数据库连接池的方法

    在 Spring Boot 应用程序中,默认使用的是 Tomcat 数据库连接池。但是,在实际应用中,我们经常遇到数据库连接中断的问题。使用 C3P0 连接池可以解决这个问题,并提供更好的性能和可靠性。 添加 Maven 依赖 要使用...

    基于tomcat和access数据库的信息管理系统网站

    7. **性能优化**:考虑到Access数据库的性能限制,可能需要优化JDBC连接池,减少不必要的数据库交互,或者考虑使用缓存技术提高响应速度。 8. **版本控制**:使用Git或其他版本控制系统管理代码,确保团队协作时...

    连接池的配置

    在IT行业中,数据库连接池是优化数据库访问性能和资源管理的重要工具。连接池的基本思想是预先创建并维护一定数量的数据库连接,供多个应用程序共享,从而避免了频繁地创建和销毁连接带来的开销。本文将深入探讨连接...

    JavaWeb:Tomcat下配置数据源连接数据库.pdf

    数据源(DataSource)是JDBC的一个接口,它使得应用程序能够以一种标准的方式获取数据库连接,同时支持连接池(Connection Pool)的概念,可以高效地管理数据库连接,提升系统性能。 在Tomcat服务器下配置数据源...

    jsp页面,连接数据库实现增删改查

    综上所述,"jsp页面,连接数据库实现增删改查"这个项目涵盖了JSP页面开发、数据库设计、JDBC操作、用户认证、数据库连接池、安全策略以及前端异步交互等多个重要知识点。通过实践这些技术,开发者能够构建出高效、...

    JSP 数据库连接登录

    10. **优化与最佳实践**:考虑到性能和资源管理,建议使用连接池来管理数据库连接,如C3P0或HikariCP。这可以提高应用程序的效率,同时减少资源浪费。 以上就是使用JSP连接数据库实现登录功能的基本步骤。在实践中...

    java登录、注册案例(servlet+mysql+tomcat8+C3P0Pool).doc

    通过C3P0,可以创建一个数据库连接池,管理数据库连接的创建、分配、回收和释放。 5. **业务逻辑处理**: - **登录逻辑**: a1. `LoginServlet`:处理登录请求,接收到前端提交的用户名和密码。 a2. `login()`...

    RHEL3U6下MAP TOMCAT JDK MYSQL连接池配置

    - 配置TOMCAT的`server.xml`文件,添加数据库连接池的配置,例如使用Apache Commons DBCP或C3P0库。 - 在`context.xml`或`web.xml`中定义数据源,包括数据库驱动类、URL、用户名、密码等信息。 ### 4. **连接池配置...

Global site tag (gtag.js) - Google Analytics