Search code examples
javasslkeytoolpemjks

Import .key and .pem file to jks file and use in Java/Spring


I have been given the following key/cert from a service team to call their API over SSL, which I verfied thru curl command.

1. QA.test.key
2. QA.test.pem 

CURL command:

curl --key QA.test.key --cert ./QA.test.pem -X POST --header "Content-Type: application/json" --header "Accept: application/json" -d '{"pan":"1234567890123456", "client": " Application Name "}' https://test-qa.abc.com/tokenize

Now, to call the API in Java over https, do I need to do the following?

  1. Create a self signed jks file
  2. import the .key and .pem to new test.jks file?
  3. Do the following

    public class TestApp {
    
    final static String KEYSTORE_PASSWORD = "testing";
    
    static
    {
        System.setProperty("javax.net.ssl.trustStore", "src/main/resources/test.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", KEYSTORE_PASSWORD);
        System.setProperty("javax.net.ssl.keyStore",  "src/main/resources/test.jks");
        System.setProperty("javax.net.ssl.keyStorePassword", KEYSTORE_PASSWORD);
    }
    
    
    public static void main(String[] args) {
        SpringApplication.run(TestApp.class, args);
    }
    

    }

I am getting Invalid Certificate error while using the jks file, what would be the best way to create a jks file and import .key and .pem file for it to work properly?


Solution

  • Create a PKCS #12 file using OpenSSL utilities. Then you can specify this as your key store using the system properties.

    openssl pkcs12 -export -in QA.test.pem -inkey QA.test.key -out test.pkcs12
    

    This command will prompt for a password to encrypt the new PKCS #12 file. It may also prompt for the password that was used to encrypt QA.test.key, if any.

    javax.net.ssl.keyStore=test.pkcs12
    javax.net.ssl.keyStorePassword=<whatever you entered when creating PKCS #12>
    javax.net.ssl.keyStoreType=PKCS12
    

    The trustStore properties are separate; they affect how to authenticate the server. If the server uses a certificate issued by a "real" CA, the necessary certificates should be present in the Java runtime already. Otherwise, you'll have to create an additional key store, which can be done using Java's keytool command.

    Note that Java 9 will use PKCS #12 files as the default keystore type.