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

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

问题描述

我必须通过 SSL 访问一些使用自签名证书的资源.一般来说,大多数工具都有一个简单的设置,允许访问这些工具而不会出错或只是警告.但是,使用 JVM 执行此操作的正确方法似乎是将签名证书作为 CA 导入密钥库.

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.

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

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天全站免登陆