Skip to content

Commit 61bf8c1

Browse files
author
XYG6
committed
TLSv1.2 support with TLSv1 fallback
Tries to use TLSv1.2 first on the HTTPS connection. If not available, falls back to TLSv1.
1 parent d036300 commit 61bf8c1

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

library/src/main/java/com/loopj/android/http/MySSLSocketFactory.java

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,17 @@
5656
* certificate validation on every device, use with caution
5757
*/
5858
public class MySSLSocketFactory extends SSLSocketFactory {
59-
final SSLContext sslContext = SSLContext.getInstance("TLS");
59+
SSLContext sslContext;
60+
61+
try {
62+
sslContext = SSLContext.getInstance("TLSv1.2");
63+
} catch (NoSuchAlgorithmException e) {
64+
// TODO fallback v1.1 if needed
65+
Log_OC.w(TAG, "TLSv1.2 is not supported in this device; falling through TLSv1.0");
66+
sslContext = SSLContext.getInstance("TLSv1");
67+
// should be available in any device; see reference of supported protocols in
68+
// http://developer.android.com/reference/javax/net/ssl/SSLSocket.html
69+
}
6070

6171
/**
6272
* Creates a new SSL Socket Factory with the given KeyStore.
@@ -186,13 +196,33 @@ public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
186196

187197
@Override
188198
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
189-
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
199+
Socket socket = sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
200+
enableSecureProtocols(socket);
201+
return socket;
190202
}
191203

192204
@Override
193205
public Socket createSocket() throws IOException {
194-
return sslContext.getSocketFactory().createSocket();
206+
Socket socket = sslContext.getSocketFactory().createSocket();
207+
enableSecureProtocols(socket);
208+
return socket;
195209
}
210+
211+
/**
212+
* Activate supported protocols on the socket.
213+
*
214+
* @param socket The socket on which to activate secure protocols.
215+
*/
216+
private void enableSecureProtocols(Socket socket) {
217+
// get supported params
218+
SSLParameters params = sslContext.getSupportedSSLParameters();
219+
String [] supportedProtocols = params.getProtocols();
220+
221+
// activate supported protocols on the socket
222+
Socket socket = sslContext.getSocketFactory().createSocket();
223+
((SSLSocket) socket).setEnabledProtocols(supportedProtocols);
224+
//((SSLSocket) socket).setEnabledProtocols(new String[] {"TLSv1.2"} );
225+
}
196226

197227
/**
198228
* Makes HttpsURLConnection trusts a set of certificates specified by the KeyStore

0 commit comments

Comments
 (0)