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

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

Introduction

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

Prototype

public RDN[] getRDNs() 

Source Link

Document

return an array of RDNs in structure order.

Usage

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

License:Open Source License

private static X500Name sortX500Name(final X500Name name, final boolean backwards) {
    RDN[] requstedRDNs = name.getRDNs();

    List<RDN> rdns = new LinkedList<>();

    List<ASN1ObjectIdentifier> sortedDNs = backwards ? ObjectIdentifiers.getBackwardDNs()
            : ObjectIdentifiers.getForwardDNs();
    int size = sortedDNs.size();
    for (int i = 0; i < size; i++) {
        ASN1ObjectIdentifier type = sortedDNs.get(i);
        RDN[] thisRDNs = getRDNs(requstedRDNs, type);
        int n = thisRDNs == null ? 0 : thisRDNs.length;
        if (n == 0) {
            continue;
        }//from   w  ww.  j  ava 2  s . c  o m

        for (RDN thisRDN : thisRDNs) {
            rdns.add(thisRDN);
        }
    }

    return new X500Name(rdns.toArray(new RDN[0]));
}

From source file:org.xipki.commons.security.shell.p12.P12ComplexCertRequestGenCmd.java

License:Open Source License

@Override
protected X500Name getSubject(final String subject) {
    X500Name name = new X500Name(subject);
    List<RDN> list = new LinkedList<>();
    RDN[] rs = name.getRDNs();
    for (RDN m : rs) {
        list.add(m);/* w w w . j a  va 2  s  .com*/
    }

    ASN1ObjectIdentifier id;

    // dateOfBirth
    if (complexSubject.booleanValue()) {
        id = ObjectIdentifiers.DN_DATE_OF_BIRTH;
        RDN[] rdns = name.getRDNs(id);

        if (rdns == null || rdns.length == 0) {
            ASN1Encodable atvValue = new DERGeneralizedTime("19950102120000Z");
            RDN rdn = new RDN(id, atvValue);
            list.add(rdn);
        }
    }

    // postalAddress
    if (complexSubject.booleanValue()) {
        id = ObjectIdentifiers.DN_POSTAL_ADDRESS;
        RDN[] rdns = name.getRDNs(id);

        if (rdns == null || rdns.length == 0) {
            ASN1EncodableVector vec = new ASN1EncodableVector();
            vec.add(new DERUTF8String("my street 1"));
            vec.add(new DERUTF8String("12345 Germany"));

            ASN1Sequence atvValue = new DERSequence(vec);
            RDN rdn = new RDN(id, atvValue);
            list.add(rdn);
        }
    }

    // DN_UNIQUE_IDENTIFIER
    id = ObjectIdentifiers.DN_UNIQUE_IDENTIFIER;
    RDN[] rdns = name.getRDNs(id);

    if (rdns == null || rdns.length == 0) {
        DERUTF8String atvValue = new DERUTF8String("abc-def-ghi");
        RDN rdn = new RDN(id, atvValue);
        list.add(rdn);
    }

    return new X500Name(list.toArray(new RDN[0]));
}

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

License:Open Source License

public static X500Name reverse(final X500Name name) {
    ParamUtil.requireNonNull("name", name);
    RDN[] orig = name.getRDNs();
    final int n = orig.length;
    RDN[] newRdn = new RDN[n];
    for (int i = 0; i < n; i++) {
        newRdn[i] = orig[n - 1 - i];/*from  w  w  w .j a v a 2s  .c o  m*/
    }
    return new X500Name(newRdn);
}

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

License:Open Source License

@Override
public SubjectInfo getSubject(final X500Name requestedSubject)
        throws CertprofileException, BadCertTemplateException {
    ParamUtil.requireNonNull("requestedSubject", requestedSubject);

    verifySubjectDnOccurence(requestedSubject);

    RDN[] requstedRdns = requestedSubject.getRDNs();
    SubjectControl scontrol = getSubjectControl();

    List<RDN> rdns = new LinkedList<>();

    for (ASN1ObjectIdentifier type : scontrol.getTypes()) {
        RdnControl control = scontrol.getControl(type);
        if (control == null) {
            continue;
        }/* w w w  .j a v  a  2  s .  c o m*/

        RDN[] thisRdns = getRdns(requstedRdns, type);
        if (thisRdns == null) {
            continue;
        }
        int len = thisRdns.length;
        if (len == 0) {
            continue;
        }

        if (ObjectIdentifiers.DN_EmailAddress.equals(type)) {
            throw new BadCertTemplateException("emailAddress is not allowed");
        }

        if (len == 1) {
            ASN1Encodable rdnValue = thisRdns[0].getFirst().getValue();
            RDN rdn;
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                rdn = createDateOfBirthRdn(type, rdnValue);
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                rdn = createPostalAddressRdn(type, rdnValue, control, 0);
            } else {
                String value = X509Util.rdnValueToString(rdnValue);
                rdn = createSubjectRdn(value, type, control, 0);
            }

            if (rdn != null) {
                rdns.add(rdn);
            }
        } else {
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createDateOfBirthRdn(type, thisRdns[i].getFirst().getValue());
                    rdns.add(rdn);
                }
            } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) {
                for (int i = 0; i < len; i++) {
                    RDN rdn = createPostalAddressRdn(type, thisRdns[i].getFirst().getValue(), control, i);
                    rdns.add(rdn);
                }
            } else {
                String[] values = new String[len];
                for (int i = 0; i < len; i++) {
                    values[i] = X509Util.rdnValueToString(thisRdns[i].getFirst().getValue());
                }
                values = sortRdns(control, values);

                int idx = 0;
                for (String value : values) {
                    rdns.add(createSubjectRdn(value, type, control, idx++));
                }
            } // if
        } // if
    } // for

    Set<String> subjectDnGroups = scontrol.getGroups();
    if (CollectionUtil.isNonEmpty(subjectDnGroups)) {
        Set<String> consideredGroups = new HashSet<>();
        final int n = rdns.size();

        List<RDN> newRdns = new ArrayList<>(rdns.size());
        for (int i = 0; i < n; i++) {
            RDN rdn = rdns.get(i);
            ASN1ObjectIdentifier type = rdn.getFirst().getType();
            String group = scontrol.getGroup(type);
            if (group == null) {
                newRdns.add(rdn);
            } else if (!consideredGroups.contains(group)) {
                List<AttributeTypeAndValue> atvs = new LinkedList<>();
                atvs.add(rdn.getFirst());
                for (int j = i + 1; j < n; j++) {
                    RDN rdn2 = rdns.get(j);
                    ASN1ObjectIdentifier type2 = rdn2.getFirst().getType();
                    String group2 = scontrol.getGroup(type2);
                    if (group.equals(group2)) {
                        atvs.add(rdn2.getFirst());
                    }
                }

                newRdns.add(new RDN(atvs.toArray(new AttributeTypeAndValue[0])));
                consideredGroups.add(group);
            }
        } // for

        rdns = newRdns;
    } // if

    X500Name grantedSubject = new X500Name(rdns.toArray(new RDN[0]));
    return new SubjectInfo(grantedSubject, null);
}

From source file:org.xipki.pki.ca.server.impl.store.CertStoreQueryExecutor.java

License:Open Source License

List<CertListInfo> listCertificates(final X509Cert caCert, final X500Name subjectPattern, final Date validFrom,
        final Date validTo, final CertListOrderBy orderBy, final int numEntries)
        throws DataAccessException, OperationException {
    ParamUtil.requireNonNull("caCert", caCert);
    ParamUtil.requireMin("numEntries", numEntries, 1);

    int caId = getCaId(caCert);
    StringBuilder sb = new StringBuilder(200);
    sb.append("SN,NBEFORE,NAFTER,SUBJECT FROM CERT WHERE CA_ID=?");
    //.append(caId)

    Integer idxNotBefore = null;/*from   w w w  .ja  v a2 s  . co m*/
    Integer idxNotAfter = null;
    Integer idxSubject = null;

    int idx = 2;
    if (validFrom != null) {
        idxNotBefore = idx++;
        sb.append(" AND NBEFORE<?");
    }
    if (validTo != null) {
        idxNotAfter = idx++;
        sb.append(" AND NAFTER>?");
    }

    String subjectLike = null;
    if (subjectPattern != null) {
        idxSubject = idx++;
        sb.append(" AND SUBJECT LIKE ?");

        StringBuilder buffer = new StringBuilder(100);
        buffer.append("%");
        RDN[] rdns = subjectPattern.getRDNs();
        for (int i = 0; i < rdns.length; i++) {
            X500Name rdnName = new X500Name(new RDN[] { rdns[i] });
            String rdnStr = X509Util.getRfc4519Name(rdnName);
            if (rdnStr.indexOf('%') != -1) {
                throw new OperationException(ErrorCode.BAD_REQUEST,
                        "the character '%' is not allowed in subjectPattern");
            }
            if (rdnStr.indexOf('*') != -1) {
                rdnStr = rdnStr.replace('*', '%');
            }
            buffer.append(rdnStr);
            buffer.append("%");
        }
        subjectLike = buffer.toString();
    }

    String sortByStr = null;
    if (orderBy != null) {
        switch (orderBy) {
        case NOT_BEFORE:
            sortByStr = "NBEFORE";
            break;
        case NOT_BEFORE_DESC:
            sortByStr = "NBEFORE DESC";
            break;
        case NOT_AFTER:
            sortByStr = "NAFTER";
            break;
        case NOT_AFTER_DESC:
            sortByStr = "NAFTER DESC";
            break;
        case SUBJECT:
            sortByStr = "SUBJECT";
            break;
        case SUBJECT_DESC:
            sortByStr = "SUBJECT DESC";
            break;
        default:
            throw new RuntimeException("unknown CertListOrderBy " + orderBy);
        }
    }

    final String sql = datasource.buildSelectFirstSql(sb.toString(), numEntries, sortByStr);
    ResultSet rs = null;
    PreparedStatement ps = borrowPreparedStatement(sql);

    List<CertListInfo> ret = new LinkedList<>();

    try {
        ps.setInt(1, caId);

        if (idxNotBefore != null) {
            @SuppressWarnings("null")
            long time = validFrom.getTime() / 1000;
            ps.setLong(idxNotBefore, time - 1);
        }

        if (idxNotAfter != null) {
            @SuppressWarnings("null")
            long time = validTo.getTime() / 1000;
            ps.setLong(idxNotAfter, time);
        }

        if (idxSubject != null) {
            ps.setString(idxSubject, subjectLike);
        }

        rs = ps.executeQuery();
        while (rs.next()) {
            String snStr = rs.getString("SN");
            BigInteger sn = new BigInteger(snStr, 16);
            Date notBefore = new Date(rs.getLong("NBEFORE") * 1000);
            Date notAfter = new Date(rs.getLong("NAFTER") * 1000);
            String subject = rs.getString("SUBJECT");
            CertListInfo info = new CertListInfo(sn, subject, notBefore, notAfter);
            ret.add(info);
        }
    } catch (SQLException ex) {
        throw datasource.translate(sql, ex);
    } finally {
        releaseDbResources(ps, rs);
    }

    return ret;
}

From source file:org.xipki.pki.ca.server.impl.store.CertStoreQueryExecutor.java

License:Open Source License

String getLatestSerialNumber(final X500Name nameWithSn) throws OperationException {
    RDN[] rdns1 = nameWithSn.getRDNs();
    RDN[] rdns2 = new RDN[rdns1.length];
    for (int i = 0; i < rdns1.length; i++) {
        RDN rdn = rdns1[i];/*w  ww . jav  a  2 s.c  om*/
        rdns2[i] = rdn.getFirst().getType().equals(ObjectIdentifiers.DN_SERIALNUMBER)
                ? new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString("%"))
                : rdn;
    }

    String namePattern = X509Util.getRfc4519Name(new X500Name(rdns2));

    final String sql = sqls.sqlLatestSerialForSubjectLike;
    ;
    ResultSet rs = null;
    PreparedStatement ps;
    try {
        ps = borrowPreparedStatement(sql);
    } catch (DataAccessException ex) {
        throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
    }

    String subjectStr;

    try {
        ps.setString(1, namePattern);
        rs = ps.executeQuery();
        if (!rs.next()) {
            return null;
        }

        subjectStr = rs.getString("SUBJECT");
    } catch (SQLException ex) {
        throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage());
    } finally {
        releaseDbResources(ps, rs);
    }

    X500Name lastName = new X500Name(subjectStr);
    RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN_SERIALNUMBER);
    if (rdns == null || rdns.length == 0) {
        return null;
    }

    return X509Util.rdnValueToString(rdns[0].getFirst().getValue());
}

From source file:org.xipki.pki.ca.server.impl.util.CaUtil.java

License:Open Source License

public static X500Name sortX509Name(final X500Name name) {
    ParamUtil.requireNonNull("name", name);
    RDN[] requstedRdns = name.getRDNs();

    List<RDN> rdns = new LinkedList<>();

    List<ASN1ObjectIdentifier> sortedDNs = SubjectDnSpec.getForwardDNs();
    int size = sortedDNs.size();
    for (int i = 0; i < size; i++) {
        ASN1ObjectIdentifier type = sortedDNs.get(i);
        RDN[] thisRdns = getRdns(requstedRdns, type);
        if (thisRdns == null) {
            continue;
        }/* w  w  w .  j a v a 2  s . com*/
        if (thisRdns.length == 0) {
            continue;
        }

        for (RDN m : thisRdns) {
            rdns.add(m);
        }
    }

    return new X500Name(rdns.toArray(new RDN[0]));
}

From source file:org.xipki.pki.ca.server.impl.X509Ca.java

License:Open Source License

private static X500Name removeEmptyRdns(final X500Name name) {
    RDN[] rdns = name.getRDNs();
    List<RDN> tmpRdns = new ArrayList<>(rdns.length);
    boolean changed = false;
    for (RDN rdn : rdns) {
        String textValue = X509Util.rdnValueToString(rdn.getFirst().getValue());
        if (StringUtil.isBlank(textValue)) {
            changed = true;//from  w w  w  .  j a v  a  2s .c  om
        } else {
            tmpRdns.add(rdn);
        }
    }

    return changed ? new X500Name(tmpRdns.toArray(new RDN[0])) : name;
}

From source file:org.xipki.pki.ca.server.impl.X509Ca.java

License:Open Source License

private static Object[] incSerialNumber(final IdentifiedX509Certprofile profile, final X500Name origName,
        final String latestSn) throws BadFormatException {
    RDN[] rdns = origName.getRDNs();

    int commonNameIndex = -1;
    int serialNumberIndex = -1;
    for (int i = 0; i < rdns.length; i++) {
        RDN rdn = rdns[i];/*w ww .  ja  va  2s.  com*/
        ASN1ObjectIdentifier type = rdn.getFirst().getType();
        if (ObjectIdentifiers.DN_CN.equals(type)) {
            commonNameIndex = i;
        } else if (ObjectIdentifiers.DN_SERIALNUMBER.equals(type)) {
            serialNumberIndex = i;
        }
    }

    String newSerialNumber = profile.incSerialNumber(latestSn);
    RDN serialNumberRdn = new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString(newSerialNumber));

    X500Name newName;
    if (serialNumberIndex != -1) {
        rdns[serialNumberIndex] = serialNumberRdn;
        newName = new X500Name(rdns);
    } else {
        List<RDN> newRdns = new ArrayList<>(rdns.length + 1);

        if (commonNameIndex == -1) {
            newRdns.add(serialNumberRdn);
        }

        for (int i = 0; i < rdns.length; i++) {
            newRdns.add(rdns[i]);
            if (i == commonNameIndex) {
                newRdns.add(serialNumberRdn);
            }
        }

        newName = new X500Name(newRdns.toArray(new RDN[0]));
    }

    return new Object[] { newName, newSerialNumber };
}

From source file:test.integ.be.e_contract.mycarenet.certra.CertRAClientTest.java

License:Open Source License

@Test
public void testGenerateCertificate() throws Exception {
    CertRASession certRASession = new CertRASession("info@e-contract.be", "0478/299492");

    String ssin = CertRAClient.getSSIN(this.signCertificateChain.get(0));

    X500NameBuilder nameBuilder = new X500NameBuilder();
    nameBuilder.addRDN(X509ObjectIdentifiers.countryName, new DERPrintableString("BE"));
    nameBuilder.addRDN(X509ObjectIdentifiers.organization, new DERPrintableString("Federal Government"));
    nameBuilder.addRDN(X509ObjectIdentifiers.organizationalUnitName,
            new DERPrintableString("eHealth-platform Belgium"));
    nameBuilder.addRDN(X509ObjectIdentifiers.organizationalUnitName, new DERPrintableString("SSIN=" + ssin));
    nameBuilder.addRDN(X509ObjectIdentifiers.commonName, new DERPrintableString("SSIN=" + ssin));
    X500Name name = nameBuilder.build();
    byte[] encodedCsr = certRASession.generateCSR(name);

    PKCS10CertificationRequest csr = new PKCS10CertificationRequest(encodedCsr);
    LOG.debug("CSR subject: " + csr.getSubject());
    X500Name subjectName = csr.getSubject();
    RDN[] rdns = subjectName.getRDNs();
    for (RDN rdn : rdns) {
        LOG.debug("--------");
        AttributeTypeAndValue[] attributes = rdn.getTypesAndValues();
        for (AttributeTypeAndValue attribute : attributes) {
            LOG.debug(attribute.getType() + " = " + attribute.getValue());
            LOG.debug("value type: " + attribute.getValue().getClass().getName());
        }/*  www. jav a2s.  c  o  m*/
    }
}