java https证书(双向证书)

 

如果是单向证书只需要:sc.init(null, tmf.getTrustManagers(), null);即可

public void initSSLConfigForTwoWay() throws Exception {
   // 1 导入自己的证书

   KeyStore selfCert = KeyStore.getInstance("pkcs12");
   selfCert.load(this.getClass().getResourceAsStream(Constant.SELFCERTPATH),Constant.SELFCERTPWD.toCharArray());
   //selfCert.load(new FileInputStream(ResourceUtils.getURL("classpath:").getPath() + Constant.SELFCERTPATH),
   //    Constant.SELFCERTPWD.toCharArray());
   KeyManagerFactory kmf = KeyManagerFactory.getInstance("sunx509");
   kmf.init(selfCert, Constant.SELFCERTPWD.toCharArray());

   // 2 导入服务器的证书,
   KeyStore caCert = KeyStore.getInstance("jks");
   caCert.load(this.getClass().getResourceAsStream(Constant.TRUSTCAPATH),Constant.TRUSTCAPWD.toCharArray());
   //caCert.load(new FileInputStream(ResourceUtils.getURL("classpath:").getPath() + Constant.TRUSTCAPATH), Constant.TRUSTCAPWD.toCharArray());

   TrustManagerFactory tmf = TrustManagerFactory.getInstance("sunx509");
   tmf.init(caCert);

   SSLContext sc = SSLContext.getInstance("TLS");
   sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

   // 3 域名设置为不验证
   SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
         sc, new DefaultHostnameVerifier());

   httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
         .build();
}

你可能感兴趣的:(java,https)