private X509Certificate genCert( PrivateKey signKey, PublicKey pubKey, String subjectDN, String issuerDN, Map<DERObjectIdentifier, DEREncodable> ext) throws GeneralSecurityException { gen.reset(); Date now = new Date(); gen.setSerialNumber(BigInteger.valueOf(0)); gen.setNotBefore(now); gen.setNotAfter(new Date(now.getTime() + CA_CERT_LIFETIME)); gen.setIssuerDN(new X509Name(issuerDN)); gen.setSubjectDN(new X509Name(subjectDN)); gen.setPublicKey(pubKey); gen.setSignatureAlgorithm(CA_CERT_SIGNATURE_ALGORITHM); if (ext != null) { for (Map.Entry<DERObjectIdentifier, DEREncodable> e : ext.entrySet()) { gen.addExtension(e.getKey(), false, e.getValue()); } } try { X509Certificate cert = gen.generateX509Certificate(signKey, "BC", new SecureRandom()); return cert; } catch (Exception e) { throw new GeneralSecurityException("Failed to create X509 certificate", e); } }
/** Generate a sample V3 certificate to use as an intermediate CA certificate */ public static X509Certificate generateIntermediateCert( PublicKey intKey, PrivateKey caKey, X509Certificate caCert) throws Exception { X509V3CertificateGenerator certGen = new X509V3CertificateGenerator(); certGen.setSerialNumber(BigInteger.valueOf(1)); certGen.setIssuerDN(caCert.getSubjectX500Principal()); certGen.setNotBefore(new Date(System.currentTimeMillis())); certGen.setNotAfter(new Date(System.currentTimeMillis() + ConfigurationClass.VALIDITY_PERIOD)); certGen.setSubjectDN(new X500Principal("CN=Test Intermediate Certificate")); certGen.setPublicKey(intKey); certGen.setSignatureAlgorithm("SHA1WithRSAEncryption"); certGen.addExtension( X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert)); certGen.addExtension( X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(intKey)); certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0)); certGen.addExtension( X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign)); return certGen.generateX509Certificate(caKey, "BC"); }