开发者

Receive & Validate certificate from server HTTPS - android

I am calling web service from my android client via https. I got to validate the certificate receive from server side. How do I do that ? At present this is my code that I use to call a web service.

private static String SendPost(String url, ArrayList<NameValuePair> pairs) {   // url = "https://....."   
    errorMessage = "";   
    String response = "";   

    DefaultHttpClient hc=new DefaultHttpClient();      
    ResponseHandler <String> res=new BasicResponseHandler();      
    HttpPost postMethod=new HttpPost(url);   

    try {   
postMethod.setEntity(new UrlEncodedFormEntity(pairs));   
        response = hc.execute(postMethod, res);   
    } catch (UnsupportedEncodingException e) {   
        e.printStackTrace();   
    } catch (ClientProtocol开发者_开发百科Exception e) {   
        e.printStackTrace();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }        

    return response;   
}  

How do I validate a self-signed certificate received from server during performing Post ? I got to do testing via public/private keys. Client will have a CA file. Ijust need the client to verify the server certificate using the CA, the service is public .This has to do with public/private key. How can I receive the certificate from the server before calling the post ?

Their are several options and code snippets available on stackoverflow. Couple of links I found with multiple answers is : Accepting a certificate for HTTPs on Android HTTPS GET (SSL) with Android and self-signed server certificate

But I can't make out which is good/applicable for me ! I don't want to disable all or accept any. Have to check the public/private keys/

Any help is highly appreciated.


Bob Lee wrote a nice blog post on how using SSL certificates with Android. I think it is applicable to your case: http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html

You just have to create a KeyStore containing your self-signed certificate and use the custom HttpClient implementation described in that post.


UPDATE:

Host name validation can be customizez by setting a custom X509HostnameVerifier on the SSLSocketFactory. Some implementations are already available in android: AllowAllHostnameVerifier, BrowserCompatHostnameVerifier, StrictHostnameVerifier

/* ... */
public class MyHostnameVerifier extends AbstractVerifier {
  boolean verify(String hostname, SSLSession session) {
    X509Certificate[] chain = session.getPeerCertificateChain();
    /* made some checks... */
    return checked;
  }
}
sslSocketFactory.setHostnameVerifier(new MyHostnameVerifier());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜