org.bouncycastle.asn1.x500.RDN Java Examples

The following examples show how to use org.bouncycastle.asn1.x500.RDN. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the (first) value of the (first) RDN of type rdnOid
 *
 * @param dn The X500Name
 * @param rdnOid OID of wanted RDN
 * @return Value of requested RDN
 */
public static String getRdn(X500Name dn, ASN1ObjectIdentifier rdnOid) {

	if (dn == null || rdnOid == null) {
		return "";
	}

	RDN[] rdns = dn.getRDNs(rdnOid);
	String value = "";

	if (rdns.length > 0) {
		RDN rdn = rdns[0];
		value = rdn.getFirst().getValue().toString();
	}

	return value;
}
 
Example #2
Source File: CertUtils.java    From oxAuth with MIT License 6 votes vote down vote up
@NotNull
public static String getCN(@Nullable X509Certificate cert) {
    try {
        if (cert == null) {
            return "";
        }
        X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
        final RDN[] rdns = x500name.getRDNs(BCStyle.CN);
        if (rdns == null || rdns.length == 0) {
            return "";
        }
        RDN cn = rdns[0];

        if (cn != null && cn.getFirst() != null && cn.getFirst().getValue() != null) {
            return IETFUtils.valueToString(cn.getFirst().getValue());
        }
    } catch (CertificateEncodingException e) {
        log.error(e.getMessage(), e);
    }
    return "";
}
 
Example #3
Source File: UserIdentityExtractor.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Override
public Object extractUserIdentity(X509Certificate[] certs) {

    if (certs == null || certs.length == 0)
        throw new IllegalArgumentException();

    X500Name name = x500Name.apply(certs);
    if (name != null) {
        RDN[] rnds = name.getRDNs(x500NameStyle);
        if (rnds != null && rnds.length > 0) {
            RDN cn = rnds[0];
            return IETFUtils.valueToString(cn.getFirst().getValue());
        }
    }
    return null;
}
 
Example #4
Source File: CaUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static X500Name sortX509Name(X500Name name) {
  Args.notNull(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;
    }
    if (thisRdns.length == 0) {
      continue;
    }

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

  return new X500Name(rdns.toArray(new RDN[0]));
}
 
Example #5
Source File: X509Util.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static String getCommonName(X500Name name) {
  Args.notNull(name, "name");
  RDN[] rdns = name.getRDNs(ObjectIdentifiers.DN.CN);
  if (rdns != null && rdns.length > 0) {
    RDN rdn = rdns[0];
    AttributeTypeAndValue atv = null;
    if (rdn.isMultiValued()) {
      for (AttributeTypeAndValue m : rdn.getTypesAndValues()) {
        if (m.getType().equals(ObjectIdentifiers.DN.CN)) {
          atv = m;
          break;
        }
      }
    } else {
      atv = rdn.getFirst();
    }
    return (atv == null) ? null : rdnValueToString(atv.getValue());
  }
  return null;
}
 
Example #6
Source File: NameUtil.java    From portecle with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets the common name from the given X500Name.
 *
 * @param name the X.500 name
 * @return the common name, null if not found
 */
public static String getCommonName(X500Name name)
{
	if (name == null)
	{
		return null;
	}

	RDN[] rdns = name.getRDNs(BCStyle.CN);
	if (rdns.length == 0)
	{
		return null;
	}

	return rdns[0].getFirst().getValue().toString();
}
 
Example #7
Source File: LdapAuthenticator.java    From keywhiz with Apache License 2.0 6 votes vote down vote up
private Set<String> rolesFromDN(String userDN) throws LDAPException, GeneralSecurityException {
  SearchRequest searchRequest = new SearchRequest(config.getRoleBaseDN(),
      SearchScope.SUB, Filter.createEqualityFilter("uniqueMember", userDN));
  Set<String> roles = Sets.newLinkedHashSet();

  LDAPConnection connection = connectionFactory.getLDAPConnection();
  try {
    SearchResult sr = connection.search(searchRequest);

    for (SearchResultEntry sre : sr.getSearchEntries()) {
      X500Name x500Name = new X500Name(sre.getDN());
      RDN[] rdns = x500Name.getRDNs(BCStyle.CN);
      if (rdns.length == 0) {
        logger.error("Could not create X500 Name for role:" + sre.getDN());
      } else {
        String commonName = IETFUtils.valueToString(rdns[0].getFirst().getValue());
        roles.add(commonName);
      }
    }
  } finally {
    connection.close();
  }

  return roles;
}
 
Example #8
Source File: ZTSClientTest.java    From athenz with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateInstanceRefreshRequestSubDomain() {

    File privkey = new File("./src/test/resources/unit_test_private_k0.pem");
    PrivateKey privateKey = Crypto.loadPrivateKey(privkey);

    InstanceRefreshRequest req = ZTSClient.generateInstanceRefreshRequest("coretech.system",
            "test", privateKey, "aws", 3600);
    assertNotNull(req);

    PKCS10CertificationRequest certReq = Crypto.getPKCS10CertRequest(req.getCsr());
    assertEquals("coretech.system.test", Crypto.extractX509CSRCommonName(certReq));

    X500Name x500name = certReq.getSubject();
    RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0];
    assertEquals("coretech.system.test", IETFUtils.valueToString(cnRdn.getFirst().getValue()));
    assertEquals("test.coretech-system.aws.athenz.cloud", Crypto.extractX509CSRDnsNames(certReq).get(0));
}
 
Example #9
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static String extractX509CSRSubjectField(PKCS10CertificationRequest certReq, ASN1ObjectIdentifier id) {

        X500Name x500name = certReq.getSubject();
        if (x500name == null) {
            return null;
        }
        RDN[] rdns = x500name.getRDNs(id);

        // we're only supporting a single field in Athenz certificates so
        // any other multiple value will be considered invalid

        if (rdns == null || rdns.length == 0) {
            return null;
        }

        if (rdns.length != 1) {
            throw new CryptoException("CSR Subject contains multiple values for the same field.");
        }

        return IETFUtils.valueToString(rdns[0].getFirst().getValue());
    }
 
Example #10
Source File: Crypto.java    From athenz with Apache License 2.0 6 votes vote down vote up
public static String extractX509CertSubjectField(X509Certificate x509Cert, ASN1ObjectIdentifier id) {

        String principalName = x509Cert.getSubjectX500Principal().getName();
        ///CLOVER:OFF
        if (principalName == null || principalName.isEmpty()) {
            return null;
        }
        ///CLOVER:ON
        X500Name x500name = new X500Name(principalName);
        RDN[] rdns = x500name.getRDNs(id);

        // we're only supporting a single field in Athenz certificates so
        // any other multiple value will be considered invalid

        if (rdns == null || rdns.length == 0) {
            return null;
        }
        ///CLOVER:OFF
        if (rdns.length != 1) {
            throw new CryptoException("CSR Subject contains multiple values for the same field.");
        }
        ///CLOVER:ON
        return IETFUtils.valueToString(rdns[0].getFirst().getValue());
    }
 
Example #11
Source File: RdnPanelList.java    From keystore-explorer with GNU General Public License v3.0 6 votes vote down vote up
public RdnPanelList(X500Name x500Name, boolean editable) {
	setLayout(new MigLayout("insets dialog, flowy", "[right]", "[]rel[]"));

	// we have to reverse RDN order for dialog
	List<RDN> rdnsAsList = Arrays.asList(x500Name.getRDNs());
	Collections.reverse(rdnsAsList);

	for (RDN rdn : rdnsAsList) {
		this.editable = editable;
		for (AttributeTypeAndValue atav : rdn.getTypesAndValues()) {
			String type = OidDisplayNameMapping.getDisplayNameForOid(atav.getType().getId());
			String value = atav.getValue().toString();
			addItem(new RdnPanel(new JComboBox<Object>(comboBoxEntries), type, value, this, editable));
		}
	}
}
 
Example #12
Source File: XmppDomainVerifier.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
private static List<String> getCommonNames(X509Certificate certificate) {
    List<String> domains = new ArrayList<>();
    try {
        X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
        RDN[] rdns = x500name.getRDNs(BCStyle.CN);
        for (int i = 0; i < rdns.length; ++i) {
            domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue()));
        }
        return domains;
    } catch (CertificateEncodingException e) {
        return domains;
    }
}
 
Example #13
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RDN createPostalAddressRdn(ASN1ObjectIdentifier type, ASN1Encodable rdnValue,
    RdnControl control, int index) throws BadCertTemplateException {
  Args.notNull(type, "type");

  if (!(rdnValue instanceof ASN1Sequence)) {
    throw new BadCertTemplateException("rdnValue of RDN postalAddress has incorrect syntax");
  }

  ASN1Sequence seq = (ASN1Sequence) rdnValue;
  final int size = seq.size();
  if (size < 1 || size > 6) {
    throw new BadCertTemplateException(
        "Sequence size of RDN postalAddress is not within [1, 6]: " + size);
  }

  ASN1EncodableVector vec = new ASN1EncodableVector();
  for (int i = 0; i < size; i++) {
    ASN1Encodable line = seq.getObjectAt(i);
    String text;
    if (line instanceof ASN1String && !(line instanceof DERUniversalString)) {
      text = ((ASN1String) line).getString();
    } else {
      throw new BadCertTemplateException(
        String.format("postalAddress[%d] has incorrect syntax", i));
    }

    ASN1Encodable asn1Line = createRdnValue(text, type, control, index);
    vec.add(asn1Line);
  }

  return new RDN(type, new DERSequence(vec));
}
 
Example #14
Source File: SubjectChecker.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static String getRdnTextValueOfRequest(RDN requestedRdn)
    throws BadCertTemplateException {
  ASN1ObjectIdentifier type = requestedRdn.getFirst().getType();
  ASN1Encodable vec = requestedRdn.getFirst().getValue();
  if (ObjectIdentifiers.DN.dateOfBirth.equals(type)) {
    if (!(vec instanceof ASN1GeneralizedTime)) {
      throw new BadCertTemplateException("requested RDN is not of GeneralizedTime");
    }
    return ((ASN1GeneralizedTime) vec).getTimeString();
  } else if (ObjectIdentifiers.DN.postalAddress.equals(type)) {
    if (!(vec instanceof ASN1Sequence)) {
      throw new BadCertTemplateException("requested RDN is not of Sequence");
    }

    ASN1Sequence seq = (ASN1Sequence) vec;
    final int n = seq.size();

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < n; i++) {
      ASN1Encodable obj = seq.getObjectAt(i);
      String textValue = X509Util.rdnValueToString(obj);
      sb.append("[").append(i).append("]=").append(textValue).append(",");
    }

    return sb.toString();
  } else {
    return X509Util.rdnValueToString(vec);
  }
}
 
Example #15
Source File: ClientAuthenticator.java    From keywhiz with Apache License 2.0 5 votes vote down vote up
static Optional<String> getClientName(Principal principal) {
  X500Name name = new X500Name(principal.getName());
  RDN[] rdns = name.getRDNs(BCStyle.CN);
  if (rdns.length == 0) {
    logger.warn("Certificate does not contain CN=xxx,...: {}", principal.getName());
    return Optional.empty();
  }
  return Optional.of(IETFUtils.valueToString(rdns[0].getFirst().getValue()));
}
 
Example #16
Source File: X500NameUtils.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Return CN of a X.500 name
 *
 * @param name X.500 name object
 * @return CN from Name or an empty string if no CN found
 */
public static String extractCN(X500Name name) {
	for (RDN rdn : name.getRDNs()) {
		AttributeTypeAndValue atav = rdn.getFirst();

		if (atav.getType().equals(BCStyle.CN)) {
			return atav.getValue().toString();
		}
	}

	return "";
}
 
Example #17
Source File: CertStore.java    From xipki with Apache License 2.0 5 votes vote down vote up
public String getLatestSerialNumber(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];
    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 = sqlLatestSerialForSubjectLike;
  ResultSet rs = null;
  PreparedStatement ps = borrowPreparedStatement(sql);

  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(DATABASE_FAILURE, ex.getMessage());
  } finally {
    datasource.releaseResources(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());
}
 
Example #18
Source File: X509Util.java    From xipki with Apache License 2.0 5 votes vote down vote up
public static X500Name reverse(X500Name name) {
  RDN[] orig = Args.notNull(name, "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];
  }
  return new X500Name(newRdn);
}
 
Example #19
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
protected RDN createSubjectRdn(String text, ASN1ObjectIdentifier type, RdnControl option,
    int index) throws BadCertTemplateException {
  if (ObjectIdentifiers.DN.emailAddress.equals(type)) {
    text = text.toLowerCase();
  }

  ASN1Encodable rdnValue = createRdnValue(text, type, option, index);
  return (rdnValue == null) ? null : new RDN(type, rdnValue);
}
 
Example #20
Source File: X509Ca.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static X500Name removeEmptyRdns(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;
    } else {
      tmpRdns.add(rdn);
    }
  }

  return changed ? new X500Name(tmpRdns.toArray(new RDN[0])) : name;
}
 
Example #21
Source File: DDistinguishedNameChooser.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private void okPressed() {
	if (editable) {

		X500Name dn = distinguishedNameChooser.getDN();

		if (dn == null) {
			return;
		}

		if (dn.toString().isEmpty()) {
			JOptionPane.showMessageDialog(this,
					res.getString("DDistinguishedNameChooser.ValueReqAtLeastOneField.message"), getTitle(),
					JOptionPane.WARNING_MESSAGE);
			return;
		}

		for (RDN rdn : dn.getRDNs(BCStyle.C)) {
			String countryCode = rdn.getFirst().getValue().toString();
			if ((countryCode != null) && (countryCode.length() != 2)) {
				JOptionPane.showMessageDialog(this,
						res.getString("DDistinguishedNameChooser.CountryCodeTwoChars.message"), getTitle(),
						JOptionPane.WARNING_MESSAGE);
				return;
			}
		}

		distinguishedName = dn;
	}

	closeDialog();
}
 
Example #22
Source File: RdnPanelList.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
public List<RDN> getRdns(boolean noEmptyRdns) {
	List<RDN> rdns = new ArrayList<>();
	for (RdnPanel rdnPanel : entries) {
		ASN1ObjectIdentifier attrType = OidDisplayNameMapping.getOidForDisplayName(rdnPanel.getAttributeName());
		if (noEmptyRdns && StringUtils.trimAndConvertEmptyToNull(rdnPanel.getAttributeValue()) == null) {
			continue;
		}
		ASN1Encodable attrValue = KseX500NameStyle.INSTANCE.stringToValue(attrType, rdnPanel.getAttributeValue());
		rdns.add(new RDN(new AttributeTypeAndValue(attrType, attrValue)));
	}
	return rdns;
}
 
Example #23
Source File: CaUtil.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RDN[] getRdns(RDN[] rdns, ASN1ObjectIdentifier type) {
  Args.notNull(rdns, "rdns");
  Args.notNull(type, "type");
  List<RDN> ret = new ArrayList<>(1);
  for (int i = 0; i < rdns.length; i++) {
    RDN rdn = rdns[i];
    if (rdn.getFirst().getType().equals(type)) {
      ret.add(rdn);
    }
  }

  return CollectionUtil.isEmpty(ret) ? null : ret.toArray(new RDN[0]);
}
 
Example #24
Source File: XmppDomainVerifier.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
private static List<String> getCommonNames(X509Certificate certificate) {
    List<String> domains = new ArrayList<>();
    try {
        X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
        RDN[] rdns = x500name.getRDNs(BCStyle.CN);
        for (int i = 0; i < rdns.length; ++i) {
            domains.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[i].getFirst().getValue()));
        }
        return domains;
    } catch (CertificateEncodingException e) {
        return domains;
    }
}
 
Example #25
Source File: CertificateUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Reorders DN to the order the elements appear in the RFC 2253 table
 * <p>
 * https://www.ietf.org/rfc/rfc2253.txt
 * <p>
 * String  X.500 AttributeType
 * ------------------------------
 * CN      commonName
 * L       localityName
 * ST      stateOrProvinceName
 * O       organizationName
 * OU      organizationalUnitName
 * C       countryName
 * STREET  streetAddress
 * DC      domainComponent
 * UID     userid
 *
 * @param dn a possibly unordered DN
 * @return the ordered dn
 */
public static String reorderDn(String dn) {
    RDN[] rdNs = new X500Name(dn).getRDNs();
    Arrays.sort(rdNs, new Comparator<RDN>() {
        @Override
        public int compare(RDN o1, RDN o2) {
            AttributeTypeAndValue o1First = o1.getFirst();
            AttributeTypeAndValue o2First = o2.getFirst();

            ASN1ObjectIdentifier o1Type = o1First.getType();
            ASN1ObjectIdentifier o2Type = o2First.getType();

            Integer o1Rank = dnOrderMap.get(o1Type);
            Integer o2Rank = dnOrderMap.get(o2Type);
            if (o1Rank == null) {
                if (o2Rank == null) {
                    int idComparison = o1Type.getId().compareTo(o2Type.getId());
                    if (idComparison != 0) {
                        return idComparison;
                    }
                    return String.valueOf(o1Type).compareTo(String.valueOf(o2Type));
                }
                return 1;
            } else if (o2Rank == null) {
                return -1;
            }
            return o1Rank - o2Rank;
        }
    });
    return new X500Name(rdNs).toString();
}
 
Example #26
Source File: CertificateToken.java    From jqm with Apache License 2.0 5 votes vote down vote up
public String getUserName()
{
    try {
        X500Name x500name = new JcaX509CertificateHolder(clientCert).getSubject();
        RDN cn = x500name.getRDNs(BCStyle.CN)[0];
        return IETFUtils.valueToString(cn.getFirst().getValue());
    } catch (CertificateEncodingException e) {
        return "";
    }
}
 
Example #27
Source File: SpkacSubject.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
private String getRdn(X500Name name, ASN1ObjectIdentifier rdnOid) {
	RDN[] rdns = name.getRDNs(rdnOid);

	if (rdns.length > 0) {
		RDN rdn = rdns[0];
		String value = rdn.getFirst().getValue().toString();

		return value;
	}

	return null;
}
 
Example #28
Source File: ClientFingerprintTrustManager.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, Socket socket) throws CertificateException {
  X509Certificate cert = chain[0];
  X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
  RDN cn = x500name.getRDNs(BCStyle.CN)[0];
  String hostname = IETFUtils.valueToString(cn.getFirst().getValue());
  checkTrusted(chain, hostname);
}
 
Example #29
Source File: BaseCertprofile.java    From xipki with Apache License 2.0 5 votes vote down vote up
private static RDN[] getRdns(RDN[] rdns, ASN1ObjectIdentifier type) {
  Args.notNull(rdns, "rdns");
  Args.notNull(type, "type");

  List<RDN> ret = new ArrayList<>(1);
  for (int i = 0; i < rdns.length; i++) {
    RDN rdn = rdns[i];
    if (rdn.getFirst().getType().equals(type)) {
      ret.add(rdn);
    }
  }

  return CollectionUtil.isEmpty(ret) ? null : ret.toArray(new RDN[0]);
}
 
Example #30
Source File: JDistinguishedName.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Set distinguished name.
 *
 * @param distinguishedName
 *            Distinguished name
 */
public void setDistinguishedName(X500Name distinguishedName) {

	if (distinguishedName == null) {
		this.distinguishedName = new X500Name(KseX500NameStyle.INSTANCE, new RDN[0]);
	} else {
		this.distinguishedName = new X500Name(KseX500NameStyle.INSTANCE, distinguishedName.getRDNs());
	}
	populate();
}