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

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

本文介绍了使用java从本地存储中获取SSL证书到sslContext对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to perform a rest call by attaching the local ssl certificate.

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

I do not have any info about KeyStore. I just know there is a Certificate installed in my PC and I have to use the certificate based on details of certificate like "Serial number", "Issuer" etc which i can see in the certificate details in the personal certificate store.

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

I need to create SSLConnectionSocketFactory object which can be attached to rest call.

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

My question is how to create the SSLContext object?

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

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


推荐答案

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

You can create the SSLContext instance using this code snippet.

// 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);

这篇关于使用java从本地存储中获取SSL证书到sslContext对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 05:58