Creates ssl context based on keystore file - Java Security

Java examples for Security:Key

Description

Creates ssl context based on keystore file

Demo Code


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

import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

public class Main {
    /**/*  w w  w . j av  a 2s .  c o m*/
     * Creates ssl context based on keystore file
     * @param keyStoreName
     * @param openPassword
     * @param usePassword
     * @return
     */
    public static SSLContext createSSLContext(String keyStoreName,
            String openPassword, String usePassword) {
        try {
            KeyStore keyStore = KeyStore.getInstance("JKS");
            keyStore.load(new FileInputStream(keyStoreName),
                    openPassword.toCharArray());
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance("SunX509");
            keyManagerFactory.init(keyStore, usePassword.toCharArray());
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
            return sslContext;
        } catch (KeyStoreException ex) {
            throw new RuntimeException(ex);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        } catch (CertificateException ex) {
            throw new RuntimeException(ex);
        } catch (UnrecoverableKeyException ex) {
            throw new RuntimeException(ex);
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related Tutorials