1

I use below code to create a socket to server and get server public key (Server TLS version is 1.2).
The problem is in Android < 5.0 at socket.startHandshake();

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

I searched many and find I have to force Android < 5 to use TLSv1.2, but I can't do this (+, +, +).

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 ...
}

How can I do this? Thanks.

user1506104
  • 6,554
  • 4
  • 71
  • 89
Hajitsu
  • 764
  • 17
  • 49

2 Answers2

1

You should force TLSv1.2 on Android KitKat and below like so:

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

Cheers!

user1506104
  • 6,554
  • 4
  • 71
  • 89
  • I do this but this error happened: `javax.net.ssl.SSLException: Connection closed by peer 12-22 11:54:26.970 3741-3762/ir.refahotp.refahotp W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method) 12-22 11:54:26.970 3741-3762/ir.refahotp.refahotp W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:405)` – Hajitsu Dec 22 '19 at 08:25
  • Which android version are you running it on? Take note that v1.2 is supported on Android 4.1+ (JellyBean) only. – user1506104 Dec 22 '19 at 08:44
  • Everything on server is ok – Hajitsu Dec 22 '19 at 11:41
  • I use Android 4.4 – Hajitsu Dec 22 '19 at 11:42
  • Can you confirm that the issue is not caused by any of the following: 1. The CA that issued the server certificate was unknown 2. The server certificate wasn't signed by a CA, but was self signed 3. The server configuration is missing an intermediate CA – user1506104 Dec 22 '19 at 12:18
0

Finally, I have to downgrade server SSL to TLSv1 and problem fixed.

Hajitsu
  • 764
  • 17
  • 49