How to use root ca with retrofit on android

265 views Asked by At

I have certificate that i use without retrofit :

public static Certificate loadCertificateFromRaw(String name) {
    Certificate certificate = null;
    InputStream caInput = null;

    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = GlobalFunctions.class.getClassLoader().getResourceAsStream("assets/" + name);
        certificate = cf.generateCertificate(caInput);
        System.out.println("ca=" + ((X509Certificate) certificate).getSubjectDN());
    } catch(Exception e) {
        e.printStackTrace();
    } finally {
        if (caInput != null) {
            try {
                caInput.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return certificate;
}

Now we moved to retrofit and i"m trying to copy this implementation

I found this article : https://medium.com/yellowme/adding-ssl-certificates-into-your-android-app-with-retrofit-1a6ea9bd3b27

But i don't want to create key and more stuff that i don't need.

Just add this *.crt file as before

this is the code i found, a you can see it has more stuff than i need but they related on each other so i don't know how remove the stuff i don't need

caFileInputStream  = context.resources.openRawResource(R.raw.root_crt)
// Here you may wanna add some headers or custom setting for your builder

// We're going to put our certificates in a Keystore
val keyStore = KeyStore.getInstance("PKCS12")
keyStore.load(caFileInputStream, "my file password".toCharArray())

// Create a KeyManagerFactory with our specific algorithm our our public keys
// Most of the cases is gonna be "X509"
val keyManagerFactory = KeyManagerFactory.getInstance("X509")
keyManagerFactory.init(keyStore, "my file password".toCharArray())

// Create a SSL context with the key managers of the KeyManagerFactory
val sslContext = SSLContext.getInstance("TLS")
sslContext.init(keyManagerFactory.keyManagers, null, SecureRandom())

//Finally set the sslSocketFactory to our builder and build it
return httpClientBuilder.sslSocketFactory(sslContext.socketFactory).build()
0

There are 0 answers