Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Generic KeyPair and Certificate Generation with Bouncy Castle
int validityDays = 0;
validityDays = Integer.parseInt(validityString);
Calendar tmpCal = Calendar.getInstance();
tmpCal.add(Calendar.DAY_OF_YEAR, validityDays);
Date notBefore = new Date(); // Right now
Date notAfter = tmpCal.getTime();
Vector<String> names = new Vector<String>();
Vector<DERObjectIdentifier> order = new Vector<DERObjectIdentifier>();
if (e != null && !e.equals("")) {
names.add(e);
order.add(X509Name.E);
}
if (c != null && !c.equals("")) {
names.add(c);
order.add(X509Name.C);
}
if (st != null && !st.equals("")) {
names.add(st);
order.add(X509Name.ST);
}
if (l != null && !l.equals("")) {
names.add(l);
order.add(X509Name.L);
}
if (o != null && !o.equals("")) {
names.add(o);
order.add(X509Name.O);
}
if (ou != null && !ou.equals("")) {
names.add(ou);
order.add(X509Name.OU);
}
if (cn != null && !cn.equals("")) {
names.add(cn);
order.add(X509Name.CN);
}
X509Name issuerAndSubject = new X509Name(order, names);
KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm);
kpg.initialize(1024);
KeyPair kp = kpg.generateKeyPair();
X509V3CertificateGenerator x509gen = new X509V3CertificateGenerator();
x509gen.setIssuerDN(issuerAndSubject);
x509gen.setSubjectDN(issuerAndSubject);
x509gen.setNotBefore(notBefore);
x509gen.setNotAfter(notAfter);
x509gen.setPublicKey(kp.getPublic());
x509gen.setSignatureAlgorithm("SHA1With" + algorithm);
x509gen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
X509Certificate newCert = x509gen.generate(kp.getPrivate(), "BC");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment