简体   繁体   English

如何在groovy中使用SSL与自签名证书?

[英]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. 我有一些资源,我必须使用SSL来访问使用自签名证书。 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. 但是,使用JVM执行此操作的正确方法似乎是将签名证书作为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. 我有一个我想要使用的groovy脚本,但我更喜欢我的脚本在任何任何JVM上独立工作而无需修改密钥库或分发新的密钥库。 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. 我只需要使用我正在处理的grails应用程序。 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... 假设你有证书,只需将它放入你的密钥库,然后通过命令行道具将你的jvm指向密钥库......

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和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

如果您调用命令行程序curl而不是使用本机groovy / JVM工具,则可以通过从命令行运行以下命令来禁用用户的证书检查:

$ echo 'insecure' >>~/.curlrc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM