Skip to content

Instantly share code, notes, and snippets.

@johanlantz
Last active March 18, 2016 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanlantz/6c53af21723ac9adfd00 to your computer and use it in GitHub Desktop.
Save johanlantz/6c53af21723ac9adfd00 to your computer and use it in GitHub Desktop.
Code sample to create CA bundle in PEM format in Android
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