Example usage for org.bouncycastle.asn1.x509 TBSCertificateStructure getExtensions

List of usage examples for org.bouncycastle.asn1.x509 TBSCertificateStructure getExtensions

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 TBSCertificateStructure getExtensions.

Prototype

public X509Extensions getExtensions() 

Source Link

Usage

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateComplianceCA_IT.java

License:Open Source License

/**
 * check if qcStatements are present as per ETSI 
 * @param _TbsC //from w w w  .  j  a v a2 s  .c  o  m
 * @return
 */
private boolean hasQcStatements(TBSCertificateStructure _TbsC) {
    //first check for CNIPA requirement
    //then check for ETSI 102 280 requirements
    //then check for ETSI 101 862      
    //qcstatements are defined in ETSI 101 862
    X509Extensions xExt = _TbsC.getExtensions();
    X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements);

    if (qcStats == null) {
        //no qcStatement
        setCertificateStateHelper(CertificateState.MISSING_EXTENSION);
        m_aLogger.log("missing qcStatements");
        return false;
    }
    int numberOfChecksOk = 4; //if this drops to zero,

    //it's not marked critical
    if (!qcStats.isCritical())
        numberOfChecksOk--;

    ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats);
    for (int i = 0; i < dns.size(); i++) {
        QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i));
        if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId()))
            numberOfChecksOk--;
        if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId()))
            numberOfChecksOk--;
        if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId()))
            numberOfChecksOk--;
    }

    if (numberOfChecksOk != 0) {
        m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(),
                CertificateElementState.INVALID_value);
        setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION);
        return false;
    }

    return true;
}

From source file:com.yacme.ext.oxsit.cust_it.comp.security.cert.CertificateCompliance_IT.java

License:Open Source License

/**
 * check if qcStatements are present as per ETSI 
 * @param _TbsC /*w w  w .  j a v  a2s  . com*/
 * @return
 */
private boolean hasQcStatements(TBSCertificateStructure _TbsC) {
    //first check for CNIPA requirement
    //then check for ETSI 102 280 requirements
    //then check for ETSI 101 862      
    //qcstatements are defined in ETSI 101 862
    X509Extensions xExt = _TbsC.getExtensions();
    X509Extension qcStats = xExt.getExtension(X509Extensions.QCStatements);

    if (qcStats == null) {
        //no qcStatement
        setCertificateStateHelper(CertificateState.MISSING_EXTENSION);
        m_aLogger.log("missing qcStatements");
        String s = m_xQc.getCertificateDisplayObj()
                .getCertificateElementCommentString(CertificateElementID.NOT_CRITICAL_EXTENSION);
        s = s + "\r";

        m_xQc.getCertificateDisplayObj().setCertificateElementCommentString(
                CertificateElementID.NOT_CRITICAL_EXTENSION, s + "qcStatement missing");
        return false;
    }
    int numberOfChecksOk = 4; //if this drops to zero,

    //it's not marked critical
    if (!qcStats.isCritical())
        numberOfChecksOk--;

    ASN1Sequence dns = (ASN1Sequence) X509Extension.convertValueToObject(qcStats);
    for (int i = 0; i < dns.size(); i++) {
        QCStatement qcs = QCStatement.getInstance(dns.getObjectAt(i));
        if (QCStatement.id_etsi_qcs_QcCompliance.equals(qcs.getStatementId()))
            numberOfChecksOk--;
        if (QCStatement.id_etsi_qcs_QcSSCD.equals(qcs.getStatementId()))
            numberOfChecksOk--;
        if (QCStatement.id_etsi_qcs_RetentionPeriod.equals(qcs.getStatementId()))
            numberOfChecksOk--;
    }

    if (numberOfChecksOk != 0) {
        m_xQc.setCertificateElementErrorState(X509Extensions.QCStatements.getId(),
                CertificateElementState.INVALID_value);
        setCertificateStateHelper(CertificateState.ERROR_IN_EXTENSION);

        m_xQc.getCertificateDisplayObj().setCertificateExtensionCommentString(
                X509Extensions.QCStatements.getId(), "some statement is wrong.");
        return false;
    }

    return true;
}

From source file:ec.rubrica.util.BouncyCastleUtils.java

License:Open Source License

public static boolean certificateHasPolicy(X509Certificate cert, String sOid) {
    try {/*from   ww  w .  j a va  2 s  .  com*/
        logger.fine("Read cert policies: " + cert.getSerialNumber().toString());

        ByteArrayInputStream bIn = new ByteArrayInputStream(cert.getEncoded());
        ASN1InputStream aIn = new ASN1InputStream(bIn);
        ASN1Sequence seq = (ASN1Sequence) aIn.readObject();
        X509CertificateStructure obj = new X509CertificateStructure(seq);
        TBSCertificateStructure tbsCert = obj.getTBSCertificate();
        if (tbsCert.getVersion() == 3) {
            X509Extensions ext = tbsCert.getExtensions();
            if (ext != null) {
                Enumeration en = ext.oids();
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) en.nextElement();
                    X509Extension extVal = ext.getExtension(oid);
                    ASN1OctetString oct = extVal.getValue();
                    ASN1InputStream extIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets()));

                    if (oid.equals(X509Extension.certificatePolicies)) {
                        ASN1Sequence cp = (ASN1Sequence) extIn.readObject();
                        for (int i = 0; i != cp.size(); i++) {
                            PolicyInformation pol = PolicyInformation.getInstance(cp.getObjectAt(i));
                            DERObjectIdentifier dOid = pol.getPolicyIdentifier();
                            String soid2 = dOid.getId();

                            logger.fine("Policy: " + soid2);
                            if (soid2.startsWith(sOid))
                                return true;
                        }
                    }
                }
            }

        }
    } catch (Exception ex) {
        logger.severe("Error reading cert policies: " + ex);
    }
    return false;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected void checkProxyConstraints(TBSCertificateStructure proxy, TBSCertificateStructure issuer,
        X509Certificate checkedProxy) throws ProxyPathValidatorException, IOException {

    logger.debug("enter: checkProxyConstraints");

    X509Extensions extensions;//ww  w. jav  a2 s  .  co m
    DERObjectIdentifier oid;
    X509Extension ext;

    X509Extension proxyKeyUsage = null;

    extensions = proxy.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.SubjectAlternativeName)
                    || oid.equals(X509Extensions.IssuerAlternativeName)) {
                // No Alt name extensions - 3.2 & 3.5
                throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION, checkedProxy,
                        "Proxy certificate cannot contain subject or issuer alternative name extension");
            } else if (oid.equals(X509Extensions.BasicConstraints)) {
                // Basic Constraint must not be true - 3.8
                BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext);
                if (basicExt.isCA()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "Proxy certificate cannot have BasicConstraint CA=true");
                }
            } else if (oid.equals(X509Extensions.KeyUsage)) {
                proxyKeyUsage = ext;

                boolean[] keyUsage = BouncyCastleUtil.getKeyUsage(ext);
                // these must not be asserted
                if (keyUsage[1] || keyUsage[5]) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy,
                            "The keyCertSign and nonRepudiation bits must not be asserted in Proxy Certificate");
                }
                boolean[] issuerKeyUsage = getKeyUsage(issuer);
                if (issuerKeyUsage != null) {
                    for (int i = 0; i < 9; i++) {
                        if (i == 1 || i == 5) {
                            continue;
                        }
                        if (!issuerKeyUsage[i] && keyUsage[i]) {
                            throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                                    checkedProxy, "Bad KeyUsage in Proxy Certificate");
                        }
                    }
                }
            }
        }
    }

    extensions = issuer.getExtensions();

    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            oid = (DERObjectIdentifier) e.nextElement();
            ext = extensions.getExtension(oid);
            if (oid.equals(X509Extensions.KeyUsage)) {
                // If issuer has it then proxy must have it also
                if (proxyKeyUsage == null) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension missing in Proxy Certificate");
                }
                // If issuer has it as critical so does the proxy
                if (ext.isCritical() && !proxyKeyUsage.isCritical()) {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.PROXY_VIOLATION,
                            checkedProxy, "KeyUsage extension in Proxy Certificate is not critical");
                }
            }
        }
    }

    logger.debug("exit: checkProxyConstraints");
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected void checkUnsupportedCriticalExtensions(TBSCertificateStructure crt, int certType,
        X509Certificate checkedProxy) throws ProxyPathValidatorException {

    logger.debug("enter: checkUnsupportedCriticalExtensions");

    X509Extensions extensions = crt.getExtensions();
    if (extensions != null) {
        Enumeration e = extensions.oids();
        while (e.hasMoreElements()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
            X509Extension ext = extensions.getExtension(oid);
            if (ext.isCritical()) {
                if (oid.equals(X509Extensions.BasicConstraints) || oid.equals(X509Extensions.KeyUsage)
                        || (oid.equals(ProxyCertInfo.OID) && CertUtil.isGsi4Proxy(certType))
                        || (oid.equals(ProxyCertInfo.OLD_OID) && CertUtil.isGsi3Proxy(certType))) {
                } else {
                    throw new ProxyPathValidatorException(ProxyPathValidatorException.UNSUPPORTED_EXTENSION,
                            checkedProxy, "Unsuppored critical exception : " + oid.getId());
                }//from   ww  w  .  ja v a  2  s.  c o  m
            }
        }
    }

    logger.debug("exit: checkUnsupportedCriticalExtensions");
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected int getCAPathConstraint(TBSCertificateStructure crt) throws IOException {
    X509Extensions extensions = crt.getExtensions();
    if (extensions == null) {
        return -1;
    }/*from ww  w . j  a  v a 2  s .com*/
    X509Extension ext = extensions.getExtension(X509Extensions.BasicConstraints);
    if (ext != null) {
        BasicConstraints basicExt = BouncyCastleUtil.getBasicConstraints(ext);
        if (basicExt.isCA()) {
            BigInteger pathLen = basicExt.getPathLenConstraint();
            return (pathLen == null) ? Integer.MAX_VALUE : pathLen.intValue();
        } else {
            return -1;
        }
    }
    return -1;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected ProxyCertInfo getProxyCertInfo(TBSCertificateStructure crt) throws IOException {
    X509Extensions extensions = crt.getExtensions();
    if (extensions == null) {
        return null;
    }/*from w  w w .j  av a 2s .  c  om*/
    X509Extension ext = extensions.getExtension(ProxyCertInfo.OID);
    if (ext == null) {
        ext = extensions.getExtension(ProxyCertInfo.OLD_OID);
    }
    return (ext != null) ? BouncyCastleUtil.getProxyCertInfo(ext) : null;
}

From source file:gov.nih.nci.cagrid.gts.service.ProxyPathValidator.java

License:Apache License

protected boolean[] getKeyUsage(TBSCertificateStructure crt) throws IOException {
    X509Extensions extensions = crt.getExtensions();
    if (extensions == null) {
        return null;
    }/*from   w  w  w  . j a va  2  s . c  om*/
    X509Extension ext = extensions.getExtension(X509Extensions.KeyUsage);
    return (ext != null) ? BouncyCastleUtil.getKeyUsage(ext) : null;
}

From source file:org.cagrid.gaards.pki.BouncyCastleCertProcessingFactory.java

License:Open Source License

/**
 * Creates a proxy certificate. A set of X.509 extensions can be optionally
 * included in the new proxy certificate. <BR>
 * 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>/*  w ww.j  av a2 s .  c  o m*/
 * If a GSI-3 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.
 * 
 * @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}. If
 *            {@link GSIConstants#DELEGATION_LIMITED
 *            GSIConstants.DELEGATION_LIMITED} and if
 *            {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled}
 *            returns true then a GSI-3 limited proxy will be created. If
 *            not, a GSI-2 limited proxy will be created. If
 *            {@link GSIConstants#DELEGATION_FULL
 *            GSIConstants.DELEGATION_FULL} and if
 *            {@link CertUtil#isGsi3Enabled() CertUtil.isGsi3Enabled}
 *            returns true then a GSI-3 impersonation proxy will be created.
 *            If not, a GSI-2 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} 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(String provider, X509Certificate issuerCert, PrivateKey issuerKey,
        PublicKey publicKey, int lifetime, int proxyType, X509ExtensionSet extSet, String cnValue,
        String signatureAlgorithm) throws GeneralSecurityException {

    if (proxyType == GSIConstants.DELEGATION_LIMITED) {
        int type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (CertUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_LIMITED_PROXY;
        } else if (CertUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_LIMITED_PROXY;
        } else if (CertUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_LIMITED_PROXY;
        } else {
            // default to Globus OID
            proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_LIMITED_PROXY
                    : GSIConstants.GSI_2_LIMITED_PROXY;
        }
    } else if (proxyType == GSIConstants.DELEGATION_FULL) {
        int type = BouncyCastleUtil.getCertificateType(issuerCert);
        if (CertUtil.isGsi4Proxy(type)) {
            proxyType = GSIConstants.GSI_4_IMPERSONATION_PROXY;
        } else if (CertUtil.isGsi3Proxy(type)) {
            proxyType = GSIConstants.GSI_3_IMPERSONATION_PROXY;
        } else if (CertUtil.isGsi2Proxy(type)) {
            proxyType = GSIConstants.GSI_2_PROXY;
        } else {
            // Default to Globus OID
            proxyType = (CertUtil.isGsi3Enabled()) ? GSIConstants.GSI_3_IMPERSONATION_PROXY
                    : GSIConstants.GSI_2_PROXY;
        }
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

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

    if (CertUtil.isGsi3Proxy(proxyType) || CertUtil.isGsi4Proxy(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 (CertUtil.isLimitedProxy(proxyType)) {
                policy = new ProxyPolicy(ProxyPolicy.LIMITED);
            } else if (CertUtil.isIndependentProxy(proxyType)) {
                policy = new ProxyPolicy(ProxyPolicy.INDEPENDENT);
            } else if (CertUtil.isImpersonationProxy(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)) {
                throw new IllegalArgumentException("Restricted proxy requires ProxyCertInfo extension");
            } else {
                throw new IllegalArgumentException("Invalid proxyType");
            }

            ProxyCertInfo proxyCertInfo = new ProxyCertInfo(policy);
            x509Ext = new ProxyCertInfoExtension(proxyCertInfo);
            if (CertUtil.isGsi4Proxy(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(X509Extensions.KeyUsage);
                if (ext != null) {

                    // TBD: handle this better
                    if (extSet != null && (extSet.get(X509Extensions.KeyUsage.getId()) != null)) {
                        throw new GeneralSecurityException("KeyUsage extension present in X509ExtensionSet "
                                + "and in issuer certificate.");
                    }

                    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(X509Extensions.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 {
        throw new IllegalArgumentException("Unsupported proxyType : " + proxyType);
    }

    // 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 = (X509Name) issuerCert.getSubjectDN();

    X509NameHelper issuer = new X509NameHelper(issuerDN);

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

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

    certGen.setSerialNumber(serialNum);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm(signatureAlgorithm);

    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());
    }

    /**
     * FIXME: Copy appropriate cert extensions - this should NOT be done the
     * last time we talked to Doug E. This should investigated more.
     */

    return certGen.generateX509Certificate(issuerKey, provider);
}

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   w  w  w .  j  av  a2s. 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);
}