Example usage for org.bouncycastle.asn1.x509 KeyUsage digitalSignature

List of usage examples for org.bouncycastle.asn1.x509 KeyUsage digitalSignature

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 KeyUsage digitalSignature.

Prototype

int digitalSignature

To view the source code for org.bouncycastle.asn1.x509 KeyUsage digitalSignature.

Click Source Link

Usage

From source file:at.ac.tuwien.ifs.tita.business.security.TiTASecurity.java

License:Apache License

/**
 * Generates a fresh Certificate for a Users KeyPair.
 * //from  ww  w.j ava  2s. c  o  m
 * @param pair the KeyPair to create a Certificate for.
 * @param userName the Issuer of the Certificate
 * @return a 10 Year valid Certificate for the User.
 * @throws TiTASecurityException If an error occurs during the generation Process.
 */
private static X509Certificate generateV3Certificate(KeyPair pair, String userName)
        throws TiTASecurityException {

    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(new X500Principal("CN=" + userName + " Certificate"));
    certGen.setNotBefore(new Date(System.currentTimeMillis()));
    certGen.setNotAfter(new Date(System.currentTimeMillis() + VALID_TIME_RANGE));
    certGen.setSubjectDN(new X500Principal("CN=" + userName + " 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));

    X509Certificate targetCertificate = null;
    try {
        targetCertificate = certGen.generate(pair.getPrivate(), "BC");
    } catch (NoSuchProviderException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Specified provider was not found.\n" + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Specified algorithm was not found.\n" + e.getMessage());
    } catch (SignatureException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Signature is not valid.\n" + e.getMessage());
    } catch (CertificateEncodingException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". Wrong encoding for Signature.\n" + e.getMessage());
    } catch (InvalidKeyException e) {
        log.error("Could create a certificate for: " + userName + ".");
        throw new TiTASecurityException("Error while Generating a Certificate for: " + userName
                + ". The Key is not valid.\n" + e.getMessage());
    }

    return targetCertificate;
}

From source file:at.asitplus.regkassen.core.modules.signature.rawsignatureprovider.NEVER_USE_IN_A_REAL_SYSTEM_SoftwareCertificateOpenSystemSignatureModule.java

License:Apache License

public void intialise() {
    try {/*from www .j  a v  a2s. com*/
        //create random demonstration ECC keys
        final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC");
        kpg.initialize(256); //256 bit ECDSA key

        //create a key pair for the demo Certificate Authority
        final KeyPair caKeyPair = kpg.generateKeyPair();

        //create a key pair for the signature certificate, which is going to be used to sign the receipts
        final KeyPair signingKeyPair = kpg.generateKeyPair();

        //get references to private keys for the CA and the signing key
        final PrivateKey caKey = caKeyPair.getPrivate();
        signingKey = signingKeyPair.getPrivate();

        //create CA certificate and add it to the certificate chain
        //NOTE: DO NEVER EVER USE IN A REAL CASHBOX, THIS IS JUST FOR DEMONSTRATION PURPOSES
        //NOTE: these certificates have random values, just for the demonstration purposes here
        //However, for testing purposes the most important feature is the EC256 Signing Key, since this is required
        //by the RK Suite
        final X509v3CertificateBuilder caBuilder = new X509v3CertificateBuilder(new X500Name("CN=RegKassa ZDA"),
                BigInteger.valueOf(new SecureRandom().nextLong()), new Date(System.currentTimeMillis() - 10000),
                new Date(System.currentTimeMillis() + 24L * 3600 * 1000), new X500Name("CN=RegKassa CA"),
                SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded()));
        caBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        caBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        final X509CertificateHolder caHolder = caBuilder
                .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey));
        final X509Certificate caCertificate = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(caHolder);
        certificateChain = new ArrayList<java.security.cert.Certificate>();
        certificateChain.add(caCertificate);

        //create signing cert
        final long serialNumberCertificate = new SecureRandom().nextLong();
        if (!closedSystemSignatureDevice) {
            serialNumberOrKeyId = Long.toHexString(serialNumberCertificate);
        }

        final X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(
                new X500Name("CN=RegKassa CA"), BigInteger.valueOf(Math.abs(serialNumberCertificate)),
                new Date(System.currentTimeMillis() - 10000),
                new Date(System.currentTimeMillis() + 24L * 3600 * 1000),
                new X500Name("CN=Signing certificate"),
                SubjectPublicKeyInfo.getInstance(signingKeyPair.getPublic().getEncoded()));
        certBuilder.addExtension(X509Extension.basicConstraints, true, new BasicConstraints(false));
        certBuilder.addExtension(X509Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));
        final X509CertificateHolder certHolder = certBuilder
                .build(new JcaContentSignerBuilder("SHA256withECDSA").setProvider("BC").build(caKey));
        signingCertificate = new JcaX509CertificateConverter().setProvider("BC").getCertificate(certHolder);

    } catch (final NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (final OperatorCreationException e) {
        e.printStackTrace();
    } catch (final CertIOException e) {
        e.printStackTrace();
    } catch (final CertificateException e) {
        e.printStackTrace();
    }
}

From source file:beta01.CreateCertByCsr.java

public CreateCertByCsr() throws Exception {
    //read p12/*from w  w w .  j a  v  a  2  s . c  om*/
    KeyStore pkcs12Store = KeyStore.getInstance("PKCS12", "BC");
    pkcs12Store.load(new FileInputStream("D:\\rootPrivateKey.p12"), "pass".toCharArray());

    //read root key pair and certificate
    PrivateKey privateKey = null;
    PublicKey publicKey = null;
    X509Certificate rootCert = null;
    for (Enumeration en = pkcs12Store.aliases(); en.hasMoreElements();) {
        String alias = (String) en.nextElement();
        if (pkcs12Store.isCertificateEntry(alias)) {
            rootCert = (X509Certificate) pkcs12Store.getCertificate(alias);
            Certificate cert = pkcs12Store.getCertificate(alias);
            publicKey = cert.getPublicKey();
        } else if (pkcs12Store.isKeyEntry(alias)) {
            privateKey = (PrivateKey) pkcs12Store.getKey(alias, "pass".toCharArray());
        }
    }
    //read CSR
    String fileName = "CSR_DSA";
    FileReader fileReader = new FileReader("D:\\" + fileName + ".p10");
    PemReader pemReader = new PemReader(fileReader);
    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(pemReader.readPemObject().getContent());

    //create certf
    JcaX509CertificateHolder holder = new JcaX509CertificateHolder(rootCert);
    X509v3CertificateBuilder certBuilder;
    certBuilder = new X509v3CertificateBuilder(holder.getSubject(),
            BigInteger.valueOf(System.currentTimeMillis()), new Date(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() + 7 * 24 * 60 * 60 * 1000), csr.getSubject(),
            csr.getSubjectPublicKeyInfo());
    certBuilder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature));

    SignatureAlgorithmIdentifierFinder algFinder = new DefaultSignatureAlgorithmIdentifierFinder();
    AlgorithmIdentifier sigAlg = algFinder.find("SHA512withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    //RSAPrivateKey rsa = (RSAPrivateKey) privateKey;
    //AsymmetricCipherKeyPair ss =new AsymmetricCipherKeyPair
    // RSAKeyParameters rsaP = new RSAPrivateCrtKeyParameters(rsa.getModulus(), rsa.getPublicExponent(), 
    // rsa.getPrivateExponent(), rsa., BigInteger.ONE, BigInteger.ONE, BigInteger.ONE, BigInteger.ONE);
    //ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build((AsymmetricKeyParameter) privateKey);

    // AsymmetricCipherKeyPair sd = new AsymmetricCipherKeyPair(null, null)

    ContentSigner signer = new JcaContentSignerBuilder("SHA512withRSA").setProvider("BC").build(privateKey);
    X509CertificateHolder holder2 = certBuilder.build(signer);
    new SimpleGenCert().converToPem(holder2, fileName);
}

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V3 certificate to use as an intermediate CA certificate
 * @param intKey// w  w  w.j a v a 2s  . c  om
 * @param caKey
 * @param caCert
 * @return 
 * @throws java.lang.Exception 
 */
public static X509CertificateHolder buildIntermediateCert(AsymmetricKeyParameter intKey,
        AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception {
    SubjectPublicKeyInfo intKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(intKey);

    X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            new X500Name("CN=Test CA Certificate"), intKeyInfo);

    X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator());

    certBldr.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extUtils.createSubjectKeyIdentifier(intKeyInfo))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(0))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey);

    return certBldr.build(signer);
}

From source file:beta01.SimpleRootCA.java

/**
 * Build a sample V3 certificate to use as an end entity certificate
 *//*from www  .  ja va  2 s  . c  om*/
public static X509CertificateHolder buildEndEntityCert(AsymmetricKeyParameter entityKey,
        AsymmetricKeyParameter caKey, X509CertificateHolder caCert) throws Exception {
    SubjectPublicKeyInfo entityKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo(entityKey);

    X509v3CertificateBuilder certBldr = new X509v3CertificateBuilder(caCert.getSubject(), BigInteger.valueOf(1),
            new Date(System.currentTimeMillis()), new Date(System.currentTimeMillis() + VALIDITY_PERIOD),
            new X500Name("CN=Test End Entity Certificate"), entityKeyInfo);

    X509ExtensionUtils extUtils = new X509ExtensionUtils(new SHA1DigestCalculator());

    certBldr.addExtension(Extension.authorityKeyIdentifier, false,
            extUtils.createAuthorityKeyIdentifier(caCert))
            .addExtension(Extension.subjectKeyIdentifier, false,
                    extUtils.createSubjectKeyIdentifier(entityKeyInfo))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(false))
            .addExtension(Extension.keyUsage, true,
                    new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));

    AlgorithmIdentifier sigAlg = algFinder.find("SHA1withRSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    ContentSigner signer = new BcRSAContentSignerBuilder(sigAlg, digAlg).build(caKey);

    return certBldr.build(signer);
}

From source file:ca.nrc.cadc.cred.CertUtil.java

License:Open Source License

/**
 * Method that generates an X509 proxy certificate
 * //from  w  w  w. jav  a2s  .c o m
 * @param csr CSR for the certificate
 * @param lifetime lifetime of the certificate in SECONDS
 * @param chain certificate used to sign the proxy certificate
 * @return generated proxy certificate
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CertificateParsingException
 * @throws CertificateEncodingException
 * @throws SignatureException
 * @throws CertificateNotYetValidException
 * @throws CertificateExpiredException
 */
public static X509Certificate generateCertificate(PKCS10CertificationRequest csr, int lifetime,
        X509CertificateChain chain) throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, CertificateParsingException, CertificateEncodingException, SignatureException,
        CertificateExpiredException, CertificateNotYetValidException {
    X509Certificate issuerCert = chain.getChain()[0];
    PrivateKey issuerKey = chain.getPrivateKey();

    Security.addProvider(new BouncyCastleProvider());

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(issuerCert.getSubjectX500Principal());

    // generate the proxy DN as the issuerDN + CN=random number
    Random rand = new Random();
    String issuerDN = issuerCert.getSubjectX500Principal().getName(X500Principal.RFC2253);
    String delegDN = String.valueOf(Math.abs(rand.nextInt()));
    String proxyDn = "CN=" + delegDN + "," + issuerDN;
    certGen.setSubjectDN(new X500Principal(proxyDn));

    // set validity
    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    // Start date. Allow for a sixty five minute clock skew here.
    date.add(Calendar.MINUTE, -65);
    Date beforeDate = date.getTime();
    for (X509Certificate currentCert : chain.getChain()) {
        if (beforeDate.before(currentCert.getNotBefore())) {
            beforeDate = currentCert.getNotBefore();
        }
    }
    certGen.setNotBefore(beforeDate);

    // End date.
    // If hours = 0, then cert lifetime is set to that of user cert
    if (lifetime <= 0) {
        // set the validity of certificates as the minimum
        // of the certificates in the chain
        Date afterDate = issuerCert.getNotAfter();
        for (X509Certificate currentCert : chain.getChain()) {
            if (afterDate.after(currentCert.getNotAfter())) {
                afterDate = currentCert.getNotAfter();
            }
        }
        certGen.setNotAfter(afterDate);
    } else {
        // check the validity of the signing certificate
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        for (X509Certificate currentCert : chain.getChain()) {
            currentCert.checkValidity(date.getTime());
        }

        certGen.setNotAfter(date.getTime());
    }

    certGen.setPublicKey(csr.getPublicKey());
    // TODO: should be able to get signature algorithm from the csr, but... obtuse
    certGen.setSignatureAlgorithm(DEFAULT_SIGNATURE_ALGORITHM);

    // extensions
    // add ProxyCertInfo extension to the new cert

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

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

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

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

    // add the Proxy Certificate Information
    // I expect this code to be removed once support to proxy
    // certificates is provided in Bouncy Castle.

    // create a proxy policy
    // types of proxy certificate policies - see RFC3820
    // impersonates the user
    final DERObjectIdentifier IMPERSONATION = new DERObjectIdentifier("1.3.6.1.5.5.7.21.1");
    // independent
    // final DERObjectIdentifier INDEPENDENT = new
    // DERObjectIdentifier(
    // "1.3.6.1.5.5.7.21.2");
    // defined by a policy language
    // final DERObjectIdentifier LIMITED = new DERObjectIdentifier(
    // "1.3.6.1.4.1.3536.1.1.1.9");

    ASN1EncodableVector policy = new ASN1EncodableVector();
    policy.add(IMPERSONATION);

    // pathLengthConstr (RFC3820)
    // The pCPathLenConstraint field, if present, specifies the
    // maximum
    // depth of the path of Proxy Certificates that can be signed by
    // this
    // Proxy Certificate. A pCPathLenConstraint of 0 means that this
    // certificate MUST NOT be used to sign a Proxy Certificate. If
    // the
    // pCPathLenConstraint field is not present then the maximum proxy
    // path
    // length is unlimited. End entity certificates have unlimited
    // maximum
    // proxy path lengths.
    // DERInteger pathLengthConstr = new DERInteger(100);

    // create the proxy certificate information
    ASN1EncodableVector vec = new ASN1EncodableVector();
    // policy.add(pathLengthConstr);
    vec.add(new DERSequence(policy));

    // OID
    final DERObjectIdentifier OID = new DERObjectIdentifier("1.3.6.1.5.5.7.1.14");
    certGen.addExtension(OID, true, new DERSequence(vec));

    return certGen.generate(issuerKey, "BC");
}

From source file:chapter6.PKCS10CertCreateExample.java

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") == false) {
        System.out.println("Request failed to verify!!");
        System.exit(1);//  w  w w .j  a va2 s  .co  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(new X500Principal(request.getCertificationRequestInfo().getSubject().getEncoded()));
    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:chapter6.X509V3CreateExample.java

public static X509Certificate generateV3Certificate(KeyPair pair) throws Exception {
    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");

    // Extension ::= SEQUENCE {
    //  extnID      OBJECT IDENTIFIER,
    //  critical    BOOLEAN DEFAULT FALSE
    //  extnValue   OCTET STRING }
    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(), CryptoDefs.Provider.BC.getName());
}

From source file:chapter7.Utils.java

/**
 * Generate a sample V3 certificate to use as an intermediate CA certificate.
 * @param intKey/*from  w w w.  j a  v a 2  s . c o  m*/
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509Certificate generateIntermediateCert(final PublicKey intKey, final PrivateKey caKey,
        final X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.ONE);
    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, CryptoDefs.Provider.BC.getName());
}

From source file:chapter7.Utils.java

/**
 * Generate a sample V3 certificate to use as an end entity certificate.
 * @param entityKey/*from www . ja v  a  2  s  .  c  o m*/
 * @param caKey
 * @param caCert
 * @return
 * @throws Exception
 */
public static X509Certificate generateEndEntityCert(final PublicKey entityKey, final PrivateKey caKey,
        final X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    certGen.setSerialNumber(BigInteger.ONE);
    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, CryptoDefs.Provider.BC.getName());
}