如何在Groovy中使用SSL和自签名证书? [英] How to use SSL with a self-signed certificate in groovy?

查看:344
本文介绍了如何在Groovy中使用SSL和自签名证书?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些资源必须通过使用自签名证书的SSL访问。一般来说,大多数工具都有一个简单的设置,允许访问这些工具时不会出现错误或只是一个警告。然而,看起来像使用JVM这样做的正确方法是将签名证书作为CA导入密钥库。



我有一个常规脚本喜欢使用,但我更喜欢我的脚本独立工作在任何JVM上,无需修改密钥库或分发新的密钥库。有没有一种简单的方法来覆盖认证验证?

解决方案

经过一番研究,我发现这篇文章。这是我最终使用的:

$ p $ 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
$ b $ 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(作为HostnameVerifier的nullHostnameVerifier)



使用后果自负:破坏证书验证!


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!

这篇关于如何在Groovy中使用SSL和自签名证书?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆