简体   繁体   中英

I am getting a SSLHandshakeException and CertPathValidatorException error while using self signed certificate

I am trying to send a https request to apache2 which afterwards is recieved by Django. The code was working fine before ssl with http but now it is giving an exception. I just need to send a https request to django via apache2. My apache2 server is running on AWS server.

This is in my MainActivity.java file.

This is my hurlstack code

 hurlStack = new HurlStack() {

        @Override
        protected HttpsURLConnection createConnection(URL url) throws IOException {
            Log.w("testing","in hurlstack exception ");

            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) super.createConnection(url);
            Log.w("testing","after url ");

            try {
                Log.w("testing","in hurlstack try ");
                httpsURLConnection.setSSLSocketFactory(getSSLSocketFactory());
                httpsURLConnection.setHostnameVerifier(getHostnameVerifier());
            } catch (Exception e) {
                e.printStackTrace();
                Log.w("testing","In hurlstack exception"+e.toString());
            }
            Log.w("testing","end of  hurlstack" + httpsURLConnection);
            return httpsURLConnection;
        }
    };

  private HostnameVerifier getHostnameVerifier() {
    Log.w("testing","In hostname verifier");
    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(hostname, session);
        }
    };
}

private TrustManager[] getWrappedTrustManagers(TrustManager[] trustManagers) {
    Log.w("testing","In trust manager");
    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("testing", "certificate error "+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("testing", "certificate server error "+e.toString());
                    }
                }
            }
    };
}

private SSLSocketFactory getSSLSocketFactory()
        throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException {
    Log.w("testing", " in ssl socket factory");
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream caInput = getResources().openRawResource(R.raw.apache_selfsigned); // this is the file with .crt extension stored in \app\src\main\res\raw folder path
    Log.w("testing", "ssl socket");
    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();
}

I have a MySingleton.java file

private MySingleton(Context context) {
    mCtx = context;
    mRequestQueue = getRequestQueue();

}

public static synchronized MySingleton getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new MySingleton(context);
    }
    return mInstance;
}

public RequestQueue getRequestQueue() {
    if (mRequestQueue == null) {
        // getApplicationContext() is key, it keeps you from leaking the
        // Activity or BroadcastReceiver if someone passes one in.
        mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext(),new HurlStack());
    }
    return mRequestQueue;
}

public <T> void addToRequestQueue(Request<T> req) {

//        getRequestQueue().getCache().clear();
      req.setRetryPolicy(new DefaultRetryPolicy(60000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    getRequestQueue().add(req);
}

Command I used to create self signed certificate are

sudo openssl req -new -x509 -nodes -out apache-selfsigned.crt -keyout apache-selfsigned.key

您需要获取上面生成的证书请求文件并对其进行自签名以生成证书文件。

openssl x509 -trustout -signkey apache-selfsigned.key -days 365 -req -in apache-selfsigned.crt -out apache-selfsigned.cer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM