Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use PEM file to create a SSL socket in Java?

See related question.

I have a PEM file provided to me and was told that it will be needed in establishing a SSL socket that connects to a c++ server for some API calls. Does anyone know how I can read in the PEM file and connect? I was also given the parapharse password.

like image 319
erotsppa Avatar asked Apr 06 '09 21:04

erotsppa


People also ask

What is the use of PEM file in SSL?

PEM files are used to store SSL certificates and their associated private keys. Multiple certificates are in the full SSL chain, and they work in this order: The end-user certificate, which is assigned to your domain name by a certificate authority (CA). This is the file you use in nginx and Apache to encrypt HTTPS.


1 Answers

It sounds like the PEM file is a client cert for you to use to login to the server. If it is the client cert, and it sounds like it is, you will likely need a ca cert file also to use in validating the servers certificate in order to establish a connection.

The CA certs need to go into a truststore and your client certs need to go into a keystore. In Java, both of these will be JKS (although it has limited support for PKCS12.) There are default keystore/truststore locations for the JRE as well as for each user. You can also specify external locations for these files in your code, as in the examples below. The commons-ssl library seems to be able to support PEM directly, without the need for JKS, but I haven't used it.

The default passphrase for these keystores in Java is "changeit" without the quotes.

This page shows you have to read the PEM into your keystore/truststore. Here is another example.

Once you have your truststore and keystore set up properly, you need to pass the following JSSE system properties to your JVM:

javax.net.ssl.keyStore
javax.net.ssl.keyStoreType
javax.net.ssl.keyStorePassword
javax.net.ssl.trustStore
javax.net.ssl.trustStoreType
javax.net.ssl.trustStorePassword

You may specify them as -D parameters to the JRE or, as in the examples below, programatically.

Once you finish that, heres a commons-ssl example of creating a socket. Also, heres the Java api for SSLSocket. Heres also an example that doesn't use any apache commons.

like image 169
John Ellinwood Avatar answered Oct 08 '22 18:10

John Ellinwood