Android: Import SSL certificate and use it to SSL connection


  1. First of all you need get SSL certificate. You can obtain certificate (file with .cer extention) from the chain included in the endpoint certificate or from the official site of the issuer (in the Base64 encoded X.509 format).

    Or if you have this certificate installed on you local computer you can obtain it by run "mmc" (Microsoft Management Console) from command line ("Prompt" or "Run"). If you don't have Certificate snap-in go to  File -> Add/Remove Snap-in... -> Select from available snap-ins "Certificates" -> Add to Selected snap-ins -> Ok.

    Find certificate what do you need -> Right click -> All Tasks -> Export -> Select Base-64 encoded X.509 (.CER) -> Save into my_certificate.cer in my_certificate_path place.

    Content of this file look like:
    -----BEGIN CERTIFICATE-----
    MIIEIDCCAwigAwIBAgIQNE7VVyDV7exJ9C/ON9srbTANBgkqhkiG9w0B...
    -----END CERTIFICATE-----
    
  2. For create the keystore download latest release of Bouncy Castle provider (bcprov-jdkxx-xxx.jar) and store it in provider_path place. You must have JRE installation for invoke keytool (located under bin folder). You may add path to keytool into CLASSPATH environment variable or use absolute path.
  3. Execute this command for create mykeystore.bks (don't use upper case and "_" for name):
    D:/PROGRA~1/Java/jre7/bin/keytool -importcert -v -trustcacerts -file "my_certificate_pathmy_certificate.cer" -alias myAlias -keystore "my_keystore_path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "provider_path/bcprov-jdkxx-xxx.jar" -storetype BKS -storepass "my_password"
    
  4. You may verify if the certificate was imported correctly
    D:/PROGRA~1/Java/jre7/bin/keytool -list -keystore "my_keystore_path/mykeystore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "provider_path/bcprov-jdkxx-xxx.jar" -storetype BKS -storepass "my_password"
    
  5. Paste you mykeystore.bks as a raw resource under res/raw (this generate R.raw.mykeystore resource)
  6. Create a custom HttpClient to use you SSL certificate for HTTPS connection:
    import java.io.InputStream;
    import java.security.KeyStore;
    
    import org.apache.http.conn.ClientConnectionManager;
    import org.apache.http.conn.scheme.PlainSocketFactory;
    import org.apache.http.conn.scheme.Scheme;
    import org.apache.http.conn.scheme.SchemeRegistry;
    import org.apache.http.conn.ssl.SSLSocketFactory;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.impl.conn.SingleClientConnManager;
    
    import android.content.Context;
    
    public class MyHttpsClient extends DefaultHttpClient {
      
        final Context context;
     
        public MyHttpsClient(Context context) {
            this.context = context;
        }
     
        @Override
        protected ClientConnectionManager createClientConnectionManager() {
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            // Register for port 443 our SSLSocketFactory with our keystore
            // to the ConnectionManager
            registry.register(new Scheme("https", newSslSocketFactory(), 443));
            return new SingleClientConnManager(getParams(), registry);
        }
     
        private SSLSocketFactory newSslSocketFactory() {
            try {
                // Get an instance of the Bouncy Castle KeyStore format
                KeyStore trusted = KeyStore.getInstance("BKS");
                // Get the raw resource, which contains the keystore with
                // your trusted certificates (root and any intermediate certs)
                InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
                try {
                    // Initialize the keystore with the provided trusted certificates
                    // Also provide the password of the keystore
                    trusted.load(in, "my_password".toCharArray());
                } finally {
                    in.close();
                }
                // Pass the keystore to the SSLSocketFactory. The factory is responsible
                // for the verification of the server certificate.
                SSLSocketFactory sf = new SSLSocketFactory(trusted);
                // Hostname verification from certificate
                // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
                sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
                return sf;
            } catch (Exception e) {
                throw new AssertionError(e);
            }
        }
    }
    
  7. Use you custom HttpClient:
    DefaultHttpClient client = new MyHttpsClient(getApplicationContext());
    

14 comments:

  1. how to fix wrong version of keystore ?

    ReplyDelete
  2. Thank you so much for very clean and clear descriotion!!!

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Thank you very much!!!! That was exaclty what I needed!!

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete
  6. THANKS FOR THIS CLEAR TUTORIAL BUT I GET THIS EXCEPTION:
    i used bcprov-ext-jdk15on-1.46.jar for Android studio 2.1

    Caused by: java.security.cert.CertificateException: Signature uses an insecure hash function: 1.2.840.113549.1.1.4
    at com.android.org.conscrypt.ChainStrengthAnalyzer.checkSignatureAlgorithm(ChainStrengthAnalyzer.java:85)
    at com.android.org.conscrypt.ChainStrengthAnalyzer.checkCert(ChainStrengthAnalyzer.java:48)
    at com.android.org.conscrypt.ChainStrengthAnalyzer.check(ChainStrengthAnalyzer.java:42)
    at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:324)
    at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
    getSlotFromBufferLocked: unknown buffer: 0xa19c4d80
    at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:115)
    at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:556)
    at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
    at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
    ... 16 more

    ReplyDelete
  7. THANKS FOR THIS CLEAR TUTORIAL BUT I GET THIS EXCEPTION:
    i used bcprov-ext-jdk15on-1.46.jar for Android studio 2.1

    ReplyDelete
  8. Why am I not going into the @Override protected ClientConnectionManager?
    I used System.out.println("to test"); to test it.

    ReplyDelete
  9. Thanks for showing this simple steps about how to install SSL Certificate in Chennai

    ReplyDelete
  10. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.
    Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

    ReplyDelete
  11. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training in chennai | Android Training|Android Training in chennai with placement | Android Training in velachery

    ReplyDelete
  12. Your thought toward the unique result is awesome also the idea behind the blog is very attractive which would bring a new growth in the corresponding field. Thanks for sharing.Hadoop Training in Chennai | Best Selenium Training in Chennai | Android Training | Android Training Institute in Chennai

    ReplyDelete
  13. It is very important for us to learn about the networking ideas and the expert guidelines to applying networking concepts. Many people become victims of network use because they are not familiar with the role of network protection. We should stand in the gap and voice out our minds and decries against network misuse. Superior PhD Dissertation Editing Service

    ReplyDelete