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

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

Introduction

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

Prototype

public Vector getValues(ASN1ObjectIdentifier oid) 

Source Link

Document

return a vector of the values found in the name, in the order they were found, with the DN label corresponding to passed in oid.

Usage

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 .  j a v a  2 s .com
 * 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 www . j a  v a2  s  .  c  o m*/
    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:edu.washington.iam.tools.IamCertificateHelper.java

License:Apache License

public static int parseCsr(IamCertificate cert) throws IamCertificateException {

    try {/*from  www . j  a va 2 s .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.ejbca.core.protocol.PKCS10RequestMessage.java

License:Open Source License

/**
 * Returns the string representation of the CN field from the DN of the certification request,
 * to be used as username.//from  w  w  w.j av a2  s .c om
 *
 * @return username, which is the CN field from the subject DN in certification request.
 */
public String getUsername() {
    if (username != null) {
        return username;
    }
    // Special if the DN contains unstructuredAddress where it becomes: 
    // CN=pix.primekey.se + unstructuredAddress=pix.primekey.se
    // We only want the CN and not the oid-part.
    // Luckily for us this is handles automatically by BC X509Name class
    X509Name xname = getRequestX509Name();
    String ret = null;
    if (xname == null) {
        log.info("No requestDN in request, probably we could not read/parse/decrypt request.");
    } else {
        Vector cnValues = xname.getValues(X509Name.CN);
        if (cnValues.size() == 0) {
            log.info("No CN in DN: " + xname.toString());
        } else {
            ret = cnValues.firstElement().toString();
            // If we have a CN with a normal name like "Test Testsson" we only want to 
            // use the first part as the username
            int index = ret.indexOf(' ');
            if (index > 0) {
                ret = ret.substring(0, index);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("UserName='" + ret + "'");
    }
    return ret;
}

From source file:org.ejbca.util.CertTools.java

License:Open Source License

/**
 * Obtain a X509Name reordered, if some fields from original X509Name 
 * doesn't appear in "ordering" parameter, they will be added at end 
 * in the original order./*from   w w  w . ja v a 2 s . c o  m*/
 *   
 * @param x509Name the X509Name that is unordered 
 * @param ldaporder true if LDAP ordering of DN should be used (default in EJBCA), false for X.500 order, ldap order is CN=A,OU=B,O=C,C=SE, x.500 order is the reverse
 * @return X509Name with ordered conmponents according to the orcering vector
 */
private static X509Name getOrderedX509Name(final X509Name x509Name, final boolean ldaporder,
        final X509NameEntryConverter converter) {
    //-- Null prevent
    // Guess order of the input name
    final boolean isLdapOrder = !isDNReversed(x509Name.toString());
    //-- New order for the X509 Fields
    final List<DERObjectIdentifier> newOrdering = new ArrayList<DERObjectIdentifier>();
    final List<Object> newValues = new ArrayList<Object>();
    //-- Add ordered fields
    @SuppressWarnings("unchecked")
    final Vector<DERObjectIdentifier> allOids = x509Name.getOIDs();
    // If we think the DN is in LDAP order, first order it as a LDAP DN, if we don't think it's LDAP order
    // order it as a X.500 DN
    final List<DERObjectIdentifier> ordering = getX509FieldOrder(isLdapOrder);
    final HashSet<DERObjectIdentifier> hs = new HashSet<DERObjectIdentifier>(allOids.size() + ordering.size());
    for (final DERObjectIdentifier oid : ordering) {
        if (!hs.contains(oid)) {
            hs.add(oid);
            @SuppressWarnings("unchecked")
            final Vector<Object> valueList = x509Name.getValues(oid);
            //-- Only add the OID if has not null value
            for (final Object value : valueList) {
                newOrdering.add(oid);
                newValues.add(value);
            }
        }
    }
    //-- Add unexpected fields to the end
    for (final DERObjectIdentifier oid : allOids) {
        if (!hs.contains(oid)) {
            hs.add(oid);
            @SuppressWarnings("unchecked")
            final Vector<Object> valueList = x509Name.getValues(oid);
            //-- Only add the OID if has not null value
            for (final Object value : valueList) {
                newOrdering.add(oid);
                newValues.add(value);
                if (log.isDebugEnabled()) {
                    log.debug("added --> " + oid + " val: " + value);
                }
            }
        }
    }
    // If the requested ordering was the reverse of the ordering the input string was in (by our guess in the beginning)
    // we have to reverse the vectors
    if (ldaporder != isLdapOrder) {
        if (log.isDebugEnabled()) {
            log.debug("Reversing order of DN, ldaporder=" + ldaporder + ", isLdapOrder=" + isLdapOrder);
        }
        Collections.reverse(newOrdering);
        Collections.reverse(newValues);
    }
    //-- Return X509Name with the ordered fields
    return new X509Name(new Vector<DERObjectIdentifier>(newOrdering), new Vector<Object>(newValues), converter);
}