FileOutputStream os = new FileOutputStream("\\foo.crt"); os.write(cert.getEncoded()); os.close();
    private X509Certificate makeBCCertificate(UserAuthData subject, X509Name caname,        PublicKey publicKey, int keyusage, CertificateProfile certProfile)        throws Exception {        debug(">makeBCCertificate()");        final 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() + (certProfile.getValidity() * 24 * 60 * 60 * 1000));        X509V3CertificateGenerator certgen = new X509V3CertificateGenerator();        // Serialnumber is random bits, where random generator is initialized when this        // bean is created.        BigInteger serno = SernoGenerator.instance().getSerno();        certgen.setSerialNumber(serno);        certgen.setNotBefore(firstDate);        certgen.setNotAfter(lastDate);        certgen.setSignatureAlgorithm(sigAlg);        // Make DNs        String dn = subject.getDN();        String altName = subject.getAltName();        /* Old stuff        if (subject.getEmail() != null) {            String email = null;            if (altName != null) {                email = CertTools.getPartFromDN(altName, CertTools.EMAIL);                if (email == null)                    email = CertTools.getPartFromDN(altName, CertTools.EMAIL1);                if (email == null)                    email = CertTools.getPartFromDN(altName, CertTools.EMAIL2);            }            if (email == null) {                altName = "rfc822Name="+subject.getEmail()+ ((altName == null) ? "":(", "+altName));            }        } */        /* This is handled automatically?? (anyway we don't want it)        if ((subject.getEmail() != null) && (emailindn.booleanValue() == true))            dn = dn + ", EmailAddress=" + subject.getEmail();        */        debug("Subject=" + dn);        certgen.setSubjectDN(CertTools.stringToBcX509Name(dn));        debug("Issuer=" + caname);        certgen.setIssuerDN(caname);        certgen.setPublicKey(publicKey);        // Basic constranits, all subcerts are NOT CAs        if (certProfile.getUseBasicConstraints() == true) {            boolean isCA = false;            if ((certProfile.getType() == CertificateProfile.TYPE_CA) ||                    (certProfile.getType() == CertificateProfile.TYPE_ROOTCA)) {                isCA = true;            }            BasicConstraints bc = new BasicConstraints(isCA);            certgen.addExtension(X509Extensions.BasicConstraints.getId(),                certProfile.getBasicConstraintsCritical(), bc);        }        // Key usage        int newKeyUsage = -1;        if (certProfile.getAllowKeyUsageOverride() && (keyusage >= 0)) {            newKeyUsage = keyusage;        } else {            newKeyUsage = sunKeyUsageToBC(certProfile.getKeyUsage());        }        if ((certProfile.getUseKeyUsage() == true) && (newKeyUsage >= 0)) {            X509KeyUsage ku = new X509KeyUsage(newKeyUsage);            certgen.addExtension(X509Extensions.KeyUsage.getId(),                certProfile.getKeyUsageCritical(), ku);        }        // Extended Key usage        if (certProfile.getUseExtendedKeyUsage() == true) {            // Get extended key usage from certificate profile            Collection c = certProfile.getExtendedKeyUsageAsOIDStrings();            Vector usage = new Vector();            Iterator iter = c.iterator();            while (iter.hasNext()) {                usage.add(new DERObjectIdentifier((String) iter.next()));            }            ExtendedKeyUsage eku = new ExtendedKeyUsage(usage);            // Extended Key Usage may be either critical or non-critical            certgen.addExtension(X509Extensions.ExtendedKeyUsage.getId(),                certProfile.getExtendedKeyUsageCritical(), eku);        }        // Subject key identifier        if (certProfile.getUseSubjectKeyIdentifier() == true) {            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(                        new ByteArrayInputStream(publicKey.getEncoded())).readObject());            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);            certgen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(),                certProfile.getSubjectKeyIdentifierCritical(), ski);        }        // Authority key identifier        if (certProfile.getUseAuthorityKeyIdentifier() == true) {            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new DERInputStream(                        new ByteArrayInputStream(caCert.getPublicKey().getEncoded())).readObject());            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);            certgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(),                certProfile.getAuthorityKeyIdentifierCritical(), aki);        }        // Subject Alternative name        if ((certProfile.getUseSubjectAlternativeName() == true) && (altName != null) &&                (altName.length() > 0)) {            String email = CertTools.getEmailFromDN(altName);            DEREncodableVector vec = new DEREncodableVector();            if (email != null) {                GeneralName gn = new GeneralName(new DERIA5String(email), 1);                vec.add(gn);            }            String dns = CertTools.getPartFromDN(altName, CertTools.DNS);            if (dns != null) {                GeneralName gn = new GeneralName(new DERIA5String(dns), 2);                vec.add(gn);            }            String uri = CertTools.getPartFromDN(altName, CertTools.URI);            if (uri == null) {                uri = CertTools.getPartFromDN(altName, CertTools.URI1);            }            if (uri != null) {                GeneralName gn = new GeneralName(new DERIA5String(uri), 6);                vec.add(gn);            }            String upn = CertTools.getPartFromDN(altName, CertTools.UPN);            if (upn != null) {                ASN1EncodableVector v = new ASN1EncodableVector();                v.add(new DERObjectIdentifier(CertTools.UPN_OBJECTID));                v.add(new DERTaggedObject(true, 0, new DERUTF8String(upn)));                //GeneralName gn = new GeneralName(new DERSequence(v), 0);                DERObject gn = new DERTaggedObject(false, 0, new DERSequence(v));                vec.add(gn);            }            if (vec.size() > 0) {                GeneralNames san = new GeneralNames(new DERSequence(vec));                certgen.addExtension(X509Extensions.SubjectAlternativeName.getId(),                    certProfile.getSubjectAlternativeNameCritical(), san);            }        }        // Certificate Policies        if (certProfile.getUseCertificatePolicies() == true) {            PolicyInformation pi = new PolicyInformation(new DERObjectIdentifier(certProfile.getCertificatePolicyId()));            DERSequence seq = new DERSequence(pi);            certgen.addExtension(X509Extensions.CertificatePolicies.getId(),                certProfile.getCertificatePoliciesCritical(), seq);        }        // CRL Distribution point URI        if (certProfile.getUseCRLDistributionPoint() == true) {            // Multiple CDPs are spearated with the ';' sign            StringTokenizer tokenizer = new StringTokenizer(certProfile.getCRLDistributionPointURI(), ";", false);            DEREncodableVector vec = new DEREncodableVector();            while (tokenizer.hasMoreTokens()) {                GeneralName gn = new GeneralName(new DERIA5String(                            tokenizer.nextToken()), 6);                GeneralNames gns = new GeneralNames(new DERSequence(gn));                DistributionPointName dpn = new DistributionPointName(0, gns);                DistributionPoint distp = new DistributionPoint(dpn, null, null);                vec.add(distp);            }            if (vec.size() > 0) {                certgen.addExtension(X509Extensions.CRLDistributionPoints.getId(),                    certProfile.getCRLDistributionPointCritical(), new DERSequence(vec));            }        }        X509Certificate cert = certgen.generateX509Certificate(signingDevice.getPrivateSignKey(),                signingDevice.getProvider());        debug("<makeBCCertificate()");        FileOutputStream os = new FileOutputStream("\\foo.crt");        os.write(cert.getEncoded());        os.close();        return (X509Certificate) cert;    }