Fetch SSL certificate from local store using java

2019-04-16 01:28发布

问题:

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

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.

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

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

回答1:

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