我使用以下代码创建服务器套接字并获取服务器公钥(服务器TLS版本为1.2)。
问题出在Android socket.startHandshake();

catch error : javax.net.ssl.SSLException: Connection closed by peer.

我搜索了很多内容,发现我不得不强制Android +,++)。
SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
SSLSocket socket = (SSLSocket) factory.createSocket(hostname, 443);
socket.setSoTimeout(10000);
socket.startHandshake();
Certificate[] certs = socket.getSession().getPeerCertificates();
Certificate cert = certs[0];
PublicKey serverKey = cert.getPublicKey();

CertificateFactory cf      = CertificateFactory.getInstance("X.509");
InputStream        caInput = context.getResources().getAssets().open("filename.cert");
Certificate        ca;
ca = cf.generateCertificate(caInput);

if (String.valueOf(serverKey).equals(String.valueOf(ca.getPublicKey()))) {
     My codes ...
}

我怎样才能做到这一点?谢谢。

最佳答案

您应该在Android KitKat及以下版本上强制使用TLSv1.2,如下所示:

if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
    socket.setEnabledProtocols(new String[]{"TLSv1.2"});
}

https://developer.android.com/reference/javax/net/ssl/SSLSocket.html

干杯!

09-06 02:06