load X509TrustManager - Java Security

Java examples for Security:Trust Manager

Description

load X509TrustManager

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;

import java.util.List;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

public class Main {
    public static void main(String[] argv) throws Exception {
        List serverCerts = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(load(serverCerts));
    }/*from   www.  ja  v a  2s . c o  m*/

    public static X509TrustManager load(List<File> serverCerts)
            throws NoSuchAlgorithmException, KeyStoreException,
            IOException, CertificateException {
        return trustManagerForKeyStore(keyStoreForCerts(serverCerts));
    }

    public static X509TrustManager trustManagerForKeyStore(KeyStore ks)
            throws NoSuchAlgorithmException, KeyStoreException {
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());

        tmf.init(ks);

        return (X509TrustManager) tmf.getTrustManagers()[0];
    }

    public static KeyStore keyStoreForCerts(List<File> serverCerts)
            throws CertificateException, KeyStoreException, IOException,
            NoSuchAlgorithmException {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);

        for (int i = 0; i < serverCerts.size(); i++) {
            try (InputStream is = new FileInputStream(serverCerts.get(i))) {
                X509Certificate caCert = (X509Certificate) cf
                        .generateCertificate(is);
                ks.setCertificateEntry("cacrt." + i, caCert);
            }
        }
        return ks;
    }
}

Related Tutorials