NemugaM
NemugaM

Reputation: 39

How to load SSL Certificate in Java

I am creating a Java program to get information from a server but I have to perform a ssl handshake with the server from the Java program.

I have myfilercert.cer file certificate for authentication purpose but I have no idea how I can load that certificate in java so that the java program can perform 'handshake' with the server where I want to get information from. Where to begin?

Upvotes: 1

Views: 17403

Answers (2)

EpicPandaForce
EpicPandaForce

Reputation: 81539

You can use Apache HttpClient (or just use the required classes from it to use SslContextBuilder, really), and then it'd be like so:

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
        sslContextBuilder.loadTrustMaterial(new File("yourTrustStore.jks"), "thePassWord");
        SSLContext sslContext = sslContextBuilder.build();
        HttpsURLConnection httpsURLConnection = (HttpsURLConnection) (new URL("https://thesite.com").openConnection());
        httpsURLConnection.setSSLSocketFactory(sslContext.getSocketFactory());

But you need to create a keystore for your certificate, which can be done with keytool. If you need this for android, you'll need SpongyCastle library, and use that as a provider for KeyTool to create a BKS keystore instead of a JKS keystore; and you will need to explicitly open the KeyStore in Java.

                KeyStore keyStore = KeyStore.getInstance("BKS",
                                                         BouncyCastleProvider.PROVIDER_NAME);
                byteArrayInputStream = new ByteArrayInputStream(keyStoreBytes);
                keyStore.load(byteArrayInputStream, keyStorePassword);
                Certificate[] certificates = keyStore.getCertificateChain("theCertAlias");
                Certificate certificate = certificates[0];

Upvotes: 1

Laurentiu L.
Laurentiu L.

Reputation: 6686

What you need is the java keystore. The keystore is a repository of security certificates used in SSL encryption. You can read here about the Server Authentication During SSL Handshake. This is a keystore tutorial.

As an alternative to keytool, i would suggest a tool with a Graphical User Interface called Portecle. You can use it to browse the contents of your .cer file and see what's in it.

It can be useful to know about the various certificate encodings. Also read about the X.509 standard.

This is an article on java keytool essentials (which is the oracle tool that works with the java keystore).

You can google and find a lot of resources that instruct you how to generate. I think you will want to keep the certificate at the application level.

Some SO questions that helped me along the way:

Good luck!

Upvotes: 3

Related Questions