/app-pinner.java Secret
Created
May 30, 2017 20:46
Star
You must be signed in to star a gist
Creates an SSL context useful for pinning certificates.
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
/** | |
* 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