Example usage for org.bouncycastle.asn1.x500 X500Name toString

List of usage examples for org.bouncycastle.asn1.x500 X500Name toString

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name toString.

Prototype

public String toString() 

Source Link

Usage

From source file:org.cesecore.certificates.certificate.request.RequestMessageTest.java

License:Open Source License

@Test
public void testSNRepresentation() {
    SimpleRequestMessage req = new SimpleRequestMessage(keyPair.getPublic(), "dnorder", "foo123");
    req.setRequestDN("C=SE,O=Foo Company,SN=12345,SURNAME=surname,CN=DnOrderTest"); // This should not matter now
    X500Name reqname = req.getRequestX500Name();
    assertEquals("C=SE,O=Foo Company,SN=12345,SURNAME=surname,CN=DnOrderTest", reqname.toString());
}

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

License:Open Source License

/**
 * Creates a (Bouncycastle) X500Name 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> 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.
 * /*from w w  w  .j a  v a 2 s . co m*/
 * @param dn String containing DN that will be transformed into X500Name, 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 nameStyle Controls how the name is encoded. Usually it should be a CeSecoreNameStyle.
 * @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 X500Name or null if input is null
 * @throws IllegalArgumentException if DN is not valid
 */
public static X500Name stringToBcX500Name(String dn, final X500NameStyle nameStyle, final boolean ldaporder) {
    final X500Name x500Name = stringToUnorderedX500Name(dn, nameStyle);
    if (x500Name == null) {
        return null;
    }
    // -- Reorder fields
    final X500Name orderedX500Name = getOrderedX500Name(x500Name, ldaporder, nameStyle);
    if (log.isTraceEnabled()) {
        log.trace(">stringToBcX500Name: x500Name=" + x500Name.toString() + " orderedX500Name="
                + orderedX500Name.toString());
    }
    return orderedX500Name;
}

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

License:Open Source License

public static X500Name stringToUnorderedX500Name(String dn, final X500NameStyle nameStyle) {
    if (log.isTraceEnabled()) {
        log.trace(">stringToUnorderedX500Name: " + dn);
    }//from   ww  w . j a  v  a  2  s .  c o m
    if (dn == null) {
        return null;
    }
    // If the entire DN is quoted (which is strange but legacy), we just remove these quotes and carry on
    if (dn.length() > 2 && dn.charAt(0) == '"' && dn.charAt(dn.length() - 1) == '"') {
        dn = dn.substring(1, dn.length() - 1);
    }
    final X500NameBuilder nameBuilder = new X500NameBuilder(nameStyle);
    boolean quoted = false;
    boolean escapeNext = false;
    int currentStartPosition = -1;
    String currentPartName = null;
    for (int i = 0; i < dn.length(); i++) {
        final char current = dn.charAt(i);
        // Toggle quoting for every non-escaped "-char
        if (!escapeNext && current == '"') {
            quoted = !quoted;
        }
        // If there is an unescaped and unquoted =-char the preceeding chars is a part name
        if (currentStartPosition == -1 && !quoted && !escapeNext && current == '=' && 1 <= i) {
            // Trim spaces (e.g. "O =value")
            int endIndexOfPartName = i;
            while (endIndexOfPartName > 0 && dn.charAt(endIndexOfPartName - 1) == ' ') {
                endIndexOfPartName--;
            }
            int startIndexOfPartName = endIndexOfPartName - 1;
            final String endOfPartNameSearchChars = ", +";
            while (startIndexOfPartName > 0
                    && (endOfPartNameSearchChars.indexOf(dn.charAt(startIndexOfPartName - 1)) == -1)) {
                startIndexOfPartName--;
            }
            currentPartName = dn.substring(startIndexOfPartName, endIndexOfPartName);
            currentStartPosition = i + 1;
        }
        // When we have found a start marker, we need to be on the lookout for the ending marker
        if (currentStartPosition != -1
                && ((!quoted && !escapeNext && (current == ',' || current == '+')) || i == dn.length() - 1)) {
            int endPosition = (i == dn.length() - 1) ? dn.length() - 1 : i - 1;
            // Remove white spaces from the end of the value
            while (endPosition > currentStartPosition && dn.charAt(endPosition) == ' ') {
                endPosition--;
            }
            // Remove white spaces from the beginning of the value
            while (endPosition > currentStartPosition && dn.charAt(currentStartPosition) == ' ') {
                currentStartPosition++;
            }
            // Only return the inner value if the part is quoted
            if (currentStartPosition < dn.length() && dn.charAt(currentStartPosition) == '"'
                    && dn.charAt(endPosition) == '"') {
                currentStartPosition++;
                endPosition--;
            }
            String currentValue = dn.substring(currentStartPosition, endPosition + 1);
            // Unescape value (except escaped #) since the nameBuilder will double each escape
            currentValue = unescapeValue(new StringBuilder(currentValue)).toString();
            try {
                // -- First search the OID by name in declared OID's
                ASN1ObjectIdentifier oid = DnComponents.getOid(currentPartName);
                // -- If isn't declared, we try to create it
                if (oid == null) {
                    oid = new ASN1ObjectIdentifier(currentPartName);
                }
                nameBuilder.addRDN(oid, currentValue);
            } catch (IllegalArgumentException e) {
                // If it is not an OID we will ignore it
                log.warn("Unknown DN component ignored and silently dropped: " + currentPartName);
            }
            // Reset markers
            currentStartPosition = -1;
            currentPartName = null;
        }
        if (escapeNext) {
            // This character was escaped, so don't escape the next one
            escapeNext = false;
        } else {
            if (!quoted && current == '\\') {
                // This escape character is not escaped itself, so the next one should be
                escapeNext = true;
            }
        }
    }
    final X500Name x500Name = nameBuilder.build();
    if (log.isTraceEnabled()) {
        log.trace(">stringToUnorderedX500Name: x500Name=" + x500Name.toString());
    }
    return x500Name;
}

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

License:Open Source License

/**
 * Every DN-string should look the same. Creates a name string ordered and looking like we want it...
 * /*from w ww . ja  va  2  s .  co m*/
 * @param dn String containing DN
 * 
 * @return String containing DN, or null if input is null
 */
public static String stringToBCDNString(String dn) {
    // BC now seem to handle multi-valued RDNs, but we keep escaping this for now to keep the behavior until support is required
    dn = handleUnescapedPlus(dn); // Log warning if dn contains unescaped '+'
    if (isDNReversed(dn)) {
        dn = reverseDN(dn);
    }
    String ret = null;
    final X500Name name = stringToBcX500Name(dn);
    if (name != null) {
        ret = name.toString();
    }
    /*
     * For some databases (MySQL for instance) the database column holding subjectDN is only 250 chars long. There have been strange error
     * reported (clipping DN natuarally) that is hard to debug if DN is more than 250 chars and we don't have a good message
     */
    if ((ret != null) && (ret.length() > 250)) {
        log.info(
                "Warning! DN is more than 250 characters long. Some databases have only 250 characters in the database for SubjectDN. Clipping may occur! DN ("
                        + ret.length() + " chars): " + ret);
    }
    return ret;
}

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

License:Open Source License

/**
 * Obtain a X500Name reordered, if some fields from original X500Name doesn't appear in "ordering" parameter, they will be added at end in the
 * original order.// www. j ava2  s.c  om
 * 
 * @param x500Name the X500Name 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
 * @param nameStyle Controls how the name is encoded. Usually it should be a CeSecoreNameStyle.
 * @return X500Name with ordered conmponents according to the orcering vector
 */
private static X500Name getOrderedX500Name(final X500Name x500Name, boolean ldaporder,
        final X500NameStyle nameStyle) {
    // -- Null prevent
    // Guess order of the input name
    final boolean isLdapOrder = !isDNReversed(x500Name.toString());
    // -- New order for the X509 Fields
    final List<ASN1ObjectIdentifier> newOrdering = new ArrayList<ASN1ObjectIdentifier>();
    final List<ASN1Encodable> newValues = new ArrayList<ASN1Encodable>();
    // -- Add ordered fields
    final ASN1ObjectIdentifier[] allOids = x500Name.getAttributeTypes();
    // 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<ASN1ObjectIdentifier> ordering = getX509FieldOrder(isLdapOrder);
    final HashSet<ASN1ObjectIdentifier> hs = new HashSet<ASN1ObjectIdentifier>(
            allOids.length + ordering.size());
    for (final ASN1ObjectIdentifier oid : ordering) {
        if (!hs.contains(oid)) {
            hs.add(oid);
            final RDN[] valueList = x500Name.getRDNs(oid);
            // -- Only add the OID if has not null value
            for (final RDN value : valueList) {
                newOrdering.add(oid);
                newValues.add(value.getFirst().getValue());
            }
        }
    }
    // -- Add unexpected fields to the end
    for (final ASN1ObjectIdentifier oid : allOids) {
        if (!hs.contains(oid)) {
            hs.add(oid);
            final RDN[] valueList = x500Name.getRDNs(oid);
            // -- Only add the OID if has not null value
            for (final RDN value : valueList) {
                newOrdering.add(oid);
                newValues.add(value.getFirst().getValue());
                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);
    }

    X500NameBuilder nameBuilder = new X500NameBuilder(nameStyle);
    for (int i = 0; i < newOrdering.size(); i++) {
        nameBuilder.addRDN(newOrdering.get(i), newValues.get(i));
    }
    // -- Return X500Name with the ordered fields
    return nameBuilder.build();
}

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

License:Open Source License

/**
 * Checks that the given SubjectDN / SAN satisfies the Name Constraints of the given issuer (if there are any).
 * This method checks the Name Constraints in the given issuer only. A complete implementation of
 * name constraints should check the whole certificate chain.
 * /*from w  w w .  j  a  v  a 2s.  c o  m*/
 * @param issuer Issuing CA.
 * @param subjectDNName Subject DN to check. Optional.
 * @param subjectAltName Subject Alternative Name to check. Optional.
 * @throws CertificateExtensionException
 */
public static void checkNameConstraints(X509Certificate issuer, X500Name subjectDNName,
        GeneralNames subjectAltName) throws IllegalNameException {
    final byte[] ncbytes = issuer.getExtensionValue(Extension.nameConstraints.getId());
    final ASN1OctetString ncstr = (ncbytes != null ? DEROctetString.getInstance(ncbytes) : null);
    final ASN1Sequence ncseq = (ncbytes != null ? DERSequence.getInstance(ncstr.getOctets()) : null);
    final NameConstraints nc = (ncseq != null ? NameConstraints.getInstance(ncseq) : null);

    if (nc != null) {
        if (subjectDNName != null) {
            // Skip check for root CAs
            final X500Name issuerDNName = X500Name.getInstance(issuer.getSubjectX500Principal().getEncoded());
            if (issuerDNName.equals(subjectDNName)) {
                return;
            }
        }

        final PKIXNameConstraintValidator validator = new PKIXNameConstraintValidator();

        GeneralSubtree[] permitted = nc.getPermittedSubtrees();
        GeneralSubtree[] excluded = nc.getExcludedSubtrees();

        if (permitted != null) {
            validator.intersectPermittedSubtree(permitted);
        }
        if (excluded != null) {
            for (GeneralSubtree subtree : excluded) {
                validator.addExcludedSubtree(subtree);
            }
        }

        if (subjectDNName != null) {
            GeneralName dngn = new GeneralName(subjectDNName);
            try {
                validator.checkPermitted(dngn);
                validator.checkExcluded(dngn);
            } catch (PKIXNameConstraintValidatorException e) {
                final String dnStr = subjectDNName.toString();
                final boolean isLdapOrder = dnHasMultipleComponents(dnStr) && !isDNReversed(dnStr);
                if (isLdapOrder) {
                    final String msg = intres.getLocalizedMessage("nameconstraints.x500dnorderrequired");
                    throw new IllegalNameException(msg);
                } else {
                    final String msg = intres.getLocalizedMessage("nameconstraints.forbiddensubjectdn",
                            subjectDNName);
                    throw new IllegalNameException(msg, e);
                }
            }
        }

        if (subjectAltName != null) {
            for (GeneralName sangn : subjectAltName.getNames()) {
                try {
                    validator.checkPermitted(sangn);
                    validator.checkExcluded(sangn);
                } catch (PKIXNameConstraintValidatorException e) {
                    final String msg = intres.getLocalizedMessage("nameconstraints.forbiddensubjectaltname",
                            sangn);
                    throw new IllegalNameException(msg, e);
                }
            }
        }
    }
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

/**
 * Tests the reversing of a DN//www.j  a  v  a2  s . c  o m
 * 
 * @throws Exception
 *             if error...
 */
@Test
public void test09TestReverseDN() throws Exception {
    log.trace(">test09TestReverse()");
    // We try to examine the that we handle modern dc components for ldap
    // correctly
    String dn1 = "dc=com,dc=bigcorp,dc=se,ou=orgunit,ou=users,cn=Tomas G";
    String dn2 = "cn=Tomas G,ou=users,ou=orgunit,dc=se,dc=bigcorp,dc=com";
    assertTrue(CertTools.isDNReversed(dn1));
    assertTrue(!CertTools.isDNReversed(dn2));
    assertTrue(CertTools.isDNReversed("C=SE,CN=Foo"));
    assertTrue(!CertTools.isDNReversed("CN=Foo,O=FooO"));
    String revdn1 = CertTools.reverseDN(dn1);
    log.debug("dn1: " + dn1);
    log.debug("revdn1: " + revdn1);
    assertEquals(dn2, revdn1);

    String dn3 = "cn=toto,cn=titi,dc=domain,dc=tld";
    String revdn3 = CertTools.reverseDN(dn3);
    assertEquals("dc=tld,dc=domain,cn=titi,cn=toto", revdn3);

    X500Name dn4 = CertTools.stringToBcX500Name(dn3, new CeSecoreNameStyle(), true);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", dn4.toString());
    X500Name dn5 = CertTools.stringToBcX500Name(dn3, new CeSecoreNameStyle(), false);
    assertEquals("DC=tld,DC=domain,CN=titi,CN=toto", dn5.toString());
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", CertTools.stringToBCDNString(dn3));

    String dn6 = "dc=tld,dc=domain,cn=titi,cn=toto";
    String revdn6 = CertTools.reverseDN(dn6);
    assertEquals("cn=toto,cn=titi,dc=domain,dc=tld", revdn6);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", CertTools.stringToBCDNString(dn3));

    X500Name dn7 = CertTools.stringToBcX500Name(dn6, new CeSecoreNameStyle(), true);
    assertEquals("CN=toto,CN=titi,DC=domain,DC=tld", dn7.toString());
    X500Name revdn7 = CertTools.stringToBcX500Name(dn6, new CeSecoreNameStyle(), false);
    assertEquals("DC=tld,DC=domain,CN=titi,CN=toto", revdn7.toString());

    // Test the test strings from ECA-1699, to prove that we fixed this issue
    String dn8 = "dc=org,dc=foo,o=FOO,cn=FOO Root CA";
    String dn9 = "cn=FOO Root CA,o=FOO,dc=foo,dc=org";
    String revdn8 = CertTools.reverseDN(dn8);
    assertEquals("cn=FOO Root CA,o=FOO,dc=foo,dc=org", revdn8);
    String revdn9 = CertTools.reverseDN(dn9);
    assertEquals("dc=org,dc=foo,o=FOO,cn=FOO Root CA", revdn9);
    X500Name xdn8ldap = CertTools.stringToBcX500Name(dn8, new CeSecoreNameStyle(), true);
    X500Name xdn8x500 = CertTools.stringToBcX500Name(dn8, new CeSecoreNameStyle(), false);
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", xdn8ldap.toString());
    assertEquals("DC=org,DC=foo,O=FOO,CN=FOO Root CA", xdn8x500.toString());
    X500Name xdn9ldap = CertTools.stringToBcX500Name(dn9, new CeSecoreNameStyle(), true);
    X500Name xdn9x500 = CertTools.stringToBcX500Name(dn9, new CeSecoreNameStyle(), false);
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", xdn9ldap.toString());
    assertEquals("DC=org,DC=foo,O=FOO,CN=FOO Root CA", xdn9x500.toString());
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", CertTools.stringToBCDNString(dn8));
    assertEquals("CN=FOO Root CA,O=FOO,DC=foo,DC=org", CertTools.stringToBCDNString(dn9));

    // Test reversing DNs with multiple OU
    String dn10 = "CN=something,OU=A,OU=B,O=someO,C=SE";
    X500Name x500dn10 = CertTools.stringToBcX500Name(dn10, new CeSecoreNameStyle(), true);
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", x500dn10.toString());
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", CertTools.stringToBCDNString(dn10));

    // When we order forwards (LdapOrder) from the beginning, and request !LdapOrder, everything should be reversed
    X500Name ldapdn11 = CertTools.stringToBcX500Name(dn10, new CeSecoreNameStyle(), false);
    assertEquals("C=SE,O=someO,OU=B,OU=A,CN=something", ldapdn11.toString());

    // When we order backwards (X.509, !LdapOrder) from the beginning, we should not reorder anything
    String dn11 = "C=SE,O=someO,OU=B,OU=A,CN=something";
    X500Name x500dn11 = CertTools.stringToBcX500Name(dn11, new CeSecoreNameStyle(), false);
    assertEquals("C=SE,O=someO,OU=B,OU=A,CN=something", x500dn11.toString());
    assertEquals("CN=something,OU=A,OU=B,O=someO,C=SE", CertTools.stringToBCDNString(dn11));

    log.trace("<test09TestReverse()");
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

@Test
public void test16GetSubjectAltNameStringWithDirectoryName() throws Exception {
    log.trace(">test16GetSubjectAltNameStringWithDirectoryName()");

    Certificate cer = CertTools.getCertfromByteArray(altNameCertWithDirectoryName);
    String altNames = CertTools.getSubjectAlternativeName(cer);
    log.debug(altNames);// w  w w  .java2 s.  c  o m

    String name = CertTools.getPartFromDN(altNames, CertTools.UPN);
    assertEquals("testDirName@jamador.pki.gva.es", name);
    assertEquals("testDirName@jamador.pki.gva.es", CertTools.getUPNAltName(cer));

    name = CertTools.getPartFromDN(altNames, CertTools.DIRECTORYNAME);
    assertEquals("CN=testDirName|dir|name", name.replace("cn=", "CN="));
    assertEquals(name.substring("CN=".length()),
            (new X500Name("CN=testDirName|dir|name").getRDNs()[0].getFirst().getValue()).toString());

    String altName = "rfc822name=foo@bar.se, uri=http://foo.bar.se, directoryName="
            + LDAPDN.escapeRDN("CN=testDirName, O=Foo, OU=Bar, C=SE") + ", dnsName=foo.bar.se";
    GeneralNames san = CertTools.getGeneralNamesFromAltName(altName);
    GeneralName[] gns = san.getNames();
    boolean found = false;
    for (int i = 0; i < gns.length; i++) {
        int tag = gns[i].getTagNo();
        if (tag == 4) {
            found = true;
            ASN1Encodable enc = gns[i].getName();
            X500Name dir = (X500Name) enc;
            String str = dir.toString();
            log.debug("DirectoryName: " + str);
            assertEquals("CN=testDirName,O=Foo,OU=Bar,C=SE", str);
        }

    }
    assertTrue(found);

    altName = "rfc822name=foo@bar.se, rfc822name=foo@bar.com, uri=http://foo.bar.se, directoryName="
            + LDAPDN.escapeRDN("CN=testDirName, O=Foo, OU=Bar, C=SE")
            + ", dnsName=foo.bar.se, dnsName=foo.bar.com";
    san = CertTools.getGeneralNamesFromAltName(altName);
    gns = san.getNames();
    int dnscount = 0;
    int rfc822count = 0;
    for (int i = 0; i < gns.length; i++) {
        int tag = gns[i].getTagNo();
        if (tag == 2) {
            dnscount++;
            ASN1Encodable enc = gns[i].getName();
            DERIA5String dir = (DERIA5String) enc;
            String str = dir.getString();
            log.info("DnsName: " + str);
        }
        if (tag == 1) {
            rfc822count++;
            ASN1Encodable enc = gns[i].getName();
            DERIA5String dir = (DERIA5String) enc;
            String str = dir.getString();
            log.info("Rfc822Name: " + str);
        }

    }
    assertEquals(2, dnscount);
    assertEquals(2, rfc822count);
    log.trace("<test16GetSubjectAltNameStringWithDirectoryName()");
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

@Test
public void testStringToBcX500WithIncompleteLoneValue() {
    //Legal as a name even if it won't be legal as a DN
    X500Name result = CertTools.stringToBcX500Name("O=");
    assertNotNull(result);//from w ww.j a  va  2  s  .  com
    assertEquals("O=", result.toString());
}

From source file:org.cesecore.util.CertToolsTest.java

License:Open Source License

@Test
public void testStringToBcX500WithTrailingComma() {
    X500Name result = CertTools.stringToBcX500Name("CN=,");
    assertNotNull(result);/*w  w w.  j  a v  a  2s  .co m*/
    assertEquals("CN=\\,", result.toString());
}