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.hp.mercury.ci.jenkins.plugins.OOBuildStep.java

private static SSLSocketFactory sslSocketFactoryFromCertificateFile(String keyStorePath, char[] password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        KeyManagementException, UnrecoverableKeyException {

    char[] ksPassword = password;
    FileInputStream fis = new FileInputStream(keyStorePath);

    //while similar to singleton patten in API, this provides a NEW instance.
    KeyStore trustore = KeyStore.getInstance("JKS");

    globalKeystore = keyStorePath;/*from  w  w  w.j  av a 2  s  .  co m*/

    trustore.load(fis, ksPassword);
    final SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustore);

    return sslSocketFactory;
}

From source file:com.wso2.mobile.mdm.utils.ServerUtilities.java

public static HttpsURLConnection getTrustedConnection(Context context, HttpsURLConnection conn) {
    HttpsURLConnection urlConnection = conn;
    try {// www.  j a  v  a2s  .  c  o  m
        KeyStore localTrustStore;

        localTrustStore = KeyStore.getInstance("BKS");

        InputStream in = context.getResources().openRawResource(R.raw.emm_truststore);

        localTrustStore.load(in, CommonUtilities.TRUSTSTORE_PASSWORD.toCharArray());

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

        tmf.init(localTrustStore);

        SSLContext sslCtx;

        sslCtx = SSLContext.getInstance("TLS");

        sslCtx.init(null, tmf.getTrustManagers(), null);

        urlConnection.setSSLSocketFactory(sslCtx.getSocketFactory());
        return urlConnection;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
        return null;
    }

}

From source file:mitm.application.djigzo.james.mailets.SMIMEEncryptTest.java

private static KeyStore loadKeyStore(File file, String password) throws Exception {
    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    keyStore.load(new FileInputStream(file), password.toCharArray());

    return keyStore;
}

From source file:com.streamsets.datacollector.credential.cyberark.TestWebServicesFetcher.java

private static KeyStore createEmptyKeyStore() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null); // initialize
    return ks;//from  w  ww .  ja  v a  2s . c  o  m
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

public static KeyStore loadPKCS12File(final String pathToP12, final String password) throws IOException,
        NoSuchAlgorithmException, CertificateException, KeyStoreException, NoSuchProviderException {
    addBCProvider();//w  ww  .  j a v a2s  .c  o m
    KeyStore keystore = KeyStore.getInstance("PKCS12");

    File p12File = new File(pathToP12);
    if (!p12File.exists()) {
        // try loading it from the classpath
        URL localP12File = PKSigningUtil.class.getClassLoader().getResource(pathToP12);
        if (localP12File == null) {
            throw new FileNotFoundException("File at " + pathToP12 + " not found");
        }
        p12File = new File(localP12File.getFile());
    }
    InputStream streamOfFile = new FileInputStream(p12File);

    keystore.load(streamOfFile, password.toCharArray());
    IOUtils.closeQuietly(streamOfFile);
    return keystore;
}

From source file:com.cloudbees.eclipse.core.util.Utils.java

/**
 * @param url//  www  .  j av  a  2 s.  c o  m
 *          url to connec. Required to determine proxy settings if available. If <code>null</code> then proxy is not
 *          configured for the client returned.
 * @return
 * @throws CloudBeesException
 */
public final static DefaultHttpClient getAPIClient(String url) throws CloudBeesException {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpClientParams.setCookiePolicy(httpclient.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);

        String version = null;
        if (CloudBeesCorePlugin.getDefault() != null) {
            version = CloudBeesCorePlugin.getDefault().getBundle().getVersion().toString();
        } else {
            version = "n/a";
        }
        HttpProtocolParams.setUserAgent(httpclient.getParams(), "CBEclipseToolkit/" + version);

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

        CloudBeesCorePlugin plugin = CloudBeesCorePlugin.getDefault();

        URL truststore;

        if (plugin == null) {
            //Outside the OSGI environment, try to open the stream from the current dir.
            truststore = new File("truststore").toURI().toURL();
        } else {
            truststore = plugin.getBundle().getResource("truststore");
        }

        InputStream instream = truststore.openStream();

        try {
            trustStore.load(instream, "123456".toCharArray());
        } finally {
            instream.close();
        }

        TrustStrategy trustAllStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(final X509Certificate[] chain, final String authType)
                    throws CertificateException {
                return true;
            }
        };

        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, null, null, trustStore,
                null, trustAllStrategy, SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        // Override https handling to use provided truststore
        @SuppressWarnings("deprecation")
        Scheme sch = new Scheme("https", socketFactory, 443);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        HttpParams params = httpclient.getParams();

        //TODO Make configurable from the UI?
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        if (CloudBeesCorePlugin.getDefault() != null) { // exclude proxy support when running outside eclipse
            IProxyService ps = CloudBeesCorePlugin.getDefault().getProxyService();
            if (ps.isProxiesEnabled()) {

                IProxyData[] pr = ps.select(new URI(url));

                //NOTE! For now we use just the first proxy settings with type HTTP or HTTPS to try out the connection. If configuration has more than 1 conf then for now this likely won't work!
                if (pr != null) {
                    for (int i = 0; i < pr.length; i++) {

                        IProxyData prd = pr[i];

                        if (IProxyData.HTTP_PROXY_TYPE.equals(prd.getType())
                                || IProxyData.HTTPS_PROXY_TYPE.equals(prd.getType())) {

                            String proxyHost = prd.getHost();
                            int proxyPort = prd.getPort();
                            String proxyUser = prd.getUserId();
                            String proxyPass = prd.getPassword();

                            HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                            httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

                            if (prd.isRequiresAuthentication()) {
                                List authpref = new ArrayList();
                                authpref.add(AuthPolicy.BASIC);
                                AuthScope authScope = new AuthScope(proxyHost, proxyPort);
                                httpclient.getCredentialsProvider().setCredentials(authScope,
                                        new UsernamePasswordCredentials(proxyUser, proxyPass));
                            }

                            break;

                        }

                    }
                }
            }
        }

        /*      httpclient.getHostConfiguration().setProxy(proxyHost,proxyPort);      
              //if there are proxy credentials available, set those too
              Credentials proxyCredentials = null;
              String proxyUser = beesClientConfiguration.getProxyUser();
              String proxyPassword = beesClientConfiguration.getProxyPassword();
              if(proxyUser != null || proxyPassword != null)
        proxyCredentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
              if(proxyCredentials != null)
        client.getState().setProxyCredentials(AuthScope.ANY, proxyCredentials);
                
        */

        return httpclient;

    } catch (Exception e) {
        throw new CloudBeesException("Error while initiating access to JSON APIs!", e);
    }
}

From source file:mitm.application.djigzo.james.mailets.SMIMESignTest.java

private static void importKeyStore(KeyAndCertificateWorkflow keyAndCertificateWorkflow, File pfxFile)
        throws Exception {
    KeyStore keyStore = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12");

    // initialize key store
    keyStore.load(new FileInputStream(pfxFile), "test".toCharArray());

    keyAndCertificateWorkflow.importKeyStore(keyStore, KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE);
}

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

/**
 * Load the Apple Keychain as a KeyStore. The KeyStore is not file based and
 * therefore does not need to be saved.//from www  .  j  a v a 2  s.co m
 *
 * @return The Keychain as a KeyStore
 * @throws CryptoException
 *             Problem encountered loading the KeyStore
 */
public static KeyStore loadAppleKeychain() throws CryptoException {
    if (!isAppleKeychainSupported()) {
        throw new CryptoException(res.getString("AppleKeychainNotSupported.exception.message"));
    }

    KeyStore keyStore = null;

    try {
        keyStore = KeyStore.getInstance(KEYCHAIN.jce(), APPLE.jce());
    } catch (KeyStoreException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoCreateKeyStore.exception.message"), KEYCHAIN.jce()), ex);
    } catch (NoSuchProviderException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoCreateKeyStore.exception.message"), KEYCHAIN.jce()), ex);
    }

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

    return keyStore;
}

From source file:com.vmware.bdd.utils.CommonUtil.java

public static KeyStore loadAppMgrKeyStore(String keystorePath) {
    File file = new File(keystorePath + Constants.APPMANAGER_KEYSTORE_FILE);
    if (file.isFile() == false) {
        char SEP = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
        file = new File(dir, Constants.APPMANAGER_KEYSTORE_FILE);
        if (file.isFile() == false) {
            file = new File(dir, "cacerts");
        }/*  w ww . j  a  v  a  2 s .  c om*/
    }

    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        logger.error("Can't get KeyStore instance. ", e);
        return null;
    }
    InputStream in = null;
    try {
        in = new FileInputStream(file);
        keyStore.load(in, Constants.APPMANAGER_KEYSTORE_PASSWORD);
    } catch (FileNotFoundException e) {
        logger.error("Can't find file " + file.getAbsolutePath(), e);
        return null;
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm error during loading keystore.", e);
        return null;
    } catch (CertificateException e) {
        logger.error("Certificate exception during loading keystore.", e);
        return null;
    } catch (IOException e) {
        logger.error("Caught IO Exception.", e);
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.warn("Input stream of appmanagers.jks close failed.");
            }
        }
    }
    return keyStore;
}

From source file:org.dasein.cloud.google.GoogleMethod.java

static @Nonnull String getToken(@Nonnull String iss, @Nonnull String p12File) throws CloudException {
    if (logger.isDebugEnabled()) {
        logger.debug("iss: " + iss);
        logger.debug("p12File: " + p12File);
    }/*from   w w w.j a va  2 s.  com*/

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    StringBuffer token = new StringBuffer();

    try {
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        token.append(".");

        String scope = "https://www.googleapis.com/auth/compute";
        String aud = "https://accounts.google.com/o/oauth2/token";
        String expiry = Long.toString((System.currentTimeMillis() / 1000) + 3600);
        String startTime = Long.toString((System.currentTimeMillis() / 1000));

        String payload = "{\"iss\": \"" + iss + "\", \"scope\": \"" + scope + "\", \"aud\": \"" + aud
                + "\", \"exp\": \"" + expiry + "\", \"iat\": \"" + startTime + "\"}";

        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        // TODO: the password is hardcoded. This has to be read from the ctx or from the environment variable
        char[] password = "notasecret".toCharArray();
        FileInputStream iStream = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(iStream, password);
        } finally {
            try {
                iStream.close();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("Could not read the keystore file");
                throw new CloudException(e);
            }
        }
        String alias = "";

        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String keyStoreAlias = aliases.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) {
                alias = keyStoreAlias;
                break;
            }
        }

        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        Signature shaSignature = Signature.getInstance("SHA256withRSA");
        shaSignature.initSign(privateKey);
        shaSignature.update(token.toString().getBytes("UTF-8"));
        String signedToken = Base64.encodeBase64URLSafeString(shaSignature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedToken);
        return token.toString();

    } catch (Exception e) {
        e.printStackTrace();
        logger.error("Could not sign the payload with the private key");
        throw new CloudException(e);
    }
}