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.paolorendano.clm.AbstractCassandraDAO.java

/**
 * Gets the SSL context.//from  w w w .  j a  v a 2  s  .co m
 *
 * @param truststorePath the truststore path
 * @param truststorePassword the truststore password
 * @param keystorePath the keystore path
 * @param keystorePassword the keystore password
 * @return the SSL context
 * @throws NoSuchAlgorithmException the no such algorithm exception
 * @throws KeyStoreException the key store exception
 * @throws CertificateException the certificate exception
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws UnrecoverableKeyException the unrecoverable key exception
 * @throws KeyManagementException the key management exception
 */
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath,
        String keystorePassword) throws NoSuchAlgorithmException, KeyStoreException, CertificateException,
        IOException, UnrecoverableKeyException, KeyManagementException {
    /* taken from http://www.datastax.com/dev/blog/accessing-secure-dse-clusters-with-cql-native-protocol */

    FileInputStream tsf = new FileInputStream(truststorePath);
    FileInputStream ksf = new FileInputStream(keystorePath);
    SSLContext ctx = SSLContext.getInstance("SSL");

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

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(ksf, keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());

    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return ctx;
}

From source file:org.kontalk.client.KontalkConnection.java

@SuppressLint("AllowAllHostnameVerifier")
private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct,
        PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) {
    try {/*from  w  w  w . j av  a2s  .co  m*/
        SSLContext ctx = SSLContext.getInstance("TLS");

        KeyManager[] km = null;
        if (privateKey != null && bridgeCert != null) {
            // in-memory keystore
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(null, null);
            keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert });

            // key managers
            KeyManagerFactory kmFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmFactory.init(keystore, null);

            km = kmFactory.getKeyManagers();

            // disable PLAIN mechanism if not upgrading from legacy
            if (!LegacyAuthentication.isUpgrading()) {
                // blacklist PLAIN mechanism
                SASLAuthentication.blacklistSASLMechanism("PLAIN");
            }
        }

        // trust managers
        TrustManager[] tm;

        if (acceptAnyCertificate) {
            tm = new TrustManager[] { new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @SuppressLint("TrustAllX509TrustManager")
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            } };
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
        }

        else {
            // builtin keystore
            TrustManagerFactory tmFactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmFactory.init(trustStore);

            tm = tmFactory.getTrustManagers();
        }

        ctx.init(km, tm, null);
        builder.setCustomSSLContext(ctx);
        if (direct)
            builder.setSocketFactory(ctx.getSocketFactory());

        // SASL EXTERNAL is already enabled in Smack
    } catch (Exception e) {
        Log.w(TAG, "unable to setup SSL connection", e);
    }
}

From source file:mitm.test.TestUtils.java

public static KeyStore loadKeyStore(File file, String password) throws KeyStoreException {
    try {//from   www.  jav  a2s  .c om
        KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

        // initialize key store
        keyStore.load(new FileInputStream(file), password.toCharArray());

        return keyStore;
    } catch (NoSuchProviderException e) {
        throw new KeyStoreException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        throw new KeyStoreException(e);
    } catch (FileNotFoundException e) {
        throw new KeyStoreException(e);
    } catch (IOException e) {
        throw new KeyStoreException(e);
    }
}

From source file:com.huotu.mallduobao.common.thirdparty.ClientCustomSSL.java

public static String doRefund(String url, String data, String celPath, String celPassword) throws Exception {
    /**// w ww  .  j  a v  a2 s. co  m
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(celPath));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, celPassword.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, celPassword.toCharArray())//?
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:learn.encryption.ssl.SSLContext_Https.java

/**
 * @description javaSSLContext//from   w w w  .j a  va2 s.c  om
 * @description https?, SSLContext (NoHttp?SecureRandombug)
 * @description client.ks?server
 * @description ??
 * @description ????getSSLContext2()
 */
//@SuppressLint("TrulyRandom")
public static SSLContext getSSLContext() {
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        // ??, ??assets
        InputStream inputStream = new FileInputStream(new File("D:\\tomcatcert\\server.ks"));
        //App.getInstance().getAssets().open("srca.cer");

        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");

        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(inputStream, "123456".toCharArray());
        //Certificate cer = cerFactory.generateCertificate(inputStream);
        Certificate cer = keyStore.getCertificate("clientKey");
        keyStore.setCertificateEntry("trust", cer);

        // KeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "123456".toCharArray());

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        // ?SSLContext
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

@SuppressWarnings("unused")
private static void loadWindowsCert() throws Exception {
    KeyStore ks = KeyStore.getInstance("Windows-MY");// "Windows-ROOT"
    ks.load(null, null);
    Enumeration<String> en = ks.aliases();
    while (en.hasMoreElements()) {
        String key = en.nextElement();
        Certificate[] certs = ks.getCertificateChain(key);
        X509Certificate cert = (X509Certificate) certs[0];
    }/*from   w ww . jav  a2  s  . c  o m*/
}

From source file:com.simple.weixin.refund.ClientCustomSSL.java

public static String doRefund(String password, String keyStrore, String url, String data) throws Exception {
    /**/*from   w  w w. j  av  a  2 s  .c o  m*/
     * ?PKCS12? ?-- API 
     */

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(new File(keyStrore));//P12
    try {
        /**
         * ?
         * */
        keyStore.load(instream, password.toCharArray());//?..MCHID
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    /**
    * ?
    * */
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, password.toCharArray())//?  
            .build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {
        HttpPost httpost = new HttpPost(url); // ??
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();

            String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
            EntityUtils.consume(entity);
            return jsonStr;
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:com.netflix.client.ssl.URLSslContextFactory.java

/**
 * Opens the specified key or trust store using the given password.
 *
 * In case of failure {@link com.netflix.client.ssl.ClientSslSocketFactoryException} is thrown, and wrapps the
 * underlying cause exception. That could be:
 * <ul>//from   ww  w. ja  v  a2  s .com
 *     <li>KeyStoreException if the JRE doesn't support the standard Java Keystore format, in other words: never</li>
 *     <li>NoSuchAlgorithmException if the algorithm used to check the integrity of the keystore cannot be found</li>
 *     <li>CertificateException if any of the certificates in the keystore could not be loaded</li>
 *     <li>
 *         IOException if there is an I/O or format problem with the keystore data, if a
 *         password is required but not given, or if the given password was incorrect. If the
 *         error is due to a wrong password, the cause of the IOException should be an UnrecoverableKeyException.
 *     </li>
 * </ul>
 *
 * @param storeFile the location of the store to load
 * @param password the password protecting the store
 * @return the newly loaded key store
 * @throws ClientSslSocketFactoryException a wrapper exception for any problems encountered during keystore creation.
 */
private static KeyStore createKeyStore(final URL storeFile, final String password)
        throws ClientSslSocketFactoryException {

    if (storeFile == null) {
        return null;
    }

    Preconditions.checkArgument(StringUtils.isNotEmpty(password),
            "Null keystore should have empty password, defined keystore must have password");

    KeyStore keyStore = null;

    try {
        keyStore = KeyStore.getInstance("jks");

        InputStream is = storeFile.openStream();

        try {
            keyStore.load(is, password.toCharArray());
        } catch (NoSuchAlgorithmException e) {
            throw new ClientSslSocketFactoryException(
                    String.format("Failed to create a keystore that supports algorithm %s: %s",
                            SOCKET_ALGORITHM, e.getMessage()),
                    e);
        } catch (CertificateException e) {
            throw new ClientSslSocketFactoryException(String.format(
                    "Failed to create keystore with algorithm %s due to certificate exception: %s",
                    SOCKET_ALGORITHM, e.getMessage()), e);
        } finally {
            try {
                is.close();
            } catch (IOException ignore) { // NOPMD                
            }
        }
    } catch (KeyStoreException e) {
        throw new ClientSslSocketFactoryException(
                String.format("KeyStore exception creating keystore: %s", e.getMessage()), e);
    } catch (IOException e) {
        throw new ClientSslSocketFactoryException(
                String.format("IO exception creating keystore: %s", e.getMessage()), e);
    }

    return keyStore;
}

From source file:com.gravspace.core.HttpServer.java

public static void start(String[] args) throws Exception {

    int port = 8082;
    if (args.length >= 1) {
        port = Integer.parseInt(args[0]);
    }//from  w  ww .jav  a  2s .c  om

    ActorSystem system = ActorSystem.create("Application-System");
    Properties config = new Properties();
    config.load(HttpServer.class.getResourceAsStream("/megapode.conf"));
    ActorRef master = system.actorOf(Props.create(CoordinatingActor.class, config), "Coordinator");

    // Set up the HTTP protocol processor
    HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
            .add(new ResponseServer("Test/1.1")).add(new ResponseContent()).add(new ResponseConnControl())
            .build();

    // Set up request handlers
    UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
    reqistry.register("*", new HttpHandler(system, master));

    // Set up the HTTP service
    HttpService httpService = new HttpService(httpproc, reqistry);

    SSLServerSocketFactory sf = null;
    if (port == 8443) {
        // Initialize SSL context
        ClassLoader cl = HttpServer.class.getClassLoader();
        URL url = cl.getResource("my.keystore");
        if (url == null) {
            System.out.println("Keystore not found");
            System.exit(1);
        }
        KeyStore keystore = KeyStore.getInstance("jks");
        keystore.load(url.openStream(), "secret".toCharArray());
        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmfactory.init(keystore, "secret".toCharArray());
        KeyManager[] keymanagers = kmfactory.getKeyManagers();
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, null, null);
        sf = sslcontext.getServerSocketFactory();
    }

    RequestListenerThread t = new RequestListenerThread(port, httpService, sf);
    t.setDaemon(false);
    t.start();

    t.join();
}

From source file:com.bbc.util.ClientCustomSSL.java

public static String clientCustomSLL(String mchid, String path, String data) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    System.out.println("?...");
    FileInputStream instream = new FileInputStream(new File("/payment/apiclient_cert.p12"));
    try {/*w  w w  .ja  va  2 s .  co  m*/
        keyStore.load(instream, mchid.toCharArray());
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchid.toCharArray()).build();
    // Allow TLSv1 protocol only
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    try {

        HttpPost httpost = new HttpPost(path);
        httpost.addHeader("Connection", "keep-alive");
        httpost.addHeader("Accept", "*/*");
        httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        httpost.addHeader("Host", "api.mch.weixin.qq.com");
        httpost.addHeader("X-Requested-With", "XMLHttpRequest");
        httpost.addHeader("Cache-Control", "max-age=0");
        httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

        httpost.setEntity(new StringEntity(data, "UTF-8"));
        CloseableHttpResponse response = httpclient.execute(httpost);
        try {
            HttpEntity entity = response.getEntity();
            System.out.println(response.getStatusLine());
            if (entity != null) {
                System.out.println("Response content length: " + entity.getContentLength());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String text;
                StringBuffer sb = new StringBuffer("");
                while ((text = bufferedReader.readLine()) != null) {
                    System.out.println(text);
                    sb.append(text);
                }
                return sb.toString();

            }
            EntityUtils.consume(entity);
            return "";
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}