Skip to content

Instantly share code, notes, and snippets.

@AkshayMoorthy
Created April 26, 2018 09:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AkshayMoorthy/2b6b23b4b29998a12986a2a4176c7e45 to your computer and use it in GitHub Desktop.
Save AkshayMoorthy/2b6b23b4b29998a12986a2a4176c7e45 to your computer and use it in GitHub Desktop.
private static SSLContext getSSLConfig(Context context) throws CertificateException, IOException,
KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
// Loading CAs from an InputStream
CertificateFactory cf = null;
cf = CertificateFactory.getInstance("X.509");
Certificate ca;
// I'm using Java7. If you used Java6 close it manually with finally.
try (InputStream cert = context.getResources().openRawResource(R.raw.nginxselfsigned)) {
ca = cf.generateCertificate(cert);
}
// Creating a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Creating a TrustManager that trusts the CAs in our KeyStore.
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Creating an SSLSocketFactory that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment