1. Are you ready for the Galaxy S20? Here is everything we know so far!

HTTPS with selfsign cert

Discussion in 'Android Development' started by HeavensSentSword, Feb 10, 2016.

  1. HeavensSentSword

    HeavensSentSword Well-Known Member
    Thread Starter

    I have been working at using a self-signed cert for downloading a image from a server. I have tried using the Android dev site's example, but to no success. I have downloaded the cert from the server and saved it into the res/raw folder in the android project.
    I tried accessing the site with my mobile phone directly and it said this
    Your connection is not private
    its security cert is not trusted by my devices os.

    But if I accept the risk it will display the image so I feel that I can download the image I just need to allow it some how.
    The whole code does this;
    1: download a json file from the internet (works)
    2: Parse out the json file that contains a mix of http and https (works)
    3: to download the image it check if the url is a http or https and send it to the right method to download (works)
    4: If http download the image(works)
    5: If https download the image(doesn't work)

    this is what I got so far:

    Code (Java):
    1.  
    2. import java.io.InputStream;
    3. import java.lang.ref.WeakReference;
    4. import java.net.HttpURLConnection;
    5. import java.net.URL;
    6. import java.security.KeyStore;
    7. import android.content.res.Resources;
    8. import android.graphics.Bitmap;
    9. import android.graphics.BitmapFactory;
    10. import android.os.AsyncTask;
    11. import android.util.Log;
    12. import android.widget.ImageView;
    13. import java.security.cert.Certificate;
    14. import java.security.cert.CertificateFactory;
    15. import java.security.cert.X509Certificate;
    16. import javax.net.ssl.HttpsURLConnection;
    17. import javax.net.ssl.SSLContext;
    18. import javax.net.ssl.TrustManagerFactory;
    19.  
    20. /**
    21. * Created by MMILLAR on 1/20/2016.
    22. * Used to download images
    23. * Then display it in the inmageView
    24. */
    25. public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
    26.  
    27.     private final WeakReference<ImageView> imageViewReference;
    28.     Resources resources = null;
    29.  
    30.  
    31.     public ImageDownloaderTask(ImageView imageView) {
    32.         imageViewReference = new WeakReference<ImageView>(imageView);
    33.     }
    34.  
    35.     @Override
    36.     protected Bitmap doInBackground(String... params)
    37.     {
    38.         return downloadBitmap(params[0]);
    39.     }
    40.     @Override
    41.     protected void onPostExecute(Bitmap bitmap) {
    42.         if (isCancelled()) {
    43.             bitmap = null;
    44.         }
    45.  
    46.         if (imageViewReference != null) {
    47.             ImageView imageView = imageViewReference.get();
    48.             if (imageView != null) {
    49.                 if (bitmap != null) {
    50.                     imageView.setImageBitmap(bitmap);
    51.                 } else {
    52.                     Log.d("Downloading the image: ", "No Image found");
    53.                 }
    54.             }
    55.  
    56.         }
    57.     }
    58.  
    59.     //URL connection to download the image
    60.     private Bitmap downloadBitmap(String url) {
    61.  
    62.         HttpURLConnection urlConnection = null;
    63.         HttpsURLConnection urlConnection2 = null;
    64.         try {
    65.  
    66.             //check to see if the image is coming from a HTTP connection
    67.             //then download via a HTTP connection
    68.             //if not then use a HTTPS connection
    69.             if(url.contains("https"))
    70.             {
    71.                 try {
    72.                     Log.d("Use HTTPS", url);
    73.                     URL urlHTTPS = new URL(url);
    74.                     urlConnection2 = (HttpsURLConnection) urlHTTPS.openConnection();
    75.  
    76.                     // Load CAs from an InputStream
    77.                     // (could be from a resource or ByteArrayInputStream or ...)
    78.                     CertificateFactory cf = CertificateFactory.getInstance("X.509");
    79.                     InputStream caInput = resources.getAssets().open("fusionsystemca.crt");
    80.                     Log.d("CA: ", caInput.toString());
    81.                     //InputStream caInput = new BufferedInputStream(new FileInputStream(resources.getAssets().open("myca.crt")));
    82.                     Certificate ca;
    83.                     try {
    84.                         ca = cf.generateCertificate(caInput);
    85.                         System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
    86.                     } finally {
    87.                         caInput.close();
    88.                     }
    89.  
    90.                     // Create a KeyStore containing our trusted CAs
    91.                     String keyStoreType = KeyStore.getDefaultType();
    92.                     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    93.                     keyStore.load(null, null);
    94.                     keyStore.setCertificateEntry("ca", ca);
    95.  
    96.                     // Create a TrustManager that trusts the CAs in our KeyStore
    97.                     String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    98.                     TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    99.                     tmf.init(keyStore);
    100.  
    101.                     // Create an SSLContext that uses our TrustManager
    102.                     SSLContext context = SSLContext.getInstance("TLS");
    103.                     context.init(null, tmf.getTrustManagers(), null);
    104.                     urlConnection2.setSSLSocketFactory(context.getSocketFactory());
    105.  
    106.                     int statusCode = urlConnection2.getResponseCode();
    107.                     Log.d("URL2 Status: " , Integer.toString(statusCode));
    108.                     //check if the HTTP status code is equal to 200, which means that it is ok
    109.                     if (statusCode != 200) {
    110.                         return null;
    111.                     }
    112.                     InputStream in = urlConnection2.getInputStream();
    113.                     if (in != null) {
    114.                         Bitmap bitmap = BitmapFactory.decodeStream(in);
    115.                         return bitmap;
    116.                     }
    117.                 }catch (Exception e)
    118.                 {
    119.                     urlConnection2.disconnect();
    120.                     Log.d("ImageDownloader", "Error downloading image from " + url);
    121.                 }
    122.  
    123.             }else
    124.             {
    125.                 Log.d("Http: " , url);
    126.                 URL uri = new URL(url);
    127.                 urlConnection = (HttpURLConnection) uri.openConnection();
    128.                 urlConnection.setRequestMethod("GET");
    129.                 int statusCode = urlConnection.getResponseCode();
    130.                 //check if the HTTP status code is equal to 200, which means that it is ok
    131.                 if (statusCode != 200) {
    132.                     return null;
    133.                 }
    134.  
    135.                 InputStream inputStream = urlConnection.getInputStream();
    136.                 if (inputStream != null) {
    137.                     Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
    138.                     return bitmap;
    139.                 }
    140.             }
    141.  
    142.         } catch (Exception e) {
    143.             urlConnection.disconnect();
    144.             Log.d("ImageDownloader", "Error downloading image from " + url);
    145.         } finally {
    146.             if (urlConnection != null) {
    147.                 urlConnection.disconnect();
    148.             }
    149.             if(urlConnection2 != null)
    150.             {
    151.                 urlConnection2.disconnect();
    152.             }
    153.         }
    154.         return null;
    155.     }
    156.  
    157.     //this is to add the selfsigned cert
    158. }
     



    1. Download the Forums for Android™ app!


      Download

       
  2. Deleted User

    Deleted User Guest

    Sorry I'm not clear what the problem is. What error/exception do you get?
     
  3. HeavensSentSword

    HeavensSentSword Well-Known Member
    Thread Starter

    So basically in the onPostExecute method when I try to download a image from a HTTPS website it returns the bitmap = null. So I am thinking that I don't have the right way of dealing with HTTPS yet. The url that I am trying to download from is right when it goes into the downloadBitmap method for HTTPS try section. But that never returns anything.
    The Http stuff all works flawlessly.
    Is there a way to just allow all cert to work regardless of where they come from?
    I tried using File > settings > server certs > accept all non trusted certs,
    But that didn't work either.
     
  4. HeavensSentSword

    HeavensSentSword Well-Known Member
    Thread Starter

    I have been running though this and it still gives me this execution error
    javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

    which I know is tied to the cert not being accepted.
    I have even tried thisto allow everything under the sun to download the image but with the same effect.
    Code (Java):
    1.   public  void trustAllHosts() {
    2.  
    3.         X509TrustManager easyTrustManager = new X509TrustManager() {
    4.  
    5.             public void checkClientTrusted(
    6.                     X509Certificate[] chain,
    7.                     String authType) throws CertificateException {
    8.  
    9.             }
    10.  
    11.             public void checkServerTrusted(
    12.                     X509Certificate[] chain,
    13.                     String authType) throws CertificateException {
    14.  
    15.             }
    16.  
    17.             public X509Certificate[] getAcceptedIssuers() {
    18.                 return null;
    19.             }
    20.  
    21.         };
    22.  
    23.         // Create a trust manager that does not validate certificate chains
    24.         TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};
    25.  
    26.         // Install the all-trusting trust manager
    27.         try {
    28.             SSLContext sc = SSLContext.getInstance("TLS");
    29.  
    30.             sc.init(null, trustAllCerts, new java.security.SecureRandom());
    31.  
    32.             HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    33.  
    34.         } catch (Exception e) {
    35.             e.printStackTrace();
    36.         }
    37.     }
     
Loading...

Share This Page

Loading...