Skip to content

Instantly share code, notes, and snippets.

@Starksoft
Forked from milhomem/clientCert.android.java
Created October 15, 2020 16:57
Show Gist options
  • Save Starksoft/9aefd33818d6b500d0d38c6df758ab17 to your computer and use it in GitHub Desktop.
Save Starksoft/9aefd33818d6b500d0d38c6df758ab17 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment