Example usage for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber

List of usage examples for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber

Introduction

In this page you can find the example usage for org.bouncycastle.x509 X509V3CertificateGenerator setSerialNumber.

Prototype

public void setSerialNumber(BigInteger serialNumber) 

Source Link

Document

set the serial number for the certificate.

Usage

From source file:io.aos.crypto.spl06.PKCS10CertCreateExample.java

License:Apache License

public static X509Certificate[] buildChain() throws Exception {
    // create the certification request
    KeyPair pair = Utils.generateRSAKeyPair();

    PKCS10CertificationRequest request = PKCS10ExtensionExample.generateRequest(pair);

    // create a root certificate
    KeyPair rootPair = Utils.generateRSAKeyPair();
    X509Certificate rootCert = X509V1CreateExample.generateV1Certificate(rootPair);

    // validate the certification request
    if (!request.verify("BC")) {
        System.out.println("request failed to verify!");
        System.exit(1);//from   w  w w.  j  a  v a  2s  . c o m
    }

    // create the certificate using the information in the request
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(rootCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(rootCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    // extract the extension request attribute
    ASN1Set attributes = request.getCertificationRequestInfo().getAttributes();

    for (int i = 0; i != attributes.size(); i++) {
        Attribute attr = Attribute.getInstance(attributes.getObjectAt(i));

        // process extension request
        if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {
            X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

            Enumeration e = extensions.oids();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                X509Extension ext = extensions.getExtension(oid);

                certGen.addExtension(oid, ext.isCritical(), ext.getValue().getOctets());
            }
        }
    }

    X509Certificate issuedCert = certGen.generateX509Certificate(rootPair.getPrivate());

    return new X509Certificate[] { issuedCert, rootCert };
}

From source file:io.aos.crypto.spl06.X509V3CreateExample.java

License:Apache License

public static X509Certificate generateV3Certificate(KeyPair pair)
        throws InvalidKeyException, NoSuchProviderException, SignatureException {
    // generate the certificate
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=Test Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 50000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(new X500Principal("CN=Test Certificate"));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    return certGen.generateX509Certificate(pair.getPrivate(), "BC");
}

From source file:io.aos.crypto.spl07.Utils.java

License:Apache License

/**
 * Generate a sample V3 certificate to use as an intermediate CA certificate
 *///from w w  w  .  j  a v a  2 s .c om
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() + 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");
}

From source file:io.aos.crypto.spl07.Utils.java

License:Apache License

/**
 * Generate a sample V3 certificate to use as an end entity certificate
 *//* www .java  2  s .  co m*/
public static X509Certificate generateEndEntityCert(PublicKey entityKey, 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() + VALIDITY_PERIOD));
    certGen.setSubjectDN(new X500Principal("CN=Test End Certificate"));
    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    return certGen.generateX509Certificate(caKey, "BC");
}

From source file:io.aos.crypto.spl08.CertReqSolution.java

License:Apache License

public static void main(String... args) throws Exception {
    // create the CA certificates
    X500PrivateCredential rootCredential = Utils.createRootCredential();
    X500PrivateCredential interCredential = Utils.createIntermediateCredential(rootCredential.getPrivateKey(),
            rootCredential.getCertificate());

    // parse the request
    PEMReader pRd = new PEMReader(new InputStreamReader(new FileInputStream("pkcs10.req")));

    PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();

    // get our validation certificate
    X509Certificate caCert = interCredential.getCertificate();

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + 50000));
    certGen.setSubjectDN(request.getCertificationRequestInfo().getSubject());
    certGen.setPublicKey(request.getPublicKey("BC"));
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    // provide some basic extensions and mark the certificate as appropriate for signing and encipherment
    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(request.getPublicKey("BC")));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    // create the chain
    List chain = Arrays/*from   www  .  j a v a 2 s. c o m*/
            .asList(new Certificate[] { certGen.generateX509Certificate(interCredential.getPrivateKey(), "BC"),
                    interCredential.getCertificate(), rootCredential.getCertificate() });

    // create the CertPath
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    CertPath path = fact.generateCertPath(chain);

    // write it out
    FileOutputStream fOut = new FileOutputStream("pkcs7.pth");

    fOut.write(path.getEncoded("PKCS7"));

    fOut.close();
}

From source file:krypto.KryptoService.java

License:Apache License

/**
 * Erzeugt ein x509 v3-Zertifikat, das 1 Tag lang gltig ist.
 * @return//from w  ww. j  ava  2s . c o m
 * @throws Exception
 */
public static X509Certificate generateCertificate(String algorithm) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    KeyPair pair = null;

    try {
        pair = generateKeyPair(algorithm, 1024);
    } catch (Exception e) {
        try {
            pair = generateKeyPair(algorithm, 512);
        } catch (Exception e2) {
            System.out.println(e2.getMessage());
        }
    }

    long day = 24 * 60 * 60 * 1000; // 1 Tag gltig

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setNotBefore(new Date(System.currentTimeMillis() - 500000));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + day));
    certGen.setSubjectDN(new X509Name(new X500Principal("CN=Test Certificate").getName()));
    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));

    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
            new ExtendedKeyUsage(KeyPurposeId.id_kp_serverAuth));

    certGen.addExtension(X509Extensions.SubjectAlternativeName, false,
            new GeneralNames(new GeneralName(GeneralName.rfc822Name, "test@test.test")));

    X509Certificate cert = null;
    try {
        cert = certGen.generate(pair.getPrivate(), "BC");
    } catch (CertificateEncodingException e) {
        System.out.println("CertificateEncodingException");
    } catch (InvalidKeyException e2) {
        System.out.println("InvalidKeyException: " + e2.getMessage());
    } catch (Exception e3) {
        // do nothing
    }

    return cert;

}

From source file:libcore.net.ssl.SslContextBuilder.java

License:Apache License

/**
 * Generates a certificate for {@code hostName} containing {@code keyPair}'s
 * public key, signed by {@code keyPair}'s private key.
 */// w w w .j  a  v  a2 s  .co m
@SuppressWarnings("deprecation") // use the old Bouncy Castle APIs to reduce dependencies.
private X509Certificate selfSignedCertificate(KeyPair keyPair) throws GeneralSecurityException {
    X509V3CertificateGenerator generator = new X509V3CertificateGenerator();
    X500Principal issuer = new X500Principal("CN=" + hostName);
    X500Principal subject = new X500Principal("CN=" + hostName);
    generator.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    generator.setIssuerDN(issuer);
    generator.setNotBefore(new Date(notBefore));
    generator.setNotAfter(new Date(notAfter));
    generator.setSubjectDN(subject);
    generator.setPublicKey(keyPair.getPublic());
    generator.setSignatureAlgorithm("SHA256WithRSAEncryption");
    return generator.generateX509Certificate(keyPair.getPrivate(), "BC");
}

From source file:lt.bsprendimai.ddesk.servlets.CertGenerator.java

License:Apache License

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request//from  ww w. java 2 s .c  o m
 *            servlet request
 * @param response
 *            servlet response
 */
@SuppressWarnings("unchecked")
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {

        UserHandler uh = (UserHandler) request.getSession().getAttribute("userHandler");
        ClientAccessor ca = (ClientAccessor) request.getSession().getAttribute("clientAccessor");

        if (uh == null || !uh.isLoggedIn() || uh.getUser().getCompany() != 0
                || uh.getUser().getLoginLevel() != 0) {
            response.sendRedirect(request.getContextPath());
            return;
        }

        if (request.getParameter("X509Principal.PWD") == null) {
            request.setAttribute("T", ca.getPerson().getName());
            request.setAttribute("USER", ca.getPerson().getLoginCode());
            request.setAttribute("EMAIL", ca.getPerson().getEmail());
            RequestDispatcher rd = request.getRequestDispatcher("/intranet/generation.jsp");
            rd.forward(request, response);
            return;
        }

        Security.addProvider(new BouncyCastleProvider());

        Hashtable attrs = new Hashtable();
        Vector order = new Vector();

        InputStreamReader rd = new InputStreamReader(CertGenerator.class.getResourceAsStream("/desk.pem"));
        PEMReader reader = new PEMReader(rd);
        Object oo = (KeyPair) reader.readObject();
        KeyPair myKey = (KeyPair) oo;

        reader.close();

        rd = new InputStreamReader(CertGenerator.class.getResourceAsStream("/desk.crt"));
        reader = new PEMReader(rd);
        X509Certificate root = (X509Certificate) reader.readObject();
        reader.close();

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
        kpg.initialize(1024);
        KeyPair kp = kpg.generateKeyPair();
        PublicKey users = kp.getPublic();

        String issuer = root.getSubjectDN().getName();

        attrs.put(X509Principal.T, request.getParameter("X509Principal.T"));
        attrs.put(X509Principal.C, request.getParameter("X509Principal.C"));
        attrs.put(X509Principal.O, request.getParameter("X509Principal.O"));
        attrs.put(X509Principal.OU, request.getParameter("X509Principal.OU"));
        attrs.put(X509Principal.L, request.getParameter("X509Principal.L"));
        attrs.put(X509Principal.CN, request.getParameter("X509Principal.CN"));
        attrs.put(X509Principal.EmailAddress, request.getParameter("X509Principal.EmailAddress"));

        order.addElement(X509Principal.T);
        order.addElement(X509Principal.C);
        order.addElement(X509Principal.O);
        order.addElement(X509Principal.OU);
        order.addElement(X509Principal.L);
        order.addElement(X509Principal.CN);
        order.addElement(X509Principal.EmailAddress);

        X509Principal subjectDn = new X509Principal(order, attrs);

        Session sess = SessionHolder.currentSession().getSess();

        CertificateEntry ce = new CertificateEntry();
        ce.setCert("");
        ce.setMd5Key("");
        ce.setName(subjectDn.getName());
        ce.setPerson(null);
        ce.setValid(false);
        sess.save(ce);
        sess.flush();

        X509V3CertificateGenerator v3c = new X509V3CertificateGenerator();

        v3c.reset();

        v3c.setSerialNumber(BigInteger.valueOf(ce.getId()));
        v3c.setIssuerDN(new X509Principal(issuer));
        v3c.setNotBefore(new Date());
        v3c.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 30)));
        v3c.setSubjectDN(subjectDn);
        v3c.setPublicKey(users);
        v3c.setSignatureAlgorithm("MD5WithRSAEncryption");

        //
        // add the extensions
        //

        v3c.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
                new NetscapeCertType(NetscapeCertType.sslClient | NetscapeCertType.objectSigning));

        X509Certificate cert = v3c.generate(myKey.getPrivate(), "BC");

        cert.getSignature();
        cert.checkValidity(new Date());

        cert.verify(myKey.getPublic());

        KeyStore store = KeyStore.getInstance("PKCS12", "BC");
        store.load(null, null);

        store.setKeyEntry(request.getParameter("X509Principal.T"), kp.getPrivate(), null,
                new Certificate[] { cert, root });

        StringWriter sr = new StringWriter();

        sr.write("-----BEGIN CERTIFICATE-----\n");
        sr.write(new String(Base64.encode(cert.getEncoded())));
        sr.write("\n");
        sr.write("-----END CERTIFICATE-----");

        byte[] pwdMD5 = Hex.encode(MessageDigest.getInstance("MD5").digest(cert.getEncoded()));

        String code = new String(pwdMD5);

        if (code.length() < 32) {
            for (int i = (32 - code.length()); i > 0; i--) {
                code = "0" + code;
            }
        }

        List<CertificateEntry> lce = (List<CertificateEntry>) sess
                .createQuery("FROM " + CertificateEntry.class.getName() + " WHERE person = ? AND valid = true ")
                .setInteger(0, ca.getPersonId()).list();

        for (CertificateEntry cea : lce) {
            ce.setValid(false);
            sess.update(cea);
            sess.flush();
        }

        ce.setCert(sr.toString().trim());
        ce.setMd5Key(code.trim());
        ce.setPerson(ca.getPersonId());
        ce.setValid(true);
        sess.update(ce);
        sess.flush();

        SessionHolder.closeSession();

        System.out.println("Writing certificate");

        response.setContentType("application/pkcs-12");
        response.setHeader("Content-disposition",
                "inline;filename=" + request.getParameter("X509Principal.T").trim() + ".p12");

        OutputStream out = response.getOutputStream();
        store.store(out, request.getParameter("X509Principal.PWD").trim().toCharArray());
        out.close();

    } catch (Exception ex) {
        try {
            SessionHolder.endSession();
        } catch (Exception ejx) {
        }
        ex.printStackTrace();

        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Error</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Error: ");
        out.println(ex.getMessage());
        out.println("</h1>");
        out.println("<br/>");
        out.println("</body>");
        out.println("</html>");

        out.close();

    }
}

From source file:net.java.bd.tools.security.OnlineKeytool.java

License:Open Source License

/**
 * Creates a self signed certificate using the public key
 * from the "online.crt" file. See BD-ROM specification part 3.2,
 * version 2.2 Annex DD./* w w w . ja  v a 2s  .c  o m*/
 * The certificate fields other than the key pair do not matter.
 * The certificate is just a place holder in the keystore.
 * The private key is created from the BDA binary file.
 * <p>
 * @throws java.lang.Exception
 */
public void createSelfSignedCert() throws Exception {
    DataInputStream dis = new DataInputStream(new FileInputStream(crtFile));

    String typeIndicator = SecurityUtil.readISO646String(dis, 4);
    if (!typeIndicator.equals("OCRT")) {
        throw new RuntimeException("Invalid TypeIndicator: " + typeIndicator + " in " + crtFile);
    }
    String versionNo = SecurityUtil.readISO646String(dis, 4);
    if (!versionNo.equals("0200")) {
        throw new RuntimeException("Invalid Version No:" + versionNo + " in " + crtFile);
    }
    // reserved bytes
    dis.skipBytes(32);
    int certVerNo = dis.readInt();
    if (certVerNo != 0) {
        throw new RuntimeException("Invalid Certificate Version No:" + certVerNo);
    }
    int contentOwnerId = dis.readInt();
    if (debug) {
        System.out.println("Content owner ID:" + contentOwnerId);
    }
    // reserved bytes
    dis.skipBytes(32);
    String contentOwnerName = SecurityUtil.readISO646String(dis, 256);
    if (debug) {
        System.out.println("Content owner Name:" + contentOwnerName);
    }
    String dn = "cn=" + contentOwnerName; // used in cert

    // read the public key modulus 'n'
    byte[] buf = new byte[256];
    int read = dis.read(buf);
    if (read == -1) {
        throw new IOException("Reached end of file before finished reading the file:" + crtFile);
    }
    BigInteger modulus = new BigInteger(1, buf);
    /*HexDumpEncoder hexDump = null;
    if (debug) {
    System.out.println("public modulus:");
    hexDump = new HexDumpEncoder();
    System.out.println(hexDump.encodeBuffer(modulus.toByteArray()));
    }*/
    BigInteger exponent = BigInteger.valueOf(65537);
    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, exponent);
    KeyFactory factory = KeyFactory.getInstance("RSA");
    PublicKey publicKey = factory.generatePublic(spec);

    // create a self signed cert for importing into the keystore.
    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();
    Calendar calendar = Calendar.getInstance();
    calendar.set(0000, 1, 1);
    Date validFrom = calendar.getTime();
    calendar.clear();
    calendar.set(9999, 1, 1);
    Date validTo = calendar.getTime();
    cg.setNotBefore(validFrom);
    cg.setNotAfter(validTo);
    cg.setPublicKey(publicKey);
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    cg.setSubjectDN(new X509Name(dn));

    cg.setIssuerDN(new X509Name(dn));
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    BigInteger serNo = new BigInteger(32, prng);
    cg.setSerialNumber(serNo);
    this.cert = cg.generate(this.privateKey);

    // read the BDA signature; not currently used
    //int read = dis.read(buf);
    //if (read == -1) {
    //    throw new IOException("Reached end of file before finished reading the file:" +
    //            crtFile);
    //}
    dis.close();
}

From source file:net.java.bd.tools.security.SecurityUtil.java

License:Open Source License

private void generateSelfSignedCertificate(String issuer, String alias, String keyPassword, boolean isRootCert)
        throws Exception {
    Date validFrom, validTo;//  w  ww .  j  av a 2s  .co  m

    // For forcing GeneralizedTime DER encoding, with Bouncy Castle Provider 
    // make the range before 1950 and after 2050. The BD-J spec recommends
    // using the default validity period used below
    Calendar calendar = Calendar.getInstance();
    calendar.set(0000, 1, 1);
    validFrom = calendar.getTime();
    calendar.clear();
    calendar.set(9999, 1, 1);
    validTo = calendar.getTime();

    // Generate a new keypair for this certificate
    KeyPair keyPair = generateKeyPair();

    X509V3CertificateGenerator cg = new X509V3CertificateGenerator();
    cg.reset();
    X509Name name = new X509Name(issuer, new X509BDJEntryConverter());

    // Generate Serial Number
    SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
    BigInteger serNo = new BigInteger(32, prng);
    cg.setSerialNumber(serNo);
    if (!isRootCert) {
        appCertSerNo = serNo;
    }
    cg.setIssuerDN(name);
    cg.setNotBefore(validFrom);
    cg.setNotAfter(validTo);
    cg.setSubjectDN(name);
    cg.setPublicKey(keyPair.getPublic());
    cg.setSignatureAlgorithm("SHA1WITHRSA");
    if (isRootCert) {
        // Need to add root cert extensions.
        if (isBindingUnitCert) {
            // This certificate is used only for signing
            cg.addExtension(X509Extensions.KeyUsage.getId(), true,
                    new X509KeyUsage(X509KeyUsage.digitalSignature));
        } else {
            int usage = X509KeyUsage.digitalSignature + X509KeyUsage.keyCertSign;
            cg.addExtension(X509Extensions.KeyUsage.getId(), true, new X509KeyUsage(usage));
        }
        cg.addExtension(X509Extensions.IssuerAlternativeName.getId(), false, getRfc822Name(altName));
        cg.addExtension(X509Extensions.BasicConstraints.getId(), true, new BasicConstraints(true));
    }
    // For an app cert, most of the extensions will be added when generating
    // a certificate in response to the certificate request file.
    cg.addExtension(X509Extensions.SubjectAlternativeName.getId(), false, getRfc822Name(altName));

    Certificate cert = cg.generate(keyPair.getPrivate());
    store.setKeyEntry(alias, keyPair.getPrivate(), keyPassword.toCharArray(), new Certificate[] { cert });
    FileOutputStream fos = new FileOutputStream(keystoreFile);
    store.store(fos, keystorePassword.toCharArray());
    fos.close();
}