Last active
August 17, 2017 10:07
-
-
Save PenzK/b9ee7ab40e27a363ea61df69a55b8a0e to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Adding ssl socket factory to okhttp builder with trusted cert | |
* | |
* @param builder OkHttpClient.Builder | |
*/ | |
private void configureTrustingCertificates(OkHttpClient.Builder builder) { | |
TrustManager[] trustManagers; | |
TLSSocketFactory sslSocketFactory; | |
try { | |
trustManagers = getTrustManagers(readKeyStore()); | |
sslSocketFactory = new TLSSocketFactory(trustManagers); | |
builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustManagers[0]); | |
} catch (GeneralSecurityException e) { | |
throw new RuntimeException(e); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
/** | |
* Returns TrustManger[] initiated with keystore | |
* @param keyStore for TrustManager | |
* @return TrustManger[] | |
* @throws GeneralSecurityException if no configured trust managers | |
*/ | |
private TrustManager[] getTrustManagers(KeyStore keyStore) throws GeneralSecurityException { | |
// Use it to build an X509 trust manager. | |
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance( | |
KeyManagerFactory.getDefaultAlgorithm()); | |
keyManagerFactory.init(keyStore, PASSWORD.toCharArray()); | |
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance( | |
TrustManagerFactory.getDefaultAlgorithm()); | |
trustManagerFactory.init(keyStore); | |
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); | |
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) { | |
throw new IllegalStateException("Unexpected default trust managers:" | |
+ Arrays.toString(trustManagers)); | |
} | |
return trustManagers; | |
} | |
/** | |
* Returns keystore read from raw folder | |
* @return read keystore | |
* @throws KeyStoreException if something goes wrong with reading | |
* @throws CertificateException if something goes wrong with loading | |
* @throws NoSuchAlgorithmException if something goes wrong with loading | |
* @throws IOException if something goes wrong with loading | |
*/ | |
private KeyStore readKeyStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { | |
KeyStore ks = KeyStore.getInstance("BKS"); | |
InputStream is = null; | |
try { | |
is = context.getResources().openRawResource(R.raw.keystore); | |
ks.load(is, PASSWORD.toCharArray()); | |
} finally { | |
if (is != null) { | |
is.close(); | |
} | |
} | |
return ks; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment