org.bouncycastle.asn1.x500.style.IETFUtils Java Examples

The following examples show how to use org.bouncycastle.asn1.x500.style.IETFUtils. 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: 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 #2
Source File: TlsHelper.java    From nifi with Apache License 2.0 6 votes vote down vote up
public static Extensions createDomainAlternativeNamesExtensions(List<String> domainAlternativeNames, String requestedDn) throws IOException {
    List<GeneralName> namesList = new ArrayList<>();

    try {
        final String cn = IETFUtils.valueToString(new X500Name(requestedDn).getRDNs(BCStyle.CN)[0].getFirst().getValue());
        namesList.add(new GeneralName(GeneralName.dNSName, cn));
    } catch (Exception e) {
        throw new IOException("Failed to extract CN from request DN: " + requestedDn, e);
    }

    if (domainAlternativeNames != null) {
        for (String alternativeName : domainAlternativeNames) {
             namesList.add(new GeneralName(IPAddress.isValid(alternativeName) ? GeneralName.iPAddress : GeneralName.dNSName, alternativeName));
         }
    }

    GeneralNames subjectAltNames = new GeneralNames(namesList.toArray(new GeneralName[]{}));
    ExtensionsGenerator extGen = new ExtensionsGenerator();
    extGen.addExtension(Extension.subjectAlternativeName, false, subjectAltNames);
    return extGen.generate();
}
 
Example #3
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 #4
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 #5
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 #6
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 #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: ClientFingerprintTrustManager.java    From incubator-tuweni with 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 #9
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 #10
Source File: TlsCertificateAuthorityClientSocketFactory.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,
                                         InetSocketAddress localAddress, HttpContext context) throws IOException {
    Socket result = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    if (!SSLSocket.class.isInstance(result)) {
        throw new IOException("Expected tls socket");
    }
    SSLSocket sslSocket = (SSLSocket) result;
    java.security.cert.Certificate[] peerCertificateChain = sslSocket.getSession().getPeerCertificates();
    if (peerCertificateChain.length != 1) {
        throw new IOException("Expected root ca cert");
    }
    if (!X509Certificate.class.isInstance(peerCertificateChain[0])) {
        throw new IOException("Expected root ca cert in X509 format");
    }
    String cn;
    try {
        X509Certificate certificate = (X509Certificate) peerCertificateChain[0];
        cn = IETFUtils.valueToString(new JcaX509CertificateHolder(certificate).getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue());
        certificates.add(certificate);
    } catch (Exception e) {
        throw new IOException(e);
    }
    if (!caHostname.equals(cn)) {
        throw new IOException("Expected cn of " + caHostname + " but got " + cn);
    }
    return result;
}
 
Example #11
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 #12
Source File: CryptoHelper.java    From Conversations with GNU General Public License v3.0 5 votes vote down vote up
public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
    Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
    List<String> emails = new ArrayList<>();
    if (alternativeNames != null) {
        for (List<?> san : alternativeNames) {
            Integer type = (Integer) san.get(0);
            if (type == 1) {
                emails.add((String) san.get(1));
            }
        }
    }
    X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
    if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
        emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
    }
    String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
    if (emails.size() >= 1) {
        return new Pair<>(Jid.of(emails.get(0)), name);
    } else if (name != null) {
        try {
            Jid jid = Jid.of(name);
            if (jid.isBareJid() && jid.getLocal() != null) {
                return new Pair<>(jid, null);
            }
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
    return null;
}
 
Example #13
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 #14
Source File: CryptoHelper.java    From Pix-Art-Messenger with GNU General Public License v3.0 5 votes vote down vote up
public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, IllegalArgumentException, CertificateParsingException {
    Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames();
    List<String> emails = new ArrayList<>();
    if (alternativeNames != null) {
        for (List<?> san : alternativeNames) {
            Integer type = (Integer) san.get(0);
            if (type == 1) {
                emails.add((String) san.get(1));
            }
        }
    }
    X500Name x500name = new JcaX509CertificateHolder(certificate).getSubject();
    if (emails.size() == 0 && x500name.getRDNs(BCStyle.EmailAddress).length > 0) {
        emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue()));
    }
    String name = x500name.getRDNs(BCStyle.CN).length > 0 ? IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()) : null;
    if (emails.size() >= 1) {
        return new Pair<>(Jid.of(emails.get(0)), name);
    } else if (name != null) {
        try {
            Jid jid = Jid.of(name);
            if (jid.isBareJid() && jid.getLocal() != null) {
                return new Pair<>(jid, null);
            }
        } catch (IllegalArgumentException e) {
            return null;
        }
    }
    return null;
}
 
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: KseX500NameStyle.java    From keystore-explorer with 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 #17
Source File: KseX500NameStyle.java    From keystore-explorer with 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 #18
Source File: ClientAuthenticateMiddleware.java    From bouncr with 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 #19
Source File: HttpBaseTest.java    From calcite-avatica with Apache License 2.0 5 votes vote down vote up
private X509Certificate generateCert(String keyName, KeyPair kp, boolean isCertAuthority,
                                     PublicKey signerPublicKey, PrivateKey signerPrivateKey)
    throws IOException, OperatorCreationException, CertificateException,
    NoSuchAlgorithmException {
  Calendar startDate = DateTimeUtils.calendar();
  Calendar endDate = DateTimeUtils.calendar();
  endDate.add(Calendar.YEAR, 100);

  BigInteger serialNumber = BigInteger.valueOf(startDate.getTimeInMillis());
  X500Name issuer = new X500Name(
      IETFUtils.rDNsFromString("cn=localhost", RFC4519Style.INSTANCE));
  JcaX509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuer,
      serialNumber, startDate.getTime(), endDate.getTime(), issuer, kp.getPublic());
  JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();
  certGen.addExtension(Extension.subjectKeyIdentifier, false,
      extensionUtils.createSubjectKeyIdentifier(kp.getPublic()));
  certGen.addExtension(Extension.basicConstraints, false,
      new BasicConstraints(isCertAuthority));
  certGen.addExtension(Extension.authorityKeyIdentifier, false,
      extensionUtils.createAuthorityKeyIdentifier(signerPublicKey));
  if (isCertAuthority) {
    certGen.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign));
  }
  X509CertificateHolder certificateHolder = certGen.build(
      new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey));
  return new JcaX509CertificateConverter().getCertificate(certificateHolder);
}
 
Example #20
Source File: TlsCertificateAuthorityClientSocketFactory.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Socket connectSocket(int connectTimeout, Socket socket, HttpHost host, InetSocketAddress remoteAddress,
                                         InetSocketAddress localAddress, HttpContext context) throws IOException {
    Socket result = super.connectSocket(connectTimeout, socket, host, remoteAddress, localAddress, context);
    if (!SSLSocket.class.isInstance(result)) {
        throw new IOException("Expected tls socket");
    }
    SSLSocket sslSocket = (SSLSocket) result;
    java.security.cert.Certificate[] peerCertificateChain = sslSocket.getSession().getPeerCertificates();
    if (peerCertificateChain.length != 1) {
        throw new IOException("Expected root ca cert");
    }
    if (!X509Certificate.class.isInstance(peerCertificateChain[0])) {
        throw new IOException("Expected root ca cert in X509 format");
    }
    String cn;
    try {
        X509Certificate certificate = (X509Certificate) peerCertificateChain[0];
        cn = IETFUtils.valueToString(new JcaX509CertificateHolder(certificate).getSubject().getRDNs(BCStyle.CN)[0].getFirst().getValue());
        certificates.add(certificate);
    } catch (Exception e) {
        throw new IOException(e);
    }
    if (!caHostname.equals(cn)) {
        throw new IOException("Expected cn of " + caHostname + " but got " + cn);
    }
    return result;
}
 
Example #21
Source File: ClientFingerprintTrustManager.java    From cava with 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 #22
Source File: ClientFingerprintTrustManager.java    From cava 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 #23
Source File: SslClientCertificateImpl.java    From hivemq-community-edition with 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 #24
Source File: SelfSignedP12Certificate.java    From besu with 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 #25
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 #26
Source File: SocketTest.java    From athenz with Apache License 2.0 4 votes vote down vote up
private String getCN(Certificate[] certificates) throws CertificateEncodingException {
    final X509Certificate[] clientCerts = (X509Certificate[])certificates;
    final X500Name certificateHolder = new JcaX509CertificateHolder(clientCerts[0]).getSubject();
    final RDN commonName = certificateHolder.getRDNs(BCStyle.CN)[0];
    return IETFUtils.valueToString(commonName.getFirst().getValue());
}
 
Example #27
Source File: CertificateService.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
private NcaId getNcaIdFromIssuerData() {
    String country = IETFUtils.valueToString(issuerDataService.getIssuerData()
                                                 .getX500name().getRDNs(BCStyle.C)[0]
                                                 .getFirst().getValue());
    return new NcaId(country + "-" + NCA_SHORT_NAME);
}
 
Example #28
Source File: CertificateService.java    From XS2A-Sandbox with Apache License 2.0 4 votes vote down vote up
private NcaName getNcaNameFromIssuerData() {
    return new NcaName(IETFUtils.valueToString(
        issuerDataService.getIssuerData().getX500name().getRDNs(BCStyle.O)[0]
            .getFirst().getValue())
    );
}