• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps HTTPS with selfsign cert

HeavensSentSword

Well-Known Member
Jan 19, 2016
134
36
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:

Java:
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyStore;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

/**
* Created by MMILLAR on 1/20/2016.
* Used to download images
* Then display it in the inmageView
*/
public class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

    private final WeakReference<ImageView> imageViewReference;
    Resources resources = null;


    public ImageDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... params)
    {
        return downloadBitmap(params[0]);
    }
    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    Log.d("Downloading the image: ", "No Image found");
                }
            }

        }
    }

    //URL connection to download the image
    private Bitmap downloadBitmap(String url) {

        HttpURLConnection urlConnection = null;
        HttpsURLConnection urlConnection2 = null;
        try {

            //check to see if the image is coming from a HTTP connection
            //then download via a HTTP connection
            //if not then use a HTTPS connection
            if(url.contains("https"))
            {
                try {
                    Log.d("Use HTTPS", url);
                    URL urlHTTPS = new URL(url);
                    urlConnection2 = (HttpsURLConnection) urlHTTPS.openConnection();

                    // Load CAs from an InputStream
                    // (could be from a resource or ByteArrayInputStream or ...)
                    CertificateFactory cf = CertificateFactory.getInstance("X.509");
                    InputStream caInput = resources.getAssets().open("fusionsystemca.crt");
                    Log.d("CA: ", caInput.toString());
                    //InputStream caInput = new BufferedInputStream(new FileInputStream(resources.getAssets().open("myca.crt")));
                    Certificate ca;
                    try {
                        ca = cf.generateCertificate(caInput);
                        System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN());
                    } finally {
                        caInput.close();
                    }

                    // Create a KeyStore containing our trusted CAs
                    String keyStoreType = KeyStore.getDefaultType();
                    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
                    keyStore.load(null, null);
                    keyStore.setCertificateEntry("ca", ca);

                    // Create a TrustManager that trusts the CAs in our KeyStore
                    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
                    tmf.init(keyStore);

                    // Create an SSLContext that uses our TrustManager
                    SSLContext context = SSLContext.getInstance("TLS");
                    context.init(null, tmf.getTrustManagers(), null);
                    urlConnection2.setSSLSocketFactory(context.getSocketFactory());

                    int statusCode = urlConnection2.getResponseCode();
                    Log.d("URL2 Status: " , Integer.toString(statusCode));
                    //check if the HTTP status code is equal to 200, which means that it is ok
                    if (statusCode != 200) {
                        return null;
                    }
                    InputStream in = urlConnection2.getInputStream();
                    if (in != null) {
                        Bitmap bitmap = BitmapFactory.decodeStream(in);
                        return bitmap;
                    }
                }catch (Exception e)
                {
                    urlConnection2.disconnect();
                    Log.d("ImageDownloader", "Error downloading image from " + url);
                }

            }else
            {
                Log.d("Http: " , url);
                URL uri = new URL(url);
                urlConnection = (HttpURLConnection) uri.openConnection();
                urlConnection.setRequestMethod("GET");
                int statusCode = urlConnection.getResponseCode();
                //check if the HTTP status code is equal to 200, which means that it is ok
                if (statusCode != 200) {
                    return null;
                }

                InputStream inputStream = urlConnection.getInputStream();
                if (inputStream != null) {
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    return bitmap;
                }
            }

        } catch (Exception e) {
            urlConnection.disconnect();
            Log.d("ImageDownloader", "Error downloading image from " + url);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if(urlConnection2 != null)
            {
                urlConnection2.disconnect();
            }
        }
        return null;
    }

    //this is to add the selfsigned cert
}
 
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.
 
Upvote 0
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.
Java:
  public  void trustAllHosts() {

        X509TrustManager easyTrustManager = new X509TrustManager() {

            public void checkClientTrusted(
                    X509Certificate[] chain,
                    String authType) throws CertificateException {

            }

            public void checkServerTrusted(
                    X509Certificate[] chain,
                    String authType) throws CertificateException {

            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        };

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};

        // Install the all-trusting trust manager
        try {
            SSLContext sc = SSLContext.getInstance("TLS");

            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Upvote 0

BEST TECH IN 2023

We've been tracking upcoming products and ranking the best tech since 2007. Thanks for trusting our opinion: we get rewarded through affiliate links that earn us a commission and we invite you to learn more about us.

Smartphones