Last active
April 18, 2024 21:18
-
-
Save milhomem/cd322bf3d0599ceb76fe to your computer and use it in GitHub Desktop.
How to connect using Client Certificate in Android with OkHttp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); |
Thank you a lot!
@cyb3rko 🥰 it’s cool isn’t it? Does this still work as is with the latest versions? Been a while I dont test this.
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
client.setSslSocketFactory not working