Skip to content

Instantly share code, notes, and snippets.

@laprasdrum
Created April 19, 2014 10:53
Show Gist options
  • Save laprasdrum/11081010 to your computer and use it in GitHub Desktop.
Save laprasdrum/11081010 to your computer and use it in GitHub Desktop.
convert X.509 certificate into PEM-formatted file with SpongyCastle
static {
Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
final KeyPair pair = RSAPemGenerator.generateRSAKeyPair();
X509V1CertificateGenerator certGenerator = new X509V1CertificateGenerator();
X509Principal dnName = new X509Principal("CN=John Doe");
certGenerator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGenerator.setSubjectDN(dnName);
certGenerator.setIssuerDN(dnName);
// yesterday
Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
// in 2 years
Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);
certGenerator.setNotBefore(validityBeginDate);
certGenerator.setNotAfter(validityEndDate);
certGenerator.setPublicKey(pair.getPublic());
certGenerator.setSignatureAlgorithm("SHA256WithRSAEncryption");
final X509Certificate cert = certGenerator.generate(pair.getPrivate());
Log.d("main", cert.toString());
// write it as PEM file
PemWriter writer = new PemWriter(new PrintWriter(new File(getExternalCacheDir() + "/cert.pem")));
// X.509 cert version
PemObjectGenerator generator = new PemObjectGenerator() {
@Override
public PemObject generate() throws PemGenerationException {
try {
return new PemObject(cert.getType(), cert.getTBSCertificate());
} catch (CertificateEncodingException e) {
e.printStackTrace();
return null;
}
}
};
}
writer.writeObject(generator);
writer.flush();
writer.close();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// result
$ cat cert.pem
-----BEGIN X.509-----
MIIBhwIGAUV4lU90MA0GCSqGSIb3DQEBCwUAMBMxETAPBgNVBAMMCEpvaG4gRG9l
MB4XDTE0MDQxODA2MDM0MloXDTE0MDQwMzE0MjE1MlowEzERMA8GA1UEAwwISm9o
biBEb2UwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDMVrGzmMWNq5YP
9yAwCvDU2mT+uipvJVahjhgFy8lLhmDpQFEKibXZervBCk77E4CTR29uNjh9MPtm
wLed5GgwV6Eg/rohWWR+xqaIHYIOXgnipGn6UUVrk1jHCBrCxtJszrDhgcjd2D10
L+/wb8K84az3uAuPG1yiwxfrxy5UEVNwQzXeVtTT8lRMsfaK/tmQpXqiqAcq0X71
yLy/Qm6LkL8r2hGyrWYq2LnjaCmJfZrZBAsO65F3aoOffDdjNeKGTp2Jyf9ZTYlj
rifRvarou2oSULMEf/p6iILQWIC8BSrLwOQCX8YUcMvtAvL7OV57WiI+f9QI5d/H
ZkrHSk8tAgMBAAE=
-----END X.509-----
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment