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:it.cnr.icar.eric.common.security.KeystoreMover.java

public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword,
        String sourceAlias, String sourceKeyPassword, String destinationKeystoreType,
        String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias,
        String destinationKeyPassword) throws Exception {

    char[] sourceKeystorePasswordArr = null;
    if (sourceKeystorePassword != null) {
        sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray();
    }/*ww w .  j ava 2s.  co  m*/

    char[] sourceKeyPasswordArr = sourceKeystorePasswordArr;
    if (sourceKeyPassword != null) {
        sourceKeyPasswordArr = sourceKeyPassword.toCharArray();
    }

    char[] destinationKeystorePasswordArr = null;
    if (destinationKeystorePassword != null) {
        destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray();
    }

    char[] destinationKeyPasswordArr = destinationKeystorePasswordArr;
    if (destinationKeyPassword != null) {
        destinationKeyPasswordArr = destinationKeyPassword.toCharArray();
    }

    FileInputStream in;

    // --------  Load source keystore to memory ---------
    in = new FileInputStream(sourceKeystorePath);
    KeyStore ksin = KeyStore.getInstance(sourceKeystoreType);

    ksin.load(in, sourceKeystorePasswordArr);
    in.close();

    // --------  Load destination keystore initial contents to memory ---------
    KeyStore ksout = KeyStore.getInstance(destinationKeystoreType);

    try {
        in = new FileInputStream(destinationKeystorePath);
        ksout.load(in, destinationKeystorePasswordArr);
    } catch (java.io.FileNotFoundException e) {
        ksout.load(null, destinationKeystorePasswordArr);
    } finally {
        in.close();
    }

    Enumeration<String> en = ksin.aliases();
    while (en.hasMoreElements()) {
        String alias = en.nextElement();

        if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) {

            if (ksout.containsAlias(alias)) {
                log.info(CommonResourceBundle.getInstance().getString(
                        "message.destinationKeystorePathAlreadyContains",
                        new Object[] { destinationKeystorePath, alias }));
                continue;
            }

            //Use existing alias if no destinationAlias specified
            if (destinationAlias == null) {
                destinationAlias = alias;
            }

            if (ksin.isCertificateEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate",
                        new Object[] { alias }));
                ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias));
            }

            if (ksin.isKeyEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingKey",
                        new Object[] { alias }));
                Certificate[] certChain = ksin.getCertificateChain(alias);
                ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr),
                        destinationKeyPasswordArr, certChain);
            }
        }

    }

    //---------  Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores--------------
    FileOutputStream out = new FileOutputStream(destinationKeystorePath);
    ksout.store(out, destinationKeystorePasswordArr);
    out.close();
    log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful"));
}

From source file:projekat.rest_client.RestTemplateFactory.java

@Override
public void afterPropertiesSet() {

    fillTypesForRestService();//from   w  w  w.  ja v  a  2  s  .c  o  m
    //za potrebe testirnja
    if (rest_keystore == null || "".equals(rest_keystore)) {
        rest_keystore = "/etc/keystores/nst2.jks";
        rest_keystore_password = "changeit";
        res_host_port = "8443";
        rest_hostname = "localhost";
    }
    InputStream keyStoreInputStream = null;
    try {
        keyStoreInputStream = new FileInputStream(rest_keystore);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("");
        }
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        try {
            trustStore.load(keyStoreInputStream, rest_keystore_password.toCharArray());
        } finally {
            keyStoreInputStream.close();
        }
        SSLContext sslcontext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // Allow TLSv1 protocol only
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        auth = new HttpComponentsClientHttpRequestFactoryBasicAuth(
                new HttpHost(rest_hostname, Integer.parseInt(res_host_port), "https"), httpClient);
        auth.setConnectTimeout(60000);
        auth.setReadTimeout(180000);
        restTemplate = new RestTemplate(auth);
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException
            | KeyManagementException ex) {
        Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            keyStoreInputStream.close();
        } catch (Exception ex) {
            Logger.getLogger(RestTemplateFactory.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:io.fabric8.elasticsearch.RequestRunner.java

protected final OkHttpClient getHttpClient() throws Exception {
    File ksFile = new File(keyStore);
    KeyStore trusted = KeyStore.getInstance("JKS");
    FileInputStream in = new FileInputStream(ksFile);
    trusted.load(in, password.toCharArray());
    in.close();//  ww w .j av a2 s.c om
    SSLContext sslContext = SSLContext.getInstance("TLS");
    TrustManagerFactory trustManagerFactory = InsecureTrustManagerFactory.INSTANCE;
    X509TrustManager trustManager = (X509TrustManager) trustManagerFactory.getTrustManagers()[0];
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    OkHttpClient client = new okhttp3.OkHttpClient.Builder()
            .sslSocketFactory(sslContext.getSocketFactory(), trustManager).readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES).build();
    return client;
}

From source file:com.bt.pi.api.http.SimpleHttpsServerFactoryBean.java

protected HttpServer getInitializedServer(InetSocketAddress address) throws IOException {
    HttpsServer server = HttpsServer.create(address, getBacklog());
    try {/*w  w  w.  j a v a 2 s  .c om*/
        SSLContext sslContext = SSLContext.getInstance(sslContextProtocol);

        KeyStore ks = KeyStore.getInstance(keyStoreType);
        InputStream is = keyStoreLocation.getInputStream();
        try {
            ks.load(is, password);
        } catch (EOFException e) {
            LOG.warn(String.format(
                    "Unable to load certificate store %s. This may be possible because https isn't enabled with a valid certificate",
                    keyStoreLocation));
            return null;
        }

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
        kmf.init(ks, password);

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
        tmf.init(ks);

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

        final SSLEngine m_engine = sslContext.createSSLEngine();

        server.setHttpsConfigurator(new HttpsConfigurator(sslContext) {
            public void configure(HttpsParameters params) {
                params.setSSLParameters(getSSLContext().getDefaultSSLParameters());
                params.setNeedClientAuth(false);
                params.setWantClientAuth(false);
                params.setCipherSuites(m_engine.getEnabledCipherSuites());
                params.setProtocols(m_engine.getEnabledProtocols());
            }
        });
    } catch (Throwable e) {
        throw new IOException("initializing HttpsServer failed due to exception", e);
    }
    return server;
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java

public HttpClient getNewHttpClient() {
    try {//  w ww .  j a  v a  2s .  c  om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.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:org.wso2.emm.agent.proxy.clients.OAuthSSLClient.java

@Override
public HttpClient getHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;//  ww w  .j  av a2 s .com
    InputStream inStream = null;
    try {
        if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            inStream = IdentityProxy.getInstance().getContext().getResources().openRawResource(R.raw.trust);
            localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schemeRegistry);

            client = new DefaultHttpClient(connectionManager, params);

        } else {
            client = new DefaultHttpClient();
        }

    } catch (KeyStoreException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "Error occurred while loading certificate.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
        String errorMsg = "Error occurred while accessing keystore.";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Error occurred while loading trust store. ";
        Log.e(TAG, errorMsg);
        throw new IDPTokenManagerException(errorMsg, e);
    } finally {
        StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;//from   w  w  w.j  a  va 2  s  .  c  om
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints.
 *
 * @throws IOException/*from   w  w  w .  j  a  v  a2s. c om*/
 *             if there are any issues with the keystore processing.
 */
private synchronized void getKeyStoreInfo() throws IOException {
    try {
        // load up the keystore..
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        signingKeystore.load(is, keyStorePW.toCharArray());

        // grab the key we'll use to sign
        signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray());

    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException(e);
    }

}

From source file:com.cloudant.client.org.lightcouch.CouchDbClientAndroid.java

private SchemeRegistry createRegistry(CouchDbProperties properties)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException {
    SchemeRegistry registry = new SchemeRegistry();
    if ("https".equals(properties.getProtocol())) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme(properties.getProtocol(), sf, properties.getPort()));
    } else {/*from w  ww  .ja  v a  2 s  . co  m*/
        registry.register(new Scheme(properties.getProtocol(), PlainSocketFactory.getSocketFactory(),
                properties.getPort()));
    }
    return registry;
}

From source file:com.lhtechnologies.DoorApp.AuthenticatorService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (intent.getAction().equals(stopAction)) {
        stopSelf();//  w  ww  . j av a 2  s.  c  om
    } else if (intent.getAction().equals(authenticateAction)) {
        //Check if we want to open the front door or flat door
        String doorToOpen = FrontDoor;
        String authCode = null;
        if (intent.hasExtra(FlatDoor)) {
            doorToOpen = FlatDoor;
            authCode = intent.getCharSequenceExtra(FlatDoor).toString();
        }

        if (intent.hasExtra(LetIn)) {
            doorToOpen = LetIn;
        }

        //Now run the connection code (Hope it runs asynchronously and we do not need AsyncTask --- NOPE --YES
        urlConnection = null;
        URL url;

        //Prepare the return intent
        Intent broadcastIntent = new Intent(AuthenticationFinishedBroadCast);

        try {
            //Try to create the URL, return an error if it fails
            url = new URL(address);

            if (!url.getProtocol().equals("https")) {
                throw new MalformedURLException("Please only use https protocol!");
            }

            String password = "password";
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(getResources().getAssets().open("LH Technologies Root CA.bks"),
                    password.toCharArray());

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
            tmf.init(keyStore);

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, tmf.getTrustManagers(), null);

            urlConnection = (HttpsURLConnection) url.openConnection();
            urlConnection.setSSLSocketFactory(context.getSocketFactory());
            urlConnection.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
            urlConnection.setConnectTimeout(15000);
            urlConnection.setRequestMethod("POST");

            urlConnection.setDoOutput(true);
            urlConnection.setChunkedStreamingMode(0);

            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream());

            //Write our stuff to the output stream;
            out.write("deviceName=" + deviceName + "&udid=" + udid + "&secret=" + secret + "&clientVersion="
                    + clientVersion + "&doorToOpen=" + doorToOpen);
            if (doorToOpen.equals(FlatDoor)) {
                out.write("&authCode=" + authCode);
                //Put an extra in so the return knows we opened the flat door
                broadcastIntent.putExtra(FlatDoor, FlatDoor);
            }

            out.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));

            //Read the answer
            String decodedString;
            String returnString = "";
            while ((decodedString = in.readLine()) != null) {
                returnString += decodedString;
            }
            in.close();

            broadcastIntent.putExtra(AuthenticatorReturnCode, returnString);

        } catch (MalformedURLException e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorMalformedURL);
        } catch (Exception e) {
            broadcastIntent.putExtra(AuthenticatorReturnCode, ClientErrorUndefined);
            broadcastIntent.putExtra(AuthenticatorErrorDescription, e.getLocalizedMessage());
        } finally {
            if (urlConnection != null)
                urlConnection.disconnect();
            //Now send a broadcast with the result
            sendOrderedBroadcast(broadcastIntent, null);
            Log.e(this.getClass().getSimpleName(), "Send Broadcast!");
        }
    }

}