Does Android Volley support SSL?
Asked Answered
P

4

13

Does anyone know whether Volley supports SSl in Android? Is there is any way to support SSL via Volley?

Pearly answered 19/9, 2015 at 21:48 Comment(2)
just use https url, i don't understand your question.Bobsleigh
Volley can support SSL. There's some helpful links in this similar question: #17046295Zicarelli
O
55

You can refer to my working sample code. Hope this helps!

public class MainActivity extends AppCompatActivity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.textView);

        String url = "https://192.168.1.100/testvolley";

        HurlStack hurlStack = new HurlStack() {
            @Override
            protected HttpURLConnection createConnection(URL url) throws IOException {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
                try {
                    httpsURLConnection.setSSLSocketFactory(getSSLSocketFactory());
                    httpsURLConnection.setHostnameVerifier(getHostnameVerifier());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return httpsURLConnection;
            }
        };

        final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    mTextView.setText(response.toString(5));
                } catch (JSONException e) {
                    mTextView.setText(e.toString());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mTextView.setText(error.toString());
            }
        });

        final RequestQueue requestQueue = Volley.newRequestQueue(this, hurlStack);

        requestQueue.add(jsonObjectRequest);
    }

    // Let's assume your server app is hosting inside a server machine
    // which has a server certificate in which "Issued to" is "localhost",for example.
    // Then, inside verify method you can verify "localhost". 
    // If not, you can temporarily return true
    private HostnameVerifier getHostnameVerifier() {
        return new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                //return true; // verify always returns true, which could cause insecure network traffic due to trusting TLS/SSL server certificates for wrong hostnames
                HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
                return hv.verify("localhost", session);
            }
        };
    }

    private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
        final X509TrustManager originalTrustManager = (X509TrustManager) trustManagers[0];
        return new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return originalTrustManager.getAcceptedIssuers();
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        try {
                            if (certs != null && certs.length > 0){
                                certs[0].checkValidity();
                            } else {
                                originalTrustManager.checkClientTrusted(certs, authType);
                            }
                        } catch (CertificateException e) {
                            Log.w("checkClientTrusted", e.toString());
                        }
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        try {
                            if (certs != null && certs.length > 0){
                                certs[0].checkValidity();
                            } else {
                                originalTrustManager.checkServerTrusted(certs, authType);
                            }
                        } catch (CertificateException e) {
                            Log.w("checkServerTrusted", e.toString());
                        }
                    }
                }
        };
    }    

    private SSLSocketFactory getSSLSocketFactory()
            throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = getResources().openRawResource(R.raw.my_cert); // this cert file stored in \app\src\main\res\raw folder path

        Certificate ca = cf.generateCertificate(caInput);
        caInput.close();

        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        TrustManager[] wrappedTrustManagers = getWrappedTrustManagers(tmf.getTrustManagers());

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, wrappedTrustManagers, null);

        return sslContext.getSocketFactory();
    }
}

IMO, you should also read more at Google's Documentation - Security with HTTPS and SSL

Odontology answered 20/9, 2015 at 0:8 Comment(21)
its not recognizing getSSLSocketFactory() method in the code.,Dried
oh yeah thanks , i missed that :) so this is the only way ? what if i don't have the ssl certificate file ?Dried
@Dried you can read my answer at #32051982, it applies for Volley also.Odontology
the default HostnameVerifier is already verifying hostname. why do you change it to other string like 'localhost'? unless you want to debug it.Robison
@teloon, please read my comment which has a server certificate in which "Issued to" is "localhost". However, if the hostname in the URL is already the hostname in the certificate then you would not need to write a custom HostnameVerifier at all. You can find more here if the URL's hostname and the server's identification hostname mismatchOdontology
@teloon: pls read more at developer.android.com/training/articles/…Odontology
This is not recognizing setSSLSocketFactory and setHostnameVerifier. What is your import for HttpURLConnection?Daphne
How to verify multiple certificates based on the url? I need to call two different servers which have different certificates.Rhinoscopy
@PrashanthDebbadwar I have not ever tested with that caseOdontology
I don't understand any SSL, and I can't read this sample code and replace what I need to replace :/Giavani
@RomulusUrakagiTs'ai so I suggest you read some of Google's links such as developer.android.com/training/articles/security-ssl.html and new blog spot for Android Nougat android-developers.blogspot.com/2016/07/…Odontology
but where does the .cert come from?Mastaba
@Mastaba you get it from the server site you want to access. I think you can find an example at developer.android.com/training/articles/security-ssl.htmlOdontology
how do I get my_cert file ? The server I am requesting is secured and it has SSL over there, so should I get it from there? OR I need to create this file ? Response awaited!!Protectionism
I have added certificate (taken from server) added the above code , but I am getting below error com.android.volley.NoConnectionError: javax.net.ssl.SSLPeerUnverifiedException: Hostname not verified:Protectionism
@Protectionism please pay attention to the comment right above getHostnameVerifierOdontology
@Odontology Do you mean, I just need to add allowAllSSL() method with above code ? that's it ?Protectionism
@Odontology But as you said, "If just for development, I think you can refer the following code (available in SO)" and I don't want the solution only for development.. As in some time we will be going to move on production.Protectionism
@Odontology Ho do I get .bks file? as I am having a crt file for certificate?Protectionism
Adding to @Odontology 's answer. If you are making calls to urls which over https, then you need not provide additional security params (like your own private certificate). Also, DO NOT implement your own version of TrustManager and HostNameVerifier.Bahrain
how to get my_cert file?Algernon
T
4

Yes, of course.

Android Volley is a library that you can use to easily and efficiently manage your networking operations over http. If the underlying layer use SSL (i.e. https) or not is totally unrelated.

In other words: the Volley framework is TCP layer agnostic and SSL only impact the TCP layer.

Theatricalize answered 19/9, 2015 at 22:8 Comment(3)
It's only normal that an HTTP library supports HTTPS, but then why does the answer above have 25 up-votes :O Are we missing something?Silly
@Mzn Volley is not working with https ? Are you able to do so ? If yes, have you added anything extra on server side or api end ?Protectionism
@Theatricalize DO you mean, volley should work same with "https" as it is working for "http" ? no need to add any extra code ? If so, have you added anything extra on server side or at api end for SSL ?Protectionism
P
2

I would like to look further @BNK 's answer. Suggest

requestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack(null, getSSLSocketFactory()));

would be enough. Don't know why , by follow @BNK 's answer that extends createConnection , Volley create about 5 connections for reuse which observed by netstat command By just passing getSSLSocketFactory() as new HurlStack() parameter, the connection opened by Volley is reduced.

Professorship answered 10/6, 2020 at 6:9 Comment(0)
M
1

Yes, I've implemented SSL Pinning with Volley. I also used certificates as a String and .cer file. Please follow my step.

You need to Create VolleySingleton class.

import android.content.Context;
import android.os.Build;

import androidx.annotation.RequiresApi;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import java.io.ByteArrayInputStream;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Base64;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class VolleySingleton {
private static VolleySingleton volleySingleton;
private RequestQueue requestQueue;
private static Context mctx;


private VolleySingleton(Context context){
    this.mctx=context;
    this.requestQueue=getRequestQueue();

}
public RequestQueue getRequestQueue(){
    if (requestQueue==null){
        requestQueue= Volley.newRequestQueue(mctx.getApplicationContext());
    }
    return requestQueue;
}
public static synchronized VolleySingleton getInstance(Context context){
    if (volleySingleton==null){
        volleySingleton=new VolleySingleton(context);
    }
    return volleySingleton;
}
public<T> void addToRequestQue(Request<T> request){
    requestQueue.add(request);

}


public HostnameVerifier getHostnameVerifier() {
    return new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            //return true;
 // verify always returns true, which could cause  insecure network traffic due to     trusting TLS/SSL server certificates for wrong hostnames
            HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
            return hv.verify("Enter your host url", session);
        }
    };

}

@RequiresApi(api = Build.VERSION_CODES.O)
public SSLSocketFactory getGlobalSSlFactory() {
    try {

//Use the certificate from raw folder...use below line
        InputStream inputStream=mctx.getResources().openRawResource(R.raw.test);
//Use the certificate as a String.. I've done the conversion here for String 
        String certificate= "Paste your certificate as string";
        byte encodedCert[] = Base64.getDecoder().decode(certificate);
        ByteArrayInputStream inputStream  = new ByteArrayInputStream(encodedCert);

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate ca = cf.generateCertificate(inputStream);
        inputStream.close();
        KeyStore keyStore = KeyStore.getInstance("BKS");
        keyStore.load(null, null);

        keyStore.setCertificateEntry("ca", ca);

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(keyStore, "xxxxxxx".toCharArray());

        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
public static X509Certificate convertToX509Cert(String certificateString) throws CertificateException {
    X509Certificate certificate = null;
    CertificateFactory cf = null;
    try {
        if (certificateString != null && !certificateString.trim().isEmpty()) {
            certificateString = certificateString.replace("-----BEGIN CERTIFICATE-----\n", "")
                    .replace("-----END CERTIFICATE-----", ""); // NEED FOR PEM FORMAT CERT STRING
            byte[] certificateData = Base64.getDecoder().decode(certificateString);
            cf = CertificateFactory.getInstance("X509");
            certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateData));
        }
    } catch (CertificateException e) {
        throw new CertificateException(e);
    }
    return certificate;
}

Now You can call your API and verify the SSL host verifier and certificate like this.

 HurlStack hurlStack = new HurlStack() {
        @Override
        protected HttpURLConnection createConnection(URL url) throws IOException {
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            try {
                httpsURLConnection.setSSLSocketFactory(VolleySingleton.getInstance(getApplicationContext()).getGlobalSSlFactory());
                httpsURLConnection.setHostnameVerifier(VolleySingleton.getInstance(getApplicationContext()).getHostnameVerifier());
                Log.i("SSL","SUCCESS");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return httpsURLConnection;
        }
    };

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,"URL", null,new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
          
         Log.i("onResponse", response.toString());
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
   
            Log.e("onErrorResponse", error.toString());
        }
    });
    final RequestQueue requestQueue = Volley.newRequestQueue(this, hurlStack);
    requestQueue.add(request); 

You can use this on production mode. Happy Coding.. Please thumps up. If It works. :)

Management answered 19/1, 2021 at 20:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.