Java Code Examples for org.bouncycastle.asn1.x500.style.IETFUtils#valueToString()

The following examples show how to use org.bouncycastle.asn1.x500.style.IETFUtils#valueToString() . 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: 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 2
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 3
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 4
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 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: 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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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 16
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 17
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 18
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 19
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 20
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())
    );
}