根据 Android 中针对 SSLSocket
和 SSLContext
的文档,API 级别16 + 支持 TLS v1.1和 v1.2协议,但默认情况下不启用。
Http://developer.android.com/reference/javax/net/ssl/sslsocket.html
Http://developer.android.com/reference/javax/net/ssl/sslcontext.html
如何在运行 Android 4.1或更高版本(但低于5.0)的设备上启用它?
我曾经尝试创建一个自定义 SSLSocketFactory,它在创建 Socket
时启用所有受支持的协议,然后使用我的自定义实现:
SetDefaultSSLSocketFactory (新的 MySSLSocketFactory ()) ;
public class MySSLSocketFactory extends SSLSocketFactory {
private SSLContext sc;
private SSLSocketFactory ssf;
public MySSLSocketFactory() {
try {
sc = SSLContext.getInstance("TLS");
sc.init(null, null, null);
ssf = sc.getSocketFactory();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
}
@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose)
throws IOException {
SSLSocket ss = (SSLSocket) ssf.createSocket(s, host, port, autoClose);
ss.setEnabledProtocols(ss.getSupportedProtocols());
ss.setEnabledCipherSuites(ss.getSupportedCipherSuites());
return ss;
}
@Override
public String[] getDefaultCipherSuites() {
return ssf.getDefaultCipherSuites();
}
@Override
public String[] getSupportedCipherSuites() {
return ssf.getSupportedCipherSuites();
}
@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
SSLSocket ss = (SSLSocket) ssf.createSocket(host, port);
ss.setEnabledProtocols(ss.getSupportedProtocols());
ss.setEnabledCipherSuites(ss.getSupportedCipherSuites());
return ss;
}
@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
SSLSocket ss = (SSLSocket) ssf.createSocket(host, port);
ss.setEnabledProtocols(ss.getSupportedProtocols());
ss.setEnabledCipherSuites(ss.getSupportedCipherSuites());
return ss;
}
@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort)
throws IOException, UnknownHostException {
SSLSocket ss = (SSLSocket) ssf.createSocket(host, port, localHost, localPort);
ss.setEnabledProtocols(ss.getSupportedProtocols());
ss.setEnabledCipherSuites(ss.getSupportedCipherSuites());
return ss;
}
@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress,
int localPort) throws IOException {
SSLSocket ss = (SSLSocket) ssf.createSocket(address, port, localAddress, localPort);
ss.setEnabledProtocols(ss.getSupportedProtocols());
ss.setEnabledCipherSuites(ss.getSupportedCipherSuites());
return ss;
}
}
但是,在尝试与启用了 只有 TLS 1.2的服务器建立连接时,它仍然会出现异常。
这是我得到的一个例外:
03-0909:21:38.427: W/System.err (2496) : 例外: 异常: SSL 握手中止: SSL = 0xb7fa0620: SSL 库中的失败,通常是协议错误
03-0909:21:38.427: W/System.err (2496) : error: 14077410: SSL 例程: SSL23 _ GET _ SERVER _ HELLO: sslv3警告握手失败 (foreign/openssl/ssl/s23 _ clnt. c: 7410xa90e6990:0x0000000)