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.jms.notify.utils.httpclient.SimpleHttpUtils.java

public static ClientKeyStore loadClientKeyStore(InputStream keyStoreStream, String keyStorePass,
        String privateKeyPass) {//from  w w w. j av a  2s .com
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(keyStoreStream, keyStorePass.toCharArray());
        kmf.init(ks, privateKeyPass.toCharArray());
        return new ClientKeyStore(kmf);
    } catch (Exception e) {
        logger.error("loadClientKeyFactory fail : " + e.getMessage(), e);
        return null;
    }
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static HttpClient getDefaultHttpsClient() {
    try {/*from w w  w  .  ja v a 2s .c  o  m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(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);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

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

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        HttpClientBuilder b = HttpClientBuilder.create();
        return b.build();
        //return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static DefaultHttpClient getLoginHttpsClient(String userName, String password) {
    try {//  w  ww  . j a v a2 s  . c o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new DefaultSecureSocketFactory(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);
        HttpConnectionParams.setConnectionTimeout(params, 300000);
        HttpConnectionParams.setSocketBufferSize(params, 10485760);
        HttpConnectionParams.setSoTimeout(params, 300000);

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

        DefaultHttpClient httpClient = new DefaultHttpClient(ccm, params);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(userName, password));
        return httpClient;
    } catch (Exception e) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Creates empty JKS keystore../* ww  w.java2 s.  c om*/
 * 
 * @return new JKS keystore
 * @throws KeyStoreException
 * @throws IOException
 * @throws CertificateException
 * @throws NoSuchAlgorithmException
 */
public static KeyStore createKeyStore()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    final KeyStore newKeyStore = KeyStore.getInstance("JKS");
    newKeyStore.load(null, null);
    return newKeyStore;
}

From source file:com.stargame.ad.util.http.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");
    }/* ww  w.j  a v a  2s .c o m*/
    LogUtil.d(AuthSSLProtocolSocketFactory.class, "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:cn.org.eshow.framwork.http.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");
    }//from ww w  . jav a  2 s . c  o m
    AbLogUtil.d(AuthSSLProtocolSocketFactory.class, "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.liferay.sync.engine.lan.session.LanSession.java

private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception {

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

    keyStore.load(null, null);

    for (SyncAccount syncAccount : SyncAccountService.findAll()) {
        if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) {
            continue;
        }/*from   w  w  w.j  a  va  2s  .com*/

        try {
            PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey());

            if (privateKey == null) {
                _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId());

                continue;
            }

            X509Certificate x509Certificate = LanPEMParserUtil
                    .parseX509Certificate(syncAccount.getLanCertificate());

            if (x509Certificate == null) {
                _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId());

                continue;
            }

            keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate);

            keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(),
                    new Certificate[] { x509Certificate });
        } catch (Exception e) {
            _logger.error(e.getMessage(), e);
        }
    }

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    keyManagerFactory.init(keyStore, "".toCharArray());

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(keyStore);

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

    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}

From source file:com.jiuyi.qujiuyi.common.util.WxRefundSSL.java

public final static String post(String entity, String mch_id, Integer clientType) throws Exception {
    try {//from  ww  w  .  j  av  a2 s . co m
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        // FileInputStream instream = new FileInputStream(new
        // File("D:\\apiclient_cert.p12"));

        FileInputStream instream = null;

        if (clientType == 0) {
            instream = new FileInputStream(new File(SysCfg.getString("apiclient.ssl")));
        } else {
            instream = new FileInputStream(new File(SysCfg.getString("apiclient.app.ssl")));
        }

        try {
            keyStore.load(instream, mch_id.toCharArray());
        } finally {
            instream.close();
        }

        SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mch_id.toCharArray()).build();

        sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }

    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    String result = "";
    try {
        HttpPost post = new HttpPost(SysCfg.getString("weixin.refund"));
        post.setEntity(new StringEntity(entity));
        CloseableHttpResponse response = httpclient.execute(post);
        try {
            HttpEntity resp = response.getEntity();
            if (resp != null) {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resp.getContent()));
                String line = null;
                while ((line = bufferedReader.readLine()) != null) {
                    result += line;
                }
            }
            EntityUtils.consume(resp);
        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@BeforeClass
public static void setUp() throws Exception {
    SharedUtils.bootstrap(false); // use real data
    String tenantName = ServerConfig.getTenant(0);
    String rpName = ServerConfig.getRelyingParty(tenantName, 0);
    String issuerUrl = ServerConfig.getRelyingPartyUrl(rpName);
    String acsName = ServerConfig.getAssertionConsumerService(rpName, 0);
    acsUrl = ServerConfig.getServiceEndpoint(acsName);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(SamlServiceTest.class.getResource("/sts-store.jks").getFile());
    char[] stsKeystorePassword = "ca$hc0w".toCharArray();
    ks.load(is, stsKeystorePassword);

    String stsAlias = "stskey";
    Certificate certificate = ks.getCertificate(stsAlias);
    Key key = ks.getKey(stsAlias, stsKeystorePassword);

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    certificates.add((X509Certificate) certificate);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(certificates);

    privateKey = (PrivateKey) key;
    x509Certificate = (X509Certificate) certificate;

    SamlServiceFactory factory = new DefaultSamlServiceFactory();
    service = factory.createSamlService(privateKey, SignatureAlgorithm.RSA_SHA256,
            SignatureAlgorithm.RSA_SHA256, issuerUrl, certPath);
}

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

/**
 * Create a new, empty KeyStore.//w w  w.j  av a  2  s  .c o  m
 *
 * @param keyStoreType
 *            The KeyStore type to create
 * @return The KeyStore
 * @throws CryptoException
 *             Problem encountered creating the KeyStore
 * @throws IOException
 *             An I/O error occurred
 */
public static KeyStore create(KeyStoreType keyStoreType) throws CryptoException, IOException {
    if (!keyStoreType.isFileBased()) {
        throw new CryptoException(MessageFormat
                .format(res.getString("NoCreateKeyStoreNotFile.exception.message"), keyStoreType.jce()));
    }

    KeyStore keyStore = getKeyStoreInstance(keyStoreType);

    try {
        keyStore.load(null, null);
    } catch (CertificateException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoLoadKeyStoreType.exception.message"), keyStoreType), ex);
    } catch (NoSuchAlgorithmException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoLoadKeyStoreType.exception.message"), keyStoreType), ex);
    }

    return keyStore;
}