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:com.microsoft.exchange.impl.ExchangeWebServicesClient.java

/**
 * /* ww  w  . j ava 2s.  co  m*/
 * @param resource
 * @param password
 * @return
 */
protected static KeyStore getKeystoreFromResource(Resource resource, char[] password) {
    try {
        KeyStore k = KeyStore.getInstance(KeyStore.getDefaultType());
        k.load(resource.getInputStream(), password);
        return k;
    } catch (KeyStoreException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (CertificateException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (IOException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("failed to load keystore from " + resource.getDescription(), e);
    }

}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGetForSAMLSSO(String url, String user, String password, int returnCodeIDP,
        int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*from   ww w. ja  v a2 s.co m*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Load a KeyStore from a file accessed by a password.
 *
 * @param keyStoreFile//w w  w  . j  av  a 2  s . c om
 *            File to load KeyStore from
 * @param password
 *            Password of the KeyStore
 * @param keyStoreType
 *            The type of the KeyStore to open
 * @return The KeyStore
 * @throws KeyStoreLoadException
 *             Problem encountered loading the KeyStore as the specified
 *             type
 * @throws CryptoException
 *             Problem encountered loading the KeyStore
 * @throws FileNotFoundException
 *             If the KeyStore file does not exist, is a directory rather
 *             than a regular file, or for some other reason cannot be
 *             opened for reading
 */
public static KeyStore load(File keyStoreFile, Password password, KeyStoreType keyStoreType)
        throws CryptoException, FileNotFoundException {
    if (!keyStoreType.isFileBased()) {
        throw new CryptoException(MessageFormat.format(res.getString("NoLoadKeyStoreNotFile.exception.message"),
                keyStoreType.jce()));
    }

    FileInputStream fis = new FileInputStream(keyStoreFile);

    KeyStore keyStore = getKeyStoreInstance(keyStoreType);

    try {
        keyStore.load(fis, password.toCharArray());
    } catch (CertificateException ex) {
        throw new KeyStoreLoadException(
                MessageFormat.format(res.getString("NoLoadKeyStoreType.exception.message"), keyStoreType), ex,
                keyStoreType);
    } catch (NoSuchAlgorithmException ex) {
        throw new KeyStoreLoadException(
                MessageFormat.format(res.getString("NoLoadKeyStoreType.exception.message"), keyStoreType), ex,
                keyStoreType);
    } catch (FileNotFoundException ex) {
        throw ex;
    } catch (IOException ex) {
        throw new KeyStoreLoadException(
                MessageFormat.format(res.getString("NoLoadKeyStoreType.exception.message"), keyStoreType), ex,
                keyStoreType);
    } finally {
        IOUtils.closeQuietly(fis);
    }

    return keyStore;
}

From source file:net.sf.keystore_explorer.crypto.keystore.KeyStoreUtil.java

/**
 * Copy a KeyStore./*  w  ww  .  ja  va2  s. c o m*/
 *
 * @param keyStore
 *            KeyStore to copy
 * @return Copy
 * @throws CryptoException
 *             Problem encountered copying the KeyStore
 */
public static KeyStore copy(KeyStore keyStore) throws CryptoException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    try {
        char[] emptyPassword = {};

        keyStore.store(baos, emptyPassword);

        KeyStore theCopy = KeyStoreUtil.create(KeyStoreType.resolveJce(keyStore.getType()));
        theCopy.load(new ByteArrayInputStream(baos.toByteArray()), emptyPassword);

        return theCopy;
    } catch (CryptoException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (IllegalStateException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    } catch (IOException ex) {
        throw new CryptoException(res.getString("NoCopyKeyStore.exception.message"), ex);
    }
}

From source file:com.micromux.cassandra.jdbc.CassandraConnection.java

private static SSLContext getSSLContext(String trustPath, String trustPass)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {

    FileInputStream tsf = null;//from  ww  w  .  j  a v a  2s  .com
    SSLContext ctx = null;

    try {

        tsf = new FileInputStream(trustPath);
        ctx = SSLContext.getInstance("SSL");

        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(tsf, trustPass.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);

        ctx.init(null, tmf.getTrustManagers(), new SecureRandom());

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (tsf != null) {
            try {
                tsf.close();
            } catch (IOException ix) {
                logger.warn("Error Closing Trust Store: " + trustPath, ix);
            }
        }

    }

    return ctx;

}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 *///from  ww w . j ava 2s . c  om
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    CredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope("localhost", idpPort),
            new UsernamePasswordCredentials(user, password));

    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
    try {
        trustStore.load(instream, "clientpass".toCharArray());
    } finally {
        try {
            instream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
    sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

    SSLContext sslContext = sslContextBuilder.build();
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
    httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

    httpClient = httpClientBuilder.build();

    HttpGet httpget = new HttpGet(url);

    HttpResponse response = httpClient.execute(httpget);
    HttpEntity entity = response.getEntity();

    Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

    if (response.getStatusLine().getStatusCode() != 200) {
        return null;
    }

    //            Redirect to a POST is not supported without user interaction
    //            http://www.ietf.org/rfc/rfc2616.txt
    //            If the 301 status code is received in response to a request other
    //            than GET or HEAD, the user agent MUST NOT automatically redirect the
    //            request unless it can be confirmed by the user, since this might
    //            change the conditions under which the request was issued.

    Source source = new Source(EntityUtils.toString(entity));
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    FormFields formFields = source.getFormFields();

    List<Element> forms = source.getAllElements(HTMLElementName.FORM);
    Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
    String postUrl = forms.get(0).getAttributeValue("action");

    Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
    Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

    for (FormField formField : formFields) {
        if (formField.getUserValueCount() != 0) {
            nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
        }
    }
    HttpPost httppost = new HttpPost(postUrl);
    httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

    response = httpClient.execute(httppost);

    entity = response.getEntity();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:mitm.common.tools.PfxTool.java

private static KeyStore loadKeyStore(String keyFile, boolean shouldExist, String password) throws Exception {
    File file = new File(keyFile);

    file = file.getAbsoluteFile();// ww  w. j  av a  2  s  .  co m

    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    if (shouldExist && !file.exists()) {
        throw new FileNotFoundException(keyFile + " pfx file not found.");
    }

    /* initialize key store */
    char[] pw = password != null ? password.toCharArray() : null;

    if (file.exists()) {
        InputStream input = new FileInputStream(file);
        keyStore.load(input, pw);
        input.close();
    } else {
        // creates an empty keystore
        keyStore.load(null, pw);
    }

    return keyStore;
}

From source file:net.lamp.support.HttpManager.java

private static HttpClient getNewHttpClient() {
    try {/*from w  w  w .  ja  va 2 s  .c  o  m*/
        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();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        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);

        HttpConnectionParams.setConnectionTimeout(params, SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        // if (NetState.Mobile == NetStateManager.CUR_NETSTATE) {
        // // ??APN?            // HttpHost proxy = NetStateManager.getAPN();
        // if (null != proxy) {
        // client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY,
        // proxy);
        // }
        // }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:de.uni_koblenz_landau.apow.helper.SyncHelper.java

/**
 * Creates a HTTPClient for usage with self signed SSL certificates.
 * //from www .  j  a  v  a2s. co  m
 * Sources:
 * http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
 * http://havrl.blogspot.de/2013/08/synchronization-algorithm-for.html 
 * 
 * @return HTTPClient
 */
private static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SelfSignedSSLSocketFactory(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:com.zrlh.llkc.funciton.Http_Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {// w  ww  .  j ava 2  s  .c o  m
        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);
        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Http_Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Http_Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}