Example usage for org.bouncycastle.asn1.x509 X509NameTokenizer X509NameTokenizer

List of usage examples for org.bouncycastle.asn1.x509 X509NameTokenizer X509NameTokenizer

Introduction

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

Prototype

public X509NameTokenizer(String oid) 

Source Link

Usage

From source file:net.jxta.impl.membership.pse.PSEUtils.java

License:Open Source License

/**
 * return the CN token from the provided cert's subjectDN
 *
 * @param cert the certificate to examine
 * @return the CN name or null if none could be found.
 *//*from   w w w  .ja v a 2s  .com*/
public static String getCertSubjectCName(X509Certificate cert) {

    // get the subject dname
    X500Principal subject = cert.getSubjectX500Principal();

    X509NameTokenizer tokens = new X509NameTokenizer(subject.getName());

    // iterate over the attributes of the dname
    while (tokens.hasMoreTokens()) {
        String aToken = tokens.nextToken();

        if (aToken.length() < 3) {
            continue;
        }

        String attribute = aToken.substring(0, 3);

        if ("CN=".equalsIgnoreCase(attribute)) {
            return aToken.substring(3);
        }
    }

    return null;
}

From source file:net.jxta.impl.membership.pse.PSEUtils.java

License:Open Source License

/**
 * return the CN token from the provided cert's issuerDN
 *
 * @param cert the certificate to examine
 * @return the CN name or null if none could be found.
 *//*from   w w w  .  j a  v  a  2  s. c om*/
public static String getCertIssuerCName(X509Certificate cert) {

    // get the subject dname
    X500Principal issuer = cert.getIssuerX500Principal();

    X509NameTokenizer tokens = new X509NameTokenizer(issuer.getName());

    // iterate over the attributes of the dname
    while (tokens.hasMoreTokens()) {
        String aToken = tokens.nextToken();

        if (aToken.length() < 3) {
            continue;
        }

        String attribute = aToken.substring(0, 3);

        if ("CN=".equalsIgnoreCase(attribute)) {
            return aToken.substring(3);
        }
    }

    return null;
}

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

License:Open Source License

/**
 * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID
 * (with order) are:/*from   www .  j  a v a2s  .  c  om*/
 * <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU,
 * O, L, ST, DC, C </code>
 * To change order edit 'dnObjects' in this source file. Important NOT to mess
 * with the ordering within this class, since cert vierification on some
 * clients (IE :-() might depend on order.
 * 
 * @param dn
 *          String containing DN that will be transformed into X509Name, The
 *          DN string has the format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in
 *          the string will be added to the end positions of OID array.
 * @param converter BC converter for DirectoryStrings, that determines which encoding is chosen
 * @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 or null if input is null
 */
public static X509Name stringToBcX509Name(String dn, X509NameEntryConverter converter, boolean ldaporder) {

    if (dn == null) {
        return null;
    }

    Vector<DERObjectIdentifier> defaultOrdering = new Vector<DERObjectIdentifier>();
    Vector<String> values = new Vector<String>();
    X509NameTokenizer x509NameTokenizer = new X509NameTokenizer(dn);

    while (x509NameTokenizer.hasMoreTokens()) {
        // This is a pair key=val (CN=xx)
        String pair = x509NameTokenizer.nextToken(); // Will escape '+' and initial '#' chars
        int index = pair.indexOf('=');

        if (index != -1) {
            String key = pair.substring(0, index).toLowerCase().trim();
            String val = pair.substring(index + 1);
            if (val != null) {
                // String whitespace from the beginning of the value, to handle the case
                // where someone type CN = Foo Bar
                val = StringUtils.stripStart(val, null);
            }

            // -- First search the OID by name in declared OID's
            DERObjectIdentifier oid = DnComponents.getOid(key);

            try {
                // -- If isn't declared, we try to create it
                if (oid == null) {
                    oid = new DERObjectIdentifier(key);
                }
                defaultOrdering.add(oid);
                values.add(getUnescapedPlus(val));
            } catch (IllegalArgumentException e) {
                // If it is not an OID we will ignore it
                log.warn("Unknown DN component ignored and silently dropped: " + key);
            }

        } else {
            log.warn("No 'key=value' pair encountered in token '" + pair + "' while converting subject DN '"
                    + dn + "' into X509Name.");
        }
    }

    X509Name x509Name = new X509Name(defaultOrdering, values, converter);

    //-- Reorder fields
    X509Name orderedX509Name = getOrderedX509Name(x509Name, ldaporder, converter);

    //log.trace("<stringToBcX509Name");
    return orderedX509Name;
}

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

License:Open Source License

/**
 * Tries to determine if a DN is in reversed form. It does this by taking the last attribute 
 * and the first attribute. If the last attribute comes before the first in the dNObjects array
 * the DN is assumed to be in reversed order.
 * /*  ww w. j ava 2  s .com*/
 * The default ordering is:
 * "CN=Tomas, O=PrimeKey, C=SE" (dNObjectsForward ordering in EJBCA) a dn or form "C=SE, O=PrimeKey, CN=Tomas" is reversed.
 * 
 *
 * @param dn String containing DN to be checked, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz".
 *
 * @return true if the DN is believed to be in reversed order, false otherwise
 */
protected static boolean isDNReversed(String dn) {
    /*if (log.isTraceEnabled()) {
       log.trace(">isDNReversed: dn: " + dn);
    }*/
    boolean ret = false;
    if (dn != null) {
        String first = null;
        String last = null;
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        if (xt.hasMoreTokens()) {
            first = xt.nextToken();
        }
        while (xt.hasMoreTokens()) {
            last = xt.nextToken();
        }
        String[] dNObjects = DnComponents.getDnObjects(true);
        if ((first != null) && (last != null)) {
            first = first.substring(0, first.indexOf('='));
            last = last.substring(0, last.indexOf('='));
            int firsti = 0, lasti = 0;
            for (int i = 0; i < dNObjects.length; i++) {
                if (first.toLowerCase().equals(dNObjects[i])) {
                    firsti = i;
                }
                if (last.toLowerCase().equals(dNObjects[i])) {
                    lasti = i;
                }
            }
            if (lasti < firsti) {
                ret = true;
            }

        }
    }
    /*if (log.isTraceEnabled()) {
       log.trace("<isDNReversed: " + ret);
    }*/
    return ret;
}

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

License:Open Source License

/**
 * Gets a specified part of a DN. Specifically the first occurrence it the DN contains several
 * instances of a part (i.e. cn=x, cn=y returns x).
 *
 * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz".
 * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
 *
 * @return String containing dnpart or null if dnpart is not present
 *///from  w  w  w  . j  ava2 s  .com
public static String getPartFromDN(String dn, String dnpart) {
    if (log.isTraceEnabled()) {
        log.trace(">getPartFromDN: dn:'" + dn + "', dnpart=" + dnpart);
    }
    String part = null;
    if ((dn != null) && (dnpart != null)) {
        String o;
        dnpart += "="; // we search for 'CN=' etc.
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        while (xt.hasMoreTokens()) {
            o = xt.nextToken();
            //log.debug("checking: "+o.substring(0,dnpart.length()));
            if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) {
                part = o.substring(dnpart.length());

                break;
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getpartFromDN: resulting DN part=" + part);
    }
    return part;
}

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

License:Open Source License

/**
* Gets a specified parts of a DN. Returns all occurences as an ArrayList, also works if DN contains several
* instances of a part (i.e. cn=x, cn=y returns {x, y, null}).
*
* @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz".
* @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
*
* @return ArrayList containing dnparts or empty list if dnpart is not present
*//*w  ww. j a va  2 s .c  o  m*/
public static ArrayList<String> getPartsFromDN(String dn, String dnpart) {
    if (log.isTraceEnabled()) {
        log.trace(">getPartsFromDN: dn:'" + dn + "', dnpart=" + dnpart);
    }
    ArrayList<String> parts = new ArrayList<String>();
    if ((dn != null) && (dnpart != null)) {
        String o;
        dnpart += "="; // we search for 'CN=' etc.
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        while (xt.hasMoreTokens()) {
            o = xt.nextToken();
            if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) {
                parts.add(o.substring(dnpart.length()));
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getpartsFromDN: resulting DN part=" + parts.toString());
    }
    return parts;
}

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

License:Open Source License

/**
* Gets a list of all custom OIDs defined in the string. A custom OID is defined as an OID, simply as that. Otherwise, if it is not a custom oid, the DNpart is defined by a name such as CN och rfc822Name.
* This method only returns a oid once, so if the input string has multiple of the same oid, only one value is returned.
*
* @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz", or "rfc822Name=foo@bar.com", etc.
* @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
*
* @return ArrayList containing unique oids or empty list if no custom OIDs are present
*///from   w  w w .j  a  v a  2 s  .c o m
public static ArrayList<String> getCustomOids(String dn) {
    if (log.isTraceEnabled()) {
        log.trace(">getCustomOids: dn:'" + dn);
    }
    ArrayList<String> parts = new ArrayList<String>();
    if (dn != null) {
        String o;
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        while (xt.hasMoreTokens()) {
            o = xt.nextToken();
            // Try to see if it is a valid OID
            try {
                int i = o.indexOf('=');
                // An oid is never shorter than 3 chars and must start with 1.
                if ((i > 2) && (o.charAt(1) == '.')) {
                    String oid = o.substring(0, i);
                    // If we have multiple of the same custom oid, don't claim that we have more
                    // This method will only return "unique" custom oids.
                    if (!parts.contains(oid)) {
                        // Check if it is a real oid, if it is not we will ignore it (IllegalArgumentException will be thrown)
                        new DERObjectIdentifier(oid);
                        parts.add(oid);
                    }
                }
            } catch (IllegalArgumentException e) {
                // Not a valid oid
            }
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("<getpartsFromDN: resulting DN part=" + parts.toString());
    }
    return parts;
}

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

License:Open Source License

/**
 * Method used to insert a CN postfix into DN by extracting the first found CN appending cnpostfix and then replacing the original CN 
 * with the new one in DN./*from  www  .  j av a 2 s .c  om*/
 * 
 * If no CN could be found in DN then should the given DN be returned untouched
 * 
 * @param dn the DN to manipulate, cannot be null
 * @param cnpostfix the postfix to insert, cannot be null
 * @return the new DN
 */
public static String insertCNPostfix(String dn, String cnpostfix) {
    String newdn = null;

    if ((dn != null) && (cnpostfix != null)) {
        String o;
        X509NameTokenizer xt = new X509NameTokenizer(dn);
        boolean alreadyreplaced = false;
        while (xt.hasMoreTokens()) {
            o = xt.nextToken();
            if (!alreadyreplaced && (o.length() > 3) && o.substring(0, 3).equalsIgnoreCase("cn=")) {
                o += cnpostfix;
                alreadyreplaced = true;
            }
            if (newdn == null) {
                newdn = o;
            } else {
                newdn += "," + o;
            }
        }
    }

    return newdn;
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * Creates a (Bouncycastle) X509Name object from a string with a DN. Known OID (with order)
 * are: <code> EmailAddress, UID, CN, SN (SerialNumber), GivenName, Initials, SurName, T, OU,
 * O, L, ST, DC, C </code>//w  ww. j  a va 2s  . co  m
 * To change order edit 'dnObjects' in this source file.
 *
 * @param dn String containing DN that will be transformed into X509Name, The DN string has the
 *        format "CN=zz,OU=yy,O=foo,C=SE". Unknown OIDs in the string will be silently
 *        dropped.
 *
 * @return X509Name
 */
public static X509Name stringToBcX509Name(String dn) {
    //log.debug(">stringToBcX509Name: " + dn);
    // first make two vectors, one with all the C, O, OU etc specifying
    // the order and one holding the actual values
    ArrayList<String> oldordering = new ArrayList<String>();
    ArrayList<String> oldvalues = new ArrayList<String>();
    X509NameTokenizer xt = new X509NameTokenizer(dn);

    while (xt.hasMoreTokens()) {
        // This is a pair (CN=xx)
        String pair = xt.nextToken();
        int ix = pair.indexOf("=");

        if (ix != -1) {
            // make lower case so we can easily compare later
            oldordering.add(pair.substring(0, ix).toLowerCase());
            oldvalues.add(pair.substring(ix + 1));
        } else {
            // Huh, what's this?
        }
    }

    // Now in the specified order, move from oldordering to newordering,
    // reshuffling as we go along
    Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>();
    Vector<String> values = new Vector<String>();
    int index = -1;

    for (String object : dNObjects) {
        while ((index = oldordering.indexOf(object)) != -1) {
            //log.debug("Found 1 "+object+" at index " + index);
            DERObjectIdentifier oid = getOid(object);

            if (oid != null) {
                //log.debug("Added "+object+", "+oldvalues.elementAt(index));
                ordering.add(oid);

                // remove from the old vectors, so we start clean the next round
                values.add(oldvalues.remove(index));
                oldordering.remove(index);
                index = -1;
            }
        }
    }

    /*
       if (log.isDebugEnabled()) {
       Iterator i1 = ordering.iterator();
       Iterator i2 = values.iterator();
       log.debug("Order: ");
       while (i1.hasNext()) {
           log.debug(((DERObjectIdentifier)i1.next()).getId());
       }
       log.debug("Values: ");
       while (i2.hasNext()) {
           log.debug((String)i2.next());
       }
       } */

    //log.debug("<stringToBcX509Name");
    return new X509Name(ordering, values);
}

From source file:org.objectweb.proactive.core.security.CertTools.java

License:Open Source License

/**
 * Gets a specified part of a DN. Specifically the first occurrence it the DN contains several
 * instances of a part (i.e. cn=x, cn=y returns x).
 *
 * @param dn String containing DN, The DN string has the format "C=SE, O=xx, OU=yy, CN=zz".
 * @param dnpart String specifying which part of the DN to get, should be "CN" or "OU" etc.
 *
 * @return String containing dnpart or null if dnpart is not present
 *//*from  w w  w  .j a  v a  2 s.  com*/
public static String getPartFromDN(String dn, String dnpart) {
    log.debug(">getPartFromDN: dn:'" + dn + "', dnpart=" + dnpart);

    String part = null;

    if ((dn != null) && (dnpart != null)) {
        String o;
        dnpart += "="; // we search for 'CN=' etc.

        X509NameTokenizer xt = new X509NameTokenizer(dn);

        while (xt.hasMoreTokens()) {
            o = xt.nextToken();

            //log.debug("checking: "+o.substring(0,dnpart.length()));
            if ((o.length() > dnpart.length()) && o.substring(0, dnpart.length()).equalsIgnoreCase(dnpart)) {
                part = o.substring(dnpart.length());

                break;
            }
        }
    }

    log.debug("<getpartFromDN: resulting DN part=" + part);

    return part;
}