Example usage for org.bouncycastle.x509 X509V3CertificateGenerator generateX509Certificate

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

Introduction

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

Prototype

public X509Certificate generateX509Certificate(PrivateKey key)
        throws SecurityException, SignatureException, InvalidKeyException 

Source Link

Document

generate an X509 certificate, based on the current issuer and subject using the default provider "BC".

Usage

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);//from  w w  w  .jav  a2 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:com.integralblue.httpresponsecache.compat.java.security.TestKeyStore.java

License:Apache License

private static X509Certificate createCertificate(PublicKey publicKey, PrivateKey privateKey,
        X500Principal subject, X500Principal issuer, int keyUsage, boolean ca,
        List<GeneralName> subjectAltNames, Vector<GeneralSubtree> permittedNameConstraints,
        Vector<GeneralSubtree> excludedNameConstraints) throws Exception {
    // Note that there is no way to programmatically make a
    // Certificate using java.* or javax.* APIs. The
    // CertificateFactory interface assumes you want to read
    // in a stream of bytes, typically the X.509 factory would
    // allow ASN.1 DER encoded bytes and optionally some PEM
    // formats. Here we use Bouncy Castle's
    // X509V3CertificateGenerator and related classes.

    long millisPerDay = 24 * 60 * 60 * 1000;
    long now = System.currentTimeMillis();
    Date start = new Date(now - millisPerDay);
    Date end = new Date(now + millisPerDay);
    BigInteger serial = BigInteger.valueOf(1);

    String keyAlgorithm = privateKey.getAlgorithm();
    String signatureAlgorithm;//from www.ja v a2 s. co m
    if (keyAlgorithm.equals("RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else if (keyAlgorithm.equals("DSA")) {
        signatureAlgorithm = "sha1WithDSA";
    } else if (keyAlgorithm.equals("EC")) {
        signatureAlgorithm = "sha1WithECDSA";
    } else if (keyAlgorithm.equals("EC_RSA")) {
        signatureAlgorithm = "sha1WithRSA";
    } else {
        throw new IllegalArgumentException("Unknown key algorithm " + keyAlgorithm);
    }

    X509V3CertificateGenerator x509cg = new X509V3CertificateGenerator();
    x509cg.setSubjectDN(subject);
    x509cg.setIssuerDN(issuer);
    x509cg.setNotBefore(start);
    x509cg.setNotAfter(end);
    x509cg.setPublicKey(publicKey);
    x509cg.setSignatureAlgorithm(signatureAlgorithm);
    x509cg.setSerialNumber(serial);
    if (keyUsage != 0) {
        x509cg.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(keyUsage));
    }
    if (ca) {
        x509cg.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    }
    for (GeneralName subjectAltName : subjectAltNames) {
        x509cg.addExtension(X509Extensions.SubjectAlternativeName, false,
                new GeneralNames(subjectAltName).getEncoded());
    }
    if (!permittedNameConstraints.isEmpty() || !excludedNameConstraints.isEmpty()) {
        x509cg.addExtension(X509Extensions.NameConstraints, true,
                new NameConstraints(permittedNameConstraints, excludedNameConstraints));
    }

    if (privateKey instanceof ECPrivateKey) {
        /*
         * bouncycastle needs its own ECPrivateKey implementation
         */
        KeyFactory kf = KeyFactory.getInstance(keyAlgorithm, "BC");
        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(privateKey.getEncoded());
        privateKey = kf.generatePrivate(ks);
    }
    X509Certificate x509c = x509cg.generateX509Certificate(privateKey);
    if (StandardNames.IS_RI) {
        /*
         * The RI can't handle the BC EC signature algorithm
         * string of "ECDSA", since it expects "...WITHEC...",
         * so convert from BC to RI X509Certificate
         * implementation via bytes.
         */
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        ByteArrayInputStream bais = new ByteArrayInputStream(x509c.getEncoded());
        Certificate c = cf.generateCertificate(bais);
        x509c = (X509Certificate) c;
    }
    return x509c;
}

From source file:com.kixeye.chassis.transport.shared.JettyConnectorRegistry.java

License:Apache License

/**
 * Register to listen to HTTPS./*from  w  w  w . j a v a  2  s  .c  o  m*/
 * 
 * @param server
 * @param address
 * @throws Exception 
 */
public static void registerHttpsConnector(Server server, InetSocketAddress address, boolean selfSigned,
        boolean mutualSsl, String keyStorePath, String keyStoreData, String keyStorePassword,
        String keyManagerPassword, String trustStorePath, String trustStoreData, String trustStorePassword,
        String[] excludedCipherSuites) throws Exception {
    // SSL Context Factory
    SslContextFactory sslContextFactory = new SslContextFactory();

    if (selfSigned) {
        char[] passwordChars = UUID.randomUUID().toString().toCharArray();

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

        keyStore.load(null, passwordChars);

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

        v3CertGen.setSerialNumber(BigInteger.valueOf(new SecureRandom().nextInt()).abs());
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "kixeye.com" + ", OU=None, O=None L=None, C=None"));

        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

        X509Certificate privateKeyCertificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        keyStore.setKeyEntry("selfSigned", keyPair.getPrivate(), passwordChars,
                new java.security.cert.Certificate[] { privateKeyCertificate });

        ByteArrayOutputStream keyStoreBaos = new ByteArrayOutputStream();
        keyStore.store(keyStoreBaos, passwordChars);

        keyStoreData = new String(Hex.encode(keyStoreBaos.toByteArray()), Charsets.UTF_8);
        keyStorePassword = new String(passwordChars);
        keyManagerPassword = keyStorePassword;

        sslContextFactory.setTrustAll(true);
    }

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

    if (StringUtils.isNotBlank(keyStoreData)) {
        keyStore.load(new ByteArrayInputStream(Hex.decode(keyStoreData)), keyStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(keyStorePath)) {
        try (InputStream inputStream = new DefaultResourceLoader().getResource(keyStorePath).getInputStream()) {
            keyStore.load(inputStream, keyStorePassword.toCharArray());
        }
    }

    sslContextFactory.setKeyStore(keyStore);
    sslContextFactory.setKeyStorePassword(keyStorePassword);
    if (StringUtils.isBlank(keyManagerPassword)) {
        keyManagerPassword = keyStorePassword;
    }
    sslContextFactory.setKeyManagerPassword(keyManagerPassword);
    KeyStore trustStore = null;
    if (StringUtils.isNotBlank(trustStoreData)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(new ByteArrayInputStream(Hex.decode(trustStoreData)), trustStorePassword.toCharArray());
    } else if (StringUtils.isNotBlank(trustStorePath)) {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream inputStream = new DefaultResourceLoader().getResource(trustStorePath)
                .getInputStream()) {
            trustStore.load(inputStream, trustStorePassword.toCharArray());
        }
    }
    if (trustStore != null) {
        sslContextFactory.setTrustStore(trustStore);
        sslContextFactory.setTrustStorePassword(trustStorePassword);
    }
    sslContextFactory.setNeedClientAuth(mutualSsl);
    sslContextFactory.setExcludeCipherSuites(excludedCipherSuites);

    // SSL Connector
    ServerConnector connector = new ServerConnector(server,
            new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.toString()),
            new HttpConnectionFactory());
    connector.setHost(address.getHostName());
    connector.setPort(address.getPort());

    server.addConnector(connector);
}

From source file:com.trsst.Command.java

License:Apache License

private static final X509Certificate createCertificate(KeyPair keyPair, String algorithm) {
    org.bouncycastle.x509.X509V3CertificateGenerator certGen = new org.bouncycastle.x509.X509V3CertificateGenerator();

    long now = System.currentTimeMillis();
    certGen.setSerialNumber(java.math.BigInteger.valueOf(now));

    org.bouncycastle.jce.X509Principal subject = new org.bouncycastle.jce.X509Principal(
            "CN=Trsst Keystore,DC=trsst,DC=com");
    certGen.setIssuerDN(subject);/*from  w w  w  . j  a  v  a 2  s  . c  om*/
    certGen.setSubjectDN(subject);

    Date fromDate = new java.util.Date(now);
    certGen.setNotBefore(fromDate);
    Calendar cal = new java.util.GregorianCalendar();
    cal.setTime(fromDate);
    cal.add(java.util.Calendar.YEAR, 100);
    Date toDate = cal.getTime();
    certGen.setNotAfter(toDate);

    certGen.setPublicKey(keyPair.getPublic());
    certGen.setSignatureAlgorithm(algorithm);
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.BasicConstraints, true,
            new org.bouncycastle.asn1.x509.BasicConstraints(false));
    certGen.addExtension(org.bouncycastle.asn1.x509.X509Extensions.KeyUsage, true,
            new org.bouncycastle.asn1.x509.KeyUsage(org.bouncycastle.asn1.x509.KeyUsage.digitalSignature
                    | org.bouncycastle.asn1.x509.KeyUsage.keyEncipherment
                    | org.bouncycastle.asn1.x509.KeyUsage.keyCertSign
                    | org.bouncycastle.asn1.x509.KeyUsage.cRLSign));
    X509Certificate x509 = null;
    try {
        x509 = certGen.generateX509Certificate(keyPair.getPrivate());
    } catch (InvalidKeyException e) {
        log.error("Error generating certificate: invalid key", e);
    } catch (SecurityException e) {
        log.error("Unexpected error generating certificate", e);
    } catch (SignatureException e) {
        log.error("Error generating generating certificate signature", e);
    }
    return x509;
}

From source file:de.perdian.apps.devlauncher.impl.ConnectorListener.java

License:Apache License

private Key ensureKeyInStore(Path keystoreFile, KeyStore keyStore)
        throws GeneralSecurityException, IOException {
    Key key = this.lookupKeyFromStore(keyStore);
    if (key == null) {

        log.info("Creating new TLS key to enable HTTPS access");

        // No key available, so we have to create the key from scratch and
        // make it available in the store
        Security.addProvider(new BouncyCastleProvider());
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(1024);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
        v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        v3CertGen.setIssuerDN(new X509Principal("CN=" + "localhost" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
        v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
        v3CertGen.setSubjectDN(new X509Principal("CN=" + "localhost" + ", OU=None, O=None L=None, C=None"));
        v3CertGen.setPublicKey(keyPair.getPublic());
        v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
        X509Certificate certificate = v3CertGen.generateX509Certificate(keyPair.getPrivate());

        // Store the key (including the certificate) into the keystore
        keyStore.setKeyEntry(TLS_KEY_NAME, keyPair.getPrivate(), TLS_KEY_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        // Write the keystore into the target file
        log.debug("Updating KeyStore at: " + keystoreFile);
        if (!Files.exists(keystoreFile.getParent())) {
            Files.createDirectories(keystoreFile.getParent());
        }/*w  w w  . j  a  va2  s.  co  m*/
        try (OutputStream keyStoreStream = new BufferedOutputStream(Files.newOutputStream(keystoreFile))) {
            keyStore.store(keyStoreStream, KEYSTORE_PASSWORD.toCharArray());
            keyStoreStream.flush();
        }

    }
    return key;
}

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  www.j  a  v  a2 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(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:org.everit.osgi.keystore.file.tests.KeyStoreUtil.java

License:Open Source License

private static Certificate generateCertificate(final PrivateKey privateKey, final PublicKey publicKey,
        final String signatureAlgorithm) throws Exception {
    Calendar calendar = Calendar.getInstance();
    Date notBefore = calendar.getTime();
    calendar.add(Calendar.MINUTE, 1);
    Date notAfter = calendar.getTime();

    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
    v3CertGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    v3CertGen.setIssuerDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C=c"));
    v3CertGen.setNotBefore(notBefore);//w w w.j  a  v  a2 s . c  o m
    v3CertGen.setNotAfter(notAfter);
    v3CertGen.setSubjectDN(new X509Principal("CN=cn, O=o, L=L, ST=il, C=c"));
    v3CertGen.setPublicKey(publicKey);
    v3CertGen.setSignatureAlgorithm(signatureAlgorithm);
    return v3CertGen.generateX509Certificate(privateKey);
}

From source file:org.geoserver.web.Start.java

License:Open Source License

private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password)
        throws Exception {

    KeyStore privateKS = KeyStore.getInstance("JKS");
    if (keyStoreFile.exists()) {
        FileInputStream fis = new FileInputStream(keyStoreFile);
        privateKS.load(fis, password.toCharArray());
        if (keyStoreContainsCertificate(privateKS, hostname))
            return;
    } else {/*  w w w.j a  va  2  s.c  o  m*/
        privateKS.load(null);
    }

    // create a RSA key pair generator using 1024 bits

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair KPair = keyPairGenerator.generateKeyPair();

    // cerate a X509 certifacte generator
    X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();

    // set validity to 10 years, issuer and subject are equal --> self singed certificate
    int random = new SecureRandom().nextInt();
    if (random < 0)
        random *= -1;
    v3CertGen.setSerialNumber(BigInteger.valueOf(random));
    v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None"));
    v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));
    v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10)));
    v3CertGen.setSubjectDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None"));

    v3CertGen.setPublicKey(KPair.getPublic());
    v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");

    X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate());

    // store the certificate containing the public key,this file is needed
    // to import the public key in other key store. 
    File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert");
    FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile());
    fos.write(PKCertificate.getEncoded());
    fos.close();

    privateKS.setKeyEntry(hostname + ".key", KPair.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { PKCertificate });

    privateKS.setCertificateEntry(hostname + ".cert", PKCertificate);

    privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray());
}

From source file:org.glite.security.delegation.GrDProxyGenerator.java

License:Apache License

/**
 * Create a proxy certificate from a given certificate
 * // w  w w  . j  a  v a  2 s.  c o  m
 * @param issuerCert
 *            issuer certificate
 * @param issuerKey
 *            issuer private key
 * @param publicKey
 *            public key of delegatee
 * @param lifetime
 *            life time of proxy
 * @param proxyType
 *            type of proxy
 * @param cnValue
 *            common name of proxy
 * @return created proxy certificate
 * @throws GeneralSecurityException
 * @deprecated Use proxy generator from util-java
 */
public X509Certificate createProxyCertificate(X509Certificate issuerCert, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime1, int proxyType1, String cnValue) throws GeneralSecurityException {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    BigInteger serialNum = null;
    serialNum = issuerCert.getSerialNumber();

    X509Name issuer = (X509Name) issuerCert.getSubjectDN();

    ASN1Sequence seqSubject = (ASN1Sequence) issuer.getDERObject();

    logger.debug("SubjectDN of IssuerCert" + issuer);

    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(X509Name.CN);
    v.add(new DERPrintableString(cnValue));

    Enumeration subjectParts = seqSubject.getObjects();

    ASN1EncodableVector subjectVector = new ASN1EncodableVector();

    while (subjectParts.hasMoreElements()) {
        DERObject part = (DERObject) subjectParts.nextElement();
        subjectVector.add(part);
    }

    subjectVector.add(new DERSet(new DERSequence(v)));

    DERSequence subjDerSeq = new DERSequence(subjectVector);

    X509Name subjectX = new X509Name(subjDerSeq);

    logger.debug("SubjectDN :" + subjectX);

    certGen.setSubjectDN(subjectX);
    certGen.setIssuerDN(issuer);

    certGen.setSerialNumber(serialNum);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm(issuerCert.getSigAlgName());
    certGen.addExtension(X509Extensions.KeyUsage, false,
            new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.digitalSignature));

    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("UTC"));

    date.add(Calendar.MINUTE, -5);
    certGen.setNotBefore(date.getTime());

    if (lifetime1 <= 0) {
        certGen.setNotAfter(issuerCert.getNotAfter());
    } else {
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime1);
        certGen.setNotAfter(date.getTime());
    }

    return certGen.generateX509Certificate(issuerKey);
}

From source file:org.globus.gsi.bc.BouncyCastleCertProcessingFactory.java

License:Apache License

/**
 * Creates a proxy certificate. A set of X.509 extensions can be optionally included in the new proxy
 * certificate. <BR>//from  ww  w .j  a  v a 2  s . c  o  m
 * If a GSI-2 proxy is created, the serial number of the proxy certificate will be the same as of the
 * issuing certificate. Also, none of the extensions in the issuing certificate will be copied into the
 * proxy certificate.<BR>
 * If a GSI-3 or GSI 4 proxy is created, the serial number of the proxy certificate will be picked
 * randomly. If the issuing certificate contains a <i>KeyUsage</i> extension, the extension will be copied
 * into the proxy certificate with <i>keyCertSign</i> and <i>nonRepudiation</i> bits turned off. No other
 * extensions are currently copied.
 *
 * The methods defaults to creating GSI 4 proxy
 *
 * @param issuerCert_
 *            the issuing certificate
 * @param issuerKey
 *            private key matching the public key of issuer certificate. The new proxy certificate will be
 *            signed by that key.
 * @param publicKey
 *            the public key of the new certificate
 * @param lifetime
 *            lifetime of the new certificate in seconds. If 0 (or less then) the new certificate will
 *            have the same lifetime as the issuing certificate.
 * @param proxyType
 *            can be one of {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED},
 *            {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL},
 *
 *            {@link GSIConstants#GSI_2_LIMITED_PROXY GSIConstants.GSI_2_LIMITED_PROXY},
 *            {@link GSIConstants#GSI_2_PROXY GSIConstants.GSI_2_PROXY},
 *            {@link GSIConstants#GSI_3_IMPERSONATION_PROXY GSIConstants.GSI_3_IMPERSONATION_PROXY},
 *            {@link GSIConstants#GSI_3_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY},
 *            {@link GSIConstants#GSI_3_INDEPENDENT_PROXY GSIConstants.GSI_3_INDEPENDENT_PROXY},
 *            {@link GSIConstants#GSI_3_RESTRICTED_PROXY GSIConstants.GSI_3_RESTRICTED_PROXY}.
 *            {@link GSIConstants#GSI_4_IMPERSONATION_PROXY GSIConstants.GSI_4_IMPERSONATION_PROXY},
 *            {@link GSIConstants#GSI_4_LIMITED_PROXY GSIConstants.GSI_3_LIMITED_PROXY},
 *            {@link GSIConstants#GSI_4_INDEPENDENT_PROXY GSIConstants.GSI_4_INDEPENDENT_PROXY},
 *            {@link GSIConstants#GSI_4_RESTRICTED_PROXY GSIConstants.GSI_4_RESTRICTED_PROXY}.
 *
 *            If {@link GSIConstants#DELEGATION_LIMITED GSIConstants.DELEGATION_LIMITED} and if
 *            {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 limited
 *            proxy will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled}
 *            returns true then a GSI-3 limited proxy will be created. If not, a GSI-4 limited proxy will
 *            be created.
 *
 *            If {@link GSIConstants#DELEGATION_FULL GSIConstants.DELEGATION_FULL} and if
 *            {@link VersionUtil#isGsi2Enabled() CertUtil.isGsi2Enabled} returns true then a GSI-2 full proxy
 *            will be created. Else if {@link VersionUtil#isGsi3Enabled() CertUtil.isGsi3Enabled} returns
 *            true then a GSI-3 full proxy will be created. If not, a GSI-4 full proxy will be created.
 *
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link GSIConstants#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.GSI_3_RESTRICTED_PROXY} or {@link GSIConstants#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.GSI_4_RESTRICTED_PROXY} then
 *            {@link org.globus.gsi.proxy.ext.ProxyCertInfoExtension ProxyCertInfoExtension} must be
 *            present in the extension set.
 *
 * @param cnValue
 *            the value of the CN component of the subject of the new certificate. If null, the defaults
 *            will be used depending on the proxy certificate type created.
 * @return <code>X509Certificate</code> the new proxy certificate.
 * @exception GeneralSecurityException
 *                if a security error occurs.
 * @deprecated
 */
public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue)
        throws GeneralSecurityException {

    X509Certificate issuerCert = issuerCert_;
    if (!(issuerCert_ instanceof X509CertificateObject)) {
        issuerCert = CertificateLoadUtil.loadCertificate(new ByteArrayInputStream(issuerCert.getEncoded()));
    }

    if (proxyType == GSIConstants.DELEGATION_LIMITED) {
        GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (ProxyCertificateUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_LIMITED_PROXY;
        } else if (ProxyCertificateUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_LIMITED_PROXY;
        } else if (ProxyCertificateUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_LIMITED_PROXY;
        } else {
            // default to RFC compliant proxy
            if (VersionUtil.isGsi2Enabled()) {
                proxyType = GSIConstants.GSI_2_LIMITED_PROXY;
            } else {
                proxyType = VersionUtil.isGsi3Enabled() ? GSIConstants.GSI_3_LIMITED_PROXY
                        : GSIConstants.GSI_4_LIMITED_PROXY;
            }
        }
    } else if (proxyType == GSIConstants.DELEGATION_FULL) {
        GSIConstants.CertificateType type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (ProxyCertificateUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY;
        } else if (ProxyCertificateUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY;
        } else if (ProxyCertificateUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_PROXY;
        } else {
            // Default to RFC complaint proxy
            if (VersionUtil.isGsi2Enabled()) {
                proxyType = GSIConstants.GSI_2_PROXY;
            } else {
                proxyType = (VersionUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY
                        : GSIConstants.GSI_4_IMPERSONATION_PROXY;
            }
        }
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    org.globus.gsi.X509Extension x509Ext = null;
    BigInteger serialNum = null;
    String delegDN = null;

    if (ProxyCertificateUtil.isGsi3Proxy(GSIConstants.CertificateType.get(proxyType))
            || ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(proxyType))) {
        Random rand = new Random();
        delegDN = String.valueOf(Math.abs(rand.nextInt()));
        serialNum = new BigInteger(20, rand);

        if (extSet != null) {
            x509Ext = extSet.get(ProxyCertInfo.OID.getId());
            if (x509Ext == null) {
                x509Ext = extSet.get(ProxyCertInfo.OLD_OID.getId());
            }
        }

        if (x509Ext == null) {
            // create ProxyCertInfo extension
            ProxyPolicy policy = null;
            if (ProxyCertificateUtil.isLimitedProxy(GSIConstants.CertificateType.get(proxyType))) {
                policy = new ProxyPolicy(ProxyPolicy.LIMITED);
            } else if (ProxyCertificateUtil.isIndependentProxy(GSIConstants.CertificateType.get(proxyType))) {
                policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT);
            } else if (ProxyCertificateUtil.isImpersonationProxy(GSIConstants.CertificateType.get(proxyType))) {
                // since limited has already been checked, this should work.
                policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION);
            } else if ((proxyType == GSIConstants.GSI_3_RESTRICTED_PROXY)
                    || (proxyType == GSIConstants.GSI_4_RESTRICTED_PROXY)) {
                String err = i18n.getMessage("restrictProxy");
                throw new IllegalArgumentException(err);
            } else {
                String err = i18n.getMessage("invalidProxyType");
                throw new IllegalArgumentException(err);
            }

            ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy);
            x509Ext = new ProxyCertInfoExtension(proxyCertInfo);
            if (ProxyCertificateUtil.isGsi4Proxy(GSIConstants.CertificateType.get(proxyType))) {
                // RFC compliant OID
                x509Ext = new ProxyCertInfoExtension(proxyCertInfo);
            } else {
                // old OID
                x509Ext = new GlobusProxyCertInfoExtension(proxyCertInfo);
            }
        }

        try {
            // add ProxyCertInfo extension to the new cert
            certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue());

            // handle KeyUsage in issuer cert
            TBSCertificateStructure crt = BouncyCastleUtil.getTBSCertificateStructure(issuerCert);

            X509Extensions extensions = crt.getExtensions();
            if (extensions != null) {
                X509Extension ext;

                // handle key usage ext
                ext = extensions.getExtension(X509Extension.keyUsage);
                if (ext != null) {

                    // TBD: handle this better
                    if (extSet != null && (extSet.get(X509Extension.keyUsage.getId()) != null)) {
                        String err = i18n.getMessage("keyUsageExt");
                        throw new GeneralSecurityException(err);
                    }

                    DERBitString bits = (DERBitString) BouncyCastleUtil.getExtensionObject(ext);

                    byte[] bytes = bits.getBytes();

                    // make sure they are disabled
                    if ((bytes[0] & KeyUsage.nonRepudiation) != 0) {
                        bytes[0] ^= KeyUsage.nonRepudiation;
                    }

                    if ((bytes[0] & KeyUsage.keyCertSign) != 0) {
                        bytes[0] ^= KeyUsage.keyCertSign;
                    }

                    bits = new DERBitString(bytes, bits.getPadBits());

                    certGen.addExtension(X509Extension.keyUsage, ext.isCritical(), bits);
                }
            }

        } catch (IOException e) {
            // but this should not happen
            throw new GeneralSecurityException(e.getMessage());
        }

    } else if (proxyType == GSIConstants.GSI_2_LIMITED_PROXY) {
        delegDN = "limited proxy";
        serialNum = issuerCert.getSerialNumber();
    } else if (proxyType == GSIConstants.GSI_2_PROXY) {
        delegDN = "proxy";
        serialNum = issuerCert.getSerialNumber();
    } else {
        String err = i18n.getMessage("unsupportedProxy", Integer.toString(proxyType));
        throw new IllegalArgumentException(err);
    }

    // add specified extensions
    if (extSet != null) {
        Iterator iter = extSet.oidSet().iterator();
        while (iter.hasNext()) {
            String oid = (String) iter.next();
            // skip ProxyCertInfo extension
            if (oid.equals(ProxyCertInfo.OID.getId()) || oid.equals(ProxyCertInfo.OLD_OID.getId())) {
                continue;
            }
            x509Ext = (org.globus.gsi.X509Extension) extSet.get(oid);
            certGen.addExtension(x509Ext.getOid(), x509Ext.isCritical(), x509Ext.getValue());
        }
    }

    X509Name issuerDN;
    if (issuerCert.getSubjectDN() instanceof X509Name) {
        issuerDN = (X509Name) issuerCert.getSubjectDN();
    } else {
        issuerDN = new X509Name(true, issuerCert.getSubjectX500Principal().getName());
    }

    X509NameHelper issuer = new X509NameHelper(issuerDN);

    X509NameHelper subject = new X509NameHelper(issuerDN);
    subject.add(BCStyle.CN, (cnValue == null) ? delegDN : cnValue);

    certGen.setSubjectDN(subject.getAsName());
    certGen.setIssuerDN(issuer.getAsName());

    certGen.setSerialNumber(serialNum);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm(issuerCert.getSigAlgName());

    GregorianCalendar date = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
    /* Allow for a five minute clock skew here. */
    date.add(Calendar.MINUTE, -5);
    certGen.setNotBefore(date.getTime());

    /* If hours = 0, then cert lifetime is set to user cert */
    if (lifetime <= 0) {
        certGen.setNotAfter(issuerCert.getNotAfter());
    } else {
        date.add(Calendar.MINUTE, 5);
        date.add(Calendar.SECOND, lifetime);
        certGen.setNotAfter(date.getTime());
    }

    return certGen.generateX509Certificate(issuerKey);
}