我正在尝试覆盖 Android 中的信任管理器。我想让底层信任管理器检查证书,但我需要确定证书是否过期。如果证书过期,我需要忽略它并接受证书。如果取出电池,某些移动设备会将日期重置为旧日期,从而导致证书看起来好像过期了。即使发生这种情况,我的应用程序也必须继续运行。
我遇到的问题是这行代码抛出了 NullPointerException:
origTrustmanager.checkServerTrusted(certs, authType);
根据文档,checkServerTrusted 永远不应该抛出 NullPointerExeption。certs 里面有两个项目。authType 设置为“RSA”。如果我不实现自定义信任管理器,则会引发异常,清楚地表明证书已过期,因此我知道底层信任管理器正在执行其工作。即使我将设备上的日期和时间设置在证书的有效期内,上面的 checkServerTrusted 行也会产生异常。为什么?显然我做错了什么。这是我的自定义信任管理器的代码以及我如何访问 URL:
class SSLTrustManager
{
private X509TrustManager origTrustmanager;
public SSLTrustManager()
{
try
{
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init((KeyStore) null);
TrustManager[] trustManagers = tmf.getTrustManagers();
this.origTrustmanager = (X509TrustManager) trustManagers[0];
}
catch (Exception ex)
{
}
}
public javax.net.ssl.SSLSocketFactory GetSocketFactory()
{
try
{
TrustManager[] wrappedTrustManagers = new TrustManager[] {
new X509TrustManager()
{
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return origTrustmanager.getAcceptedIssuers();
}
public void checkClientTrusted(X509Certificate[] certs, String authType)
{
try
{
origTrustmanager.checkClientTrusted(certs, authType);
}
catch (CertificateException e)
{
}
}
public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException
{
try
{
origTrustmanager.checkServerTrusted(certs, authType);
}
catch(Exception ex)
{
}
}
}
};
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, wrappedTrustManagers, new java.security.SecureRandom());
javax.net.ssl.SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return sslSocketFactory;
}
catch (Exception ex)
{
return null;
}
}
}
访问url的代码:
SSLTrustManager sslTrustManager = new SSLTrustManager();
HttpsURLConnection.setDefaultSSLSocketFactory(sslTrustManager.GetSocketFactory());
URL siteUrl = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) siteUrl.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());