Search in sources :

Example 36 with Certificate

use of java.security.cert.Certificate in project http-kit by http-kit.

the class HttpsTest method print_https_cert.

private static void print_https_cert(HttpsURLConnection con) {
    if (con != null) {
        try {
            System.out.println("Response Code : " + con.getResponseCode());
            System.out.println("Cipher Suite : " + con.getCipherSuite());
            System.out.println("\n");
            Certificate[] certs = con.getServerCertificates();
            for (Certificate cert : certs) {
                System.out.println("Cert Type : " + cert.getType());
                System.out.println("Cert Hash Code : " + cert.hashCode());
                System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm());
                System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat());
                System.out.println("\n");
            }
        } catch (SSLPeerUnverifiedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) IOException(java.io.IOException) Certificate(java.security.cert.Certificate)

Example 37 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)

Example 38 with Certificate

use of java.security.cert.Certificate in project Openfire by igniterealtime.

the class IdentityStore method generateCSR.

/**
     * Creates a Certificate Signing Request based on the private key and certificate identified by the provided alias.
     *
     * When the alias does not identify a private key and/or certificate, this method will throw an exception.
     *
     * The certificate that is identified by the provided alias can be an unsigned certificate, but also a certificate
     * that is already signed. The latter implies that the generated request is a request for certificate renewal.
     *
     * An invocation of this method does not change the state of the underlying store.
     *
     * @param alias An identifier for a private key / certificate in this store (cannot be null).
     * @return A PEM-encoded Certificate Signing Request (never null).
     */
public String generateCSR(String alias) throws CertificateStoreConfigException {
    // Input validation
    if (alias == null || alias.trim().isEmpty()) {
        throw new IllegalArgumentException("Argument 'alias' cannot be null or an empty String.");
    }
    alias = alias.trim();
    try {
        if (!store.containsAlias(alias)) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': the alias does not exist in the store.");
        }
        final Certificate certificate = store.getCertificate(alias);
        if (certificate == null || (!(certificate instanceof X509Certificate))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding certificate in the store, or it is not an X509 certificate.");
        }
        final Key key = store.getKey(alias, configuration.getPassword());
        if (key == null || (!(key instanceof PrivateKey))) {
            throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "': there is no corresponding key in the store, or it is not a private key.");
        }
        final String pemCSR = CertificateManager.createSigningRequest((X509Certificate) certificate, (PrivateKey) key);
        return pemCSR;
    } catch (IOException | KeyStoreException | UnrecoverableKeyException | NoSuchAlgorithmException | OperatorCreationException e) {
        throw new CertificateStoreConfigException("Cannot generate CSR for alias '" + alias + "'", e);
    }
}
Also used : IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 39 with Certificate

use of java.security.cert.Certificate in project Openfire by igniterealtime.

the class IdentityStore method corresponds.

protected boolean corresponds(String alias, List<X509Certificate> certificates) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    if (!store.containsAlias(alias)) {
        return false;
    }
    final Key key = store.getKey(alias, configuration.getPassword());
    if (key == null) {
        return false;
    }
    if (!(key instanceof PrivateKey)) {
        return false;
    }
    final Certificate certificate = store.getCertificate(alias);
    if (certificate == null) {
        return false;
    }
    if (!(certificate instanceof X509Certificate)) {
        return false;
    }
    final X509Certificate x509Certificate = (X509Certificate) certificate;
    // First certificate in the chain should correspond with the certificate in the store
    if (!x509Certificate.getPublicKey().equals(certificates.get(0).getPublicKey())) {
        return false;
    }
    return true;
}
Also used : X509Certificate(java.security.cert.X509Certificate) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 40 with Certificate

use of java.security.cert.Certificate in project Smack by igniterealtime.

the class TLSUtils method getChannelBindingTlsServerEndPoint.

/**
     * Get the channel binding data for the 'tls-server-end-point' channel binding type. This channel binding type is
     * defined in RFC 5929 § 4.
     *
     * @param sslSession the SSL/TLS session from which the data should be retrieved.
     * @return the channel binding data.
     * @throws SSLPeerUnverifiedException
     * @throws CertificateEncodingException
     * @throws NoSuchAlgorithmException
     * @see <a href="https://tools.ietf.org/html/rfc5929#section-4">RFC 5929 § 4.</a>
     */
public static byte[] getChannelBindingTlsServerEndPoint(final SSLSession sslSession) throws SSLPeerUnverifiedException, CertificateEncodingException, NoSuchAlgorithmException {
    final Certificate[] peerCertificates = sslSession.getPeerCertificates();
    final Certificate certificate = peerCertificates[0];
    final String certificateAlgorithm = certificate.getPublicKey().getAlgorithm();
    // RFC 5929 § 4.1 hash function selection.
    String algorithm;
    switch(certificateAlgorithm) {
        case "MD5":
        case "SHA-1":
            algorithm = "SHA-256";
            break;
        default:
            algorithm = certificateAlgorithm;
            break;
    }
    final MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
    final byte[] certificateDerEncoded = certificate.getEncoded();
    messageDigest.update(certificateDerEncoded);
    return messageDigest.digest();
}
Also used : MessageDigest(java.security.MessageDigest) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

Certificate (java.security.cert.Certificate)723 X509Certificate (java.security.cert.X509Certificate)469 CertificateFactory (java.security.cert.CertificateFactory)272 ByteArrayInputStream (java.io.ByteArrayInputStream)237 KeyStore (java.security.KeyStore)133 PrivateKey (java.security.PrivateKey)132 IOException (java.io.IOException)106 CertificateException (java.security.cert.CertificateException)102 KeyFactory (java.security.KeyFactory)89 KeyStoreException (java.security.KeyStoreException)88 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)72 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)69 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)63 ArrayList (java.util.ArrayList)63 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)56 Entry (java.security.KeyStore.Entry)53 PublicKey (java.security.PublicKey)48 InputStream (java.io.InputStream)40 FileInputStream (java.io.FileInputStream)39 Key (java.security.Key)36