ataylor
ataylor

Reputation: 66109

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?

Upvotes: 13

Views: 27039

Answers (2)

ataylor
ataylor

Reputation: 66109

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

import javax.net.ssl.HostnameVerifier
import javax.net.ssl.HttpsURLConnection
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManager
import javax.net.ssl.X509TrustManager

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.setDefaultSSLSocketFactory(sc.getSocketFactory())
HttpsURLConnection.setDefaultHostnameVerifier(nullHostnameVerifier as HostnameVerifier)

Use at your own risk: this subverts certificate verification!

Upvotes: 24

hvgotcodes
hvgotcodes

Reputation: 120308

i just had to go thru this with a grails app i am working on. You will only deal with the keystore once. Assuming you have the cert, just put it into your keystore, then point your jvm at the keystore via command line props...

edit - i dont know of any way to bypass the need for the keystore. But you can create one with just the cert(s) you need and pass it around with your app. You only do it once.

edit edit -- here is the command for the keytool and the java CL prop

keytool -import -trustcacerts -alias www.the-domain.com -file the-cert.der -keystore store.jks

-Djavax.net.ssl.trustStore=/path/to/store.jks

Upvotes: 10

Related Questions