简体   繁体   中英

How to download a binary large file throw HTTPS when the web server require a client TLS certificate?

I didn't find any way to implement an SSLContext with DownloadManager. Is there a way to add a Client certificate (keystore)?

For now, it is a self signed certificate (both client&server). I'm able to connect to this server with okhttp (managing SSLContext) but with DownloadManager i get an error 'SSL Handshake'.

Here is my code,

 @Nullable
private static SSLContext initTrustManager(Context context) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        InputStream is = context.getAssets().open("s_cert.cer");
        Certificate ca;
        try {
            ca = certificateFactory.generateCertificate(is);
            Log.i("TrustManager", "ca=" + ((X509Certificate) ca).getSubjectDN());
        } finally {
            is.close();
        }
        String keyStoreType = KeyStore.getDefaultType();
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(keyStore);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, tmf.getTrustManagers(), null);
        return sslContext;
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}

And here is how I implement it:

builder.sslSocketFactory(initTrustManager(context).getSocketFactory());

This is working code, so if you still get exceptions, pay attention to SSL certificate itself or make some changes inside api of server. Hope it helps))

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