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:mitm.common.security.certificate.GenerateBulkPFX.java

private static void loadCA() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, IOException, UnrecoverableKeyException {
    KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12");

    File file = new File("test/resources/testdata/keys/testCA.p12");

    FileInputStream input = new FileInputStream(file);

    caKeyStore.load(input, "test".toCharArray());

    rootCertificate = (X509Certificate) caKeyStore.getCertificate("root");
    caCertificate = (X509Certificate) caKeyStore.getCertificate("ca");
    caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null);

    assertNotNull(caCertificate);/* w ww.  j  a  v  a2s . com*/
    assertNotNull(caPrivateKey);
}

From source file:com.dalaran.async.task.http.AbstractHTTPService.java

public 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();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", 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.utest.webservice.client.rest.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 ww . j  a  v  a  2 s.co m
    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: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   w ww . jav  a2  s . c  o m
    System.out.println("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.nieyue.weixin.ssl.ClientCustomSSL.java

/**
 * ?/*from ww w .  j a  v  a  2s  .  c o  m*/
 * @return
 * @throws Exception
 */
public static CloseableHttpClient getCloseableHttpClient() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    FileInputStream instream = new FileInputStream(
            new File(ClientCustomSSL.class.getResource("").getPath() + "apiclient_cert.p12"));
    //?
    //FileInputStream instream = new FileInputStream("src/com/nieyue/weixin/ssl/apiclient_cert.p12");
    try {
        keyStore.load(instream, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    @SuppressWarnings("deprecation")
    SSLContext sslcontext = SSLContexts.custom()
            .loadKeyMaterial(keyStore, ThirdParty.GetValueByKey(ThirdParty.WEIXIN_YAYAO_MCH_ID).toCharArray())
            .build();
    // Allow TLSv1 protocol only
    @SuppressWarnings("deprecation")
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return httpclient;
}

From source file:org.wso2.cdm.agent.utils.HTTPConnectorUtils.java

public static HttpClient getCertifiedHttpClient(Context context) {
    try {/*from  w  w w .  jav  a2 s .c o m*/
        HttpClient client = null;
        if (CommonUtilities.SERVER_PROTOCOL.toLowerCase().equals("https://")) {
            Log.e("", "in");
            KeyStore localTrustStore = KeyStore.getInstance("BKS");
            InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);
            localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());
            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
            schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
            HttpParams params = new BasicHttpParams();
            ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
            client = new DefaultHttpClient(cm, params);
        } else {
            client = new DefaultHttpClient();
        }

        return client;
    } catch (Exception e) {

        return null;
    }
}

From source file:it.geosolutions.sfs.web.Start.java

private static void assureSelfSignedServerCertificate(String hostname, File keyStoreFile, String password)
        throws Exception {

    KeyStore privateKS = KeyStore.getInstance("JKS");
    if (keyStoreFile.exists()) {
        FileInputStream fis = new FileInputStream(keyStoreFile);
        privateKS.load(fis, password.toCharArray());
        if (keyStoreContainsCertificate(privateKS, hostname))
            return;
    } else {/*from   w w  w . j a v  a 2s . c om*/
        privateKS.load(null);
    }

    // create a RSA key pair generator using 1024 bits

    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(1024);
    KeyPair KPair = keyPairGenerator.generateKeyPair();

    // cerate a X509 certifacte generator
    //       X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();  

    // set validity to 10 years, issuer and subject are equal --> self singed certificate
    int random = new SecureRandom().nextInt();
    if (random < 0)
        random *= -1;
    //       v3CertGen.setSerialNumber(BigInteger.valueOf(random));  
    //            v3CertGen.setIssuerDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None"));  
    //            v3CertGen.setNotBefore(new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30));  
    //            v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365*10)));  
    //            v3CertGen.setSubjectDN(new X509Principal("CN=" + hostname + ", OU=None, O=None L=None, C=None"));
    //                        
    //            v3CertGen.setPublicKey(KPair.getPublic());  
    //            v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");   
    //            
    //            X509Certificate PKCertificate = v3CertGen.generateX509Certificate(KPair.getPrivate());
    //            
    // store the certificate containing the public key,this file is needed
    // to import the public key in other key store. 
    File certFile = new File(keyStoreFile.getParentFile(), hostname + ".cert");
    FileOutputStream fos = new FileOutputStream(certFile.getAbsoluteFile());
    //            fos.write(PKCertificate.getEncoded());  
    fos.close();

    //            privateKS.setKeyEntry(hostname+".key", KPair.getPrivate(),  
    //                    password.toCharArray(),  
    //                    new java.security.cert.Certificate[]{PKCertificate});
    //            
    //            privateKS.setCertificateEntry(hostname+".cert",PKCertificate); 

    privateKS.store(new FileOutputStream(keyStoreFile), password.toCharArray());
}

From source file:com.example.froyoandwams.FroyoSupport.java

private static SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {//from ww w  .  j a  va 2  s  .  c o  m
        final KeyStore ks = KeyStore.getInstance("BKS");

        Activity mainActivity = MainActivity.getInstance();
        final InputStream in = mainActivity.getResources().openRawResource(R.raw.mobileservicestore);
        try {
            ks.load(in, "mobileservices".toCharArray());
        } finally {
            in.close();
        }

        return new AdditionalKeyStoresSSLSocketFactory(ks);

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    try (InputStream inputStream = trustFile.getInputStream()) {
        trustStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }// w  ww. j a v  a2 s.  co m

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

    return trustManagerFactory;
}

From source file:org.springframework.cloud.vault.ClientHttpRequestFactoryFactory.java

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    try (InputStream inputStream = keystoreFile.getInputStream()) {
        keyStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }/*from w w w.  j  av a 2  s.c o  m*/

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}