get SSLSocektFactory - Java Network

Java examples for Network:SSL

Description

get SSLSocektFactory

Demo Code


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

import java.security.KeyStore;

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 void main(String[] argv) throws Exception {
        String keyStorePath = "java2s.com";
        String passwd = "java2s.com";
        String trustKeyStorePath = "java2s.com";
        System.out.println(getSSLSocketFactory(keyStorePath, passwd,
                trustKeyStorePath));//w  w  w  . j a  va 2 s.  c  om
    }

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

    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