使用 okHttp 信任所有证书

出于测试目的,我试图向 okHttp 客户机添加一个套接字工厂,它在设置代理时信任所有内容。这已经做了很多次,但是我的信任套接字工厂的实现似乎缺少了一些东西:

class TrustEveryoneManager implements X509TrustManager {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }


@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { }


@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
OkHttpClient client = new OkHttpClient();


final InetAddress ipAddress = InetAddress.getByName("XX.XXX.XXX.XXX"); // some IP
client.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ipAddress, 8888)));


SSLContext sslContext = SSLContext.getInstance("TLS");
TrustManager[] trustManagers = new TrustManager[]{new TrustEveryoneManager()};
sslContext.init(null, trustManagers, null);
client.setSslSocketFactory(sslContext.getSocketFactory);

没有请求被发送出我的应用程序,没有异常被记录,所以它似乎是默默地失败在 okHttp。经过进一步的调查,似乎在 okHttp 的 Connection.upgradeToTls()中,当强制握手时,会吞噬一个 Exception。我得到的例外是: javax.net.ssl.SSLException: SSL handshake terminated: ssl=0x74b522b0: SSL_ERROR_ZERO_RETURN occurred. You should never see this.

下面的代码生成一个 SSLContext,它在创建不抛出任何异常的 SSLSocketFactory 时起到了魔力般的作用:

protected SSLContext getTrustingSslContext() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
final SSLContextBuilder trustingSSLContextBuilder = SSLContexts.custom()
.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true; // Accepts any ssl cert whether valid or not.
}
});
return trustingSSLContextBuilder.build();
}

问题是,我正试图从我的应用程序中完全删除所有 Apache HttpClient 依赖项。使用 Apache HttpClient 生成 SSLContext的底层代码看起来非常简单,但是我显然遗漏了一些东西,因为我无法配置我的 SSLContext来匹配它。

有没有人能够生成一个 SSLContext 实现,在不使用 Apache HttpClient 的情况下做我想做的事情?

138859 次浏览

为了防止有人在这里摔倒,我唯一的解决方案是创建 OkHttpClient,就像解释的 给你一样。

密码如下:

private static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}


@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}


@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
}
};


// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();


OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager)trustAllCerts[0]);
builder.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});


OkHttpClient okHttpClient = builder.build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}

您永远不应该在代码中重写证书验证!如果需要进行测试,请使用内部/测试 CA,并在设备或模拟器上安装 CA 根证书。如果不知道如何设置 CA,可以使用 BurpSuite 或 Charles Proxy。

更新 OkHttp 3.0,getAcceptedIssuers()函数必须返回 空数组而不是 null

不推荐使用以下方法

sslSocketFactory(SSLSocketFactory sslSocketFactory)

考虑将其更新为

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

SSLSocketFactory 不公开其 X509TrustManager,OkHttp 需要这个字段来构建一个干净的证书链。相反,此方法必须使用反射来提取信任管理器。应用程序应该更喜欢调用 sslSocketFactory (SSLSocketFactory,X509TrustManager) ,这样可以避免这种反射。

资料来源: OkHttp 文档

OkHttpClient.Builder builder = new OkHttpClient.Builder();


builder.sslSocketFactory(sslContext.getSocketFactory(),
new X509TrustManager() {
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}


@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
}


@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[]{};
}
});

这是 sonxurxo 在 Kotlin 的解决方案,如果有人需要的话。

private fun getUnsafeOkHttpClient(): OkHttpClient {
// Create a trust manager that does not validate certificate chains
val trustAllCerts = arrayOf<TrustManager>(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}


override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) {
}


override fun getAcceptedIssuers() = arrayOf<X509Certificate>()
})


// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, java.security.SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory


return OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, trustAllCerts[0] as X509TrustManager)
.hostnameVerifier { _, _ -> true }.build()
}


如果有人需要,这就是 Scala 解决方案

def anUnsafeOkHttpClient(): OkHttpClient = {
val manager: TrustManager =
new X509TrustManager() {
override def checkClientTrusted(x509Certificates: Array[X509Certificate], s: String) = {}


override def checkServerTrusted(x509Certificates: Array[X509Certificate], s: String) = {}


override def getAcceptedIssuers = Seq.empty[X509Certificate].toArray
}
val trustAllCertificates =  Seq(manager).toArray


val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCertificates, new java.security.SecureRandom())
val sslSocketFactory = sslContext.getSocketFactory()
val okBuilder = new OkHttpClient.Builder()
okBuilder.sslSocketFactory(sslSocketFactory, trustAllCertificates(0).asInstanceOf[X509TrustManager])
okBuilder.hostnameVerifier(new NoopHostnameVerifier)
okBuilder.build()

}

我为 Kotlin 做了一个扩展函数,粘贴到任何你喜欢的地方,然后在创建 abc 0的时候导入它。

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
val naiveTrustManager = object : X509TrustManager {
override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
}


val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
init(null, trustAllCerts, SecureRandom())
}.socketFactory


sslSocketFactory(insecureSocketFactory, naiveTrustManager)
hostnameVerifier(HostnameVerifier { _, _ -> true })
return this
}

像这样使用它:

val okHttpClient = OkHttpClient.Builder().apply {
// ...
if (BuildConfig.DEBUG) //if it is a debug build ignore ssl errors
ignoreAllSSLErrors()
//...
}.build()