Skip to content

Instantly share code, notes, and snippets.

@maplerise
Created May 30, 2017
Embed
What would you like to do?
Creates an SSL context useful for pinning certificates.
/**
* Creates an SSL context useful for pinning certificates.
*/
private class SSLContextPinner {
private SSLContext sslContext;
private TrustManager trustManager;
public SSLContextPinner(String pemAssetName) {
try {
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null, null);
InputStream certInputStream = getAssets().open(pemAssetName);
BufferedInputStream bis = new BufferedInputStream(certInputStream);
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
int idx = -1;
while (bis.available() > 0) {
Certificate cert = certificateFactory.generateCertificate(bis);
keyStore.setCertificateEntry("" + ++idx, cert);
Log.i("App", "pinned " + idx + ": " + ((X509Certificate) cert).getSubjectDN());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
trustManager = trustManagers[0];
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, null);
} catch(Exception e) {
sslContext = null;
trustManager = null;
Log.e("App", e.toString());
}
}
public SSLContext getSSLContext() { return sslContext; }
public X509TrustManager getX509TrustManager() { return (X509TrustManager) trustManager; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment