Example usage for org.bouncycastle.asn1.x509 X509Name CN

List of usage examples for org.bouncycastle.asn1.x509 X509Name CN

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 X509Name CN.

Prototype

ASN1ObjectIdentifier CN

To view the source code for org.bouncycastle.asn1.x509 X509Name CN.

Click Source Link

Document

common name - StringType(SIZE(1..64))

Usage

From source file:android.net.http.DomainNameChecker.java

License:Apache License

/**
 * Checks the site certificate against the DNS domain name of the site being visited
 * @param certificate The certificate to check
 * @param thisDomain The DNS domain name of the site being visited
 * @return True iff if there is a domain match as specified by RFC2818
 *//* w w w.ja v  a  2 s . c o m*/
private static boolean matchDns(X509Certificate certificate, String thisDomain) {
    boolean hasDns = false;
    try {
        Collection subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            Iterator i = subjectAltNames.iterator();
            while (i.hasNext()) {
                List altNameEntry = (List) (i.next());
                if (altNameEntry != null && 2 <= altNameEntry.size()) {
                    Integer altNameType = (Integer) (altNameEntry.get(0));
                    if (altNameType != null) {
                        if (altNameType.intValue() == ALT_DNS_NAME) {
                            hasDns = true;
                            String altName = (String) (altNameEntry.get(1));
                            if (altName != null) {
                                if (matchDns(thisDomain, altName)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (CertificateParsingException e) {
        // one way we can get here is if an alternative name starts with
        // '*' character, which is contrary to one interpretation of the
        // spec (a valid DNS name must start with a letter); there is no
        // good way around this, and in order to be compatible we proceed
        // to check the common name (ie, ignore alternative names)
        if (HttpLog.LOGV) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to parse certificate";
            }

            if (HttpLog.LOGV) {
                HttpLog.v("DomainNameChecker.matchDns(): " + errorMessage);
            }
        }
    }

    if (!hasDns) {
        X509Name xName = new X509Name(certificate.getSubjectDN().getName());
        Vector val = xName.getValues();
        Vector oid = xName.getOIDs();
        for (int i = 0; i < oid.size(); i++) {
            if (oid.elementAt(i).equals(X509Name.CN)) {
                return matchDns(thisDomain, (String) (val.elementAt(i)));
            }
        }
    }

    return false;
}

From source file:brooklyn.util.crypto.FluentKeySigner.java

License:Apache License

public String getCommonName() {
    return (String) new X509Principal(issuerPrincipal.getName()).getValues(X509Name.CN).elementAt(0);
}

From source file:cc.abstra.trantor.security.ssl.OwnSSLProtocolSocketFactory.java

License:Apache License

/**
 * Parses a X.500 distinguished name for the value of the 
 * "Common Name" field.// w  w w  . ja v a 2  s.c  om
 * This is done a bit sloppy right now and should probably be done a bit
 * more according to <code>RFC 2253</code>.
 *
 * @param dn  a X.500 distinguished name.
 * @return the value of the "Common Name" field.
 */
private String getCN(String dn) {
    X509Name name = new X509Name(dn);
    Vector<?> vector = name.getValues(X509Name.CN);
    if ((vector != null) && (vector.size() > 0)) {
        return (String) vector.get(0);
    } else {
        return null;
    }
}

From source file:com.ah.be.cloudauth.HmCloudAuthCertMgmtImpl.java

@SuppressWarnings("rawtypes")
private void verifyCSRContent(BeRadSecCertCreationResultEvent result, String commonName)
        throws HmCloudAuthException {
    String methodName = "verifyCSRContent";
    if (result.isCreateError()) {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_CREATE_ERR);
    }//from w  ww . j a  v  a  2 s . c om
    if (result.isNeedCreate()) {
        byte[] csrContent = result.getCsrContent();
        final List pemItems = org.apache.commons.ssl.PEMUtil.decode(csrContent);
        if (pemItems.isEmpty()) {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }

        final PEMItem csrPemItem = (PEMItem) pemItems.get(0);
        if (csrPemItem.pemType.startsWith(CERTIFICATE_REQUEST)) {
            final PKCS10CertificationRequest csr = new PKCS10CertificationRequest(csrPemItem.getDerBytes());
            CertificationRequestInfo requestInfo = csr.getCertificationRequestInfo();
            X509Name subject = requestInfo.getSubject();

            Vector commondNameVector = subject.getValues(X509Name.CN);
            Vector countryVector = subject.getValues(X509Name.C);
            Vector organizationVector = subject.getValues(X509Name.O);
            if (commondNameVector.isEmpty() || countryVector.isEmpty() || organizationVector.isEmpty()) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_FORMAT_ERR);
            }
            if (!commonName.equalsIgnoreCase(commondNameVector.get(0).toString())
                    || !ORGANIZATION.equals(organizationVector.get(0).toString())
                    || !COUNTRY.equals(countryVector.get(0).toString())) {
                throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_VERIFY_ERR);
            }
        } else {
            throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_DECODE_ERR);
        }
    } else {
        throw new HmCloudAuthException(methodName, UpdateCAStatus.CSR_STATUS_ERR);
    }
    return;
}

From source file:com.almarsoft.GroundhogReader.lib.DomainNameChecker.java

License:Apache License

/**
 * Checks the site certificate against the DNS domain name of the site being visited
 * @param certificate The certificate to check
 * @param thisDomain The DNS domain name of the site being visited
 * @return True iff if there is a domain match as specified by RFC2818
 *///w w w  . j  a  v a  2s.  c  om
private static boolean matchDns(X509Certificate certificate, String thisDomain) {
    boolean hasDns = false;
    try {
        Collection subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            Iterator i = subjectAltNames.iterator();
            while (i.hasNext()) {
                List altNameEntry = (List) (i.next());
                if (altNameEntry != null && 2 <= altNameEntry.size()) {
                    Integer altNameType = (Integer) (altNameEntry.get(0));
                    if (altNameType != null) {
                        if (altNameType.intValue() == ALT_DNS_NAME) {
                            hasDns = true;
                            String altName = (String) (altNameEntry.get(1));
                            if (altName != null) {
                                if (matchDns(thisDomain, altName)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (CertificateParsingException e) {
        // one way we can get here is if an alternative name starts with
        // '*' character, which is contrary to one interpretation of the
        // spec (a valid DNS name must start with a letter); there is no
        // good way around this, and in order to be compatible we proceed
        // to check the common name (ie, ignore alternative names)
    }

    if (!hasDns) {
        X509Name xName = new X509Name(certificate.getSubjectDN().getName());
        Vector val = xName.getValues();
        Vector oid = xName.getOIDs();
        for (int i = 0; i < oid.size(); i++) {
            if (oid.elementAt(i).equals(X509Name.CN)) {
                return matchDns(thisDomain, (String) (val.elementAt(i)));
            }
        }
    }

    return false;
}

From source file:com.fsck.k9.helper.DomainNameChecker.java

License:Apache License

/**
 * Checks the site certificate against the DNS domain name of the site being
 * visited//from w  w w.  j a va 2  s  . c  o  m
 *
 * @param certificate
 *            The certificate to check
 * @param thisDomain
 *            The DNS domain name of the site being visited
 * @return True iff if there is a domain match as specified by RFC2818
 */
private static boolean matchDns(X509Certificate certificate, String thisDomain) {
    boolean hasDns = false;
    try {
        Collection<?> subjectAltNames = certificate.getSubjectAlternativeNames();
        if (subjectAltNames != null) {
            Iterator<?> i = subjectAltNames.iterator();
            while (i.hasNext()) {
                List<?> altNameEntry = (List<?>) (i.next());
                if ((altNameEntry != null) && (2 <= altNameEntry.size())) {
                    Integer altNameType = (Integer) (altNameEntry.get(0));
                    if (altNameType != null) {
                        if (altNameType.intValue() == ALT_DNS_NAME) {
                            hasDns = true;
                            String altName = (String) (altNameEntry.get(1));
                            if (altName != null) {
                                if (matchDns(thisDomain, altName)) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (CertificateParsingException e) {
        // one way we can get here is if an alternative name starts with
        // '*' character, which is contrary to one interpretation of the
        // spec (a valid DNS name must start with a letter); there is no
        // good way around this, and in order to be compatible we proceed
        // to check the common name (ie, ignore alternative names)
        if (K9.DEBUG) {
            String errorMessage = e.getMessage();
            if (errorMessage == null) {
                errorMessage = "failed to parse certificate";
            }

            Log.v(K9.LOG_TAG, "DomainNameChecker.matchDns(): " + errorMessage);
        }
    }

    if (!hasDns) {
        X509Name xName = new X509Name(certificate.getSubjectDN().getName());
        Vector<?> val = xName.getValues();
        Vector<?> oid = xName.getOIDs();
        for (int i = 0; i < oid.size(); i++) {
            if (oid.elementAt(i).equals(X509Name.CN)) {
                return matchDns(thisDomain, (String) (val.elementAt(i)));
            }
        }
    }

    return false;
}

From source file:de.mendelson.util.security.keygeneration.KeyGenerator.java

/**
 * Generates a self-signed X509 Version 3 certificate
 *
 *///from w  w  w  .  j  av a 2  s. c  o m
private X509Certificate generateCertificate(PublicKey publicKey, PrivateKey privateKey,
        KeyGenerationValues generationValues) throws Exception {
    //Stores certificate attributes
    Hashtable<ASN1ObjectIdentifier, String> attributes = new Hashtable<ASN1ObjectIdentifier, String>();
    Vector<ASN1ObjectIdentifier> order = new Vector<ASN1ObjectIdentifier>();
    attributes.put(X509Name.CN, generationValues.getCommonName());
    order.add(0, X509Name.CN);
    attributes.put(X509Name.OU, generationValues.getOrganisationUnit());
    order.add(0, X509Name.OU);
    attributes.put(X509Name.O, generationValues.getOrganisationName());
    order.add(0, X509Name.O);
    attributes.put(X509Name.L, generationValues.getLocalityName());
    order.add(0, X509Name.L);
    attributes.put(X509Name.ST, generationValues.getStateName());
    order.add(0, X509Name.ST);
    attributes.put(X509Name.C, generationValues.getCountryCode());
    order.add(0, X509Name.C);
    attributes.put(X509Name.E, generationValues.getEmailAddress());
    order.add(0, X509Name.E);
    X509V3CertificateGenerator certificateGenerator = new X509V3CertificateGenerator();
    // Set the issuer distinguished name
    certificateGenerator.setIssuerDN(new X509Principal(order, attributes));
    //add a key extension if this is requested
    if (generationValues.getKeyExtension() != null) {
        certificateGenerator.addExtension(X509Extensions.KeyUsage, true, generationValues.getKeyExtension());
    }
    //add a extended key extension if this is requested
    if (generationValues.getExtendedKeyExtension() != null) {
        certificateGenerator.addExtension(X509Extensions.ExtendedKeyUsage, false,
                generationValues.getExtendedKeyExtension());
    }
    // Valid before and after dates now to iValidity days in the future
    Date startDate = new Date(System.currentTimeMillis());
    long duration = TimeUnit.DAYS.toMillis(generationValues.getKeyValidInDays());
    Date endDate = new Date(startDate.getTime() + duration);
    certificateGenerator.setNotBefore(startDate);
    certificateGenerator.setNotAfter(endDate);
    certificateGenerator.setSubjectDN(new X509Principal(order, attributes));
    certificateGenerator.setPublicKey(publicKey);
    certificateGenerator.setSignatureAlgorithm(generationValues.getSignatureAlgorithm());
    BigInteger serialNumber = new BigInteger(Long.toString(System.currentTimeMillis() / 1000));
    certificateGenerator.setSerialNumber(serialNumber);
    // Generate an X.509 certificate, based on the current issuer and subject
    X509Certificate cert = certificateGenerator.generate(privateKey, "BC");
    // Return the certificate
    return cert;
}

From source file:edu.washington.iam.tools.IamCertificateHelper.java

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {//from   w ww .ja  va2s . c o  m
        PEMReader pRd = new PEMReader(new StringReader(cert.pemRequest));
        PKCS10CertificationRequest request = (PKCS10CertificationRequest) pRd.readObject();
        if (request == null)
            throw new IamCertificateException("invalid CSR (request)");
        CertificationRequestInfo info = request.getCertificationRequestInfo();
        if (info == null)
            throw new IamCertificateException("invalid CSR (info)");

        X509Name dn = info.getSubject();
        if (dn == null)
            throw new IamCertificateException("invalid CSR (dn)");
        log.debug("dn=" + dn.toString());
        cert.dn = dn.toString();
        try {
            List cns = dn.getValues(X509Name.CN);
            cert.cn = (String) (cns.get(0));
            log.debug("cn=" + cert.cn);
            cert.names.add(cert.cn); // first entry for names is always cn
            cns = dn.getValues(X509Name.C);
            cert.dnC = (String) (cns.get(0));
            cns = dn.getValues(X509Name.ST);
            cert.dnST = (String) (cns.get(0));
        } catch (Exception e) {
            log.debug("get cn error: " + e);
            throw new IamCertificateException("invalid CSR");
        }

        // see if we've got alt names (in extensions)

        ASN1Set attrs = info.getAttributes();
        if (attrs != null) {
            for (int a = 0; a < attrs.size(); a++) {
                Attribute attr = Attribute.getInstance(attrs.getObjectAt(a));
                if (attr.getAttrType().equals(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) {

                    // is the extension
                    X509Extensions extensions = X509Extensions.getInstance(attr.getAttrValues().getObjectAt(0));

                    // get the subAltName extension
                    DERObjectIdentifier sanoid = new DERObjectIdentifier(
                            X509Extensions.SubjectAlternativeName.getId());
                    X509Extension xext = extensions.getExtension(sanoid);
                    if (xext != null) {
                        log.debug("processing altname extensions");
                        ASN1Object asn1 = X509Extension.convertValueToObject(xext);
                        Enumeration dit = DERSequence.getInstance(asn1).getObjects();
                        while (dit.hasMoreElements()) {
                            GeneralName gn = GeneralName.getInstance(dit.nextElement());
                            log.debug("altname tag=" + gn.getTagNo());
                            log.debug("altname name=" + gn.getName().toString());
                            if (gn.getTagNo() == GeneralName.dNSName)
                                cert.names.add(gn.getName().toString());
                        }
                    }

                }
            }
        }

        // check key size
        PublicKey pk = request.getPublicKey();
        log.debug("key alg = " + pk.getAlgorithm());
        log.debug("key fmt = " + pk.getFormat());
        if (pk.getAlgorithm().equals("RSA")) {
            RSAPublicKey rpk = (RSAPublicKey) pk;
            cert.keySize = rpk.getModulus().bitLength();
            log.debug("key size = " + cert.keySize);
        }

    } catch (IOException e) {
        log.debug("ioerror: " + e);
        throw new IamCertificateException("invalid CSR " + e.getMessage());
    } catch (Exception e) {
        log.debug("excp: " + e);
        throw new IamCertificateException("invalid CSR");
    }
    return 1;
}

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  w w .  j  ava2 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.dcache.gridsite.BouncyCastleCredentialDelegation.java

License:Open Source License

private static X509Name buildProxyDN(X500Principal principal) throws GeneralSecurityException {
    ASN1StreamParser parser = new ASN1StreamParser(principal.getEncoded());

    DERSequence seq;//www .  j a va 2 s . c o m
    try {
        ASN1Encodable object = parser.readObject().getDERObject();
        if (!(object instanceof DERSequence)) {
            throw new IOException("not a DER-encoded ASN.1 sequence");
        }
        seq = (DERSequence) object;
    } catch (IOException e) {
        throw new GeneralSecurityException("failed to parse DN: " + e.getMessage());
    }

    List<ASN1Encodable> rdn = new ArrayList<>(seq.size() + 1);
    for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
        rdn.add((ASN1Encodable) e.nextElement());
    }

    DERSequence atv = new DERSequence(new ASN1Object[] { X509Name.CN, new DERPrintableString("proxy") });
    rdn.add(new DERSet(atv));

    ASN1Encodable[] rdnArray = rdn.toArray(new ASN1Encodable[rdn.size()]);
    return new X509Name(new DERSequence(rdnArray));
}