config SSL Socket Factory - Java Network

Java examples for Network:SSL

Description

config SSL Socket Factory

Demo Code


//package com.java2s;
import java.io.FileInputStream;
import java.io.IOException;

import java.security.KeyStore;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class Main {

    public static final String KEY_STORE = "JKS";
    public static final String SunX509 = "SunX509";
    public static final String SSL = "SSL";

    public static void configSSLSocketFactory(HttpsURLConnection conn,
            String keyStorePath, String passwd, String trustKeyStorePath) {
        conn.setSSLSocketFactory(getSSLSocketFactory(keyStorePath, passwd,
                trustKeyStorePath));//from  w ww . j  ava  2s .co  m
    }

    private static SSLSocketFactory getSSLSocketFactory(
            String keyStorePath, String passwd, String trustKeyStorePath) {
        try {
            // ???????
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(SunX509);
            KeyStore keyStore = getKeyStore(keyStorePath, passwd);
            keyManagerFactory.init(keyStore, passwd.toCharArray());

            // ???????
            TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(SunX509);
            KeyStore trustkeyStore = getKeyStore(trustKeyStorePath, passwd);
            trustManagerFactory.init(trustkeyStore);

            // ????SSL???
            SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(keyManagerFactory.getKeyManagers(),
                    trustManagerFactory.getTrustManagers(), null);
            SSLSocketFactory socketFactory = sslContext.getSocketFactory();
            return socketFactory;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static KeyStore getKeyStore(String keyStorePath, String passwd) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(keyStorePath);
            KeyStore ks = KeyStore.getInstance(KEY_STORE);
            ks.load(fis, passwd.toCharArray());
            return ks;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

Related Tutorials