Skip to content

Instantly share code, notes, and snippets.

@milhomem
Last active April 18, 2024 21:18
Show Gist options
  • Save milhomem/cd322bf3d0599ceb76fe to your computer and use it in GitHub Desktop.
Save milhomem/cd322bf3d0599ceb76fe to your computer and use it in GitHub Desktop.
How to connect using Client Certificate in Android with OkHttp
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream clientCertificateContent = new FileInputStream("/path/to/publicAndPrivateKey.p12");
keyStore.load(clientCertificateContent, "private key password".toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "private key password".toCharArray());
FileInputStream myTrustedCAFileContent = new FileInputStream("/path/to/embedded/CA-Chain.pem");
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate myCAPublicKey = (X509Certificate) certificateFactory.generateCertificate(myTrustedCAFileContent);
KeyStore trustedStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustedStore.load(null);
trustedStore.setCertificateEntry(myCAPublicKey.getSubjectX500Principal().getName(), myCAPublicKey);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustedStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, null);
OkHttpClient client = new OkHttpClient();
client.setSslSocketFactory(sslContext.getSocketFactory());
client.newCall(new Request.Builder()
.url("https://easytaxi.com.br")
.build()
).execute();
@testmayank013
Copy link

client.setSslSocketFactory not working

@cyb3rko
Copy link

cyb3rko commented Apr 18, 2024

Thank you a lot!

@milhomem
Copy link
Author

@cyb3rko 🥰 it’s cool isn’t it? Does this still work as is with the latest versions? Been a while I dont test this.

@cyb3rko
Copy link

cyb3rko commented Apr 18, 2024

For context:
I'm currently implementing mTLS for gotify/android.
I got it working in Retrofit 2.5.0 which we are currently still using.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment