KeyPairGenerator kpGen = KeyPairGenerator.getInstance("RSA", "BC");
kpGen.initialize(1024, new SecureRandom());
KeyPair pair = kpGen.generateKeyPair();
// Generate self-signed certificate
X500NameBuilder builder = new X500NameBuilder(BCStyle.INSTANCE);
builder.addRDN(BCStyle.OU, Constants.getName());
builder.addRDN(BCStyle.O, Constants.getName());
builder.addRDN(BCStyle.CN, hostname);
Date notBefore = new Date(System.currentTimeMillis() - ONEDAY);
Date notAfter = new Date(System.currentTimeMillis() + 10 * ONEYEAR);
BigInteger serial = BigInteger.valueOf(System.currentTimeMillis());
X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(builder.build(),
serial, notBefore, notAfter, builder.build(), pair.getPublic());
ContentSigner sigGen = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
.setProvider(BC).build(pair.getPrivate());
X509Certificate cert = new JcaX509CertificateConverter().setProvider(BC)
.getCertificate(certGen.build(sigGen));
cert.checkValidity(new Date());