Click here to Skip to main content
15,358,946 members
Articles / Security / Cryptography
Posted 25 Apr 2011


24 bookmarked

SSL Verification for Android Applications

Rate me:
Please Sign up or sign in to vote.
4.25/5 (6 votes)
25 Apr 2011CPOL3 min read
Perform SSL Verification while using Web Services


When we try to access a Web Service hosted on HTTPS and is secured over SSL, Host Verification and/or Peer Verification are to be handled in our application.


Android supports the and org.apache packages to access Web Services. I use Apache packages as I find them more useful and easier than using Java packages.

System Requirements

To Start

Host and Peer Verification are shown here. Each Android application has its own trusted store called KeyStore. In the KeyStore, we can store our self-signed SSL certificates that will be used for the verification purposes of our Web Service. Android trusts a couple of Trust Certificates, but if our signed certificate is not signed among those, then we need to add our certificate to the trusted store of the application.

Assuming you already have a self-signed certificate (if not, kindly use the key tool of Java to create one), let's add the certificate to a keystore using Bouncy Castle that we can access in our application. Like keytool is used in Java to create certificates, Bouncy Castle is the only way to add certificates to the Android keystore.

1. Creating the KeyStore

Download and unzip Bouncy Castle in a proper location and add the .jar file to the class path. Open cmd, go to the application folder, and type the following command:

keytool -import -v -trustcacerts -alias 0 -file mycertificate.crt 
  -keystore res/raw/mystore.bks -storetype BKS -provider 
  org.bouncycastle.jce.provider.BouncyCastleProvider -storepass mypassword
  • file parameter points to your certificate file that you want to add
  • keystore => gives the store name that you want to give
  • storepass => password to access the keystore

On successful execution of the command, the mystore.bks file will be generated successfully.

2. Create a Class to Use Our Store for HTTPS Connections

To use the store that we created above, we have to create a custom Apache DefaultHttpClient that knows to use the store for HTTPS requests.

public class MyHttpClient extends DefaultHttpClient {

    final Context context;
    public MyHttpClient(Context context) {
        this.context = context;

    protected ClientConnectionManager createClientConnectionManager {
        SchemeRegistry registry = new SchemeRegistry();
        registry.register("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register("https", newSslSocketFactory(), 443));
        return new SingleClientConnManager(getParams(), registry);

    private SSLSocketFactory newSslSocketFactory() {
        try {
             KeyStore trusted = KeyStore.getInstance("BKS");
             InputStream in = context.getResources().openRawResource(R.raw.mystore);
             try {
                 trusted.load(in, "mypassword".toCharArray());
             finally {

             SSLSocketFactory mySslFact = new SslFactory(trusted);
             //mySslFact.setHostNameVerifier(new MyHstNameVerifier());
             return mySslFact;
         } catch(Exception e) {
         throw new AssertionError(e);

This code helps us to accept a server certificate and sets the certificate for verification. You can see how we are using our -storename parameter "BKS" to get the instance of the KeyStore, loading the certificate file mystore from R.raw, and setting its password that was used while adding it to the store.

3. Copy mystore File

Import the generated mystore.bks file to the res/raw folder. So our above class can access it from there.

With this, SSL Peer Verification is taken care of. We just have to create an instance of MyHttpClient in place of DefaultHttpClient and Peer Verification will be handled by itself.

4. Process for Host Verification

Android supports only the host/domain via which the web service is being called - if any other host is tried to connect it throws exception. For example, if our application connects to a host, and then tries to connect another host for any reason, Android won't allow to do that. For this to be allowed, we got to set the hostnames that we want to allow the application to access.

public class MyHostVerifier extends org.apache.http.conn.ssl.AbstractVerifier {

    String[] allowHost = {"", "", ""}; 


    public void verify(String host, String[] cns, 
	String[] subjectAlts) throws SSLException {
        // If the host is any the hosts to be allowed, return, else throw exception 
        for (int i=0; i < allowHost.length; i++) {
             if (host == allowHost[i])
         throw SSLException;

Uncomment setHostVerifier in the MyHttpClient class and our class is ready to handle SSL Host Verification as well.

That's it. Thanks.


  • 2011.04.25: Initial submission


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

All Time Programming
Software Developer (Senior)
India India
I am a Freelance Software Developer and a Consultant. I provide service in Desktop, Client-Server, Database, Web and Mobile application developments. I like working on challenging projects and implementing new technologies and platforms.
I had started my career in IT development from DBase, COBOL, C and reached today to Java, C#, .NET, Android, BlackBerry (RIM), Windows Mobile, etc.

Comments and Discussions

QuestionKeyStore.getInstance Long Time in AVD Pin
MarzioP13-Oct-13 23:56
MemberMarzioP13-Oct-13 23:56 
GeneralMy vote of 1 Pin
praveenrajb24-Oct-12 18:58
Memberpraveenrajb24-Oct-12 18:58 
SuggestionCreating the KeyStore - the easy way Pin
jpstotz7-Mar-12 4:50
Memberjpstotz7-Mar-12 4:50 
QuestionSSL Verification for Android Pin
SteveJG25-Oct-11 1:42
MemberSteveJG25-Oct-11 1:42 
QuestionLost on BouncyCastle [modified] Pin
SilverBlue25-Aug-11 3:47
MemberSilverBlue25-Aug-11 3:47 
AnswerRe: Lost on BouncyCastle Pin
All Time Programming25-Aug-11 4:22
MemberAll Time Programming25-Aug-11 4:22 
QuestionUntrusted Server certificate Pin
lzliu17-Aug-11 18:23
Memberlzliu17-Aug-11 18:23 
GeneralMy vote of 5 Pin
Member 432084429-Apr-11 6:57
MemberMember 432084429-Apr-11 6:57 
GeneralRe: My vote of 5 Pin
All Time Programming9-May-11 19:55
MemberAll Time Programming9-May-11 19:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.