使用java从本地存储中获取SSL证书到sslContext对象

时间:2016-11-29 20:33:20

标签: java authentication ssl ssl-certificate keystore

我需要通过附加本地ssl证书来执行休息呼叫。

我没有关于KeyStore的任何信息。我只知道我的电脑上安装了证书,我必须根据证书的详细信息使用证书,如“序列号”,“发行人”等,我可以在个人证书商店的证书详细信息中看到。

我需要创建SSLConnectionSocketFactory对象,该对象可以附加到休息调用。

我的问题是如何创建SSLContext对象?

  SSLContext sslContext;// How to create this object and pass it to sslSocketFactory.

  HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; 
  SSLConnectionSocketFactory sslSocketFactory = new  SSLConnectionSocketFactory(sslContext, hostnameVerifier); 

1 个答案:

答案 0 :(得分:1)

您可以使用此代码段创建SSLContext实例。

// Load Certificate
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
Certificate certificate = certificateFactory.generateCertificate(new FileInputStream(new File("CERTIFICATE_LOCATION")));

// Create TrustStore
KeyStore trustStoreContainingTheCertificate = KeyStore.getInstance("JKS");
trustStoreContainingTheCertificate.load(null, null);

trustStoreContainingTheCertificate.setCertificateEntry("ANY_CERTIFICATE_ALIAS", certificate);

// Create SSLContext
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStoreContainingTheCertificate);

SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);

SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
System.out.println(sslSocketFactory);