Example usage for java.security KeyStore load

List of usage examples for java.security KeyStore load

Introduction

In this page you can find the example usage for java.security KeyStore load.

Prototype

public final void load(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException 

Source Link

Document

Loads this KeyStore from the given input stream.

Usage

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair load(File keyStoreFile) {
    if (keyStoreFile != null) {
        try {/*from   w  w  w.ja va2  s  .c o  m*/
            KeyStore ks = KeyStore.getInstance("JKS", "SUN");
            if (keyStoreFile.exists()) {
                FileInputStream stream = new FileInputStream(keyStoreFile);
                ks.load(stream, SECRET);
                IOUtils.closeQuietly(stream);

                PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
                if (privateKey == null)
                    return null;
                PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
                return new KeyPair(publicKey, privateKey);
            }
        } catch (Throwable th) {
            logger.error("Failed to initialize key store");
            throw new OpenFlameRuntimeException(th.getMessage(), th);
        }
    } else {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }
    return null;
}

From source file:monasca.common.middleware.HttpClientPoolFactory.java

private static KeyStore loadKeystore(String type, String keyStore, String keyPass) throws Exception {
    final KeyStore ks = KeyStore.getInstance("jks");
    if ((keyStore != null) && !keyStore.isEmpty()) {
        File keystoreFile = new File(keyStore);
        if (!keystoreFile.canRead()) {
            throw new FileNotFoundException(String.format("%s '%s' is not readable", type, keyStore));
        }//from  w  ww.ja  v  a2s  .  co m
        try (FileInputStream is1 = new FileInputStream(keystoreFile)) {
            ks.load(is1, keyPass.toCharArray());
        } catch (Exception e) {
            String errorMessage = String.format("Unable to open %s '%s': %s", type, keyStore, e.getMessage());
            logger.error(errorMessage);
            throw new Exception(errorMessage, e);
        }
    } else {
        ks.load(null, null);
    }
    return ks;
}

From source file:org.wso2.cdm.agent.proxy.ServerApiAccess.java

public static HttpClient getCertifiedHttpClient() {
    try {/*  www.ja  v  a 2 s .c  o  m*/
        HttpClient client = null;
        if (CommonUtilities.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            InputStream in = IdentityProxy.getInstance().getContext().getResources()
                    .openRawResource(R.raw.emm_truststore);
            localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(cm, params);

        } else {
            client = new DefaultHttpClient();
        }
        return client;
    } catch (Exception e) {
        Log.d(TAG, e.toString());
        return null;
    }
}

From source file:eu.trentorise.smartcampus.network.RemoteConnector.java

private static HttpClient getAcceptAllHttpClient(HttpParams inParams) {
    HttpClient client = null;/* w  w w  .  j a  va 2s  .co  m*/

    HttpParams params = inParams != null ? inParams : new BasicHttpParams();

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

        // IMPORTANT: use CustolSSLSocketFactory for 2.2
        SSLSocketFactory sslSocketFactory = new CustomSSLSocketFactory(trustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        client = new DefaultHttpClient(params);
    }

    return client;
}

From source file:net.di2e.ecdr.source.rest.TLSUtil.java

public static void setTLSOptions(WebClient client, boolean disableCNCheck) {
    ClientConfiguration clientConfiguration = WebClient.getConfig(client);

    HTTPConduit httpConduit = clientConfiguration.getHttpConduit();

    String keyStorePath = System.getProperty(SSL_KEYSTORE_JAVA_PROPERTY);
    String keyStorePassword = System.getProperty(SSL_KEYSTORE_PASSWORD_JAVA_PROPERTY);
    if (StringUtils.isNotBlank(keyStorePath) && StringUtils.isNotBlank(keyStorePassword)) {
        try {/*w  w w  .  j a va  2s.  c om*/
            TLSClientParameters tlsParams = new TLSClientParameters();
            LOGGER.debug("Setting disable of CN check on client URL {} to [{}]", client.getCurrentURI(),
                    disableCNCheck);
            tlsParams.setDisableCNCheck(disableCNCheck);

            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            // add the keystore if it exists
            File keystore = new File(keyStorePath);
            if (keystore.exists() && keyStorePassword != null) {
                FileInputStream fis = new FileInputStream(keystore);
                try {
                    LOGGER.debug("Loading keyStore {}", keystore);
                    keyStore.load(fis, keyStorePassword.toCharArray());
                } catch (IOException e) {
                    LOGGER.error("Unable to load keystore. {}", keystore, e);
                } catch (CertificateException e) {
                    LOGGER.error("Unable to load certificates from keystore. {}", keystore, e);
                } finally {
                    IOUtils.closeQuietly(fis);
                }
                KeyManagerFactory keyFactory = KeyManagerFactory
                        .getInstance(KeyManagerFactory.getDefaultAlgorithm());
                keyFactory.init(keyStore, keyStorePassword.toCharArray());
                KeyManager[] km = keyFactory.getKeyManagers();
                tlsParams.setKeyManagers(km);
            }

            httpConduit.setTlsClientParameters(tlsParams);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read keystore: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to locate one of the SSL stores: {} | {}", keyStorePath, e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read keystore: ", e);
        }
    }
}

From source file:org.jboss.as.test.integration.logging.handlers.SocketHandlerTestCase.java

private static KeyStore loadKeyStore() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    return ks;//from   w  ww.  j a  va  2  s . c  o m
}

From source file:gov.va.med.imaging.proxy.ssl.AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null)
        throw new IllegalArgumentException("Keystore url may not be null");

    Logger.getLogger(AuthSSLProtocolSocketFactory.class).debug("Initializing key store");
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;/*  w  w  w.  ja v a 2s  . c  o  m*/
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:com.cloudhopper.httpclient.util.SchemeFactory.java

static public Scheme createHttpsScheme(File keystoreFile, String keystorePassword, File truststoreFile,
        String truststorePassword) throws NoSuchAlgorithmException, KeyStoreException, FileNotFoundException,
        IOException, KeyManagementException, CertificateException, UnrecoverableKeyException {

    if (keystoreFile == null && truststoreFile == null) {
        // To insure we don't break anything, if keystore and trust store is not specified, 
        // call the legacy createHttpsScheme.
        return createHttpsScheme();
    } else {/*from   ww  w  . java2 s .  c om*/
        // Configure https scheme with a keystore to authenticate ourselves to the server
        // and/or a truststore to verify the server's certificate.
        KeyStore keystore = null;
        if (keystoreFile != null) {
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(keystoreFile);
            try {
                // A null password is valid when the keystore does not have a password.
                if (keystorePassword != null) {
                    keystore.load(instream, keystorePassword.toCharArray());
                } else {
                    keystore.load(instream, null);
                }
            } finally {
                instream.close();
            }

        }
        KeyStore truststore = null;
        if (truststoreFile != null) {
            truststore = KeyStore.getInstance(KeyStore.getDefaultType());
            FileInputStream instream = new FileInputStream(truststoreFile);
            try {
                // A null password is valid when the keystore does not have a password.
                if (truststorePassword != null) {
                    truststore.load(instream, truststorePassword.toCharArray());
                } else {
                    truststore.load(instream, null);
                }
            } finally {
                instream.close();
            }
        }
        // Not sure if identifing which params were passed in as null and calling the 
        // appropriate constructor is necessary, because the Apache Docs don't describe
        // what happens when we pass in null. Play it conservative rather than test the
        // behavior. 
        SSLSocketFactory socketFactory;
        if (keystore != null && truststore != null) {
            socketFactory = new SSLSocketFactory(keystore, keystorePassword, truststore);
        } else if (keystore != null) {
            socketFactory = new SSLSocketFactory(keystore, keystorePassword);
        } else {
            socketFactory = new SSLSocketFactory(truststore);
        }
        return new Scheme("https", socketFactory, 443);
    }
}

From source file:com.bright.json.JSonRequestor.java

private static HttpClient getNewHttpClient() {
    try {/* ww  w  .j  a v  a 2  s. c  o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.jms.notify.utils.httpclient.SimpleHttpUtils.java

public static TrustKeyStore loadTrustKeyStore(InputStream keyStoreStream, String keyStorePass) {
    try {/*ww w.  j a v a  2  s  .  c  o  m*/
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(keyStoreStream, keyStorePass.toCharArray());
        tmf.init(ks);
        return new TrustKeyStore(tmf);
    } catch (Exception e) {
        logger.error("loadTrustCertFactory fail : " + e.getMessage(), e);
        return null;
    }
}