在我的应用程序中,我需要处理 SSLSocket。我有这个在 Android6.0 及更高版本上运行的代码,当我在 Android 5.+ 上运行相同的代码时,我得到了 HandshakeException
private void openSSLSocket(String mHost, int mPort){
try {
SocketFactory sf = SSLSocketFactory.getDefault();
mSocket = (SSLSocket) sf.createSocket(mHost, mPort);
mSocket.setEnabledProtocols(new String[]{"TLSv1"});
mInputStream = mSocket.getInputStream();
mOutputStream = mSocket.getOutputStream();
mSocket.setSoTimeout(0);
}catch (Exception e){
e.printStackTrace();
}
}
我在 android 开发者网站上阅读了这篇文章并实现了下面的代码我得到了服务器管理员的 .crt 文件
private void openSSLSocketWithCA(String mHost, int mPort) {
try{
// Load CAs from an InputStream
// (could be from a resource or ByteArrayInputStream or ...)
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// From https://www.washington.edu/itconnect/security/ca/load-der.crt
InputStream caInput = am.open("star_******_chained.crt");
Certificate ca;
try {
ca = cf.generateCertificate(caInput);
System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
caInput.close();
}
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
mSocket = (SSLSocket) sf.createSocket(mHost, mPort);
mSocket.setEnabledProtocols(new String[]{"TLSv1"});
mInputStream = mSocket.getInputStream();
mOutputStream = mSocket.getOutputStream();
mSocket.setSoTimeout(0);
}catch (Exception e){
e.printStackTrace();
}
}
即使这样,我在调用 mSocket.getInputStream(); 时也会收到 HandshakeException;方法
这是日志
W/System.err: javax.net.ssl.SSLHandshakeException: Handshake failed
W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:374)
W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.waitForHandshake(OpenSSLSocketImpl.java:598)
W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.getInputStream(OpenSSLSocketImpl.java:560)
W/System.err: at *******.***.*******.common.CometSocketApi.openSSLSocketWithCA(CometSocketApi.java:464)