集册 Java实例教程 获取SSLSocektFactory

获取SSLSocektFactory

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

511
获取SSLSocektFactory
//时 代 J     a    v  a - nowjava.com 提供

//package com.nowjava;

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 {
/**
时 代 J a v a - N o w J a v a . c o m
**/

    public static void main(String[] argv) throws Exception {

        String keyStorePath = "nowjava.com";

        String passwd = "nowjava.com";

        String trustKeyStorePath = "nowjava.com";

        System.out.println(getSSLSocketFactory(keyStorePath, passwd,

                trustKeyStorePath));

    }


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