public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, 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) { emails.add(IETFUtils.valueToString(x500name.getRDNs(BCStyle.EmailAddress)[0].getFirst().getValue())); } String name = IETFUtils.valueToString(x500name.getRDNs(BCStyle.CN)[0].getFirst().getValue()); if (emails.size() >= 1) { return new Pair<>(Jid.fromString(emails.get(0)), name); } else { return null; } }
@Test public void testGenerateInstanceRefreshRequestSubDomain() { File privkey = new File("./src/test/resources/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)); }
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; }
private boolean checkRdn(RDN certRDN, AttributeTypeAndValue expectedTypeAndValue) { String expectedValue = IETFUtils.valueToString(expectedTypeAndValue.getValue()); boolean constraintFound = false; AttributeTypeAndValue[] typesAndValues = certRDN.getTypesAndValues(); for (AttributeTypeAndValue typesAndValue : typesAndValues) { if (typesAndValue.getType().equals(expectedTypeAndValue.getType())) { String actualValue = IETFUtils.valueToString(typesAndValue.getValue()); if (actualValue.equals(expectedValue)) { constraintFound = true; } else { constraintFound = false; break; } } } return constraintFound; }
public static String getSubjectCNFromCertificate(X509Certificate certificate) { try { X500Name x500name = new JcaX509CertificateHolder(certificate).getIssuer(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; return IETFUtils.valueToString(cn.getFirst().getValue()); } catch (CertificateEncodingException e) { log.error("Unable to get issuer CN", e); return null; } }
private X509CertificateObject generateCert(String keyName, KeyPair kp, boolean isCertAuthority, PublicKey signerPublicKey, PrivateKey signerPrivateKey) throws IOException, CertIOException, 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 cert = certGen.build( new JcaContentSignerBuilder(SIGNING_ALGORITHM).build(signerPrivateKey)); return new X509CertificateObject(cert.toASN1Structure()); }
@Override public HttpResponse handle(HttpRequest request, MiddlewareChain chain) { request = MixinUtils.mixin(request, new Class[]{PrincipalAvailable.class}); String clientDN = request.getHeaders().get("X-Client-DN"); if (!isAuthenticated((PrincipalAvailable) request) && clientDN != null) { RDN cn = new X500Name(clientDN).getRDNs(BCStyle.CN)[0]; String account = IETFUtils.valueToString(cn.getFirst().getValue()); } return castToHttpResponse(chain.next(request)); }
public static Pair<Jid,String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, 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.fromString(emails.get(0)), name); } else if (name != null){ try { Jid jid = Jid.fromString(name); if (jid.isBareJid() && !jid.isDomainJid()) { return new Pair<>(jid,null); } } catch (InvalidJidException e) { return null; } } return null; }
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; } }
/** * Extract email addresses from a certificate * * @param cert the X509 certificate holder * @return a List of all email addresses found * @throws CertificateException */ private static List<String> getEmailFromCert(X509CertificateHolder cert) throws CertificateException { List<String> res = new ArrayList<>(); X500Name subject = cert.getSubject(); for (RDN emails : subject.getRDNs(BCStyle.EmailAddress)) { for (AttributeTypeAndValue emailAttr: emails.getTypesAndValues()) { log.debug("Add email from RDN: " + IETFUtils.valueToString(emailAttr.getValue())); res.add(IETFUtils.valueToString(emailAttr.getValue())); } } Extension subjectAlternativeNames = cert .getExtension(Extension.subjectAlternativeName); if (subjectAlternativeNames != null) { for (GeneralName name : GeneralNames.getInstance( subjectAlternativeNames.getParsedValue()).getNames()) { if (name.getTagNo() == GeneralName.rfc822Name) { String email = IETFUtils.valueToString(name.getName()); log.debug("Add email from subjectAlternativeName: " + email); res.add(email); } } } return res; }
public static String extractX509CSRCommonName(PKCS10CertificationRequest certReq) { String cn = null; X500Name x500name = certReq.getSubject(); RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0]; if (cnRdn != null) { cn = IETFUtils.valueToString(cnRdn.getFirst().getValue()); } return cn; }
public static String extractX509CertCommonName(X509Certificate x509Cert) { // in case there are multiple CNs, we're only looking at the first one String cn = null; String principalName = x509Cert.getSubjectX500Principal().getName(); if (principalName != null && !principalName.isEmpty()) { X500Name x500name = new X500Name(principalName); RDN cnRdn = x500name.getRDNs(BCStyle.CN)[0]; if (cnRdn != null) { cn = IETFUtils.valueToString(cnRdn.getFirst().getValue()); } } return cn; }
@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; }
@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], DefaultSymbols); } } else { IETFUtils.appendTypeAndValue(buf, rdns[i].getFirst(), DefaultSymbols); } } return buf.toString(); }
static Optional<String> getClientName(ContainerRequest request) { Principal principal = request.getSecurityContext().getUserPrincipal(); if (principal == null) { return Optional.empty(); } 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())); }
public static Pair<Jid, String> extractJidAndName(X509Certificate certificate) throws CertificateEncodingException, InvalidJidException, 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.fromString(emails.get(0)), name); } else if (name != null) { try { Jid jid = Jid.fromString(name); if (jid.isBareJid() && !jid.isDomainJid()) { return new Pair<>(jid, null); } } catch (InvalidJidException e) { return null; } } return null; }
private String getSingleRDN(ASN1ObjectIdentifier oid) { RDN[] rdn = mName.getRDNs(oid); if (rdn.length > 0) { return IETFUtils.valueToString(rdn[0].getFirst().getValue()); } return null; }
/** * @param aCert * Source certificate. May not be <code>null</code>. * @return The common name of the certificate subject * @throws CertificateEncodingException * In case of an internal error */ @Nonnull public static String getSubjectCommonName (@Nonnull final X509Certificate aCert) throws CertificateEncodingException { ValueEnforcer.notNull (aCert, "Certificate"); final X500Name x500name = new JcaX509CertificateHolder (aCert).getSubject (); final RDN cn = x500name.getRDNs (BCStyle.CN)[0]; return IETFUtils.valueToString (cn.getFirst ().getValue ()); }
public SubjectInfo getSubject(X500Name requestedSubject) throws CertprofileException, BadCertTemplateException { SubjectInfo subjectInfo = certprofile.getSubject(requestedSubject); RDN[] countryRdns = subjectInfo.grantedSubject().getRDNs(ObjectIdentifiers.DN_C); if (countryRdns != null) { for (RDN rdn : countryRdns) { String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()); if (!SubjectDnSpec.isValidCountryAreaCode(textValue)) { throw new BadCertTemplateException("invalid country/area code '" + textValue + "'"); } } } return subjectInfo; }
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 ""; } }
private String getAccountFromClientDN(HttpRequest request) { return some(request.getHeaders().get("X-Client-DN"), clientDN -> new X500Name(clientDN).getRDNs(BCStyle.CN)[0], cn -> IETFUtils.valueToString(cn.getFirst().getValue())).orElse(null); }
private void ietfUtilsTest() throws Exception { IETFUtils.valueToString(new DERUTF8String(" ")); }
@Override public boolean verify(String domain, SSLSession sslSession) { try { Certificate[] chain = sslSession.getPeerCertificates(); if (chain.length == 0 || !(chain[0] instanceof X509Certificate)) { return false; } X509Certificate certificate = (X509Certificate) chain[0]; Collection<List<?>> alternativeNames = certificate.getSubjectAlternativeNames(); List<String> xmppAddrs = new ArrayList<>(); List<String> srvNames = new ArrayList<>(); List<String> domains = new ArrayList<>(); if (alternativeNames != null) { for (List<?> san : alternativeNames) { Integer type = (Integer) san.get(0); if (type == 0) { Pair<String, String> otherName = parseOtherName((byte[]) san.get(1)); if (otherName != null) { switch (otherName.first) { case SRVName: srvNames.add(otherName.second); break; case xmppAddr: xmppAddrs.add(otherName.second); break; default: Log.d(LOGTAG, "oid: " + otherName.first + " value: " + otherName.second); } } } else if (type == 2) { Object value = san.get(1); if (value instanceof String) { domains.add((String) value); } } } } if (srvNames.size() == 0 && xmppAddrs.size() == 0 && domains.size() == 0) { 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())); } } Log.d(LOGTAG, "searching for " + domain + " in srvNames: " + srvNames + " xmppAddrs: " + xmppAddrs + " domains:" + domains); return xmppAddrs.contains(domain) || srvNames.contains("_xmpp-client." + domain) || matchDomain(domain, domains); } catch (Exception e) { return false; } }
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()); }
public static Set<String> getNames(ASN1ObjectIdentifier type, X500Name name) { return Stream.of(name.getRDNs(type)) .flatMap(n -> Stream.of(n.getTypesAndValues())) .map(n -> IETFUtils.valueToString(n.getValue())) .collect(Collectors.toSet()); }
private void doInternalPrivateKey(CertificateResource resource, InputStream key, String passphrase, InputStream file, InputStream bundle) throws InvalidPassphraseException, CertificateException, IOException, FileFormatException, MismatchedCertificateException { X509Certificate cert = X509CertificateUtils.loadCertificateFromPEM(file); X509Certificate[] ca = X509CertificateUtils .loadCertificateChainFromPEM(bundle); X509CertificateUtils.validateChain(ca, cert); KeyPair pair = X509CertificateUtils.loadKeyPairFromPEM(key, passphrase.toCharArray()); if (!pair.getPublic().equals(cert.getPublicKey())) { throw new MismatchedCertificateException( "The certificate does not match the private key."); } ByteArrayOutputStream privateKeyFile = new ByteArrayOutputStream(); X509CertificateUtils.saveKeyPair(pair, privateKeyFile); ByteArrayOutputStream certStream = new ByteArrayOutputStream(); X509CertificateUtils.saveCertificate(new Certificate[] { cert }, certStream); ByteArrayOutputStream caStream = new ByteArrayOutputStream(); X509CertificateUtils.saveCertificate(ca, caStream); X500Name x500name = new JcaX509CertificateHolder(cert).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; for (RDN rdn : x500name.getRDNs()) { for (AttributeTypeAndValue v : rdn.getTypesAndValues()) { log.info(v.getType().toString() + ": " + IETFUtils.valueToString(v.getValue())); } } if (!resource.getName().equals(DEFAULT_CERTIFICATE_NAME)) { resource.setName(IETFUtils.valueToString(cn.getFirst().getValue())); } resource.setCommonName(IETFUtils .valueToString(cn.getFirst().getValue())); resource.setCountry(""); resource.setLocation(""); resource.setOrganization(""); resource.setOrganizationalUnit(""); resource.setState(""); resource.setPrivateKey(new String(privateKeyFile.toByteArray(), "UTF-8")); resource.setCertificate(new String(certStream.toByteArray(), "UTF-8")); resource.setBundle(new String(caStream.toByteArray(), "UTF-8")); }