Hajitsu
Hajitsu

Reputation: 784

Socket Handshake in Android < 5.0 (Lollipop) with TLSv1.2 problem

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.

Upvotes: 1

Views: 677

Answers (2)

Hajitsu
Hajitsu

Reputation: 784

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

Upvotes: 0

user1506104
user1506104

Reputation: 7106

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!

Upvotes: 1

Related Questions