Java Code Examples for org.bouncycastle.asn1.x500.RDN

The following examples show how to use org.bouncycastle.asn1.x500.RDN. These examples are extracted from open source projects. 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 Project: portecle   Author: scop   File: NameUtil.java    License: 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 #2
Source Project: athenz   Author: yahoo   File: ZTSClientTest.java    License: 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 #3
Source Project: athenz   Author: yahoo   File: Crypto.java    License: 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 #4
Source Project: athenz   Author: yahoo   File: Crypto.java    License: 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 #5
Source Project: keystore-explorer   Author: kaikramer   File: X500NameUtils.java    License: 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 #6
Source Project: keystore-explorer   Author: kaikramer   File: RdnPanelList.java    License: 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 #7
Source Project: keywhiz   Author: square   File: LdapAuthenticator.java    License: 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 Project: oxAuth   Author: GluuFederation   File: CertUtils.java    License: 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 #9
Source Project: xipki   Author: xipki   File: X509Util.java    License: 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 #10
Source Project: xipki   Author: xipki   File: CaUtil.java    License: 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 #11
Source Project: keycloak   Author: keycloak   File: UserIdentityExtractor.java    License: 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 #12
Source Project: incubator-tuweni   Author: apache   File: ClientFingerprintTrustManager.java    License: 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 #13
Source Project: incubator-tuweni   Author: apache   File: ClientFingerprintTrustManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
    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 #14
Source Project: hadoop-ozone   Author: apache   File: TestSecureOzoneCluster.java    License: Apache License 2.0 5 votes vote down vote up
public void validateCertificate(X509Certificate cert) throws Exception {

    // Assert that we indeed have a self signed certificate.
    X500Name x500Issuer = new JcaX509CertificateHolder(cert).getIssuer();
    RDN cn = x500Issuer.getRDNs(BCStyle.CN)[0];
    String hostName = InetAddress.getLocalHost().getHostName();
    String scmUser = "[email protected]" + hostName;
    assertEquals(scmUser, cn.getFirst().getValue().toString());

    // Subject name should be om login user in real world but in this test
    // UGI has scm user context.
    assertEquals(scmUser, cn.getFirst().getValue().toString());

    LocalDate today = LocalDateTime.now().toLocalDate();
    Date invalidDate;

    // Make sure the end date is honored.
    invalidDate = java.sql.Date.valueOf(today.plus(1, ChronoUnit.DAYS));
    assertTrue(cert.getNotAfter().after(invalidDate));

    invalidDate = java.sql.Date.valueOf(today.plus(400, ChronoUnit.DAYS));
    assertTrue(cert.getNotAfter().before(invalidDate));

    assertTrue(cert.getSubjectDN().toString().contains(scmId));
    assertTrue(cert.getSubjectDN().toString().contains(clusterId));

    assertTrue(cert.getIssuerDN().toString().contains(scmUser));
    assertTrue(cert.getIssuerDN().toString().contains(scmId));
    assertTrue(cert.getIssuerDN().toString().contains(clusterId));

    // Verify that certificate matches the public key.
    String encodedKey1 = cert.getPublicKey().toString();
    String encodedKey2 = om.getCertificateClient().getPublicKey().toString();
    assertEquals(encodedKey1, encodedKey2);
  }
 
Example #15
Source Project: besu   Author: hyperledger   File: SelfSignedP12Certificate.java    License: Apache License 2.0 5 votes vote down vote up
public String getCommonName() {
  try {
    final X500Name subject = new X509CertificateHolder(certificate.getEncoded()).getSubject();
    final RDN commonNameRdn = subject.getRDNs(BCStyle.CN)[0];
    return IETFUtils.valueToString(commonNameRdn.getFirst().getValue());
  } catch (final IOException | CertificateEncodingException e) {
    throw new RuntimeException("Error extracting common name from certificate", e);
  }
}
 
Example #16
Source Project: hivemq-community-edition   Author: hivemq   File: SslClientCertificateImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private String subjectProperty(final ASN1ObjectIdentifier objectIdentifier, final X509Certificate cert) throws CertificateEncodingException {
    final X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
    final RDN[] rdNs = x500name.getRDNs(objectIdentifier);
    if (rdNs.length < 1) {
        return null;
    }
    final RDN cn = rdNs[0];
    return IETFUtils.valueToString(cn.getFirst().getValue());
}
 
Example #17
Source Project: cava   Author: ConsenSys   File: ClientFingerprintTrustManager.java    License: 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 #18
Source Project: cava   Author: ConsenSys   File: ClientFingerprintTrustManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType, SSLEngine engine)
    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 #19
Source Project: localization_nifi   Author: wangrenlei   File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reorders DN to the order the elements appear in the RFC 2253 table
 *
 * https://www.ietf.org/rfc/rfc2253.txt
 *
 * 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 #20
Source Project: bouncr   Author: kawasima   File: ClientAuthenticateMiddleware.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Override
public HttpResponse handle(HttpRequest request, MiddlewareChain<HttpRequest, NRES, ?, ?> chain) {
    request = MixinUtils.mixin(request, PrincipalAvailable.class);
    String clientDN = request.getHeaders().get("X-Client-DN");
    if (!isAuthenticated(request) && clientDN != null) {
        RDN cn = new X500Name(clientDN).getRDNs(BCStyle.CN)[0];
        String account = IETFUtils.valueToString(cn.getFirst().getValue());

    }
    return castToHttpResponse(chain.next(request));
}
 
Example #21
Source Project: nifi-registry   Author: apache   File: CertificateUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reorders DN to the order the elements appear in the RFC 2253 table
 *
 * https://www.ietf.org/rfc/rfc2253.txt
 *
 * 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 #22
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubject() throws Exception {
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(TestConstants.SERVICE_NAME, mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);
    RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN);
    Assert.assertEquals(cnRDNs.length, 1);
    Assert.assertEquals(String.format("%s-%s.%s", POD_NAME, TestConstants.TASK_NAME, TestConstants.SERVICE_NAME),
            cnRDNs[0].getFirst().getValue().toString());
}
 
Example #23
Source Project: dcos-commons   Author: mesosphere   File: CertificateNamesGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetSubjectWithLongCN() throws Exception {
    Mockito.when(mockTaskSpec.getName()).thenReturn(UUID.randomUUID().toString());
    CertificateNamesGenerator certificateNamesGenerator =
            new CertificateNamesGenerator(UUID.randomUUID().toString(), mockTaskSpec, mockPodInstance, SCHEDULER_CONFIG);
    RDN[] cnRDNs = certificateNamesGenerator.getSubject().getRDNs(BCStyle.CN);
    Assert.assertEquals(cnRDNs.length, 1);
    Assert.assertEquals(64, cnRDNs[0].getFirst().getValue().toString().length());
}
 
Example #24
Source Project: athenz   Author: yahoo   File: CryptoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testExtractX509CSRSubjectFieldNull() {
    PKCS10CertificationRequest certReq = mock(PKCS10CertificationRequest.class);
    when(certReq.getSubject()).thenReturn(null);
    assertNull(Crypto.extractX509CSRSubjectField(certReq, null));

    X500Name x500Name = mock(X500Name.class);
    when(certReq.getSubject()).thenReturn(x500Name);
    RDN[] rdns = new RDN[2];
    when(x500Name.getRDNs(null)).thenReturn(rdns);
    assertThrows(CryptoException.class, () -> {
        Crypto.extractX509CSRSubjectField(certReq, null);
    });
}
 
Example #25
Source Project: keystore-explorer   Author: kaikramer   File: KseX500NameStyle.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public RDN[] fromString(String name) {
	// Parse backwards
	RDN[] tmp = IETFUtils.rDNsFromString(name, this);
	RDN[] res = new RDN[tmp.length];

	for (int i = 0; i != tmp.length; i++) {
		res[res.length - i - 1] = tmp[i];
	}

	return res;
}
 
Example #26
Source Project: keystore-explorer   Author: kaikramer   File: KseX500NameStyle.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String toString(X500Name name) {
	// Convert in reverse
	StringBuffer buf = new StringBuffer();
	boolean first = true;

	RDN[] rdns = name.getRDNs();

	for (int i = rdns.length - 1; i >= 0; i--) {
		if (first) {
			first = false;
		} else {
			buf.append(',');
		}

		if (rdns[i].isMultiValued()) {
			AttributeTypeAndValue[] atv = rdns[i].getTypesAndValues();
			boolean firstAtv = true;

			for (int j = 0; j != atv.length; j++) {
				if (firstAtv) {
					firstAtv = false;
				} else {
					buf.append('+');
				}

				IETFUtils.appendTypeAndValue(buf, atv[j], DEFAULT_SYMBOLS);
			}
		} else {
			IETFUtils.appendTypeAndValue(buf, rdns[i].getFirst(), DEFAULT_SYMBOLS);
		}
	}

	return buf.toString();
}
 
Example #27
Source Project: keystore-explorer   Author: kaikramer   File: X500NameUtils.java    License: 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 #28
Source Project: keystore-explorer   Author: kaikramer   File: SpkacSubject.java    License: 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 #29
Source Project: keystore-explorer   Author: kaikramer   File: RdnPanelList.java    License: 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 #30
Source Project: keystore-explorer   Author: kaikramer   File: DDistinguishedNameChooser.java    License: 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();
}