javax.naming.ldap.Rdn Java Examples

The following examples show how to use javax.naming.ldap.Rdn. 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: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
Example #2
Source File: ProxiedEntityUtils.java    From timely with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to normalize a DN by taking it and reversing the components if it
 * doesn't start with CN. Some systems requires the DN components be in a
 * specific order, or that order reversed. We cannot arbitrarily reorder the
 * components however, e.g., sorting them.
 */
public static String normalizeDN(String userName) {
    String normalizedUserName = userName.trim().toLowerCase();
    try {
        if (!normalizedUserName.startsWith("cn") || Pattern.compile(",[^ ]").matcher(normalizedUserName).find()) {
            LdapName name = new LdapName(userName);
            StringBuilder sb = new StringBuilder();
            ArrayList<Rdn> rdns = new ArrayList<>(name.getRdns());
            if (rdns.size() > 0 && !rdns.get(0).toString().toLowerCase().startsWith("cn"))
                Collections.reverse(rdns);
            for (Rdn rdn : rdns) {
                if (sb.length() > 0)
                    sb.append(", ");
                sb.append(rdn.toString());
            }
            normalizedUserName = sb.toString().toLowerCase();
        }
    } catch (InvalidNameException e) {
        // ignore -- might be a sid rather than a DN
    }
    log.trace("Normalized [" + userName + "] into [" + normalizedUserName + "]");
    return normalizedUserName;
}
 
Example #3
Source File: CertificateUtils.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
 *
 * Example:
 *
 * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
 * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
 * CN=test1, O=testOrg, C=US compared to                           -> false
 *                           compared to                           -> true
 *
 * @param dn1 the first DN to compare
 * @param dn2 the second DN to compare
 * @return true if the DNs are equivalent, false otherwise
 */
public static boolean compareDNs(String dn1, String dn2) {
    if (dn1 == null) {
        dn1 = "";
    }

    if (dn2 == null) {
        dn2 = "";
    }

    if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
        return dn1.equals(dn2);
    }
    try {
        List<Rdn> rdn1 = new LdapName(dn1).getRdns();
        List<Rdn> rdn2 = new LdapName(dn2).getRdns();

        return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
    } catch (InvalidNameException e) {
        logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
        return false;
    }
}
 
Example #4
Source File: LdapConnection.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Extract rdn value from username
 * @param dn distinguished name or username
 * @return username
 */
private String extractRdnValue(String dn) throws IOException {
    if (dn.startsWith("uid=")) {
        String rdn = dn;
        if (rdn.indexOf(',') > 0) {
            rdn = rdn.substring(0, rdn.indexOf(','));
        }
        try {
            return (String) new Rdn(rdn).getValue();
        } catch (InvalidNameException e) {
            throw new IOException(e);
        }
    } else {
        return dn;
    }
}
 
Example #5
Source File: TestLdap.java    From davmail with GNU General Public License v2.0 6 votes vote down vote up
public void testLdapDnAuthentication() throws NamingException {
    String dn = new Rdn("uid", Settings.getProperty("davmail.username"))+",ou=people";
    Hashtable<String, String> env = new Hashtable<>();
    //env.put("java.naming.security.authentication", "CRAM-MD5");
    env.put("java.naming.security.authentication", "simple");
    env.put("java.naming.security.principal", dn);
    env.put("java.naming.security.credentials", Settings.getProperty("davmail.password"));

    env.put("com.sun.jndi.ldap.connect.pool", "true");
    env.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");
    env.put("java.naming.provider.url", "ldap://127.0.0.1:" + Settings.getIntProperty("davmail.ldapPort"));
    env.put("java.naming.referral", "follow");

    new InitialLdapContext(env, null);

}
 
Example #6
Source File: CertKeyToUserNameMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
/**
 * Returns Subject DN from X509Certificate
 *
 * @param cert
 * @return Subject DN as a user name
 */
@Override
public String getUserName(Certificate cert) {
    X509Certificate certificate = (X509Certificate) cert;
    String dn = certificate.getSubjectDN().getName();
    LdapName ldapDn = getLdapName(dn);

    if (key == null) {
        throw new IllegalArgumentException("Must set a key");
    }

    for (Rdn rdn : ldapDn.getRdns()) {
        if (key.equalsIgnoreCase(rdn.getType())) {
            return (String)rdn.getValue();
        }
    }

    throw new IllegalArgumentException("No " + key + " key found in certificate DN: " + dn);
}
 
Example #7
Source File: LdapGroupSearcherFactory.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private LdapEntry parseRole(String dn, String groupNameAttribute, URI groupReferralAddress) {

            try {
                LdapName ldapName = new LdapName(Rdn.unescapeValue(dn).toString());
                for (int i = ldapName.size() - 1; i >= 0; i--) {
                    String rdnString = ldapName.get(i);
                    Rdn rdn = new Rdn(rdnString);
                    Attribute attr = rdn.toAttributes().get(groupNameAttribute);
                    if (attr != null) {
                        Object value = attr.get();
                        if (value != null) {
                            return new LdapEntry( (value instanceof byte[]) ? new String((byte[]) value, StandardCharsets.UTF_8) : value.toString(), dn, groupReferralAddress);
                        }
                    }
                }
            } catch (NamingException e) {
                SECURITY_LOGGER.tracef("Unable to parse role from DN (%s): %s", dn, e.getMessage());
            }
            return null;
        }
 
Example #8
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
Example #9
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
Example #10
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
Example #11
Source File: DistinguishedName.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public DistinguishedName(X500Principal principal) throws TechnicalConnectorException {
   CertificateParser parser = new CertificateParser(principal.getName("RFC2253"));
   this.setId(parser.getId());
   this.setType(parser.getIdentifier());
   this.setApplicationId(parser.getApplication());

   try {
      List<Rdn> rdns = (new LdapName(principal.getName("RFC1779"))).getRdns();
      Iterator i$ = rdns.iterator();

      while(i$.hasNext()) {
         Rdn rdn = (Rdn)i$.next();
         if (rdn.getType().equals("OU")) {
            String value = this.getValue(rdn.getValue());
            if (!"eHealth-platform Belgium".equals(value) && !value.contains("=")) {
               this.setName(this.getValue(rdn.getValue()));
               break;
            }
         }
      }

   } catch (InvalidNameException var7) {
      throw new IllegalArgumentException("Invalid Principal", var7);
   }
}
 
Example #12
Source File: CertificateUtils.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
 *
 * Example:
 *
 * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
 * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
 * CN=test1, O=testOrg, C=US compared to                           -> false
 *                           compared to                           -> true
 *
 * @param dn1 the first DN to compare
 * @param dn2 the second DN to compare
 * @return true if the DNs are equivalent, false otherwise
 */
public static boolean compareDNs(String dn1, String dn2) {
    if (dn1 == null) {
        dn1 = "";
    }

    if (dn2 == null) {
        dn2 = "";
    }

    if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
        return dn1.equals(dn2);
    }
    try {
        List<Rdn> rdn1 = new LdapName(dn1).getRdns();
        List<Rdn> rdn2 = new LdapName(dn2).getRdns();

        return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
    } catch (InvalidNameException e) {
        logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
        return false;
    }
}
 
Example #13
Source File: SSL.java    From crate with Apache License 2.0 6 votes vote down vote up
private static String extractCN(String subjectDN) {
    /*
     * Get commonName using LdapName API
     * The DN of X509 certificates are in rfc2253 format. Ldap uses the same format.
     *
     * Doesn't use X500Name because it's internal API
     */
    try {
        LdapName ldapName = new LdapName(subjectDN);
        for (Rdn rdn : ldapName.getRdns()) {
            if ("CN".equalsIgnoreCase(rdn.getType())) {
                return rdn.getValue().toString();
            }
        }
        throw new RuntimeException("Could not extract commonName from certificate subjectDN: " + subjectDN);
    } catch (InvalidNameException e) {
        throw new RuntimeException("Could not extract commonName from certificate", e);
    }
}
 
Example #14
Source File: DirectoryGroupDN.java    From hesperides with GNU General Public License v3.0 6 votes vote down vote up
public static String extractCnFromDn(String dn) {
    String cn = null;
    try {
        LdapName ldapName = new LdapName(dn);
        for (Rdn rdn : ldapName.getRdns()) {
            if (rdn.getType().equalsIgnoreCase("CN")) {
                cn = (String) rdn.getValue();
            }
        }
    } catch (InvalidNameException e) {
        throw new IllegalArgumentException("Invalid DN: " + dn, e);
    }
    if (cn == null) {
        throw new IllegalArgumentException("Can't find CN in DN: " + dn);
    }
    return cn;
}
 
Example #15
Source File: HostnameVerifierImpl.java    From mariadb-connector-j with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static String extractCommonName(String principal) throws SSLException {
  if (principal == null) {
    return null;
  }
  try {
    LdapName ldapName = new LdapName(principal);

    for (Rdn rdn : ldapName.getRdns()) {
      if (rdn.getType().equalsIgnoreCase("CN")) {
        Object obj = rdn.getValue();
        if (obj != null) {
          return obj.toString();
        }
      }
    }
    return null;
  } catch (InvalidNameException e) {
    throw new SSLException("DN value \"" + principal + "\" is invalid");
  }
}
 
Example #16
Source File: CertificateUtils.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Returns true if the two provided DNs are equivalent, regardless of the order of the elements. Returns false if one or both are invalid DNs.
 * <p>
 * Example:
 * <p>
 * CN=test1, O=testOrg, C=US compared to CN=test1, O=testOrg, C=US -> true
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test1, C=US -> true
 * CN=test1, O=testOrg, C=US compared to CN=test2, O=testOrg, C=US -> false
 * CN=test1, O=testOrg, C=US compared to O=testOrg, CN=test2, C=US -> false
 * CN=test1, O=testOrg, C=US compared to                           -> false
 * compared to                           -> true
 *
 * @param dn1 the first DN to compare
 * @param dn2 the second DN to compare
 * @return true if the DNs are equivalent, false otherwise
 */
public static boolean compareDNs(String dn1, String dn2) {
    if (dn1 == null) {
        dn1 = "";
    }

    if (dn2 == null) {
        dn2 = "";
    }

    if (StringUtils.isEmpty(dn1) || StringUtils.isEmpty(dn2)) {
        return dn1.equals(dn2);
    }
    try {
        List<Rdn> rdn1 = new LdapName(dn1).getRdns();
        List<Rdn> rdn2 = new LdapName(dn2).getRdns();

        return rdn1.size() == rdn2.size() && rdn1.containsAll(rdn2);
    } catch (InvalidNameException e) {
        logger.warn("Cannot compare DNs: {} and {} because one or both is not a valid DN", dn1, dn2);
        return false;
    }
}
 
Example #17
Source File: SSLAwareTokenResolver.java    From cougar with Apache License 2.0 6 votes vote down vote up
/**
 * Find an the info from the cert chain provided. <code>null</code> if none found
 */
protected String findCertInfo(X509Certificate[] x509certificates) throws NamingException {
    if (x509certificates != null && x509certificates.length != 0) {
        // Only ever use the first certificate, as this si the client supplied one.
        // Further ones are trust stores and CAs that have signed the first cert.
        Principal subject = x509certificates[0].getSubjectDN();
        if (subject != null && subject.getName() != null) {
            List<Rdn> rdns;
            try {
                rdns = new LdapName(subject.getName()).getRdns();
            }
            catch (InvalidNameException ine) {
                return null;
            }
            return certInfoExtractor.extractCertInfo(rdns);
        }
    }
    return null;
}
 
Example #18
Source File: CertificateUtil.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static Map<String, String> getRdns(final String dn) throws InvalidNameException {
  Map<String, String> rdns = new HashMap<>();
  LdapName ldapName = new LdapName(dn);
  for (Rdn rdn : ldapName.getRdns()) {
    rdns.put(rdn.getType(), rdn.getValue().toString());
  }
  return rdns;
}
 
Example #19
Source File: EscapeUnescapeTests.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
static void printEscapedVal(Object[] values) {
    String escVal;
    for (int i = 0; i < values.length; i++) {
        escVal = Rdn.escapeValue(values[i]);
        System.out.println("Orig val: " + values[i] +
                            "       Escaped val: " + escVal);
    }
}
 
Example #20
Source File: SslCertificateAuditor.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static Map<String, String> parseLdapName(final String dn) {
  try {
    Map<String, String> result = new HashMap<>();
    LdapName ldapName = new LdapName(dn);
    for (Rdn rdn : ldapName.getRdns()) {
      result.put(rdn.getType(), rdn.getValue().toString());
    }
    return result;
  }
  catch (Exception e) {
    Throwables.throwIfUnchecked(e);
    throw new RuntimeException(e);
  }
}
 
Example #21
Source File: BinaryCertPreviewer.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Component preview(final byte[] uploadedBytes) {
    Label commonNameLabel = new Label("certCommonName", new Model<>());
    if (uploadedBytes.length == 0) {
        LOG.info("Enpty certificate");
        return commonNameLabel;
    }

    try (ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes)) {
        X509Certificate certificate = (X509Certificate) CertificateFactory.getInstance("X.509").
                generateCertificate(certificateStream);

        StringBuilder commonNameBuilder = new StringBuilder("cn=");

        LdapName ldapName = new LdapName(certificate.getIssuerDN().getName());

        for (Rdn rdn : ldapName.getRdns()) {
            if ("CN".equalsIgnoreCase(rdn.getType())) {
                commonNameBuilder.append(rdn.getValue() == null
                        ? StringUtils.EMPTY
                        : rdn.getValue().toString());
            }
        }
        commonNameLabel.setDefaultModelObject(commonNameBuilder.toString());
    } catch (Exception e) {
        LOG.error("Error evaluating certificate file", e);
        commonNameLabel.setDefaultModelObject(getString(Constants.ERROR));
    }

    return this.addOrReplace(commonNameLabel);
}
 
Example #22
Source File: EscapeUnescapeTests.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
static void printEscapedVal(Object[] values) {
    String escVal;
    for (int i = 0; i < values.length; i++) {
        escVal = Rdn.escapeValue(values[i]);
        System.out.println("Orig val: " + values[i] +
                            "       Escaped val: " + escVal);
    }
}
 
Example #23
Source File: ServiceLocator.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
 * Processes a sequence of RDNs having a DC attribute.
 * The special RDN "DC=." denotes the root of the domain tree.
 * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
 * RDN "DC=." all reset the domain name and processing continues.
 *
 * @param dn A string distinguished name (RFC 2253).
 * @return A domain name or null if none can be derived.
 * @throw InvalidNameException If the distinugished name is invalid.
 */
static String mapDnToDomainName(String dn) throws InvalidNameException {
    if (dn == null) {
        return null;
    }
    StringBuffer domain = new StringBuffer();
    LdapName ldapName = new LdapName(dn);

    // process RDNs left-to-right
    //List<Rdn> rdnList = ldapName.getRdns();

    List<Rdn> rdnList = ldapName.getRdns();
    for (int i = rdnList.size() - 1; i >= 0; i--) {
        //Rdn rdn = rdnList.get(i);
        Rdn rdn = rdnList.get(i);

        // single-valued RDN with a DC attribute
        if ((rdn.size() == 1) &&
            ("dc".equalsIgnoreCase(rdn.getType()) )) {
            Object attrval = rdn.getValue();
            if (attrval instanceof String) {
                if (attrval.equals(".") ||
                    (domain.length() == 1 && domain.charAt(0) == '.')) {
                    domain.setLength(0); // reset (when current or previous
                                         //        RDN value is "DC=.")
                }
                if (domain.length() > 0) {
                    domain.append('.');
                }
                domain.append(attrval);
            } else {
                domain.setLength(0); // reset (when binary-valued attribute)
            }
        } else {
            domain.setLength(0); // reset (when multi-valued RDN or non-DC)
        }
    }
    return (domain.length() != 0) ? domain.toString() : null;
}
 
Example #24
Source File: ServiceLocator.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
 * Processes a sequence of RDNs having a DC attribute.
 * The special RDN "DC=." denotes the root of the domain tree.
 * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
 * RDN "DC=." all reset the domain name and processing continues.
 *
 * @param dn A string distinguished name (RFC 2253).
 * @return A domain name or null if none can be derived.
 * @throw InvalidNameException If the distinugished name is invalid.
 */
static String mapDnToDomainName(String dn) throws InvalidNameException {
    if (dn == null) {
        return null;
    }
    StringBuffer domain = new StringBuffer();
    LdapName ldapName = new LdapName(dn);

    // process RDNs left-to-right
    //List<Rdn> rdnList = ldapName.getRdns();

    List<Rdn> rdnList = ldapName.getRdns();
    for (int i = rdnList.size() - 1; i >= 0; i--) {
        //Rdn rdn = rdnList.get(i);
        Rdn rdn = rdnList.get(i);

        // single-valued RDN with a DC attribute
        if ((rdn.size() == 1) &&
            ("dc".equalsIgnoreCase(rdn.getType()) )) {
            Object attrval = rdn.getValue();
            if (attrval instanceof String) {
                if (attrval.equals(".") ||
                    (domain.length() == 1 && domain.charAt(0) == '.')) {
                    domain.setLength(0); // reset (when current or previous
                                         //        RDN value is "DC=.")
                }
                if (domain.length() > 0) {
                    domain.append('.');
                }
                domain.append(attrval);
            } else {
                domain.setLength(0); // reset (when binary-valued attribute)
            }
        } else {
            domain.setLength(0); // reset (when multi-valued RDN or non-DC)
        }
    }
    return (domain.length() != 0) ? domain.toString() : null;
}
 
Example #25
Source File: SSLUtil.java    From qpid-broker-j with Apache License 2.0 5 votes vote down vote up
public static String getIdFromSubjectDN(String dn)
{
    String cnStr = null;
    String dcStr = null;
    if(dn == null)
    {
        return "";
    }
    else
    {
        try
        {
            LdapName ln = new LdapName(dn);
            for(Rdn rdn : ln.getRdns())
            {
                if("CN".equalsIgnoreCase(rdn.getType()))
                {
                    cnStr = rdn.getValue().toString();
                }
                else if("DC".equalsIgnoreCase(rdn.getType()))
                {
                    if(dcStr == null)
                    {
                        dcStr = rdn.getValue().toString();
                    }
                    else
                    {
                        dcStr = rdn.getValue().toString() + '.' + dcStr;
                    }
                }
            }
            return cnStr == null || cnStr.length()==0 ? "" : dcStr == null ? cnStr : cnStr + '@' + dcStr;
        }
        catch (InvalidNameException e)
        {
            LOGGER.warn("Invalid name: '{}'", dn);
            return "";
        }
    }
}
 
Example #26
Source File: CertificateModel.java    From Spark with Apache License 2.0 5 votes vote down vote up
private String extractCommonName(String certName) throws InvalidNameException {
	String name = null;
	LdapName ldapDN = new LdapName(certName);
	for (Rdn rdn : ldapDN.getRdns()) {
		if (rdn.getType().equals("CN")) {
			name = rdn.getValue().toString();
		}
	}
	return name;
}
 
Example #27
Source File: BasicSchemaSpecification.java    From spring-ldap with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the policy is satisfied by the supplied LdapAttributes object.
 * 
 * @throws NamingException 
 */	
public boolean isSatisfiedBy(LdapAttributes record) throws NamingException {
	if (record != null) {
		
		//DN is required.
		LdapName dn = record.getName();
		if (dn != null) {
			
			//objectClass definition is required.
			if (record.get("objectClass") != null) {
				
				//Naming attribute is required.
                   Rdn rdn = dn.getRdn(dn.size() - 1);
                   if (record.get(rdn.getType()) != null) {
					Object object = record.get(rdn.getType()).get();
					
					if (object instanceof String) {
						String value = (String) object;
						if (((String)rdn.getValue()).equalsIgnoreCase(value)) {
							return true;
						}
					} else if(object instanceof byte[]) {
						String rdnValue = LdapEncoder.printBase64Binary(((String)rdn.getValue()).getBytes());
						String attributeValue = LdapEncoder.printBase64Binary((byte[]) object);
						if (rdnValue.equals(attributeValue)) return true;
					} 
				}
			}
		}
	}
	
	return false;
}
 
Example #28
Source File: ServiceLocator.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
 * Processes a sequence of RDNs having a DC attribute.
 * The special RDN "DC=." denotes the root of the domain tree.
 * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
 * RDN "DC=." all reset the domain name and processing continues.
 *
 * @param dn A string distinguished name (RFC 2253).
 * @return A domain name or null if none can be derived.
 * @throw InvalidNameException If the distinugished name is invalid.
 */
static String mapDnToDomainName(String dn) throws InvalidNameException {
    if (dn == null) {
        return null;
    }
    StringBuffer domain = new StringBuffer();
    LdapName ldapName = new LdapName(dn);

    // process RDNs left-to-right
    //List<Rdn> rdnList = ldapName.getRdns();

    List<Rdn> rdnList = ldapName.getRdns();
    for (int i = rdnList.size() - 1; i >= 0; i--) {
        //Rdn rdn = rdnList.get(i);
        Rdn rdn = rdnList.get(i);

        // single-valued RDN with a DC attribute
        if ((rdn.size() == 1) &&
            ("dc".equalsIgnoreCase(rdn.getType()) )) {
            Object attrval = rdn.getValue();
            if (attrval instanceof String) {
                if (attrval.equals(".") ||
                    (domain.length() == 1 && domain.charAt(0) == '.')) {
                    domain.setLength(0); // reset (when current or previous
                                         //        RDN value is "DC=.")
                }
                if (domain.length() > 0) {
                    domain.append('.');
                }
                domain.append(attrval);
            } else {
                domain.setLength(0); // reset (when binary-valued attribute)
            }
        } else {
            domain.setLength(0); // reset (when multi-valued RDN or non-DC)
        }
    }
    return (domain.length() != 0) ? domain.toString() : null;
}
 
Example #29
Source File: EscapeUnescapeTests.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static void printEscapedVal(Object[] values) {
    String escVal;
    for (int i = 0; i < values.length; i++) {
        escVal = Rdn.escapeValue(values[i]);
        System.out.println("Orig val: " + values[i] +
                            "       Escaped val: " + escVal);
    }
}
 
Example #30
Source File: ServiceLocator.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Maps a distinguished name (RFC 2253) to a fully qualified domain name.
 * Processes a sequence of RDNs having a DC attribute.
 * The special RDN "DC=." denotes the root of the domain tree.
 * Multi-valued RDNs, non-DC attributes, binary-valued attributes and the
 * RDN "DC=." all reset the domain name and processing continues.
 *
 * @param dn A string distinguished name (RFC 2253).
 * @return A domain name or null if none can be derived.
 * @throws InvalidNameException If the distinguished name is invalid.
 */
static String mapDnToDomainName(String dn) throws InvalidNameException {
    if (dn == null) {
        return null;
    }
    StringBuilder domain = new StringBuilder();
    LdapName ldapName = new LdapName(dn);

    // process RDNs left-to-right
    //List<Rdn> rdnList = ldapName.getRdns();

    List<Rdn> rdnList = ldapName.getRdns();
    for (int i = rdnList.size() - 1; i >= 0; i--) {
        //Rdn rdn = rdnList.get(i);
        Rdn rdn = rdnList.get(i);

        // single-valued RDN with a DC attribute
        if ((rdn.size() == 1) &&
            ("dc".equalsIgnoreCase(rdn.getType()) )) {
            Object attrval = rdn.getValue();
            if (attrval instanceof String) {
                if (attrval.equals(".") ||
                    (domain.length() == 1 && domain.charAt(0) == '.')) {
                    domain.setLength(0); // reset (when current or previous
                                         //        RDN value is "DC=.")
                }
                if (domain.length() > 0) {
                    domain.append('.');
                }
                domain.append(attrval);
            } else {
                domain.setLength(0); // reset (when binary-valued attribute)
            }
        } else {
            domain.setLength(0); // reset (when multi-valued RDN or non-DC)
        }
    }
    return (domain.length() != 0) ? domain.toString() : null;
}