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: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.  ja va 2s  .c om
 * 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);
}

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>/* w  w w . ja va 2s. c om*/
 * 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 certType
 *            can be one of {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_LIMITED_PROXY GSIConstants.CertificateType.GSI_2_LIMITED_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_2_PROXY GSIConstants.CertificateType.GSI_2_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_3_IMPERSONATION_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_3_INDEPENDENT_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY}.
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_IMPERSONATION_PROXY GSIConstants.CertificateType.GSI_4_IMPERSONATION_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_LIMITED_PROXY GSIConstants.CertificateType.GSI_3_LIMITED_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_INDEPENDENT_PROXY GSIConstants.CertificateType.GSI_4_INDEPENDENT_PROXY},
 *            {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY GSIConstants.CertificateType.GSI_4_RESTRICTED_PROXY}.
 *
 * @param extSet
 *            a set of X.509 extensions to be included in the new proxy certificate. Can be null. If
 *            delegation mode is {@link org.globus.gsi.GSIConstants.CertificateType#GSI_3_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY} or {@link org.globus.gsi.GSIConstants.CertificateType#GSI_4_RESTRICTED_PROXY
 *            GSIConstants.CertificateType.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.
 */
public X509Certificate createProxyCertificate(X509Certificate issuerCert_, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime, GSIConstants.CertificateType certType, X509ExtensionSet extSet,
        String cnValue) throws GeneralSecurityException {

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

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

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

    if (ProxyCertificateUtil.isGsi3Proxy(certType) || ProxyCertificateUtil.isGsi4Proxy(certType)) {
        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(certType)) {
                policy = new ProxyPolicy(ProxyPolicy.LIMITED);
            } else if (ProxyCertificateUtil.isIndependentProxy(certType)) {
                policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT);
            } else if (ProxyCertificateUtil.isImpersonationProxy(certType)) {
                // since limited has already been checked, this should work.
                policy = new ProxyPolicy(ProxyPolicy.IMPERSONATION);
            } else if ((certType == GSIConstants.CertificateType.GSI_3_RESTRICTED_PROXY)
                    || (certType == GSIConstants.CertificateType.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(certType)) {
                // 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 (certType == GSIConstants.CertificateType.GSI_2_LIMITED_PROXY) {
        delegDN = "limited proxy";
        serialNum = issuerCert.getSerialNumber();
    } else if (certType == GSIConstants.CertificateType.GSI_2_PROXY) {
        delegDN = "proxy";
        serialNum = issuerCert.getSerialNumber();
    } else {
        String err = i18n.getMessage("unsupportedProxy", certType);
        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);
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

License:Mozilla Public License

/**
 * Handles the nitty gritty of signing a CSR
 *
 * @param rootCert The certificate of the root authority who will vouch for the entity
 * @param rootPrivKey The private key of the root authority who will vouch for the entity
 * @param csr The entitie's CSR/*  ww w  .ja v a  2s .  co m*/
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return A certificate chain as an array of X509Certificate instances or null if an
 * error occurred
 */
private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey,
        PKCS10CertificationRequest csr, String keyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    try {
        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(rootCert.getSubjectX500Principal());
        certGen.setNotBefore(validFrom);
        certGen.setNotAfter(validTo);
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setPublicKey(csr.getPublicKey("BC"));

        if (keyType.toLowerCase().equals("rsa"))
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        if (keyType.toLowerCase().equals("dsa"))
            certGen.setSignatureAlgorithm("DSAWithSHA1");

        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(rootCert));
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.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_clientAuth));

        X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC");
        return new X509Certificate[] { issuedCert, rootCert };
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:org.jcryptool.visual.jctca.Util.java

License:Open Source License

public static X509Certificate certificateForKeyPair(String principal, String country, String street, String zip,
        String city, String unit, String organisation, String mail, PublicKey pub, PrivateKey priv,
        BigInteger serialNumber, X509Certificate caCert, Date expiryDate, Date startDate, PrivateKey caKey) {
    try {/*from   ww w.j a  v a2 s .  c om*/
        KeyPair keyPair = new KeyPair(pub, priv); // public/private key pair
                                                  // that we are creating
                                                  // certificate for

        X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
        X509Name subjectName = new X509Name("CN=" + principal + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "ST=" + street + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "L=" + zip + " " + city + ", " + "C=" + country + ", " + //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
                "OU=" + unit + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "O=" + organisation + ", " + //$NON-NLS-1$ //$NON-NLS-2$
                "E=" + mail); //$NON-NLS-1$

        certGen.setSerialNumber(serialNumber);
        if (caCert != null) {
            certGen.setIssuerDN(caCert.getSubjectX500Principal());
            certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                    new AuthorityKeyIdentifierStructure(caCert));
            // FIXME not working any more with BouncyCastle 1.51
            //                certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(
            //                        keyPair.getPublic()));
        } else {
            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.setNotBefore(startDate);
        certGen.setNotAfter(expiryDate);
        certGen.setSubjectDN(subjectName);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA512withRSA");//$NON-NLS-1$

        X509Certificate cert;

        cert = certGen.generate(caKey, "BC");//$NON-NLS-1$
        return cert;
    } catch (CertificateEncodingException e) {
        LogUtil.logError(e);
    } catch (InvalidKeyException e) {
        LogUtil.logError(e);
    } catch (IllegalStateException e) {
        LogUtil.logError(e);
    } catch (NoSuchProviderException e) {
        LogUtil.logError(e);
    } catch (NoSuchAlgorithmException e) {
        LogUtil.logError(e);
    } catch (SignatureException e) {
        LogUtil.logError(e);
    } catch (CertificateParsingException e) {
        LogUtil.logError(e);
    }

    return null;

    // note: private key of CA
}

From source file:org.jivesoftware.util.CertificateManager.java

License:Open Source License

/**
 * Creates an X509 version3 certificate.
 *
 * @param kp           KeyPair that keeps the public and private keys for the new certificate.
 * @param months       time to live//from  w w  w . ja  v a2  s .  c  o  m
 * @param issuerDN     Issuer string e.g "O=Grid,OU=OGSA,CN=ACME"
 * @param subjectDN    Subject string e.g "O=Grid,OU=OGSA,CN=John Doe"
 * @param domain       Domain of the server.
 * @param signAlgoritm Signature algorithm. This can be either a name or an OID.
 * @return X509 V3 Certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
private static synchronized X509Certificate createX509V3Certificate(KeyPair kp, int months, String issuerDN,
        String subjectDN, String domain, String signAlgoritm) throws GeneralSecurityException, IOException {
    PublicKey pubKey = kp.getPublic();
    PrivateKey privKey = kp.getPrivate();

    byte[] serno = new byte[8];
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
    random.setSeed((new Date().getTime()));
    random.nextBytes(serno);
    BigInteger serial = (new java.math.BigInteger(serno)).abs();

    X509V3CertificateGenerator certGenerator = new X509V3CertificateGenerator();
    certGenerator.reset();

    certGenerator.setSerialNumber(serial);
    certGenerator.setIssuerDN(new X509Name(issuerDN));
    certGenerator.setNotBefore(new Date(System.currentTimeMillis()));
    certGenerator.setNotAfter(new Date(System.currentTimeMillis() + months * (1000L * 60 * 60 * 24 * 30)));
    certGenerator.setSubjectDN(new X509Name(subjectDN));
    certGenerator.setPublicKey(pubKey);
    certGenerator.setSignatureAlgorithm(signAlgoritm);

    // Generate the subject alternative name
    boolean critical = subjectDN == null || "".equals(subjectDN.trim());
    ASN1Sequence othernameSequence = new DERSequence(
            new ASN1Encodable[] { new DERObjectIdentifier("1.3.6.1.5.5.7.8.5"),
                    new DERTaggedObject(true, 0, new DERUTF8String(domain)) });
    GeneralName othernameGN = new GeneralName(GeneralName.otherName, othernameSequence);
    GeneralNames subjectAltNames = new GeneralNames(new GeneralName[] { othernameGN });
    // Add subject alternative name extension
    certGenerator.addExtension(X509Extensions.SubjectAlternativeName, critical, subjectAltNames);

    X509Certificate cert = certGenerator.generateX509Certificate(privKey, "BC", new SecureRandom());
    cert.checkValidity(new Date());
    cert.verify(pubKey);

    return cert;
}

From source file:org.kopi.ebics.certificate.X509Generator.java

License:Open Source License

/**
 * Returns an <code>X509Certificate</code> from a given
 * <code>KeyPair</code> and limit dates validations
 * @param keypair the given key pair//from  w w  w. j a  v  a 2 s . c  o  m
 * @param issuer the certificate issuer
 * @param notBefore the begin validity date
 * @param notAfter the end validity date
 * @param keyusage the certificate key usage
 * @return the X509 certificate
 * @throws GeneralSecurityException
 * @throws IOException
 */
public X509Certificate generate(KeyPair keypair, String issuer, Date notBefore, Date notAfter, int keyusage)
        throws GeneralSecurityException, IOException {
    X509V3CertificateGenerator generator;
    BigInteger serial;
    X509Certificate certificate;
    ASN1EncodableVector vector;

    serial = BigInteger.valueOf(generateSerial());
    generator = new X509V3CertificateGenerator();
    generator.setSerialNumber(serial);
    generator.setIssuerDN(new X509Principal(issuer));
    generator.setNotBefore(notBefore);
    generator.setNotAfter(notAfter);
    generator.setSubjectDN(new X509Principal(issuer));
    generator.setPublicKey(keypair.getPublic());
    generator.setSignatureAlgorithm(X509Constants.SIGNATURE_ALGORITHM);
    generator.addExtension(X509Extensions.BasicConstraints, false, new BasicConstraints(true));
    generator.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            getSubjectKeyIdentifier(keypair.getPublic()));
    generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            getAuthorityKeyIdentifier(keypair.getPublic(), issuer, serial));
    vector = new ASN1EncodableVector();
    vector.add(KeyPurposeId.id_kp_emailProtection);

    generator.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(new DERSequence(vector)));

    switch (keyusage) {
    case X509Constants.SIGNATURE_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.nonRepudiation));
        break;
    case X509Constants.AUTHENTICATION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.digitalSignature));
        break;
    case X509Constants.ENCRYPTION_KEY_USAGE:
        generator.addExtension(X509Extensions.KeyUsage, false, new KeyUsage(KeyUsage.keyAgreement));
        break;
    default:
        generator.addExtension(X509Extensions.KeyUsage, false,
                new KeyUsage(KeyUsage.keyEncipherment | KeyUsage.digitalSignature));
        break;
    }

    certificate = generator.generate(keypair.getPrivate(), "BC", new SecureRandom());
    certificate.checkValidity(new Date());
    certificate.verify(keypair.getPublic());

    return certificate;
}

From source file:org.krakenapps.ca.util.CertificateBuilder.java

License:Apache License

public static X509Certificate createCertificate(CertificateRequest req) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    X509Principal subject = parseDn(req.getSubjectDn());
    X509Principal issuer = parseDn(req.getIssuerDn());

    certGen.setSerialNumber(req.getSerial());
    certGen.setIssuerDN(issuer);/*from www.j  a  va2s.c o  m*/
    certGen.setSubjectDN(subject);
    certGen.setNotBefore(req.getNotBefore());
    certGen.setNotAfter(req.getNotAfter());
    certGen.setPublicKey(req.getKeyPair().getPublic());
    certGen.setSignatureAlgorithm(req.getSignatureAlgorithm());

    if (req.getCrlUrl() != null) {
        GeneralName gn = new GeneralName(6, new DERIA5String(req.getCrlUrl().toString()));

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(gn);

        GeneralNames gns = new GeneralNames(new DERSequence(vec));
        DistributionPointName dpn = new DistributionPointName(0, gns);

        List<DistributionPoint> l = new ArrayList<DistributionPoint>();
        l.add(new DistributionPoint(dpn, null, null));

        CRLDistPoint crlDp = new CRLDistPoint(l.toArray(new DistributionPoint[0]));

        certGen.addExtension(new DERObjectIdentifier("2.5.29.31"), false, crlDp);
    }

    return certGen.generate(req.getIssuerKey(), "BC");
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a CA Root certificate./*from www  . j a  va  2 s  .  c  o  m*/
 */
private static X509Certificate generateRootCert(String DN, KeyPair pair) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(new X509Name(true, X509Name.DefaultLookUp, DN));
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, true, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(pair.getPublic());
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifier(
            new GeneralNames(new GeneralName(new X509Name(true, X509Name.DefaultLookUp, DN))), BigInteger.ONE));
    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(pair.getPublic()));

    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    certGen.addExtension(X509Extensions.KeyUsage, true,
            new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign | KeyUsage.nonRepudiation));
    certGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false, new NetscapeCertType(
            NetscapeCertType.smimeCA | NetscapeCertType.sslCA | NetscapeCertType.objectSigning));

    return certGen.generate(pair.getPrivate(), "BC");
}

From source file:org.mailster.core.crypto.CertificateUtilities.java

License:Open Source License

/**
 * Generate a sample V3 certificate to use as an intermediate or end entity 
 * certificate depending on the <code>isEndEntity</code> argument.
 *//* w  ww  .ja  va 2s .c om*/
private static X509Certificate generateV3Certificate(String DN, boolean isEndEntity, PublicKey entityKey,
        PrivateKey caKey, X509Certificate caCert) throws Exception {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    certGen.setIssuerDN(caCert.getSubjectX500Principal());
    certGen.setSubjectDN(new X509Name(true, X509Name.DefaultLookUp, DN));

    setSerialNumberAndValidityPeriod(certGen, false, DEFAULT_VALIDITY_PERIOD);

    certGen.setPublicKey(entityKey);
    certGen.setSignatureAlgorithm("SHA1WithRSAEncryption");

    certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifier(caCert.getEncoded(),
                    new GeneralNames(new GeneralName(
                            new X509Name(true, X509Name.DefaultLookUp, caCert.getSubjectDN().getName()))),
                    caCert.getSerialNumber()));

    certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
            new SubjectKeyIdentifierStructure(entityKey));

    if (isEndEntity) {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
    } else {
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(0));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign | KeyUsage.cRLSign));
    }
    return certGen.generate(caKey, "BC");
}

From source file:org.mailster.core.crypto.MailsterKeyStoreFactory.java

License:Open Source License

private void generateSSLServerCertificate(KeyStore store, X500PrivateCredential rootCredential)
        throws Exception {
    LOG.info("Generating SSL server certificate ...");
    KeyPair pair = CertificateUtilities.generateRSAKeyPair(getCryptoStrength());
    String DN = "CN=localhost, " + DN_ROOT;
    X509V3CertificateGenerator v3CertGen = CertificateUtilities.initCertificateGenerator(pair,
            rootCredential.getCertificate().getSubjectX500Principal().getName(), DN, false,
            CertificateUtilities.DEFAULT_VALIDITY_PERIOD);

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

    v3CertGen.addExtension(MiscObjectIdentifiers.netscapeCertType, false,
            new NetscapeCertType(NetscapeCertType.sslServer | NetscapeCertType.sslClient));

    // Firefox 2 disallows these extensions in an SSL server cert. IE7 doesn't care.
    // v3CertGen.addExtension(X509Extensions.KeyUsage,
    // true, new KeyUsage(KeyUsage.dataEncipherment | KeyUsage.keyAgreement |
    // KeyUsage.keyEncipherment));

    Vector<KeyPurposeId> typicalSSLServerExtendedKeyUsages = new Vector<KeyPurposeId>();

    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_serverAuth);
    typicalSSLServerExtendedKeyUsages.add(KeyPurposeId.id_kp_clientAuth);

    v3CertGen.addExtension(X509Extensions.ExtendedKeyUsage, false,
            new ExtendedKeyUsage(typicalSSLServerExtendedKeyUsages));

    X509Certificate publicKeyCertificate = v3CertGen.generate(pair.getPrivate());
    store.setKeyEntry(MAILSTER_SSL_ALIAS, pair.getPrivate(), KEYSTORE_PASSWORD,
            new Certificate[] { publicKeyCertificate, rootCredential.getCertificate() });
    CertificateUtilities.exportCertificate(publicKeyCertificate, SSL_CERT_FULL_PATH, false);
}