开发者

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

开发者 https://www.devze.com 2023-01-07 05:56 出处:网络
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 se

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?


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!


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
0

精彩评论

暂无评论...
验证码 换一张
取 消