How to properly import a selfsigned certificate into Java keystore that is available to all Java applications by default?

certificate, java, keystore, keytool, ssl-certificate

Solution

On Windows the easiest way is to use the program portecle.

- Download and install portecle.

- First make 100% sure you know which JRE or JDK is being used to run your program. On a 64 bit Windows 7 there could be quite a few JREs. Process Explorer can help you with this or you can use: `System.out.println(System.getProperty("java.home"));`

- Copy the file JAVA_HOME\lib\security\cacerts to another folder.

- In Portecle click File > Open Keystore File

- Select the cacerts file

- Enter this password: changeit

- Click Tools > Import Trusted Certificate

- Browse for the file mycertificate.pem

- Click Import

- Click OK for the warning about the trust path.

- Click OK when it displays the details about the certificate.

- Click Yes to accept the certificate as trusted.

- When it asks for an alias click OK and click OK again when it says it has imported the certificate.

- Click save. Don’t forget this or the change is discarded.

- Copy the file cacerts back where you found it.

On Linux:

You can download the SSL certificate from a web server that is already using it like this:

$ echo -n | openssl s_client -connect www.example.com:443 | \
   sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > /tmp/examplecert.crt

Optionally verify the certificate information:

$ openssl x509 -in /tmp/examplecert.crt -text

Import the certificate into the Java cacerts keystore:

$ keytool -import -trustcacerts -keystore /opt/java/jre/lib/security/cacerts \
   -storepass changeit -noprompt -alias mycert -file /tmp/examplecert.crt

Problem

I do want to import a self signed certificate into Java so any Java application that will try to establish a SSL connection will trust this certificate. So far, I managed to import it in ``` keytool -import -trustcacerts -noprompt -storepass changeit -alias $REMHOST -file $REMHOST.pem keytool -import -trustcacerts -noprompt -keystore cacerts -storepass changeit -alias $REMHOST -file $REMHOST.pem ``` Still, when I try to run `HTTPSClient.class` I still get: ``` javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target ```

Original source

Related problems