Search in sources :

Example 6 with KeyStoreException

use of java.security.KeyStoreException in project Openfire by igniterealtime.

the class CertificateManager method getEndEntityCertificate.

/**
     * Decide whether or not to trust the given supplied certificate chain, returning the
     * End Entity Certificate in this case where it can, and null otherwise.
     * A self-signed certificate will, for example, return null.
     * For certain failures, we SHOULD generate an exception - revocations and the like,
     * but we currently do not.
     *
     * @param chain an array of X509Certificate where the first one is the endEntityCertificate.
     * @param certStore a keystore containing untrusted certificates (including ICAs, etc).
     * @param trustStore a keystore containing Trust Anchors (most-trusted CA certificates).
     * @return trusted end-entity certificate, or null.
     */
public static X509Certificate getEndEntityCertificate(Certificate[] chain, KeyStore certStore, KeyStore trustStore) {
    if (chain.length == 0) {
        return null;
    }
    X509Certificate first = (X509Certificate) chain[0];
    try {
        first.checkValidity();
    } catch (CertificateException e) {
        Log.warn("EE Certificate not valid: " + e.getMessage());
        return null;
    }
    if (chain.length == 1 && first.getSubjectX500Principal().equals(first.getIssuerX500Principal())) {
        // Chain is single cert, and self-signed.
        try {
            if (trustStore.getCertificateAlias(first) != null) {
                // Interesting case: trusted self-signed cert.
                return first;
            }
        } catch (KeyStoreException e) {
            Log.warn("Keystore error while looking for self-signed cert; assuming untrusted.");
        }
        return null;
    }
    final List<Certificate> all_certs = new ArrayList<>();
    try {
        // It's a mystery why these objects are different.
        for (Enumeration<String> aliases = certStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (certStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) certStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Now add the trusted certs.
        for (Enumeration<String> aliases = trustStore.aliases(); aliases.hasMoreElements(); ) {
            String alias = aliases.nextElement();
            if (trustStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) trustStore.getCertificate(alias);
                all_certs.add(cert);
            }
        }
        // Finally, add all the certs in the chain:
        for (int i = 0; i < chain.length; ++i) {
            all_certs.add(chain[i]);
        }
        CertStore cs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(all_certs));
        X509CertSelector selector = new X509CertSelector();
        selector.setCertificate(first);
        // / selector.setSubject(first.getSubjectX500Principal());
        PKIXBuilderParameters params = new PKIXBuilderParameters(trustStore, selector);
        params.addCertStore(cs);
        params.setDate(new Date());
        params.setRevocationEnabled(false);
        /* Code here is the right way to do things. */
        CertPathBuilder pathBuilder = CertPathBuilder.getInstance(CertPathBuilder.getDefaultType());
        CertPath cp = pathBuilder.build(params).getCertPath();
        /**
             * This section is an alternative to using CertPathBuilder which is
             * not as complete (or safe), but will emit much better errors. If
             * things break, swap around the code.
             *
             **** COMMENTED OUT. ****
            ArrayList<X509Certificate> ls = new ArrayList<X509Certificate>();
            for (int i = 0; i < chain.length; ++i) {
                ls.add((X509Certificate) chain[i]);
            }
            for (X509Certificate last = ls.get(ls.size() - 1); !last
                    .getIssuerX500Principal().equals(last.getSubjectX500Principal()); last = ls
                    .get(ls.size() - 1)) {
                X509CertSelector sel = new X509CertSelector();
                sel.setSubject(last.getIssuerX500Principal());
                ls.add((X509Certificate) cs.getCertificates(sel).toArray()[0]);
            }
            CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(ls);
             ****** END ALTERNATIVE. ****
             */
        // Not entirely sure if I need to do this with CertPathBuilder.
        // Can't hurt.
        CertPathValidator pathValidator = CertPathValidator.getInstance("PKIX");
        pathValidator.validate(cp, params);
        return (X509Certificate) cp.getCertificates().get(0);
    } catch (CertPathBuilderException e) {
        Log.warn("Path builder: " + e.getMessage());
    } catch (CertPathValidatorException e) {
        Log.warn("Path validator: " + e.getMessage());
    } catch (Exception e) {
        Log.warn("Unkown exception while validating certificate chain: " + e.getMessage());
    }
    return null;
}
Also used : PKIXBuilderParameters(java.security.cert.PKIXBuilderParameters) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) CertificateException(java.security.cert.CertificateException) X509CertSelector(java.security.cert.X509CertSelector) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) KeyStoreException(java.security.KeyStoreException) GeneralSecurityException(java.security.GeneralSecurityException) CertPathValidatorException(java.security.cert.CertPathValidatorException) CertException(org.bouncycastle.cert.CertException) CertPathBuilderException(java.security.cert.CertPathBuilderException) PKCSException(org.bouncycastle.pkcs.PKCSException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) CertPathValidator(java.security.cert.CertPathValidator) CertPathValidatorException(java.security.cert.CertPathValidatorException) CollectionCertStoreParameters(java.security.cert.CollectionCertStoreParameters) CertPathBuilderException(java.security.cert.CertPathBuilderException) CertPathBuilder(java.security.cert.CertPathBuilder) CertPath(java.security.cert.CertPath) CertStore(java.security.cert.CertStore) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 7 with KeyStoreException

use of java.security.KeyStoreException in project hadoop by apache.

the class AbstractJavaKeyStoreProvider method innerSetCredential.

CredentialEntry innerSetCredential(String alias, char[] material) throws IOException {
    writeLock.lock();
    try {
        keyStore.setKeyEntry(alias, new SecretKeySpec(new String(material).getBytes("UTF-8"), "AES"), password, null);
    } catch (KeyStoreException e) {
        throw new IOException("Can't store credential " + alias + " in " + this, e);
    } finally {
        writeLock.unlock();
    }
    changed = true;
    return new CredentialEntry(alias, material);
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException)

Example 8 with KeyStoreException

use of java.security.KeyStoreException in project hadoop by apache.

the class AbstractJavaKeyStoreProvider method flush.

@Override
public void flush() throws IOException {
    writeLock.lock();
    try {
        if (!changed) {
            LOG.debug("Keystore hasn't changed, returning.");
            return;
        }
        LOG.debug("Writing out keystore.");
        try (OutputStream out = getOutputStreamForKeystore()) {
            keyStore.store(out, password);
        } catch (KeyStoreException e) {
            throw new IOException("Can't store keystore " + this, e);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException("No such algorithm storing keystore " + this, e);
        } catch (CertificateException e) {
            throw new IOException("Certificate exception storing keystore " + this, e);
        }
        changed = false;
    } finally {
        writeLock.unlock();
    }
}
Also used : OutputStream(java.io.OutputStream) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 9 with KeyStoreException

use of java.security.KeyStoreException in project OpenAttestation by OpenAttestation.

the class Pkcs12 method setRsaCredentialX509.

/**
     * Replaces an existing keypair with the same alias or adds a new keypair
     * if one did not already exist.
     * 
     * The chain is optional and if provided it must be the certificates that
     * signed the credential's public key, in order, with the Root CA being LAST.
     * 
     * @param key
     * @param chain
     * @param alias 
     * @param keyPassword
     */
public void setRsaCredentialX509(RsaCredentialX509 key, X509Certificate[] chain, String alias, String keyPassword) throws KeyManagementException {
    try {
        List<String> aliases = Collections.list(keystore.aliases());
        if (aliases.contains(alias)) {
            keystore.deleteEntry(alias);
        }
        X509Certificate[] chain1;
        if (chain != null) {
            chain1 = new X509Certificate[chain.length + 1];
            chain1[0] = key.getCertificate();
            System.arraycopy(chain, 0, chain1, 1, chain.length);
        } else {
            chain1 = new X509Certificate[] { key.getCertificate() };
        }
        keystore.setKeyEntry(alias, key.getPrivateKey(), keyPassword.toCharArray(), chain1);
    } catch (KeyStoreException e) {
        throw new KeyManagementException("Cannot add credential", e);
    }
}
Also used : KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) KeyManagementException(java.security.KeyManagementException)

Example 10 with KeyStoreException

use of java.security.KeyStoreException in project OpenAttestation by OpenAttestation.

the class Pkcs12 method save.

/**
     * Saves the keystore to the resource passed in to the constructor.
     * 
     * @throws IOException if there was an error writing the keystore to the resource
     * @throws KeyStoreException if the keystore has not been initialized, or if the integrity check algorithm is not available, or if any certificates in the keystore could not be loaded
     */
public void save() throws IOException, KeyStoreException {
    try {
        OutputStream out = keystoreResource.getOutputStream();
        //, 
        keystore.store(out, keystorePassword.toCharArray());
        out.close();
    } catch (NoSuchAlgorithmException e) {
        // if the algorithm used to check the integrity of the keystore cannot be found
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        // if any certificates in the keystore could not be loaded
        throw new KeyStoreException(e);
    }
}
Also used : OutputStream(java.io.OutputStream) CertificateException(java.security.cert.CertificateException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException)

Aggregations

KeyStoreException (java.security.KeyStoreException)797 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)506 IOException (java.io.IOException)409 KeyStore (java.security.KeyStore)359 CertificateException (java.security.cert.CertificateException)353 UnrecoverableKeyException (java.security.UnrecoverableKeyException)194 X509Certificate (java.security.cert.X509Certificate)189 KeyManagementException (java.security.KeyManagementException)172 Certificate (java.security.cert.Certificate)132 InputStream (java.io.InputStream)103 SSLContext (javax.net.ssl.SSLContext)103 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)95 FileInputStream (java.io.FileInputStream)94 File (java.io.File)80 PrivateKey (java.security.PrivateKey)71 TrustManager (javax.net.ssl.TrustManager)70 FileNotFoundException (java.io.FileNotFoundException)61 ByteArrayInputStream (java.io.ByteArrayInputStream)58 CertificateFactory (java.security.cert.CertificateFactory)58 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)53