Skip to content

Instantly share code, notes, and snippets.

@maplerise
Created May 30, 2017 20:46
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save maplerise/99dfd4d0282101b1330ed7954e5d1d92 to your computer and use it in GitHub Desktop.
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