Search in sources :

Example 36 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class KeyStoreCertificateStore method getByAlias.

/**
     * Gets a certificate in the keystore with a given alias name.
     * @param alias The alias of the certificate.  Returns null if a certificate with the alias name does not exist in the keystore.
     */
public X509Certificate getByAlias(String alias) {
    X509Certificate retVal = null;
    Certificate cert = null;
    try {
        cert = ks.getCertificate(alias);
        if (cert != null && cert instanceof X509Certificate) {
            // check if there is private key
            Key key = ks.getKey(alias, privateKeyPassword == null ? null : privateKeyPassword.toCharArray());
            if (key != null && key instanceof PrivateKey)
                retVal = X509CertificateEx.fromX509Certificate((X509Certificate) cert, (PrivateKey) key);
            else
                retVal = (X509Certificate) cert;
        }
    } catch (Exception e) {
        throw new NHINDException("", e);
    }
    return retVal;
}
Also used : PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 37 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class KeyStoreCertificateStore method bootstrapFromFile.

private void bootstrapFromFile() {
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        if (!keyStoreFile.exists()) {
            // create a new keystore file
            ks.load(null, keyStorePassword == null ? null : keyStorePassword.toCharArray());
            FileOutputStream outStream = new FileOutputStream(keyStoreFile);
            ks.store(outStream, keyStorePassword == null ? null : keyStorePassword.toCharArray());
            IOUtils.closeQuietly(outStream);
        } else {
            // load from keystore file
            FileInputStream inStream = new FileInputStream(keyStoreFile);
            ks.load(inStream, keyStorePassword == null ? null : keyStorePassword.toCharArray());
            IOUtils.closeQuietly(inStream);
            Enumeration<String> aliases = ks.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                Certificate cert = ks.getCertificate(alias);
                if (cert != null && cert instanceof X509Certificate) {
                    X509Certificate addCert;
                    // check if there is private key
                    Key key = ks.getKey(alias, privateKeyPassword == null ? null : privateKeyPassword.toCharArray());
                    if (key != null && key instanceof PrivateKey)
                        addCert = X509CertificateEx.fromX509Certificate((X509Certificate) cert, (PrivateKey) key);
                    else
                        addCert = (X509Certificate) cert;
                    certs.add(addCert);
                }
            }
        }
    } catch (Exception e) {
        throw new NHINDException("", e);
    }
}
Also used : PrivateKey(java.security.PrivateKey) FileOutputStream(java.io.FileOutputStream) NHINDException(org.nhindirect.stagent.NHINDException) FileInputStream(java.io.FileInputStream) X509Certificate(java.security.cert.X509Certificate) Key(java.security.Key) PrivateKey(java.security.PrivateKey) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 38 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class LdapCertUtilImpl method ldapSearch.

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);
    }
}
Also used : Base64(org.apache.commons.codec.binary.Base64) Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) CertificateException(java.security.cert.CertificateException) InitialDirContext(javax.naming.directory.InitialDirContext) DirContext(javax.naming.directory.DirContext) NHINDException(org.nhindirect.stagent.NHINDException) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NamingException(javax.naming.NamingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NHINDException(org.nhindirect.stagent.NHINDException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ByteArrayInputStream(java.io.ByteArrayInputStream) SearchControls(javax.naming.directory.SearchControls) NamingException(javax.naming.NamingException)

Example 39 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class LdapPublicCertUtilImpl method ldapSearch.

/**
	 * Searches for certificates in public LDAP servers using the subject name.
	 * @param subjectName The subject's email address or domain name.
	 * @return Collection of certificates matching the LDAP query for the subject name.
	 */
public Collection<X509Certificate> ldapSearch(String subjectName) {
    final Collection<X509Certificate> retVal = new ArrayList<X509Certificate>();
    String domainName;
    // find by host
    int index;
    if ((index = subjectName.indexOf("@")) > -1)
        domainName = subjectName.substring(index + 1);
    else
        domainName = subjectName;
    final String lookupName = LDAP_SRV_PREFIX + domainName;
    InitialDirContext ctx = null;
    try {
        ctx = getDirContext(lookupName);
        if (ctx != null) {
            // discover the naming contexts
            List<String> dNs = getBaseNamingContexts(ctx);
            if (!dNs.isEmpty()) {
                for (String dn : dNs) {
                    NamingEnumeration<SearchResult> searchResult = ctx.search(dn, EMAIL_ATTRIBUTE + "=" + subjectName, getDefaultSearchControls());
                    while (searchResult != null && searchResult.hasMore()) {
                        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)
                                Attribute certAttribute = certAttributes.get(CERT_ATTRIBUTE_BINARY);
                                // binary modifier
                                if (certAttribute == null)
                                    certAttribute = certAttributes.get(CERT_ATTRIBUTE);
                                if (certAttribute != null) {
                                    NamingEnumeration<? extends Object> allValues = certAttribute.getAll();
                                    // LDAP may contain a collection of certificates.
                                    while (allValues.hasMoreElements()) {
                                        byte[] rawCert = null;
                                        Object obj = allValues.nextElement();
                                        rawCert = (byte[]) obj;
                                        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
                                        final ByteArrayInputStream inputStream = new ByteArrayInputStream(rawCert);
                                        try {
                                            X509Certificate addCert = (X509Certificate) cf.generateCertificate(inputStream);
                                            retVal.add(addCert);
                                        } finally {
                                            IOUtils.closeQuietly(inputStream);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new NHINDException("", e);
    } finally {
        this.closeDirContext(ctx);
    }
    return retVal;
}
Also used : Attribute(javax.naming.directory.Attribute) ArrayList(java.util.ArrayList) Attributes(javax.naming.directory.Attributes) SearchResult(javax.naming.directory.SearchResult) InitialDirContext(javax.naming.directory.InitialDirContext) CertificateFactory(java.security.cert.CertificateFactory) NHINDException(org.nhindirect.stagent.NHINDException) X509Certificate(java.security.cert.X509Certificate) NamingException(javax.naming.NamingException) UnknownHostException(java.net.UnknownHostException) NHINDException(org.nhindirect.stagent.NHINDException) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 40 with NHINDException

use of org.nhindirect.stagent.NHINDException in project nhin-d by DirectProject.

the class LdapCertificateStoreProvider method get.

public CertificateResolver get() {
    final Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP_FACTORY);
    String[] ldapURLs = ldapConfiguration.getLdapURLs();
    String ldapProviderUrl = null;
    for (String ldapURL : ldapURLs) {
        if (ldapProviderUrl == null) {
            ldapProviderUrl = ldapURL + " ";
        } else {
            ldapProviderUrl += ldapURL + " ";
        }
    }
    env.put(Context.PROVIDER_URL, ldapProviderUrl);
    if (ldapConfiguration.getLdapConnectionTimeOut() != null) {
        try {
            int connectionTimeOut = Integer.parseInt(ldapConfiguration.getLdapConnectionTimeOut());
            if (connectionTimeOut < 1) {
                LOGGER.error("Connection timeout must be a positive integer");
                throw new NHINDException("Invalid value for the LDAP connection timeout");
            }
        } catch (NumberFormatException nfe) {
            LOGGER.error("Connection timeout string is not a valid number.");
            throw new NHINDException("Invalid value for the LDAP connection timeout", nfe);
        }
        env.put(LDAP_TIMEOUT, ldapConfiguration.getLdapConnectionTimeOut());
    }
    if (ldapConfiguration.getEmployLdapAuthInformation() != null) {
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, ldapConfiguration.getEmployLdapAuthInformation().getLdapPrincipal());
        env.put(Context.SECURITY_CREDENTIALS, ldapConfiguration.getEmployLdapAuthInformation().getLdapPassword());
    } else {
        env.put(Context.SECURITY_AUTHENTICATION, "none");
    }
    LdapEnvironment ldapEnvironment = new LdapEnvironment(env, ldapConfiguration.getReturningCertAttribute(), ldapConfiguration.getLdapSearchBase(), ldapConfiguration.getLdapSearchAttribute());
    LdapCertUtilImpl ldapcertUtilImpl = new LdapCertUtilImpl(ldapEnvironment, ldapConfiguration.getLdapCertPassphrase(), ldapConfiguration.getCertificateFormat());
    return new LDAPCertificateStore(ldapcertUtilImpl, bootstrapStore, policy);
}
Also used : LdapEnvironment(org.nhindirect.stagent.cert.impl.LdapEnvironment) Hashtable(java.util.Hashtable) LDAPCertificateStore(org.nhindirect.stagent.cert.impl.LDAPCertificateStore) LdapCertUtilImpl(org.nhindirect.stagent.cert.impl.LdapCertUtilImpl) NHINDException(org.nhindirect.stagent.NHINDException)

Aggregations

NHINDException (org.nhindirect.stagent.NHINDException)45 X509Certificate (java.security.cert.X509Certificate)30 ArrayList (java.util.ArrayList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 IOException (java.io.IOException)11 Key (java.security.Key)10 PrivateKey (java.security.PrivateKey)10 KeyStore (java.security.KeyStore)9 CacheException (org.apache.jcs.access.exception.CacheException)7 X509CertificateEx (org.nhindirect.stagent.cert.X509CertificateEx)7 MessagingException (javax.mail.MessagingException)6 Collection (java.util.Collection)4 UnknownHostException (java.net.UnknownHostException)3 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)3 Certificate (java.security.cert.Certificate)3 InternetHeaders (javax.mail.internet.InternetHeaders)3 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)3 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)3 MutableKeyStoreProtectionManager (org.nhindirect.common.crypto.MutableKeyStoreProtectionManager)3 File (java.io.File)2