Example usage for org.bouncycastle.x509 X509V3CertificateGenerator addExtension

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

Introduction

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

Prototype

public void addExtension(ASN1ObjectIdentifier oid, boolean critical, byte[] value) 

Source Link

Document

add a given extension field for the standard extensions tag (tag 3)

Usage

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

License:Apache License

/**
 * Generates a fresh Certificate for a Users KeyPair.
 * /* www  .j a  v a2 s . c om*/
 * @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:brooklyn.util.crypto.FluentKeySigner.java

License:Apache License

public X509Certificate newCertificateFor(X500Principal subject, PublicKey keyToCertify) {
    try {// w  w  w  .  ja v  a2 s  . co m
        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(serialNumber != null ? serialNumber :
        // must be positive
                BigInteger.valueOf(srand.nextLong()).abs().add(BigInteger.ONE));
        v3CertGen.setIssuerDN(issuerPrincipal);
        v3CertGen.setNotBefore(validityStartDate);
        v3CertGen.setNotAfter(validityEndDate);
        v3CertGen.setSignatureAlgorithm(signatureAlgorithm);

        v3CertGen.setSubjectDN(subject);
        v3CertGen.setPublicKey(keyToCertify);

        v3CertGen.addExtension(X509Extension.subjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keyToCertify));

        if (authorityKeyIdentifier != null)
            v3CertGen.addExtension(X509Extension.authorityKeyIdentifier, false, authorityKeyIdentifier);

        X509Certificate pkCertificate = v3CertGen.generate(issuerKey.getPrivate(), "BC");
        return pkCertificate;

    } catch (Exception e) {
        throw Exceptions.propagate(e);
    }
}

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

License:Open Source License

/**
 * Method that generates an X509 proxy certificate
 * /*from w  ww  . ja va2  s. c  om*/
 * @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);// www  .ja  v  a2 s.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(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/*ww w .  j  ava 2s .com*/
 * @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/*w ww.java 2 s .com*/
 * @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());
}

From source file:com.eucalyptus.auth.crypto.DefaultCryptoProvider.java

License:Open Source License

@Override
public X509Certificate generateCertificate(KeyPair keys, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey) {/*w ww  . j  av  a  2 s  . co  m*/
    signer = (signingKey == null ? signer : subjectDn);
    signingKey = (signingKey == null ? keys.getPrivate() : signingKey);
    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(keys.getPublic()));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(keys.getPublic());
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

From source file:com.eucalyptus.auth.util.KeyTool.java

License:Open Source License

public X509Certificate getCertificate(KeyPair keyPair, String certDn) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    X500Principal dnName = new X500Principal(certDn);

    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(dnName);//from w w  w .j  a  v  a 2s. com
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));

    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(this.keySigningAlgorithm);
    try {
        X509Certificate cert = certGen.generate(keyPair.getPrivate(), PROVIDER);
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        System.exit(-3);
        return null;
    }
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

License:Open Source License

@Override
public X509Certificate generateCertificate(PublicKey key, X500Principal subjectDn, X500Principal signer,
        PrivateKey signingKey, Date notAfter) {
    if (signingKey == null) {
        LOG.error("No signing key is provided");
        return null;
    }/*from   w  w w.  j  a  v  a2s  . c o m*/
    if (signer == null) {
        LOG.error("No signiner principal is specified");
        return null;
    }
    if (subjectDn == null) {
        LOG.error("No subject principal is specified");
        return null;
    }
    if (key == null) {
        LOG.error("No requesting key is specified");
        return null;
    }

    EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_CERTIFICATE, signer.toString(),
            subjectDn.toString()).info();
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setSerialNumber(BigInteger.valueOf(System.nanoTime()).shiftLeft(4)
            .add(BigInteger.valueOf((long) Math.rint(Math.random() * 1000))));
    certGen.setIssuerDN(signer);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    try {
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(key));
    } catch (InvalidKeyException e) {
        LOG.error("Error adding subject key identifier extension.", e);
    }
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    certGen.setNotAfter(notAfter);
    certGen.setSubjectDN(subjectDn);
    certGen.setPublicKey(key);
    certGen.setSignatureAlgorithm(KEY_SIGNING_ALGORITHM);
    try {
        X509Certificate cert = certGen.generate(signingKey, PROVIDER);
        cert.checkValidity();
        return cert;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}