Posts Tagged ‘certificate’

Downloading a Server’s HTTPS Certificate with Groovy

Posted in Code on August 2nd, 2012 by ataylor284 – 1 Comment

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