Search in sources :

Example 1 with Certificate

use of java.security.cert.Certificate in project buck by facebook.

the class ApkBuilderStep method createKeystoreProperties.

private PrivateKeyAndCertificate createKeystoreProperties() throws IOException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance(JARSIGNER_KEY_STORE_TYPE);
    KeystoreProperties keystoreProperties = keystorePropertiesSupplier.get();
    InputStream inputStream = filesystem.getInputStreamForRelativePath(pathToKeystore);
    char[] keystorePassword = keystoreProperties.getStorepass().toCharArray();
    try {
        keystore.load(inputStream, keystorePassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException e) {
        throw new HumanReadableException(e, "%s is an invalid keystore.", pathToKeystore);
    }
    String alias = keystoreProperties.getAlias();
    char[] keyPassword = keystoreProperties.getKeypass().toCharArray();
    Key key = keystore.getKey(alias, keyPassword);
    // key can be null if alias/password is incorrect.
    if (key == null) {
        throw new HumanReadableException("The keystore [%s] key.alias [%s] does not exist or does not identify a key-related " + "entry", pathToKeystore, alias);
    }
    Certificate certificate = keystore.getCertificate(alias);
    return new PrivateKeyAndCertificate((PrivateKey) key, (X509Certificate) certificate);
}
Also used : InputStream(java.io.InputStream) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStore(java.security.KeyStore) HumanReadableException(com.facebook.buck.util.HumanReadableException) Key(java.security.Key) PrivateKey(java.security.PrivateKey) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 2 with Certificate

use of java.security.cert.Certificate in project jetty.project by eclipse.

the class SslContextFactory method getCertChain.

public static X509Certificate[] getCertChain(SSLSession sslSession) {
    try {
        Certificate[] javaxCerts = sslSession.getPeerCertificates();
        if (javaxCerts == null || javaxCerts.length == 0)
            return null;
        int length = javaxCerts.length;
        X509Certificate[] javaCerts = new X509Certificate[length];
        java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
        for (int i = 0; i < length; i++) {
            byte[] bytes = javaxCerts[i].getEncoded();
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            javaCerts[i] = (X509Certificate) cf.generateCertificate(stream);
        }
        return javaCerts;
    } catch (SSLPeerUnverifiedException pue) {
        return null;
    } catch (Exception e) {
        LOG.warn(Log.EXCEPTION, e);
        return null;
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) IOException(java.io.IOException) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 3 with Certificate

use of java.security.cert.Certificate in project jetty.project by eclipse.

the class CertificateValidator method validate.

/**
     * validates a specific certificate inside of the keystore being passed in
     * 
     * @param keyStore the keystore to validate against
     * @param cert the certificate to validate
     * @throws CertificateException if keystore error and unable to validate
     */
public void validate(KeyStore keyStore, Certificate cert) throws CertificateException {
    Certificate[] certChain = null;
    if (cert != null && cert instanceof X509Certificate) {
        ((X509Certificate) cert).checkValidity();
        String certAlias = null;
        try {
            if (keyStore == null) {
                throw new InvalidParameterException("Keystore cannot be null");
            }
            certAlias = keyStore.getCertificateAlias((X509Certificate) cert);
            if (certAlias == null) {
                certAlias = "JETTY" + String.format("%016X", __aliasCount.incrementAndGet());
                keyStore.setCertificateEntry(certAlias, cert);
            }
            certChain = keyStore.getCertificateChain(certAlias);
            if (certChain == null || certChain.length == 0) {
                throw new IllegalStateException("Unable to retrieve certificate chain");
            }
        } catch (KeyStoreException kse) {
            LOG.debug(kse);
            throw new CertificateException("Unable to validate certificate" + (certAlias == null ? "" : " for alias [" + certAlias + "]") + ": " + kse.getMessage(), kse);
        }
        validate(certChain);
    }
}
Also used : InvalidParameterException(java.security.InvalidParameterException) CertificateException(java.security.cert.CertificateException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 4 with Certificate

use of java.security.cert.Certificate in project tomcat by apache.

the class JSSESupport method getPeerCertificateChain.

@Override
public java.security.cert.X509Certificate[] getPeerCertificateChain() throws IOException {
    // Look up the current SSLSession
    if (session == null)
        return null;
    Certificate[] certs = null;
    try {
        certs = session.getPeerCertificates();
    } catch (Throwable t) {
        log.debug(sm.getString("jsseSupport.clientCertError"), t);
        return null;
    }
    if (certs == null)
        return null;
    java.security.cert.X509Certificate[] x509Certs = new java.security.cert.X509Certificate[certs.length];
    for (int i = 0; i < certs.length; i++) {
        if (certs[i] instanceof java.security.cert.X509Certificate) {
            // always currently true with the JSSE 1.1.x
            x509Certs[i] = (java.security.cert.X509Certificate) certs[i];
        } else {
            try {
                byte[] buffer = certs[i].getEncoded();
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                x509Certs[i] = (java.security.cert.X509Certificate) cf.generateCertificate(stream);
            } catch (Exception ex) {
                log.info(sm.getString("jseeSupport.certTranslationError", certs[i]), ex);
                return null;
            }
        }
        if (log.isTraceEnabled())
            log.trace("Cert #" + i + " = " + x509Certs[i]);
    }
    if (x509Certs.length < 1)
        return null;
    return x509Certs;
}
Also used : CertificateFactory(java.security.cert.CertificateFactory) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) Certificate(java.security.cert.Certificate)

Example 5 with Certificate

use of java.security.cert.Certificate 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)

Aggregations

Certificate (java.security.cert.Certificate)1411 X509Certificate (java.security.cert.X509Certificate)854 CertificateFactory (java.security.cert.CertificateFactory)382 KeyStore (java.security.KeyStore)355 ByteArrayInputStream (java.io.ByteArrayInputStream)324 IOException (java.io.IOException)243 CertificateException (java.security.cert.CertificateException)234 PrivateKey (java.security.PrivateKey)232 KeyStoreException (java.security.KeyStoreException)190 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)143 ArrayList (java.util.ArrayList)123 InputStream (java.io.InputStream)116 FileInputStream (java.io.FileInputStream)109 KeyFactory (java.security.KeyFactory)97 Test (org.junit.Test)94 File (java.io.File)89 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)84 Key (java.security.Key)79 PublicKey (java.security.PublicKey)79 GeneralSecurityException (java.security.GeneralSecurityException)78