我成功地遵循了该教程。
您需要创建一个密钥库文件(例如“cert_keystore.pkcs12”)来包含您的服务器证书并将其添加到您的应用程序中。
我发现它最容易使用密钥库文件的PKCS12格式。 (在使用keytool
转换密钥库时添加-deststoretype PKCS12
参数)
我的测试服务器在IP地址上,我必须禁用主机名验证才能使用我的自签名证书。这other tutorial是有用的。
我不得不将HttpsURLConnection.setDefaultHostnameVerifier()
添加到newSslSocketFactory()的自定义HostnameVerifier和HttpsURLConnection.setDefaultSSLSocketFactory()
。
(newSslSocketFactory()中Volley.newRequestQueue(mCtx.getApplicationContext(), new HurlStack(null, newSslSocketFactory())
使用)
新newSslSocketFactory()现在函数为:
private SSLSocketFactory newSslSocketFactory()
{
try
{
KeyStore trusted = KeyStore.getInstance ("PKCS12");
// Get the raw resource, which contains the keystore with
// your trusted certificates (root and any intermediate certs)
InputStream in = mCtx.getApplicationContext().getAssets().open ("cert_keystore.pkcs12");
try {
// Initialize the keystore with the provided trusted certificates
// Provide the password of the keystore
trusted.load (in, "password".toCharArray());
} finally {
in.close();
}
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(trusted);
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify (String hostname, SSLSession session) {
return hostname.equals ("192.168.1.10"); //The Hostname of your server
}
};
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sf = context.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory (sf);
return sf;
}
catch (Exception e)
{
throw new AssertionError(e);
}
}