if (isCA == true) { int keyusage = X509KeyUsage.keyCertSign + X509KeyUsage.cRLSign; X509KeyUsage ku = new X509KeyUsage(keyusage); certgen.addExtension(X509Extensions.KeyUsage.getId(), true, ku); }
    public static X509Certificate genSelfCert(String dn, long validity, PrivateKey privKey, PublicKey pubKey, boolean isCA)    throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {        // Create self signed certificate        String sigAlg="SHA1WithRSA";        Date firstDate = new Date();        // Set back startdate ten minutes to avoid some problems with wrongly set clocks.        firstDate.setTime(firstDate.getTime() - 10*60*1000);        Date lastDate = new Date();        // validity in days = validity*24*60*60*1000 milliseconds        lastDate.setTime(lastDate.getTime() + (validity * (24 * 60 * 60 * 1000)));        X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();        // Serialnumber is random bits, where random generator is initialized with Date.getTime() when this        // bean is created.        byte[] serno = new byte[8];        SecureRandom random = SecureRandom.getInstance("SHA1PRNG");        random.setSeed((long)(new Date().getTime()));        random.nextBytes(serno);        certgen.setSerialNumber((new java.math.BigInteger(serno)).abs());        certgen.setNotBefore(firstDate);        certgen.setNotAfter(lastDate);        certgen.setSignatureAlgorithm(sigAlg);        certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));        certgen.setIssuerDN(CertTools.stringToBcX509Name(dn));        certgen.setPublicKey(pubKey);        // Basic constranits is always critical and MUST be present at-least in CA-certificates.        BasicConstraints bc = new BasicConstraints(isCA);        certgen.addExtension(X509Extensions.BasicConstraints.getId(), true, bc);        // Subject and Authority key identifier is always non-critical and MUST be present for certificates to verify in Mozilla.        try {            if (isCA == true) {                SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((DERConstructedSequence)new DERInputStream(                new ByteArrayInputStream(pubKey.getEncoded())).readObject());                SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);                SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((DERConstructedSequence)new DERInputStream(                new ByteArrayInputStream(pubKey.getEncoded())).readObject());                AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);                certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);                certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);            }        } catch (IOException e) {// do nothing        }        X509Certificate selfcert = certgen.generateX509Certificate(privKey);        return selfcert;    } //genselfCert