前言
在接口开发中,如果双方是通过https进行数据传输,有可能会用到SSL证书;那么证书在什么时候使用?下面我简单说说我最近的一次经历,希望共勉;
一.什么是证书?
关于SSL证书,大家可以百度下;如下图所示,是SSL证书常见的几种文件格式
二.构建DefaultHttpClient对象
下面的代码适用用Java语言,大家可以直接使用
/**
* 加载客户端证书和密钥
* @return
*/
@SuppressWarnings("deprecation")
public static DefaultHttpClient getHttpClientForCrt() throws Exception{
DefaultHttpClient client = null;
/**
* 路径存放在properties文件中
*/
String keyStore = PropertiesUtil.getPropValue("pfxPath").trim();// 证书的路径,pfx格式
String trustStore = PropertiesUtil.getPropValue("jksPath").trim();// 密钥库文件,jks格式
String keyPass = PropertiesUtil.getPropValue("keyStorePassword").trim();// pfx文件的密码
String trustPass = PropertiesUtil.getPropValue("keyStorePassword").trim();// jks文件的密码
logger.info("");
//TLS协议
SSLContext ctx = SSLContext.getInstance("TLS");
// ClassPathResource keySource = new ClassPathResource(keyStore);
// ClassPathResource trustSource = new ClassPathResource(trustStore);
File keySource = new File(keyStore);
File trustSource = new File(trustStore);
KeyStore ks = KeyStore.getInstance("pkcs12");
FileInputStream fiKeySource = new FileInputStream(keySource);
FileInputStream fitrustSource = new FileInputStream(trustSource);
//加载pfx文件
ks.load(fiKeySource, keyPass.toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
kmf.init(ks, keyPass.toCharArray());
KeyStore ts = KeyStore.getInstance("jks");
// 加载jks文件
ts.load(fitrustSource, trustPass.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
tmf.init(ts);
ctx.init(kmf.getKeyManagers(), new TrustManager[] { tm }, null);
SSLSocketFactory ssf = new SSLSocketFactory(ctx);
SchemeRegistry sr = new SchemeRegistry();
ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
sr.register(new Scheme("https", ssf, 443));
PoolingClientConnectionManager cm = new PoolingClientConnectionManager(sr);
cm.setMaxTotal(200);
cm.setDefaultMaxPerRoute(20);
BasicHttpParams params = new BasicHttpParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
client = new DefaultHttpClient(cm, params);
return client;
}