// /CLOVER:OFF protected SearchControls getDefaultSearchControls() { SearchControls ctls = new SearchControls(); ctls.setReturningObjFlag(true); ctls.setSearchScope(SearchControls.SUBTREE_SCOPE); ctls.setReturningAttributes(new String[] {ldapEnvironment.getReturningCertAttribute()}); return ctls; }
public Collection<X509Certificate> ldapSearch(String subjectName) { DirContext ctx = null; try { ctx = getInitialDirContext(ldapEnvironment.getEnv()); final SearchControls ctls = getDefaultSearchControls(); NamingEnumeration<SearchResult> searchResult = ctx.search( ldapEnvironment.getLdapSearchBase(), ldapEnvironment.getLdapSearchAttribute() + "=" + subjectName, ctls); ArrayList<X509Certificate> certificates = new ArrayList<X509Certificate>(); while (searchResult != null && searchResult.hasMoreElements()) { final SearchResult certEntry = searchResult.nextElement(); if (certEntry != null) { final Attributes certAttributes = certEntry.getAttributes(); if (certAttributes != null) { // get only the returning cert attribute (for now, ignore all other attributes) final Attribute certAttribute = certAttributes.get(ldapEnvironment.getReturningCertAttribute()); if (certAttribute != null) { NamingEnumeration<? extends Object> allValues = certAttribute.getAll(); // LDAP may contain a collection of certificates. while (allValues.hasMoreElements()) { String ksBytes = (String) allValues.nextElement(); Base64 base64 = new Base64(); byte[] decode = base64.decode(ksBytes.getBytes()); ByteArrayInputStream inputStream = new ByteArrayInputStream(decode); if (certificateFormat.equalsIgnoreCase("pkcs12")) { try { processPKCS12FileFormatAndAddToCertificates(inputStream, certificates); } catch (Exception e) { closeDirContext(ctx); throw new NHINDException("", e); } } else { if (certificateFormat.equalsIgnoreCase("X.509") || certificateFormat.equalsIgnoreCase("X509")) { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream); certificates.add(addCert); } else { closeDirContext(ctx); throw new NHINDException("Invalid certificate format requested"); } } } } } } } return certificates; } catch (NamingException e) { closeDirContext(ctx); throw new NHINDException("", e); } catch (CertificateException e) { closeDirContext(ctx); throw new NHINDException("", e); } }