调用SSLSocket#getInputStream时获取SSLHandshakeException(握手失败)

时间:2017-08-25 13:59:09

标签: android serversocket sslsocketfactory

我正在测试运行为SSLSocket的服务器的IntentService连接我在Android应用上运行。为此,我使用PacketSender发送带有数据的SSL数据包,在使用Socket而不是SSLSocket时它正在工作。

当从PacketSender接收数据时,应用程序设法接受连接,但在尝试呼叫getInputStream时抛出异常(见下文):

Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb967c838: Failure in SSL library, usually a protocol error
error:100b60c1:SSL routines:ssl3_get_client_hello:NO_SHARED_CIPHER (external/boringssl/src/ssl/s3_srvr.c:1085 0xac4e759f:0x00000000)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
... 7 more

我按照此answer尝试从普通Socket切换到SSLSocket

编辑:尝试为服务器应用实施自签名证书,但错误仍然存​​在。

private SSLContext createSSLContext(){
    try{
        byte[] der = SERVER_CERT.getBytes();
        ByteArrayInputStream derInputStream = new ByteArrayInputStream(der);
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
        String alias = cert.getSubjectX500Principal().getName();

        // Create keystore and add to ssl context
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null);
        trustStore.setCertificateEntry(alias, cert);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(trustStore, null);
        KeyManager[] keyManagers = kmf.getKeyManagers();

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(trustStore);
        TrustManager[] trustManagers = tmf.getTrustManagers();

        SSLContext sslContext = SSLContext.getInstance("TLSv1.1");
        sslContext.init(keyManagers, trustManagers, null);

        return sslContext;
    } catch (Exception ex){
        ex.printStackTrace();
    }

    return null;
}

0 个答案:

没有答案