集册 Java实例教程 配置SSL套接字工厂

配置SSL套接字工厂

欢马劈雪     最近更新时间:2020-01-02 10:19:05

567
配置SSL套接字工厂


//package com.nowjava;// from NowJava.com - 时代Java

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) {
            /*
            NowJava.com - 时代Java 提供
            */

        conn.setSSLSocketFactory(getSSLSocketFactory(keyStorePath, passwd,

                trustKeyStorePath));

    }


    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.
展开阅读全文