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.tvs.signaltracker.Utils.java

public static HttpClient getNewHttpClient() {
    try {// www.  j  a v  a  2 s . co m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new EasySSLSocketFactory(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:ee.ria.xroad.common.TestCertUtil.java

/**
 * Loads a keystore with the given type from the specified filename.
 * @param type type of the keystore//  w  w w.ja  va  2s. c o m
 * @param file keystore filename
 * @param password keystore password
 * @return KeyStore
 */
public static KeyStore loadKeyStore(String type, String file, String password) {
    try {
        KeyStore keyStore = KeyStore.getInstance(type);
        InputStream fis = getFile(file);
        keyStore.load(fis, password.toCharArray());
        fis.close();

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

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

public static SSLSocketFactory setupSSLSocketFactory(Context context, PrivateKey privateKey,
        X509Certificate certificate, boolean acceptAnyCertificate)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException, NoSuchProviderException {

    // in-memory keystore
    KeyManager[] km = null;/*from   ww  w  .ja  v  a  2 s  . c o  m*/
    if (privateKey != null && certificate != null) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(null, null);
        keystore.setKeyEntry("private", privateKey, null, new Certificate[] { certificate });

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

    // trust managers
    TrustManager[] tm;

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

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

            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType)
                    throws CertificateException {
            }
        } };
    } else {
        // load merged truststore (system + internal)
        KeyStore trustStore = InternalTrustStore.getTrustStore(context);

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

        tm = tmFactory.getTrustManagers();
    }

    SSLContext ctx = SSLContext.getInstance("TLSv1");
    ctx.init(km, tm, null);
    return new TlsOnlySocketFactory(ctx.getSocketFactory(), true);
}

From source file:io.dropwizard.revolver.http.RevolverHttpClientFactory.java

private static SSLContext getSSLContext(final String keyStorePath, final String keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        KeyManagementException, UnrecoverableKeyException {
    final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream instream = RevolverHttpClientFactory.class.getClassLoader()
            .getResourceAsStream(keyStorePath)) {
        keyStore.load(instream, keyStorePassword.toCharArray());
    }/*from   w w w  .jav a  2 s.  c  o  m*/
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, keyStorePassword.toCharArray());
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:com.android.volley.toolbox.http.HttpClientStack.java

public static org.apache.http.conn.ssl.SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory sf = null;/* w ww .ja  va2 s. c o  m*/
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        sf = new JindunSSLSocketFactory(trustStore);
        //          sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return sf;
}

From source file:org.opendatakit.aggregate.externalservice.GoogleOauth2ExternalService.java

protected static GoogleCredential getCredential(String scopes, CallingContext cc)
        throws ODKExternalServiceCredentialsException {
    try {//  ww  w . j a v a 2  s .  co  m
        String serviceAccountUser = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.GOOGLE_API_SERVICE_ACCOUNT_EMAIL);
        String privateKeyString = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.PRIVATE_KEY_FILE_CONTENTS);

        if (serviceAccountUser == null || privateKeyString == null || serviceAccountUser.length() == 0
                || privateKeyString.length() == 0) {
            throw new ODKExternalServiceCredentialsException(
                    "No OAuth2 credentials. Have you supplied any OAuth2 credentials on the Site Admin / Preferences page?");
        }

        byte[] privateKeyBytes = Base64.decodeBase64(privateKeyString.getBytes(UTF_CHARSET));

        // TODO: CHANGE TO MORE OPTIMAL METHOD
        KeyStore ks = null;
        ks = KeyStore.getInstance("PKCS12");
        ks.load(new ByteArrayInputStream(privateKeyBytes), "notasecret".toCharArray());
        Enumeration<String> aliasEnum = null;
        aliasEnum = ks.aliases();

        Key key = null;
        while (aliasEnum.hasMoreElements()) {
            String keyName = (String) aliasEnum.nextElement();
            key = ks.getKey(keyName, "notasecret".toCharArray());
            break;
        }
        PrivateKey serviceAccountPrivateKey = (PrivateKey) key;

        HttpClientFactory httpClientFactory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
        HttpTransport httpTransport = httpClientFactory.getGoogleOAuth2Transport();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountUser)
                .setServiceAccountScopes(Collections.singleton(scopes))
                .setServiceAccountPrivateKey(serviceAccountPrivateKey).build();
        credential.refreshToken();
        return credential;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ODKExternalServiceCredentialsException(e);
    }
}

From source file:com.linkage.crm.csb.sign.CtSignature.java

/**
 * ./* www. j a v  a2  s.co m*/
 * 
 * @param pwd String 
 * @param alias String 
 * @param priKeyFile 
 * @return Signature 
 */
public static Signature createSignatureForSign(String pwd, String alias, String priKeyFile) {
    try {
        logger.debug("keypath=============" + priKeyFile);
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream ksfis = new FileInputStream(priKeyFile);
        BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
        char[] kpass = pwd.toCharArray();
        ks.load(ksbufin, kpass);
        PrivateKey priKey = (PrivateKey) ks.getKey(alias, kpass);
        Signature rsa = Signature.getInstance("SHA1withDSA");
        rsa.initSign(priKey);
        return rsa;
    } catch (Exception ex) {
        logger.error("errors appeared while trying to signature", ex);
        return null;
    }
}

From source file:com.linkage.crm.csb.sign.CtSignature.java

/**
 * @param originalText String //from   w  w  w. j  a  v a  2  s  .  com
 * @param pwd String 
 * @param alias String 
 * @param priKeyFile 
 * @return String 
 */
public static String signature(String originalText, String pwd, String alias, String priKeyFile) {
    try {
        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream ksfis = new FileInputStream(priKeyFile);
        BufferedInputStream ksbufin = new BufferedInputStream(ksfis);
        char[] kpass = pwd.toCharArray();
        ks.load(ksbufin, kpass);
        PrivateKey priKey = (PrivateKey) ks.getKey(alias, kpass);
        Signature rsa = Signature.getInstance("SHA1withDSA");
        rsa.initSign(priKey);
        rsa.update(originalText.getBytes());
        byte[] signedText = rsa.sign();
        return HexUtils.toHexString(signedText);
    } catch (Exception ex) {
        logger.error("errors appeared while trying to signature", ex);
        return null;
    }
}

From source file:com.microsoft.windowsazure.mobileservices.zumoe2etestapp.framework.FroyoSupport.java

private static SSLSocketFactory createAdditionalCertsSSLSocketFactory() {
    try {//www . java2s .  c  o  m
        final KeyStore ks = KeyStore.getInstance("BKS");

        final InputStream in = MainActivity.getInstance().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:net.netheos.pcsapi.providers.StorageProviderFactory.java

/**
 * Builds a specific HttpClient to certain providers
 *
 * @param providerName/*ww w  .  j ava2  s  . c o  m*/
 * @return client to be used, or null if default should be used.
 */
private static HttpClient buildDedicatedHttpClient(String providerName) throws IOException {
    /**
     * Basic java does not trust CloudMe CA CloudMe CA needs to be added
     */
    if (providerName.equals("cloudme") && !PcsUtils.ANDROID) {
        try {
            KeyStore ks = KeyStore.getInstance("JKS");
            InputStream is = null;

            try {
                is = StorageProviderFactory.class.getResourceAsStream("/cloudme.jks");
                ks.load(is, "changeit".toCharArray());
            } finally {
                PcsUtils.closeQuietly(is);
            }

            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory caTrustManagerFactory = TrustManagerFactory.getInstance("SunX509");
            caTrustManagerFactory.init(ks);
            context.init(null, caTrustManagerFactory.getTrustManagers(), null);

            SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", 80, new PlainSocketFactory()));
            schemeRegistry.register(new Scheme("https", 443, new SSLSocketFactory(context)));

            ClientConnectionManager cnxManager = new PoolingClientConnectionManager(schemeRegistry);

            return new DefaultHttpClient(cnxManager);

        } catch (GeneralSecurityException ex) {
            throw new UnsupportedOperationException("Can't configure HttpClient for Cloud Me", ex);
        }
    }

    return null;
}