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:org.pixmob.fm2.util.HttpUtils.java

private static KeyStore loadCertificates(Context context) throws IOException {
    try {// ww w.j  a  va  2s .c o  m
        final KeyStore localTrustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
        try {
            localTrustStore.load(in, "mysecret".toCharArray());
        } finally {
            in.close();
        }

        return localTrustStore;
    } catch (Exception e) {
        final IOException ioe = new IOException("Failed to load SSL certificates");
        ioe.initCause(e);
        throw ioe;
    }
}

From source file:com.weitaomi.systemconfig.wechat.ClientCustomSSL.java

public static String connectKeyStore(String url, String xml, String path, int flag) throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    File file = LoadFileFactory.getFile(path);
    char[] arr = null;
    if (flag == 0) {
        arr = WechatConfig.MCHID.toCharArray();
    }//w w w  .j  a  v a 2  s  .c  o m
    if (flag == 1) {
        arr = WechatConfig.MCHID_OFFICIAL.toCharArray();
    }
    FileInputStream instream = new FileInputStream(file);
    try {
        keyStore.load(instream, arr);
    } finally {
        instream.close();
    }

    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, arr).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();

    StringEntity entityRequest = new StringEntity(xml, "utf-8");
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(entityRequest);
    //        httpPost.setHeader("Content-Type", "application/json");//; charset=utf-8
    HttpResponse response = httpclient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new RuntimeException("");
    }
    HttpEntity resEntity = response.getEntity();
    InputStream inputStream = resEntity.getContent();
    return HttpRequestUtils.readInstream(inputStream, "UTF-8");
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java

private static SSLContextBuilder loadTrustMaterial(SSLContextBuilder builder, final File file, final char[] tsp,
        final TrustStrategy trustStrategy)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(file, "Truststore file"); //$NON-NLS-1$
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {/* www.  ja  va  2  s . c o  m*/
        trustStore.load(instream, tsp);
    } finally {
        instream.close();
    }
    return builder.loadTrustMaterial(trustStore, trustStrategy);
}

From source file:nz.net.catalyst.MaharaDroid.upload.http.RestClient.java

private static SSLSocketFactory getSocketFactory(Boolean d) {
    // Enable debug mode to ignore all certificates
    if (DEBUG) {/*from  w  w w  . j a  va2s  . c  o  m*/
        KeyStore trustStore;
        try {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            return sf;

        } catch (KeyStoreException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (NoSuchAlgorithmException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (CertificateException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (IOException e3) {
            // TODO Auto-generated catch block
            e3.printStackTrace();
        } catch (KeyManagementException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        } catch (UnrecoverableKeyException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
    }

    return SSLSocketFactory.getSocketFactory();
}

From source file:io.apiman.gateway.platforms.servlet.connectors.ssl.SSLSessionStrategyFactory.java

private static SSLContextBuilder loadKeyMaterial(SSLContextBuilder builder, File file, char[] ksp, char[] kp,
        PrivateKeyStrategy privateKeyStrategy) throws NoSuchAlgorithmException, KeyStoreException,
        UnrecoverableKeyException, CertificateException, IOException {
    Args.notNull(file, "Keystore file"); //$NON-NLS-1$
    final KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {//from   w w w.  j  av a 2s  .c  o  m
        identityStore.load(instream, ksp);
    } finally {
        instream.close();
    }
    return builder.loadKeyMaterial(identityStore, kp, privateKeyStrategy);
}

From source file:eu.eubrazilcc.lvl.core.http.client.TrustedHttpsClient.java

/**
 * Creates a custom SSL context where clients will trust own CA and self-signed certificates and associates a HTTP client to the context.
 * @return a HTTP client that will trust own CA and self-signed certificates.
 * @throws Exception if an error occurs.
 *///w ww .  j av  a2  s .co m
private static final CloseableHttpClient createHttpClient(final File trustStoreDir, final char[] password,
        final String url) {
    CloseableHttpClient httpClient = null;
    try {
        final File trustStoreFile = new File(trustStoreDir, "trusted.keystore");
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // create a new, empty trust store
        if (!trustStoreFile.exists()) {
            trustStoreDir.mkdirs();
            trustStoreFile.createNewFile();
            trustStore.load(null, password);

        }
        // import certificate to trust store
        importCertificate(url, trustStore);
        // save trust store to disk
        try (final FileOutputStream outstream = new FileOutputStream(trustStoreFile)) {
            trustStore.store(outstream, password);
        }
        // trust own CA and all self-signed certificates         
        final SSLContext sslContext = SSLContexts.custom()
                .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
        // allow trusted protocols only
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "SSLv2Hello", "TLSv1", "TLSv1.1", "TLSv1.2" }, null,
                new DefaultHostnameVerifier());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (Exception e) {
        LOGGER.error("Failed to create HTTP client", e);
    }
    return httpClient;
}

From source file:com.app.mvc.http.ext.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");
    }/*w w  w. j  a v  a2s .  c o  m*/
    log.debug("Initializing key store");
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Get the key from the KeyStore./* ww  w . j  a v a  2 s . c o m*/
 *
 * @param keyStoreFilename
 * @param keypass
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws CertificateException
 */
private static Key getKeyFromStore(final String keyStoreFilename, final char[] keypass) throws IOException,
        UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    final InputStream keyStoreInputStream = thisClass.getResourceAsStream(keyStoreFilename); // Try the Sun KeyStore
    // first
    if (keyStoreInputStream == null) {
        throw new IOException("Unable to locate key store file " + keyStoreFilename); // File should always be found
    }
    Key key = null;
    try {
        final KeyStore keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(keyStoreInputStream, keypass);
        key = keystore.getKey(KEY_ALIAS, keypass);
    } finally {
        if (keyStoreInputStream != null) {
            keyStoreInputStream.close();
        }
    }
    return key;
}

From source file:com.blackducksoftware.tools.commonframework.core.encryption.Password.java

/**
 * Generates a new key. Should be used manually and only when creating a new
 * key is necessary. WARNING: If the keys in the KeyStore files are replaced
 * then we will not be able to decrypt passwords that were encrypted with
 * the old keys.// w w w . ja  v a  2  s.c o  m
 *
 * @param keypass
 *            char[] with the keypass that will gain access to the key
 *            (currently hard coded in)
 * @throws IOException
 */
@SuppressWarnings("unused")
private static Key setKey(final char[] keypass, final File keyFile) throws Exception {

    Key key = null;
    FileOutputStream output = null;
    try {
        output = new FileOutputStream(keyFile.getCanonicalPath());
        key = KeyGenerator.getInstance(ENCRYPTION_ALGORITHM).generateKey();
        final KeyStore keystore = KeyStore.getInstance(KEYSTORE_TYPE);
        keystore.load(null, null);
        keystore.setKeyEntry(KEY_ALIAS, key, keypass, null);
        keystore.store(output, keypass);
    } finally {
        if (output != null) {
            output.close();
        }
    }

    return key;
}

From source file:net.link.util.common.KeyUtils.java

public static KeyStore newKeyStore() {

    try {//from   w w w. j ava 2 s .  co  m
        KeyStore keyStore = KeyStore.getInstance("pkcs12");
        keyStore.load(null, null);

        return keyStore;
    } catch (IOException e) {
        throw new InternalInconsistencyException("Key Store can't be created or stored.", e);
    } catch (CertificateException e) {
        throw new InternalInconsistencyException("Certificate couldn't be stored.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("KeyStores integrity algorithm not supported.", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException(
                "PKCS12 KeyStores not supported or store does not support the key or certificate.", e);
    }
}