Example usage for javax.net.ssl KeyManagerFactory getInstance

List of usage examples for javax.net.ssl KeyManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl KeyManagerFactory getInstance.

Prototype

public static final KeyManagerFactory getInstance(String algorithm, Provider provider)
        throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyManagerFactory object that acts as a factory for key managers.

Usage

From source file:com.nesscomputing.httpclient.internal.HttpClientTrustManagerFactory.java

@Nonnull
private static X509KeyManager getKeyManagerForKeystore(@Nonnull KeyStore keyStore, @Nonnull String password)
        throws GeneralSecurityException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");

    keyManagerFactory.init(keyStore, password.toCharArray());

    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            return (X509KeyManager) keyManager;
        }//from   w  ww.  ja va2s  .  c o  m
    }

    throw new IllegalStateException("Couldn't find an X509KeyManager");
}

From source file:org.opennms.netmgt.provision.server.SSLServer.java

/**
 * <p>init</p>//  w w w .j  ava 2  s  . co  m
 *
 * @throws java.lang.Exception if any.
 */
@Override
public void init() throws Exception {
    super.init();
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(getKeyManagerAlgorithm(), getKeyManagerProvider());
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    char[] password = getPassword().toCharArray();

    java.io.FileInputStream fis = null;
    try {
        fis = new java.io.FileInputStream(getPathToKeyStore());
        ks.load(fis, password);
    } finally {
        if (fis != null) {
            fis.close();
        }
    }

    kmf.init(ks, password);
    KeyManager[] km = kmf.getKeyManagers();

    SSLContext sslContext = SSLContext.getInstance(getSslContextProtocol());
    sslContext.init(km, null, new SecureRandom());
    SSLServerSocketFactory serverFactory = sslContext.getServerSocketFactory();
    setServerSocket(serverFactory.createServerSocket(getPort()));
    onInit();
}

From source file:org.cloudcoder.builder2.server.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    String keystoreFilename = options.getKeystoreFilename();
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }/* www  . j  ava2  s .  co m*/

    KeyStore keyStore;
    String keystorePassword = options.getKeystorePassword();
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

From source file:org.cloudcoder.submitsvc.oop.builder.WebappSocketFactory.java

private SSLSocketFactory createSocketFactory() throws IOException, GeneralSecurityException {
    String keyStoreType = "JKS";
    InputStream keyStoreInputStream = this.getClass().getClassLoader().getResourceAsStream(keystoreFilename);
    if (keyStoreInputStream == null) {
        throw new IOException("Could not load keystore " + keystoreFilename);
    }// ww w .j a v  a  2  s.c  om

    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(keyStoreInputStream, keystorePassword.toCharArray());
    } finally {
        IOUtils.closeQuietly(keyStoreInputStream);
    }

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    //trustManagerFactory.init(trustStore);
    // XXX Load the cert (public key) here instead of the private key?
    trustManagerFactory.init(keyStore);

    // TrustManager
    X509TrustManager x509TrustManager = null;
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            x509TrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
    if (x509TrustManager == null) {
        throw new IllegalArgumentException("Cannot find x509TrustManager");
    }

    // KeyManager
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    keyManagerFactory.init(keyStore, keystorePassword.toCharArray());
    X509KeyManager x509KeyManager = null;
    for (KeyManager keyManager : keyManagerFactory.getKeyManagers()) {
        if (keyManager instanceof X509KeyManager) {
            x509KeyManager = (X509KeyManager) keyManager;
            break;
        }
    }
    if (x509KeyManager == null) {
        throw new NullPointerException();
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { x509KeyManager }, new TrustManager[] { x509TrustManager }, null);

    return sslContext.getSocketFactory();
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@After
// Clean up the credentialManagerDirectory we created for testing
public void cleanUp() throws NoSuchAlgorithmException, KeyManagementException, NoSuchProviderException,
        KeyStoreException, UnrecoverableKeyException, CertificateException, IOException {
    //      assertTrue(credentialManagerDirectory.exists());
    //      assertFalse(credentialManagerDirectory.listFiles().length == 0); // something was created there

    if (credentialManagerDirectory.exists()) {
        try {//from   ww w .ja v  a 2s.c  om
            FileUtils.deleteDirectory(credentialManagerDirectory);
            System.out.println(
                    "Deleting Credential Manager's directory: " + credentialManagerDirectory.getAbsolutePath());
        } catch (IOException e) {
            System.out.println(e.getStackTrace());
        }
    }

    // Reset the SSLSocketFactory in JVM so we always have a clean start
    SSLContext sc = null;
    sc = SSLContext.getInstance("SSLv3");

    // Create a "default" JSSE X509KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    kmf.init(ks, "blah".toCharArray());

    // Create a "default" JSSE X509TrustManager.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(null, null);
    tmf.init(ts);

    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    SSLContext.setDefault(sc);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:org.apache.nifi.processors.grpc.ListenGRPC.java

@OnScheduled
public void startServer(final ProcessContext context) throws NoSuchAlgorithmException, IOException,
        KeyStoreException, CertificateException, UnrecoverableKeyException {
    final ComponentLog logger = getLogger();
    // gather configured properties
    final Integer port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final Integer flowControlWindow = context.getProperty(PROP_FLOW_CONTROL_WINDOW).asDataSize(DataUnit.B)
            .intValue();/*from w  ww.  jav a2s . c  o  m*/
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);
    final Pattern authorizedDnPattern = Pattern
            .compile(context.getProperty(PROP_AUTHORIZED_DN_PATTERN).getValue());
    final FlowFileIngestServiceInterceptor callInterceptor = new FlowFileIngestServiceInterceptor(getLogger());
    callInterceptor.enforceDNPattern(authorizedDnPattern);

    final FlowFileIngestService flowFileIngestService = new FlowFileIngestService(getLogger(),
            sessionFactoryReference, context);
    NettyServerBuilder serverBuilder = NettyServerBuilder.forPort(port)
            .addService(ServerInterceptors.intercept(flowFileIngestService, callInterceptor))
            // default (de)compressor registries handle both plaintext and gzip compressed messages
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .flowControlWindow(flowControlWindow).maxMessageSize(maxMessageSize);

    if (useSecure && sslContext != null) {
        // construct key manager
        if (StringUtils.isBlank(sslContextService.getKeyStoreFile())) {
            throw new IllegalStateException(
                    "SSL is enabled, but no keystore has been configured. You must configure a keystore.");
        }

        final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
        final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
        try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
            keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
        }
        keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());

        SslContextBuilder sslContextBuilder = SslContextBuilder.forServer(keyManagerFactory);

        // if the trust store is configured, then client auth is required.
        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder = sslContextBuilder.trustManager(trustManagerFactory);
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.REQUIRE);
        } else {
            sslContextBuilder = sslContextBuilder.clientAuth(ClientAuth.NONE);
        }
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder);
        serverBuilder = serverBuilder.sslContext(sslContextBuilder.build());
    }
    logger.info("Starting gRPC server on port: {}", new Object[] { port.toString() });
    this.server = serverBuilder.build().start();
}

From source file:org.apache.nifi.processors.grpc.InvokeGRPC.java

/**
 * Whenever this processor is triggered, we need to construct a client in order to communicate
 * with the configured gRPC service.//from w  ww.ja  v  a 2 s.c  o m
 *
 * @param context the processor context
 */
@OnScheduled
public void initializeClient(final ProcessContext context) throws Exception {

    channelReference.set(null);
    blockingStubReference.set(null);
    final ComponentLog logger = getLogger();

    final String host = context.getProperty(PROP_SERVICE_HOST).getValue();
    final int port = context.getProperty(PROP_SERVICE_PORT).asInteger();
    final Integer maxMessageSize = context.getProperty(PROP_MAX_MESSAGE_SIZE).asDataSize(DataUnit.B).intValue();
    String userAgent = USER_AGENT_PREFIX;
    try {
        userAgent += "_" + InetAddress.getLocalHost().getHostName();
    } catch (final UnknownHostException e) {
        logger.warn("Unable to determine local hostname. Defaulting gRPC user agent to {}.",
                new Object[] { USER_AGENT_PREFIX }, e);
    }

    final NettyChannelBuilder nettyChannelBuilder = NettyChannelBuilder.forAddress(host, port)
            // supports both gzip and plaintext, but will compress by default.
            .compressorRegistry(CompressorRegistry.getDefaultInstance())
            .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
            .maxInboundMessageSize(maxMessageSize).userAgent(userAgent);

    // configure whether or not we're using secure comms
    final boolean useSecure = context.getProperty(PROP_USE_SECURE).asBoolean();
    final SSLContextService sslContextService = context.getProperty(PROP_SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    final SSLContext sslContext = sslContextService == null ? null
            : sslContextService.createSSLContext(SSLContextService.ClientAuth.NONE);

    if (useSecure && sslContext != null) {
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient();
        if (StringUtils.isNotBlank(sslContextService.getKeyStoreFile())) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore keyStore = KeyStore.getInstance(sslContextService.getKeyStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getKeyStoreFile())) {
                keyStore.load(is, sslContextService.getKeyStorePassword().toCharArray());
            }
            keyManagerFactory.init(keyStore, sslContextService.getKeyStorePassword().toCharArray());
            sslContextBuilder.keyManager(keyManagerFactory);
        }

        if (StringUtils.isNotBlank(sslContextService.getTrustStoreFile())) {
            final TrustManagerFactory trustManagerFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm(), sslContext.getProvider());
            final KeyStore trustStore = KeyStore.getInstance(sslContextService.getTrustStoreType());
            try (final InputStream is = new FileInputStream(sslContextService.getTrustStoreFile())) {
                trustStore.load(is, sslContextService.getTrustStorePassword().toCharArray());
            }
            trustManagerFactory.init(trustStore);
            sslContextBuilder.trustManager(trustManagerFactory);
        }
        nettyChannelBuilder.sslContext(sslContextBuilder.build());

    } else {
        nettyChannelBuilder.usePlaintext(true);
    }

    final ManagedChannel channel = nettyChannelBuilder.build();
    final FlowFileServiceGrpc.FlowFileServiceBlockingStub blockingStub = FlowFileServiceGrpc
            .newBlockingStub(channel);
    channelReference.set(channel);
    blockingStubReference.set(blockingStub);
}

From source file:org.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

/**
 * init sets the criteria for which an SSL connection is made when
 * a TLS channel is started for a profile.  It should only be
 * called once.  For the properties, the initiator is defined as
 * the peer who starts the channel for the TLS profile, the
 * listener is the peer that receives the the channel start
 * request, irregardless of which actually started the session.<p>
 *
 * @param config <code>ProfileConfiguration</code> object that
 * contains key value pairs to initialize the TLS layer.  None of
 * these are mandatory, but if you wish communication to be
 * anonymous with no authentication, (i.e., the listener to not
 * send back a certificate), you must set "Listener Anonymous" to
 * "true" and "Initiator Authentication Required" to "false".
 * The meaningful properties that can be set are these:<p>
 * <table>//w  ww. j av a  2s.c o m
 * <tr>
 * <td>Listener Anonymous</td><td>(true|false) must be set to false if the
 *   listener will not authenticate itself</td>
 * </tr><tr>
 * <td>Initiator Authentication Required</td><td>(true|false) set if the
 *       initiator should send a certificate and the listener expects a
 *       certificate.</td>
 * </tr><tr>
 * <td>Cipher Suite</td><td><i>not yet implemented.</i>the algorithms that
 *       can be used for encryption, authentication, and key exchange.</td>
 * </tr><tr>
 * <td>Key Algorithm</td><td>key management algorithm. See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Provider</td><td>provider of the key management
 *       algorithm.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code> See
 *       {@link com.sun.net.ssl.KeyManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Algorithm</td><td>algorithm to be used by the trust
 *       manager.  See
 *       {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Trust Provider</td><td>provider of the trust manager.  Defaults to
 *    <code>com.sun.net.ssl.internal.ssl.Provider</code>.  See
 *    {@link com.sun.net.ssl.TrustManagerFactory#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Passphrase</td><td>pass phrase used to encrypt the key
 *    store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Data Type</td><td>data type of the key store passed in.
 *     "file" is currently the only value accepted, meaning Key Store
 *     is the name of a file containing keys.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store</td><td>value of the key store, dependent on the type in
 *     Key Store Data Type.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Key Store Format</td><td>format of the keys within the key store.
 *  Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Key Store Provider</td><td>provider for the key stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Passphrase</td><td>pass phrase used to encrypt the trust
 *     store.  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Data Type</td><td>data type of the certificates in the
 * trust store.  "file" is currently th only value accepted,
 * meaning the trust store is a file on the local disk.  See
 *     {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store</td><td>value of the trust store, dependent on the type
 *     in Trust
 *     Store Data Type  See {@link java.security.KeyStore#load}</td>
 * </tr><tr>
 * <td>Trust Store Format</td><td>format of the certificates within the
 *     trust store.
 * Default is "JKS".  See {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Trust Store Provider</td><td>provider for the trust stores.  See
 *     {@link java.security.KeyStore#getInstance}</td>
 * </tr><tr>
 * <td>Allowed SSL Protocols</td><td>Comma separated list of algorithms 
 * that may be used for SSL/TLS negotiations. By default, this will be 
 * whatever the {@link SSLSocket} implementation supports.
 * @see SSLSocket#getSupportedProtocols()
 * @see SSLSocket#setEnabledProtocols(String[])
 * </tr><tr>
 * </table>
 * @throws BEEPException For any error in the profile configuration, a
 * negative response in the form of a BEEP error will be sent back to the
 * requesting peer.  The session will continue to be open and usable, at
 * least from the standpoint of this peer.
 *
 * @see com.sun.net.ssl.KeyManagerFactory
 * @see com.sun.net.ssl.TrustManagerFactory
 * @see java.security.KeyStore
 * @see com.sun.net.ssl.SSLContext
 */
public StartChannelListener init(String uri, ProfileConfiguration config) throws BEEPException {
    KeyManagerFactory kmf = null;
    KeyManager[] km = null;
    KeyStore ks = null;
    TrustManagerFactory tmf = null;
    TrustManager[] tm = null;
    KeyStore ts = null;
    SSLContext ctx;
    this.sslProtocols = null;

    // set the URI of this instance of the profile
    this.uri = uri;

    try {

        // create an SSL context object
        ctx = SSLContext.getInstance("TLS");
    } catch (java.security.NoSuchAlgorithmException e) {
        throw new BEEPException("TLS Algorithm Not Found. Probable " + "cause is the JSSE provider has not "
                + "been added to the java.security file.");
    }

    try {
        String protocols = config.getProperty(PROPERTY_SSL_PROTOCOLS);
        if (protocols != null) {
            this.sslProtocols = protocols.split(",");
        }
        // initialize the key managers, trust managers, and
        keyAlgorithm = config.getProperty(PROPERTY_KEY_MANAGER_ALGORITHM);
        keyProvider = config.getProperty(PROPERTY_KEY_MANAGER_PROVIDER);
        trustAlgorithm = config.getProperty(PROPERTY_TRUST_MANAGER_ALGORITHM);
        trustProvider = config.getProperty(PROPERTY_TRUST_MANAGER_PROVIDER);
        keyPassphrase = config.getProperty(PROPERTY_KEYSTORE_PASSPHRASE);
        keyStoreType = config.getProperty(PROPERTY_KEYSTORE_TYPE);
        keyStoreName = config.getProperty(PROPERTY_KEYSTORE_NAME);
        keyStoreFormat = config.getProperty(PROPERTY_KEYSTORE_FORMAT, "JKS");
        keyStoreProvider = config.getProperty(PROPERTY_KEYSTORE_PROVIDER);
        trustPassphrase = config.getProperty(PROPERTY_TRUSTSTORE_PASSPHRASE);
        trustStoreType = config.getProperty(PROPERTY_TRUSTSTORE_TYPE);
        trustStoreName = config.getProperty(PROPERTY_TRUSTSTORE_NAME);
        trustStoreFormat = config.getProperty(PROPERTY_TRUSTSTORE_FORMAT, "JKS");
        trustStoreProvider = config.getProperty(PROPERTY_TRUSTSTORE_PROVIDER);

        // determine if the client must authenticate or if the server can
        // 
        needClientAuth = new Boolean(config.getProperty(PROPERTY_CLIENT_AUTHENTICATION, "false"))
                .booleanValue();
        serverAnonymous = new Boolean(config.getProperty(PROPERTY_SERVER_ANONYMOUS, "true")).booleanValue();

        if (keyAlgorithm != null) {
            if (keyProvider != null) {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm, keyProvider);
            } else {
                kmf = KeyManagerFactory.getInstance(keyAlgorithm);
            }

            // add support for a default type of key manager factory?
            if (keyStoreProvider != null) {
                ks = KeyStore.getInstance(keyStoreFormat, keyStoreProvider);
            } else {
                ks = KeyStore.getInstance(keyStoreFormat);
            }

            if (keyStoreType.equals("file")) {
                ks.load(new FileInputStream(keyStoreName), keyPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_KEY_STORE);
            }

            // initialize the key factory manager 
            kmf.init(ks, keyPassphrase.toCharArray());

            km = kmf.getKeyManagers();
        } else {
            km = null;
        }

        if (trustAlgorithm != null) {
            if (trustProvider != null) {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm, trustProvider);
            } else {
                tmf = TrustManagerFactory.getInstance(trustAlgorithm);
            }

            // add support for a default type of trust manager factory?
            if (trustStoreProvider != null) {
                ts = KeyStore.getInstance(trustStoreFormat, trustStoreProvider);
            } else {
                ts = KeyStore.getInstance(trustStoreFormat);
            }

            if (trustStoreType.equals("file")) {
                ts.load(new FileInputStream(trustStoreName), trustPassphrase.toCharArray());
            } else {
                throw new BEEPException(ERR_ILLEGAL_TRUST_STORE);
            }

            // initialize the trust factory manager 
            tmf.init(ts);

            tm = tmf.getTrustManagers();
        } else {
            tm = null;
        }

        // create a socket factory from the key factories and
        // trust factories created for the algorithms and stores
        // specfied.  No option is given to change the secure
        // random number generator
        ctx.init(km, tm, null);

        socketFactory = ctx.getSocketFactory();

        return this;
    } catch (Exception e) {
        log.error(e);

        throw new BEEPException(e);
    }
}

From source file:org.apache.ambari.view.hive.client.Connection.java

SSLSocketFactory getTwoWaySSLSocketFactory() throws SQLException {
    SSLSocketFactory socketFactory = null;

    try {//from   w w w .ja v  a 2s  . c om
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
                Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING,
                Utils.HiveAuthenticationParams.SUNJSSE_ALGORITHM_STRING);
        String keyStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE);
        String keyStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_KEY_STORE_PASSWORD);
        KeyStore sslKeyStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_KEY_STORE_TYPE);

        if (keyStorePath == null || keyStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_KEY_STORE
                    + " Not configured for 2 way SSL connection, keyStorePath param is empty");
        }
        try (FileInputStream fis = new FileInputStream(keyStorePath)) {
            sslKeyStore.load(fis, keyStorePassword.toCharArray());
        }
        keyManagerFactory.init(sslKeyStore, keyStorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(Utils.HiveAuthenticationParams.SUNX509_ALGORITHM_STRING);
        String trustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE);
        String trustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD);
        KeyStore sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE);

        if (trustStorePath == null || trustStorePath.isEmpty()) {
            throw new IllegalArgumentException(Utils.HiveAuthenticationParams.SSL_TRUST_STORE
                    + " Not configured for 2 way SSL connection");
        }
        try (FileInputStream fis = new FileInputStream(trustStorePath)) {
            sslTrustStore.load(fis, trustStorePassword.toCharArray());
        }
        trustManagerFactory.init(sslTrustStore);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
        socketFactory = new SSLSocketFactory(context);
    } catch (Exception e) {
        throw new SQLException("Error while initializing 2 way ssl socket factory ", e);
    }
    return socketFactory;
}