SSL多线程安全问题

项目原因,代码实现证书控制,网上很多介绍使用System.setProt。。。等方法,后突然想到应该会有多线程安全问题,应为我方系统可能多个证书,故在iteye咨询大牛帮忙,详细见:

 http://www.iteye.com/problems/94392

后按照一个那个朋友介绍,使用代码读取文件方式加载ssl,详细见:

SSLContext ctx = httpsMap.get(prjcodVal.getCPDPRJCOD().toUpperCase());
		if(ctx == null){
			//SSL设置,使用文件方式,如果使用system赋值方式会有多线程问题
			ctx = SSLContext.getInstance("SSL");
			KeyManagerFactory kmf = KeyManagerFactory
					.getInstance("SunX509");
			TrustManagerFactory tmf = TrustManagerFactory
					.getInstance("SunX509");
			KeyStore ks = KeyStore.getInstance("JKS");
			KeyStore tks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(Constants
					.getConstants().getStrCertFilePath()
					+ prjcodVal.getCPDPRJCOD().toUpperCase() + ".jks"),
					Constants.getConstants().getStrHTTPSCERPWD().toCharArray());
			tks.load(new FileInputStream(Constants
					.getConstants().getStrCertFilePath()
					+ prjcodVal.getCPDPRJCOD().toUpperCase() + ".jks"),
					Constants.getConstants().getStrHTTPSCERPWD().toCharArray());
			kmf.init(ks, Constants.getConstants().getStrHTTPSCERPWD().toCharArray());
			tmf.init(tks);
			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(),
					null);
			httpsMap.put(prjcodVal.getCPDPRJCOD().toUpperCase(), ctx);
		} 
		((HttpsURLConnection)httpUrlConnection).setSSLSocketFactory(ctx.getSocketFactory());
		((HttpsURLConnection) httpUrlConnection)
			.setHostnameVerifier(new HostnameVerifier() {
				//让JRE相信所有的证书和对系统的域名和证书域名
				public boolean verify(String urlHostName,
						SSLSession session) {
					return true;
				}
			});

 读取之前从静态属性map中读取一下,如果不存在,则获取,然后放入map中,这样也可以提高效率。

猜你喜欢

转载自smallbee.iteye.com/blog/1852100