Last active
March 18, 2016 18:01
-
-
Save johanlantz/6c53af21723ac9adfd00 to your computer and use it in GitHub Desktop.
Code sample to create CA bundle in PEM format in Android
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
public void getCertificateBundle() { | |
TrustManager managers[]= {null}; | |
TrustManagerFactory tmf = null; | |
try { | |
tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | |
} catch (NoSuchAlgorithmException e) { | |
e.printStackTrace(); | |
} | |
try { | |
tmf.init((KeyStore) null); | |
} catch (KeyStoreException e) { | |
e.printStackTrace(); | |
} | |
managers = tmf.getTrustManagers(); | |
StringWriter sw = new StringWriter(); | |
for (int i = 0; i < managers.length; i++) { | |
if (managers[i] instanceof X509TrustManager) { | |
X509TrustManager trustMgr = (X509TrustManager) managers[i]; | |
X509Certificate[] certificates = trustMgr.getAcceptedIssuers(); | |
for (int j = 0; j < certificates.length; j++) { | |
try { | |
sw.write("-----BEGIN CERTIFICATE-----\n"); | |
sw.write(Base64.encodeToString(certificates[j].getEncoded(), Base64.DEFAULT)); | |
sw.write("-----END CERTIFICATE-----\n"); | |
} catch (CertificateEncodingException e) { | |
Log.e(TAG, "Encoding error"); | |
e.printStackTrace(); | |
} | |
} | |
} | |
} | |
PrintWriter writer = null; | |
try { | |
writer = new PrintWriter(Environment.getExternalStorageDirectory() + File.separator + "bundle.crt", "UTF-8"); | |
writer.print(sw.toString()); | |
writer.close(); | |
} catch (FileNotFoundException e) { | |
e.printStackTrace(); | |
} catch (UnsupportedEncodingException e) { | |
e.printStackTrace(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment