【问题标题】:Getting SSLPeerUnverifiedException in Android在 Android 中获取 SSLPeerUnverifiedException
【发布时间】:2013-06-01 22:07:33
【问题描述】:

当我尝试使用 HTTPS 连接进行连接时,我收到 SSL Peer Unverified Exception。 我是 HTTPS 的新手。 我的代码是:

HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

DefaultHttpClient client = new DefaultHttpClient();
SchemeRegistry registry = new SchemeRegistry();
SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
socketFactory.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
registry.register(new Scheme("https", socketFactory, 443));
SingleClientConnManager mgr = new SingleClientConnManager(client.getParams(), registry);
DefaultHttpClient httpClient = new DefaultHttpClient(mgr, client.getParams());                  HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
HttpPost httppost = new HttpPost("https://server.example.com/Login");
List<BasicNameValuePair> nameValuePairs = new ArrayList<BasicNameValuePair>(
                            2);
                    nameValuePairs.add(new BasicNameValuePair("LoginId",uname));
                    nameValuePairs.add(new BasicNameValuePair("Password",pass));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {

}               
Log.i("zacharia", "Response :"+EntityUtils.toString(response.getEntity()));
} catch (Exception e) {
}

【问题讨论】:

    标签: android ssl https http-post


    【解决方案1】:

    可能会抛出 SSL Peer Unverified Exception 有几个原因,最常见的是当服务器发送的证书是自签名证书而不是授权 CA 签名的证书时,如果这是问题,则 android 中的常见方法是将证书添加到受信任的证书链中,然后按如下方式发出请求:

    KeyStore selfsignedKeys = KeyStore.getInstance("BKS");
    selfsignedKeys.load(context.getResources().openRawResource(R.raw.selfsignedcertsbks),
    "genericPassword".toCharArray());
    TrustManagerFactory trustMgr = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustMgr.init(selfsignedKeys);
    SSLContext selfsignedSSLcontext = SSLContext.getInstance("TLS");
    selfsignedSSLcontext.init(null, trustMgr.getTrustManagers(), new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(selfsignedSSLcontext.getSocketFactory());
    URL serverURL = new URL("https://server.example.com/endpointTest");
    HttpsURLConnection serverConn = (HttpsURLConnection)serverURL.openConnection();
    

    请注意,这种方法仅在您确定证书未由 CA 签名的情况下,并且为了使其正常工作,您需要拥有自己的证书,将其放入 BKS 密钥库中(供 android 读取它)然后使用“接受”该自签名证书的 SSL 上下文打开一个 HttpURLConnection,因为 DefaultHttpClient 不会根据默认 SSLContext 处理这些请求。

    如果您想了解有关 SSL 的更多信息,我建议您阅读 Jeff Six 社论 O'Reilly 所著的《Android 平台的应用程序安全性》一书...

    问候!

    【讨论】:

      猜你喜欢
      • 2016-10-15
      • 2018-08-26
      • 2017-09-18
      • 2016-04-12
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      相关资源
      最近更新 更多