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

The following examples show how to use org.bouncycastle.asn1.x500.style.IETFUtils. 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: athenz   Source 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 2
Source Project: athenz   Source 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 3
Source Project: athenz   Source 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 4
Source Project: keywhiz   Source 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 5
Source Project: oxAuth   Source 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 6
Source Project: nifi   Source File: TlsHelper.java    License: 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 7
Source Project: keycloak   Source 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 8
@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 9
@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 10
Source Project: besu   Source 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 11
@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 12
Source Project: cava   Source 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: cava   Source 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
@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 15
Source Project: calcite-avatica   Source File: HttpBaseTest.java    License: 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 16
@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 17
@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
@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 19
Source Project: keywhiz   Source File: ClientAuthenticator.java    License: 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 20
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 21
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 22
Source Project: Conversations   Source File: CryptoHelper.java    License: 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 23
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 24
@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 25
Source Project: jqm   Source File: CertificateToken.java    License: 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 26
Source Project: XS2A-Sandbox   Source File: CertificateService.java    License: 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())
    );
}
 
Example 27
Source Project: XS2A-Sandbox   Source File: CertificateService.java    License: 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 Project: athenz   Source File: SocketTest.java    License: 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());
}