Friday, January 20, 2012

Feeling Groovy II - https

In my former post I wrote about making direct get and post request to a webserver. Now I had to add some support for https protocol. Of course changing the URL was not enough as the SSL communication needs to know if the server certificate can be trusted or not. Well it was fun to google around for the details, but I do not really want to do it again.
So here are the steps:

1. Get the certificate!
2. Create a keystore!
keytool -import -file cert.cer -alias server -keystore server.jks
3. Modifiy the connection to use keystore and ignore some errors!
def decorateConnection(url, connection) {
    if (url.startsWith('https:')) {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.defaultType)
        keyStore.load(getClass().getResourceAsStream('server.jks'), 'xxx'.toCharArray())
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.defaultAlgorithm)
        tmf.init(keyStore)
        SSLContext ctx = SSLContext.getInstance("TLS")
        ctx.init(null, tmf.trustManagers, null)
        connection.SSLSocketFactory = ctx.socketFactory
        connection.hostnameVerifier = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true
            }
        }
    }
}
When you create the keystore a password must be specified, that is that 'xxx' in the row 4.
Special thanks to people on stackoverflow.com and coderanch.com!

No comments:

Post a Comment