Downloading a Server’s HTTPS Certificate with Groovy

If you ever need to access a web service with HTTPS as a client in Java or groovy, and the service uses a self-signed certificate, you might need to import the SSL certificate into your local keystore.

To import the certificate, first you need to get it from the remote web server. Here’s a convenient little groovy script that downloads the certificate as a X509Certificate.

import javax.net.ssl.*

if (args.size() != 2) {
    println "usage: getCert host port"
}
def (host, port) = args
def cert
def trustManager = [
    checkClientTrusted: { chain, authType ->  },
    checkServerTrusted: { chain, authType -> cert = chain[0] },
    getAcceptedIssuers: { null }
] as X509TrustManager

def context = SSLContext.getInstance("TLS")
context.init(null, [trustManager] as TrustManager[], null)
context.socketFactory.createSocket(host, port as int).with {
    startHandshake()
    close()
}
println "-----BEGIN CERTIFICATE-----"
println cert.encoded.encodeBase64(true)
println "-----END CERTIFICATE-----"

This program prints out the certificate in a format that can be fed to keytool like so:

# get the certificate from the remote server
groovy getCert testserver 443 > certificate.txt
# print out the certificate details in a readable format
keytool -printcert -file certificate.txt
# import the certificate into the local keystore
keytool -import -file certificate.txt -alias testserver -keystore $JAVA_HOME/jre/lib/security/cacerts
  1. Luis Oscar Trigueiros says:

    Hi,
    Thank you this is a very good post, just a few weeks ago a had to something like this for an SVN integration with Gradle, but I end up using the HTTP Commons client 3.0 with the EasyX509TrustManager redefinition because the script was to be run by several people and I did not wanted for then to do the extra import certificate step.
    Do you know how to import the cert with Commons HTTP client 4.0 ?

    Kind regards, Oscar

  1. There are no trackbacks for this post yet.