Last active
May 11, 2023 14:25
-
-
Save erickok/7692592 to your computer and use it in GitHub Desktop.
Loading a self-signed SSL certificate .crt file and packaging it into a SSLSocketFactory for use with a HttpsURLConnection.
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
// Usage example... | |
HttpsURLConnection connection = (HttpsURLConnection) new URL("https://someurl.com").openConnection(); | |
connection.setSSLSocketFactory(buildSslSocketFactory()); | |
private static SSLSocketFactory buildSslSocketFactory(Context context) { | |
// Add support for self-signed (local) SSL certificates | |
// Based on http://developer.android.com/training/articles/security-ssl.html#UnknownCa | |
try { | |
// Load CAs from an InputStream | |
// (could be from a resource or ByteArrayInputStream or ...) | |
CertificateFactory cf = CertificateFactory.getInstance("X.509"); | |
// From https://www.washington.edu/itconnect/security/ca/load-der.crt | |
InputStream is = context.getResources().getAssets().openAsset("somefolder/somecertificate.crt"); | |
InputStream caInput = new BufferedInputStream(is); | |
Certificate ca; | |
try { | |
ca = cf.generateCertificate(caInput); | |
// System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); | |
} finally { | |
caInput.close(); | |
} | |
// Create a KeyStore containing our trusted CAs | |
String keyStoreType = KeyStore.getDefaultType(); | |
KeyStore keyStore = KeyStore.getInstance(keyStoreType); | |
keyStore.load(null, null); | |
keyStore.setCertificateEntry("ca", ca); | |
// Create a TrustManager that trusts the CAs in our KeyStore | |
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); | |
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); | |
tmf.init(keyStore); | |
// Create an SSLContext that uses our TrustManager | |
SSLContext context = SSLContext.getInstance("TLS"); | |
context.init(null, tmf.getTrustManagers(), null); | |
return context.getSocketFactory(); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} catch (KeyStoreException e) { | |
e.printStackTrace(); | |
} catch (KeyManagementException e) { | |
e.printStackTrace(); | |
} catch (CertificateException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage says: connection.setSSLSocketFactory(buildSslSocketFactory());
private static SSLSocketFactory buildSslSocketFactory(Context context) {
what is Context ?