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

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

Introduction

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

Prototype

public ASN1ObjectIdentifier[] getAttributeTypes() 

Source Link

Document

return an array of OIDs contained in the attribute type of each RDN in structure order.

Usage

From source file:org.cesecore.certificates.util.DnComponentsTest.java

License:Open Source License

@Test
public void test02() {
    String dn = CertTools.stringToBCDNString("uri=fff,CN=oid,SN=12345,NAME=name,C=se");
    final X500Name name = CertTools.stringToBcX500Name(dn);
    ASN1ObjectIdentifier[] oids = name.getAttributeTypes();
    assertEquals(BCStyle.CN, oids[0]);/*from  w  w  w.  ja v a2s .  c  o  m*/
    assertEquals(BCStyle.NAME, oids[1]);
    assertEquals(BCStyle.SERIALNUMBER, oids[2]);
    assertEquals(BCStyle.C, oids[3]);
    assertEquals("CN=oid,Name=name,SN=12345,C=se", dn);

    String dn1 = CertTools.stringToBCDNString("SURNAME=Json,=fff,CN=oid,SN=12345,NAME=name,C=se");
    final X500Name name1 = CertTools.stringToBcX500Name(dn1);
    ASN1ObjectIdentifier[] oids1 = name1.getAttributeTypes();
    assertEquals(BCStyle.CN, oids1[0]);
    assertEquals(BCStyle.NAME, oids1[1]);
    assertEquals(BCStyle.SERIALNUMBER, oids1[2]);
    assertEquals(BCStyle.SURNAME, oids1[3]);
    assertEquals(BCStyle.C, oids1[4]);
    assertEquals("CN=oid,Name=name,SN=12345,SURNAME=Json,C=se", dn1);

    String dn2 = CertTools.stringToBCDNString(
            "jurisdictionCountry=SE,jurisdictionState=Stockholm,SURNAME=Json,=fff,CN=oid,jurisdictionLocality=Solna,SN=12345,unstructuredname=foo.bar.com,unstructuredaddress=1.2.3.4,NAME=name,C=se");
    final X500Name name2 = CertTools.stringToBcX500Name(dn2);
    ASN1ObjectIdentifier[] oids2 = name2.getAttributeTypes();
    assertEquals(CeSecoreNameStyle.JURISDICTION_COUNTRY, oids2[0]);
    assertEquals(CeSecoreNameStyle.JURISDICTION_STATE, oids2[1]);
    assertEquals(CeSecoreNameStyle.JURISDICTION_LOCALITY, oids2[2]);
    assertEquals(CeSecoreNameStyle.UnstructuredAddress, oids2[3]);
    assertEquals(CeSecoreNameStyle.UnstructuredName, oids2[4]);
    assertEquals(BCStyle.CN, oids2[5]);
    assertEquals(BCStyle.NAME, oids2[6]);
    assertEquals(BCStyle.SERIALNUMBER, oids2[7]);
    assertEquals(BCStyle.SURNAME, oids2[8]);
    assertEquals(BCStyle.C, oids2[9]);
    assertEquals(
            "JurisdictionCountry=SE,JurisdictionState=Stockholm,JurisdictionLocality=Solna,unstructuredAddress=1.2.3.4,unstructuredName=foo.bar.com,CN=oid,Name=name,SN=12345,SURNAME=Json,C=se",
            dn2);

}

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./*from w w w . j a  va  2s  .  c  o  m*/
 * 
 * @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.ejbca.core.protocol.cmp.CmpRAUnidTest.java

License:Open Source License

@Override
protected void checkDN(X500Name expected, X500Name actual) {
    final ASN1ObjectIdentifier[] expectedOIDs = expected.getAttributeTypes();
    final ASN1ObjectIdentifier[] actualOIDs = actual.getAttributeTypes();
    assertEquals("Not the expected number of elements in the created certificate.", expectedOIDs.length,
            actualOIDs.length);//from w  w w .  j a v a 2 s. c o m
    String expectedValue, actualValue;
    for (int i = 0; i < expectedOIDs.length; i++) {
        final ASN1ObjectIdentifier oid = expectedOIDs[i];
        expectedValue = expected.getRDNs(oid)[0].getFirst().getValue().toString();
        actualValue = actual.getRDNs(oid)[0].getFirst().getValue().toString();
        if (!oid.equals(BCStyle.SN)) {
            log.debug("Check that " + oid.getId() + " is OK. Expected '" + expectedValue + "'. Actual '"
                    + actualValue + "'.");
            assertEquals("Not expected " + oid, expectedValue, actualValue);
            continue;
        }
        log.debug("Special handling of the SN " + oid.getId() + ". Input '" + expectedValue + "'. Transformed '"
                + actualValue + "'.");
        final String expectedSNPrefix = UNIDPREFIX + LRA;
        final String actualSNPrefix = actualValue.substring(0, expectedSNPrefix.length());
        assertEquals("New serial number prefix not as expected.", expectedSNPrefix, actualSNPrefix);
        final String actualSNRandom = actualValue.substring(expectedSNPrefix.length());
        assertTrue("Random in serial number not OK: " + actualSNRandom,
                Pattern.compile("^\\w{6}$").matcher(actualSNRandom).matches());
    }
}

From source file:org.ejbca.core.protocol.unid.UnidFnrHandler.java

License:Open Source License

@Override
public RequestMessage processRequestMessage(RequestMessage req, String certificateProfileName,
        String unidDataSource) throws HandlerException {

    if (this.storage == null) {
        this.storage = new MyStorage(unidDataSource);
    }/*  ww  w  . jav  a  2s . co  m*/

    final X500Name dn = req.getRequestX500Name();
    if (LOG.isDebugEnabled()) {
        LOG.debug(">processRequestMessage:'" + dn + "' and '" + certificateProfileName + "'");
    }
    final String unidPrefix = getPrefixFromCertProfileName(certificateProfileName);
    if (unidPrefix == null) {
        return req;
    }
    final ASN1ObjectIdentifier[] oids = dn.getAttributeTypes();
    X500NameBuilder nameBuilder = new X500NameBuilder(new CeSecoreNameStyle());
    boolean changed = false;
    for (int i = 0; i < oids.length; i++) {
        if (oids[i].equals(CeSecoreNameStyle.SERIALNUMBER)) {
            RDN[] rdns = dn.getRDNs(oids[i]);
            String value = rdns[0].getFirst().getValue().toString();
            final String newSerial = storeUnidFrnAndGetNewSerialNr(value, unidPrefix);
            if (newSerial != null) {
                nameBuilder.addRDN(oids[i], newSerial);
                changed = true;
            }
        } else {
            nameBuilder.addRDN(dn.getRDNs(oids[i])[0].getFirst());
        }
    }
    if (changed) {
        req = new RequestMessageSubjectDnAdapter(req, nameBuilder.build());
    }
    return req;
}

From source file:org.xipki.ca.api.profile.x509.BaseX509Certprofile.java

License:Open Source License

protected void verifySubjectDNOccurence(final X500Name requestedSubject) throws BadCertTemplateException {
    Set<RDNControl> occurences = getSubjectDNControls();
    if (occurences == null) {
        return;/*w w  w  . ja  va2s  .  c  o  m*/
    }

    ASN1ObjectIdentifier[] types = requestedSubject.getAttributeTypes();
    for (ASN1ObjectIdentifier type : types) {
        RDNControl occu = null;
        for (RDNControl occurence : occurences) {
            if (occurence.getType().equals(type)) {
                occu = occurence;
                break;
            }
        }
        if (occu == null) {
            throw new BadCertTemplateException(
                    "subject DN of type " + oidToDisplayName(type) + " is not allowed");
        }

        RDN[] rdns = requestedSubject.getRDNs(type);
        if (rdns.length > occu.getMaxOccurs() || rdns.length < occu.getMinOccurs()) {
            throw new BadCertTemplateException("occurrence of subject DN of type " + oidToDisplayName(type)
                    + " not within the allowed range. " + rdns.length + " is not within [" + occu.getMinOccurs()
                    + ", " + occu.getMaxOccurs() + "]");
        }
    }

    for (RDNControl occurence : occurences) {
        if (occurence.getMinOccurs() == 0) {
            continue;
        }

        boolean present = false;
        for (ASN1ObjectIdentifier type : types) {
            if (occurence.getType().equals(type)) {
                present = true;
                break;
            }
        }

        if (present == false) {
            throw new BadCertTemplateException(
                    "requied subject DN of type " + oidToDisplayName(occurence.getType()) + " is not present");
        }
    }
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

private List<ValidationIssue> checkSubject(final X500Name subject, final X500Name requestedSubject) {
    // collect subject attribute types to check
    Set<ASN1ObjectIdentifier> oids = new HashSet<>();

    for (ASN1ObjectIdentifier oid : subjectDNOptions.keySet()) {
        oids.add(oid);//  ww w  .j  a v  a2s.  c  o  m
    }

    for (ASN1ObjectIdentifier oid : subject.getAttributeTypes()) {
        oids.add(oid);
    }

    List<ValidationIssue> result = new LinkedList<>();
    for (ASN1ObjectIdentifier type : oids) {
        ValidationIssue issue = checkSubjectAttribute(type, subject, requestedSubject);
        result.add(issue);
    }

    return result;
}

From source file:org.xipki.common.util.X509Util.java

License:Open Source License

public static String canonicalizName(final X500Name name) {
    ASN1ObjectIdentifier[] _types = name.getAttributeTypes();
    int n = _types.length;
    List<String> types = new ArrayList<>(n);
    for (ASN1ObjectIdentifier type : _types) {
        types.add(type.getId());//from  ww w. j ava 2  s . c  o  m
    }

    Collections.sort(types);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
        String type = types.get(i);
        if (i > 0) {
            sb.append(",");
        }
        sb.append(type).append("=");
        RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier(type));

        for (int j = 0; j < rdns.length; j++) {
            if (j > 0) {
                sb.append(";");
            }
            RDN rdn = rdns[j];
            String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()).toLowerCase();
            sb.append(textValue);
        }
    }

    return sb.toString();
}

From source file:org.xipki.commons.security.util.X509Util.java

License:Open Source License

public static String canonicalizName(final X500Name name) {
    ParamUtil.requireNonNull("name", name);
    ASN1ObjectIdentifier[] tmpTypes = name.getAttributeTypes();
    int len = tmpTypes.length;
    List<String> types = new ArrayList<>(len);
    for (ASN1ObjectIdentifier type : tmpTypes) {
        types.add(type.getId());/*from  ww w. ja  v a 2s  .c  o  m*/
    }

    Collections.sort(types);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < len; i++) {
        String type = types.get(i);
        if (i > 0) {
            sb.append(",");
        }
        sb.append(type).append("=");
        RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier(type));

        List<String> values = new ArrayList<>(1);
        for (int j = 0; j < rdns.length; j++) {
            RDN rdn = rdns[j];
            if (rdn.isMultiValued()) {
                AttributeTypeAndValue[] atvs = rdn.getTypesAndValues();
                for (AttributeTypeAndValue atv : atvs) {
                    if (type.equals(atv.getType().getId())) {
                        String textValue = IETFUtils.valueToString(atv.getValue()).toLowerCase();
                        values.add(textValue);
                    }
                }
            } else {
                String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()).toLowerCase();
                values.add(textValue);
            }
        } // end for(j)

        sb.append(values.get(0));

        final int n2 = values.size();
        if (n2 > 1) {
            for (int j = 1; j < n2; j++) {
                sb.append(";").append(values.get(j));
            }
        }
    } // end for(i)

    return sb.toString();
}

From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java

License:Open Source License

protected void verifySubjectDnOccurence(final X500Name requestedSubject) throws BadCertTemplateException {
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);

    SubjectControl occurences = getSubjectControl();
    if (occurences == null) {
        return;/*  w  w w  . jav a  2s .  co  m*/
    }

    ASN1ObjectIdentifier[] types = requestedSubject.getAttributeTypes();
    for (ASN1ObjectIdentifier type : types) {
        RdnControl occu = occurences.getControl(type);
        if (occu == null) {
            throw new BadCertTemplateException(
                    String.format("subject DN of type %s is not allowed", oidToDisplayName(type)));
        }

        RDN[] rdns = requestedSubject.getRDNs(type);
        if (rdns.length > occu.getMaxOccurs() || rdns.length < occu.getMinOccurs()) {
            throw new BadCertTemplateException(String.format(
                    "occurrence of subject DN of type %s not within the allowed range. "
                            + "%d is not within [%d, %d]",
                    oidToDisplayName(type), rdns.length, occu.getMinOccurs(), occu.getMaxOccurs()));
        }
    }

    for (ASN1ObjectIdentifier m : occurences.getTypes()) {
        RdnControl occurence = occurences.getControl(m);
        if (occurence.getMinOccurs() == 0) {
            continue;
        }

        boolean present = false;
        for (ASN1ObjectIdentifier type : types) {
            if (occurence.getType().equals(type)) {
                present = true;
                break;
            }
        }

        if (!present) {
            throw new BadCertTemplateException(String.format("required subject DN of type %s is not present",
                    oidToDisplayName(occurence.getType())));
        }
    }
}

From source file:org.xipki.pki.ca.qa.SubjectChecker.java

License:Open Source License

public List<ValidationIssue> checkSubject(final X500Name subject, final X500Name requestedSubject) {
    ParamUtil.requireNonNull("subject", subject);
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);

    // collect subject attribute types to check
    Set<ASN1ObjectIdentifier> oids = new HashSet<>();

    for (ASN1ObjectIdentifier oid : subjectControl.getTypes()) {
        oids.add(oid);/*from w ww.  j a va  2s  . c o  m*/
    }

    for (ASN1ObjectIdentifier oid : subject.getAttributeTypes()) {
        oids.add(oid);
    }

    List<ValidationIssue> result = new LinkedList<>();

    ValidationIssue issue = new ValidationIssue("X509.SUBJECT.group", "X509 subject RDN group");
    result.add(issue);
    if (CollectionUtil.isNonEmpty(subjectControl.getGroups())) {
        Set<String> groups = new HashSet<>(subjectControl.getGroups());
        for (String g : groups) {
            boolean toBreak = false;
            RDN rdn = null;
            for (ASN1ObjectIdentifier type : subjectControl.getTypesForGroup(g)) {
                RDN[] rdns = subject.getRDNs(type);
                if (rdns == null || rdns.length == 0) {
                    continue;
                }

                if (rdns.length > 1) {
                    issue.setFailureMessage("AttributeTypeAndValues of group " + g + " is not in one RDN");
                    toBreak = true;
                    break;
                }

                if (rdn == null) {
                    rdn = rdns[0];
                } else if (rdn != rdns[0]) {
                    issue.setFailureMessage("AttributeTypeAndValues of group " + g + " is not in one RDN");
                    toBreak = true;
                    break;
                }
            }

            if (toBreak) {
                break;
            }
        }
    }

    for (ASN1ObjectIdentifier type : oids) {
        ValidationIssue valIssue;
        try {
            valIssue = checkSubjectAttribute(type, subject, requestedSubject);
        } catch (BadCertTemplateException ex) {
            valIssue = new ValidationIssue("X509.SUBJECT.REQUEST", "Subject in request");
            valIssue.setFailureMessage(ex.getMessage());
        }
        result.add(valIssue);
    }

    return result;
}