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());
    

45 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. 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
  11. 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
  12. Thanks A lot,
    This is amazing post, Though I am not an android developer, but I am able to crack my issue with the help of your post,

    This issue due to new SSL certificate and I am struggling last two days.
    Again thank you very much.

    ReplyDelete
  13. Wonderful piece of work. Master stroke. I have become a fan of your words. Pls keep on writing.

    Article submission sites
    Guest posting sites

    ReplyDelete
  14. I enjoy what you guys are usually up too. This sort of clever work and coverage! Keep up the wonderful works guysl.Good going.
    apple service center chennai
    apple service center in chennai
    apple mobile service centre in chennai

    ReplyDelete

  15. Có lẽ cần phải trải qua tuổi thanh xuân( Phương pháp học toán tư duy ) mới có thể hiểu được tuổi xuân là khoảng thời gian ta( dạy trẻ học toán tư duy ) sống ích kỷ biết chừng nào. Có lúc nghĩ, sở dĩ tình yêu cần phải đi một vòng tròn lớn như vậy, phải trả một cái giá quá đắt như thế,( Làm cho trẻ thích học toán ) là bởi vì nó đến không đúng thời điểm. Khi có được( Toán mầm non ) tình yêu, chúng ta thiếu đi trí tuệ. Đợi đến khi( Cách dạy con học toán lớp 1 ) có đủ trí tuệ, chúng ta đã không còn sức lực để yêu một tình yêu thuần khiết nữa.

    ReplyDelete
  16. તમારી પાસે એક સરસ લેખ છે. તમે એક ઉત્પાદક દિવસ માંગો છો

    bon ngam chan

    máy ngâm chân giải độc

    bồn mát xa chân

    chậu ngâm chân giá rẻ

    ReplyDelete
  17. Nội Thất Trẻ Em Bảo An Kids là doanh nghiệp chuyên thiết kế và thi công các sản phẩm nội thất trẻ em bao gồm: Phòng ngủ trẻ em, Giường tầng, bàn học sinh, kệ sách, tủ treo quần áo…

    ReplyDelete
  18. Vanskeligheter( van bi ) vil passere. På samme måte som( van điện từ ) regnet utenfor( van giảm áp ) vinduet, hvor nostalgisk( van xả khí ) er det som til slutt( van cửa ) vil fjerne( van công nghiệp ) himmelen.

    ReplyDelete
  19. Good to know about the email list business. I was looking for such a service for a long time o grow my local business but the rates that other companies were offering were not satisfactory. Thanks for sharing the recommendations in this post.hadoop training institutes in bangalore

    ReplyDelete
  20. Very interesting, good job and thanks for sharing such a good blog.

    Became An Expert In Selenium ! Learn from experienced Trainers and get the knowledge to crack a coding interview, @Softgen Infotech Located in BTM Layout.

    ReplyDelete
  21. Wonderful thanks for sharing an amazing idea. keep it...

    Get SAP S4 HANA Training in Bangalore from Real Time Industry Experts with 100% Placement Assistance in MNC Companies. Book your Free Demo with Softgen Infotech.

    ReplyDelete
  22. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete

  23. Class College Education training Beauty teaching university academy lesson  teacher master student  spa manager  skin care learn eyelash extensions tattoo spray


    ReplyDelete
  24. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete

  25. Writing articles that are very interesting and very neat, at first I did not understand how to write good articles,
    after I saw your website I began to learn and understand how to write the right articles.
    Thank you for giving a very good example of writing, I will often come to your website to learn how to write like the one on your website.
    humsafar lyrics

    ReplyDelete
  26. "The blog is absolutely truly incredible. So Thanks for giving this Information About Satta King

    Read More about "How to Play Satta King with Secure Mannar"

    ReplyDelete
  27. Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

    Amazon Web Services Online Training

    Amazon Web Services Classes Online

    Amazon Web Services Training Online

    Online Amazon Web Services Course

    Amazon Web Services Course Online

    ReplyDelete
  28. "Thanks for the Information and keep writing this type of content.
    Get In Touch with Us"
    If Want Play onlineSatta King click SattaKing :-

    ReplyDelete
  29. I have been impressed after reading this due to some quality work and informative ideas. I just want to say thanks to the author and wish you all the best! Your enthusiasm is refreshing. And if you are thinking to know about Satta King then you can visit here:- Satta King

    ReplyDelete
  30. hello this is my new site please checkout here by clicking on itkalyanchartresult

    ReplyDelete
  31. nice post click heresattaking vip
    nice post click heresattaking vip
    nice post click heresattaking vip
    nice post click heresattaking vip

    ReplyDelete
  32. I'm so glad I came across this post, it was incredibly informative and knowledgeable. I look forward to seeing more of your content, thank you!
    Full stack training in Pune

    ReplyDelete