利用反射获得数据源连接信息

   在生产环境中MySQL以云插件的方式提供给应用,连接凭据由运维掌控而对应用开发者屏蔽,在需要的时候难免有些不便。这时候我们可以采用反射的方式还原出来,代码如下:

import java.lang.reflect.Field;
import org.apache.log4j.Logger;

public class CrackDbInfo {
	protected static final Logger log = Logger.getLogger(CrackDbInfo.class);

	/**
	 * 利用反射获取数据源连接信息
	 * 
	 * @param dataSource
	 * @return
	 */
	public static String retriveCredentials(javax.sql.DataSource dataSource) {
		String result = null;
		try {
			Field host = dataSource.getClass().getDeclaredField("host");
			host.setAccessible(true);
			Object hostValue = host.get(dataSource);
			Field port = dataSource.getClass().getDeclaredField("port");
			port.setAccessible(true);
			Object portValue = port.get(dataSource);
			Field database = dataSource.getClass().getDeclaredField("database");
			database.setAccessible(true);
			Object databaseValue = database.get(dataSource);
			Field user = dataSource.getClass().getDeclaredField("user");
			user.setAccessible(true);
			Object userValue = user.get(dataSource);
			Field pwd = dataSource.getClass().getDeclaredField("password");
			pwd.setAccessible(true);
			Object pwdValue = pwd.get(dataSource);
			result = String
					.format("{\"user\": \"%s\", \"pwd\": \"%s\", \"host\": \"%s\", \"port\": %s, \"database\": \"%s\"}",
							userValue.toString(), pwdValue.toString(), hostValue.toString(),
							portValue.toString(), databaseValue.toString());
		} catch (NoSuchFieldException e) {
			log.error(e.getMessage(), e);
		} catch (SecurityException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalArgumentException e) {
			log.error(e.getMessage(), e);
		} catch (IllegalAccessException e) {
			log.error(e.getMessage(), e);
		}
		return result;
	}
}

 

@see:http://lixuanbin.github.io/2016/06/30/hack-datasource-credentials-via-reflection/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值