ataylor ataylor - 1 year ago 304
Groovy Question

How to use SSL with a self-signed certificate in groovy?

I have some resources I must access with SSL that use self-signed certificates. In general, most tools have a simple setting to allow these to be accessed without error or just a warning. However, it seems like the proper way to do this with the JVM is to import the signing certificate into a keystore as a CA.

I have a groovy script I'd like to use, but I'd prefer my script to work standalone on any any JVM without modifying the keystore or distributing a new keystore. Is there a simple way to override the certification verification?

Answer Source

After a bit of research, I found this post. Here's what I ended up using:


def nullTrustManager = [
    checkClientTrusted: { chain, authType ->  },
    checkServerTrusted: { chain, authType ->  },
    getAcceptedIssuers: { null }

def nullHostnameVerifier = [
    verify: { hostname, session -> true }

SSLContext sc = SSLContext.getInstance("SSL")
sc.init(null, [nullTrustManager as X509TrustManager] as TrustManager[], null)
HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as HostnameVerifier)

Use at your own risk: this subverts certificate verification!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download