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:ee.ria.xroad.common.util.CryptoUtils.java

/**
 * Loads a key store from a file./*  w  ww. j av  a2 s.  co  m*/
 * @param type the type of key store to load ("pkcs12" for PKCS12 type)
 * @param file the file to load
 * @param password the password for the key store
 * @return the loaded keystore
 * @throws Exception if any errors occur
 */
public static KeyStore loadKeyStore(String type, File file, char[] password) throws Exception {
    KeyStore keyStore = KeyStore.getInstance(type);
    try (FileInputStream fis = new FileInputStream(file)) {
        keyStore.load(fis, password);
    }

    return keyStore;
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Fetch a public key (certificate) from KeyStore
 *
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW   a String containing the KeyStore password
 * @param alias        a String containing the alias of targeted certificate
 * @return the PublicKey object containing the targeted public key
 *
 *///from   w  ww .j  a  va 2 s .  c o m
public static PublicKey getPublicKeyByAlias(String keyStorePath, String keyStorePW, String alias) {
    KeyStore ks;
    FileInputStream is = null;
    try {
        ks = KeyStore.getInstance("JKS");
        is = new FileInputStream(keyStorePath);
        ks.load(is, keyStorePW.toCharArray());
        Certificate certificate = ks.getCertificate(alias);
        if (certificate != null) {
            return certificate.getPublicKey();
        }
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException when attempting to extract a public key by an alias in a keystore. "
                + e);
    } catch (IOException e) {
        logger.error("IOException when attempting to extract a public key by an alias in a keystore. " + e);
    } catch (KeyStoreException e) {
        logger.error(
                "KeyStoreException when attempting to extract a public key by an alias in a keystore. " + e);
    } catch (NoSuchAlgorithmException e) {
        logger.error(
                "NoSuchAlgorithmException when attempting to extract a public key by an alias in a keystore. "
                        + e);
    } catch (CertificateException e) {
        logger.error(
                "CertificateException when attempting to extract a public key by an alias in a keystore. " + e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                logger.error("IOException when attempting to close an input stream. " + ioe);
            }
        }
    }
    return null;
}

From source file:com.dongfang.dicos.sina.UtilSina.java

public static HttpClient getNewHttpClient(Context context) {
    try {//from ww  w . ja  va  2s . co 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();

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

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

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, UtilSina.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, UtilSina.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            // ??APN
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

private static PrivateKey readKeyStoreKey(InputStream in, String storeType, String alias, char[] pass)
        throws Exception {
    try {//  w  ww . ja v a 2 s  .  c  o  m
        KeyStore ks = KeyStore.getInstance(storeType);
        //load the key store
        //TODO: specify other than "null" if want key store integrity check
        //need key store passwd
        ks.load(in, null);
        return (PrivateKey) ks.getKey(alias, pass);
    } finally {
        MiscUtils.closeStream(in);
    }
}

From source file:com.zzl.zl_app.cache.Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {/*  w w  w .j a  v  a2s. c  om*/
        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", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();//w ww  . j  av a2 s . c  om

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Fetch private key from KeyStore//ww  w.j av  a  2s. c  om
 *
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW   a String containing the KeyStore password
 * @param keyName      a String containing the alias of targeted certificate
 * @param keyPW        a String containing the key password
 * @return the PrivateKeyEntry object containing the targeted private key
 *
 */
public static PrivateKeyEntry getKeyEntry(String keyStorePath, String keyStorePW, String keyName,
        String keyPW) {
    KeyStore ks;
    PrivateKeyEntry keyEntry = null;
    FileInputStream is = null;
    try {
        ks = KeyStore.getInstance("JKS");
        is = new FileInputStream(keyStorePath);
        ks.load(is, keyStorePW.toCharArray());
        keyEntry = (PrivateKeyEntry) ks.getEntry(keyName, new KeyStore.PasswordProtection(keyPW.toCharArray()));
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException when attempting to get a key entry in a keystore. " + e);
    } catch (IOException e) {
        logger.error("IOException when attempting to get a key entry in a keystore. " + e);
    } catch (KeyStoreException e) {
        logger.error("KeyStoreException when attempting to get a key entry in a keystore. " + e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to get a key entry in a keystore. " + e);
    } catch (CertificateException e) {
        logger.error("CertificateException when attempting to get a key entry in a keystore. " + e);
    } catch (UnrecoverableEntryException e) {
        logger.error("UnrecoverableEntryException when attempting to get a key entry in a keystore. " + e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                logger.error("IOException when attempting to close an input stream. " + ioe);
            }
        }
    }
    return keyEntry;
}

From source file:com.ah.ui.actions.home.clientManagement.service.CertificateGenSV.java

public static X509Certificate ananysisP12(InputStream in, char[] keyStorePassword)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(in, keyStorePassword);
    in.close();/*  w  ww  . j a v  a2  s  .c  om*/
    Enumeration<String> enums = keyStore.aliases();
    if (enums.hasMoreElements()) {
        String keyAlis = enums.nextElement();
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(keyAlis);
        return certificate;
    }
    return null;
}

From source file:jetbrains.buildServer.clouds.azure.asm.connector.AzureApiConnector.java

private static KeyStore createKeyStorePKCS12(String base64Certificate, OutputStream keyStoreOutputStream,
        String keystorePwd) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    KeyStore store = KeyStore.getInstance("PKCS12", BouncyCastleProvider.PROVIDER_NAME);
    store.load(null, null);

    // read in the value of the base 64 cert without a password (PBE can be applied afterwards if this is needed
    final byte[] decode = Base64.decode(base64Certificate);
    InputStream sslInputStream = new ByteArrayInputStream(decode);
    store.load(sslInputStream, "".toCharArray());

    // we need to a create a physical keystore as well here
    store.store(keyStoreOutputStream, keystorePwd.toCharArray());
    keyStoreOutputStream.close();/*from   w w  w.  j a  v  a 2 s  .  co m*/
    return store;
}

From source file:com.haoqee.chat.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    try {//from  www .j a  v a  2  s .co  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();

        // HttpConnectionParams.setConnectionTimeout(params, 10000);
        // HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        // HttpProtocolParams.setContentCharset(params, HTTP.);

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

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}