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.vkassin.mtrade.CSPLicense.java

public HttpClient getNewHttpClient() {
    try {// ww  w.j  a  va2  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", 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:com.axelor.apps.account.ebics.client.HttpRequestSender.java

private DefaultHttpClient getSecuredHttpClient(Certificate cert) throws AxelorException {

    DefaultHttpClient client = new DefaultHttpClient();

    try {/* w  w  w  .j  a va  2  s . c  o  m*/
        KeyStore keystore = KeyStore.getInstance("jks");
        char[] password = "NoPassword".toCharArray();
        keystore.load(null, password);
        keystore.setCertificateEntry("certficate.host", cert);
        Scheme https = new Scheme("https", 443, new SSLSocketFactory(keystore));
        client.getConnectionManager().getSchemeRegistry().register(https);
    } catch (Exception e) {
        e.printStackTrace();
        throw new AxelorException(I18n.get("Error adding certificate"), IException.TECHNICAL);
    }

    return client;
}

From source file:io.github.thefishlive.updater.HttpServer.java

public void run() {
    try {/*from w ww .  j a v  a2s .  co  m*/
        int port = GitUpdater.port;

        // Set up the HTTP protocol processor
        HttpProcessor httpproc = HttpProcessorBuilder.create().add(new ResponseDate())
                .add(new ResponseServer("GitUpdater/1.0-SNAPSHOT")).add(new ResponseContent())
                .add(new ResponseConnControl()).build();

        // Set up request handlers
        UriHttpRequestHandlerMapper reqistry = new UriHttpRequestHandlerMapper();
        reqistry.register("*", new ResponceHandler());

        // Set up the HTTP service
        HttpService httpService = new HttpService(httpproc, reqistry);

        SSLServerSocketFactory sf = null;
        if (port == 8443) {
            // Initialize SSL context
            ClassLoader cl = getClass().getClassLoader();
            URL url = cl.getResource("my.keystore");
            if (url == null) {
                System.out.println("Keystore not found");
                System.exit(1);
            }
            KeyStore keystore = KeyStore.getInstance("jks");
            keystore.load(url.openStream(), "secret".toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, "secret".toCharArray());
            KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            sf = sslcontext.getServerSocketFactory();
        }

        try {
            Thread t = new RequestListenerThread(port, httpService, sf);
            t.setDaemon(false);
            t.start();
        } catch (BindException ex) {
            System.out.println("Error binding to port " + port);
            System.out.println("Perhaps another server is running on that port");
            return;
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.thoughtworks.go.security.KeyStoreManager.java

@Deprecated // Need to move the logic into this class so we don't have to touch the KeyStore in our code
public KeyStore load(File keystoreFile, String password) throws Exception {
    FileInputStream inputStream = null;
    try {/*from www.  jav a2 s . c  o  m*/
        KeyStore store = KeyStore.getInstance(KEYSTORE_TYPE);
        inputStream = maybeInputStream(keystoreFile);
        store.load(inputStream, maybePassword(password));
        return store;
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:net.di2e.ecdr.security.ssl.client.cxf.CxfSSLClientConfigurationImpl.java

@Override
public void configurationUpdateCallback(Map<String, String> updatedConfiguration) {
    if (updatedConfiguration != null) {
        String keystore = updatedConfiguration.get(ConfigurationManager.KEY_STORE);
        String keystorePassword = updatedConfiguration.get(ConfigurationManager.KEY_STORE_PASSWORD);

        KeyManager[] keyManagers = null;
        if (StringUtils.isNotBlank(keystore) && keystorePassword != null) {
            try {
                KeyManager manager = KeyManagerUtils.createClientKeyManager(new File(keystore),
                        keystorePassword);
                keyManagers = new KeyManager[1];
                keyManagers[0] = manager;

            } catch (IOException | GeneralSecurityException ex) {
                LOGGER.debug("Could not access keystore {}, using default java keystore.", keystore);
            }/*from  w  w  w. j a  v a 2 s .  c  o m*/
        }

        String trustStoreLocation = updatedConfiguration.get(ConfigurationManager.TRUST_STORE);
        String trustStorePassword = updatedConfiguration.get(ConfigurationManager.TRUST_STORE_PASSWORD);
        TrustManager[] trustManagers = null;
        if (StringUtils.isNotBlank(trustStoreLocation) && trustStorePassword != null) {
            try (FileInputStream fis = new FileInputStream(trustStoreLocation)) {
                KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                try {
                    trustStore.load(fis,
                            StringUtils.isNotEmpty(trustStorePassword) ? trustStorePassword.toCharArray()
                                    : null);
                    trustManagers = new TrustManager[1];
                    trustManagers[0] = TrustManagerUtils.getDefaultTrustManager(trustStore);
                } catch (IOException ioe) {
                    LOGGER.debug("Could not load truststore {}, using default java truststore");
                }
            } catch (IOException | GeneralSecurityException ex) {
                LOGGER.debug("Could not access truststore {}, using default java truststore.",
                        trustStoreLocation);
            }
        }
        synchronized (tlsClientParameters) {
            LOGGER.debug(
                    "Setting the CXF KeyManager and TrustManager based on the Platform Global Configuration values");
            tlsClientParameters.setKeyManagers(keyManagers);
            tlsClientParameters.setTrustManagers(trustManagers);
        }
    }
}

From source file:org.commonjava.indy.httprox.ProxyHttpsTest.java

protected KeyStore getTrustStore(File jks) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream instream = new FileInputStream(jks)) {
        trustStore.load(instream, "passwd".toCharArray());
    }//from  ww w. j a v  a2  s . com
    return trustStore;
}

From source file:be.fedict.hsm.model.KeyStoreLoaderBean.java

private Map<String, PrivateKeyEntry> loadPKCS11(KeyStoreEntity keyStoreEntity) throws KeyStoreException,
        IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableEntryException {
    File tmpConfigFile = File.createTempFile("pkcs11-", ".conf");
    tmpConfigFile.deleteOnExit();/*  w  w w  . ja  v a  2 s.  c om*/
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile));
    configWriter.println("name=HSM-" + keyStoreEntity.getId());
    String path = keyStoreEntity.getPath();
    LOG.debug("PKCS11 path: " + path);
    LOG.debug("slot list index: " + keyStoreEntity.getSlotListIndex());
    configWriter.println("library=" + path);
    configWriter.println("slotListIndex=" + keyStoreEntity.getSlotListIndex());
    configWriter.close();
    SunPKCS11 sunPKCS11 = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    LOG.debug("adding SunPKCS11 JCA provider: " + sunPKCS11.getName());
    /*
     * Reloads also need to work properly.
     */
    Security.removeProvider(sunPKCS11.getName());
    Security.addProvider(sunPKCS11);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", sunPKCS11);
    if (null != keyStoreEntity.getPassword()) {
        keyStore.load(null, keyStoreEntity.getPassword().toCharArray());
    } else {
        keyStore.load(null, null);
    }
    String keyStorePassword = keyStoreEntity.getPassword();
    return loadKeys(keyStoreEntity, keyStore, keyStorePassword);
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {// w  w w . j a  v a 2s .  c  om
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

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

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

From source file:com.google.samples.apps.abelana.AbelanaThings.java

public AbelanaThings(Context ctx, String phint) {
    final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
    final HttpTransport httpTransport = new NetHttpTransport();
    Resources r = ctx.getResources();
    byte[] android, server;
    byte[] password = new byte[32];

    android = Base64.decode("vW7CmbQWdPjpdfpBU39URsjHQV50KEKoSfafHdQPSh8",
            Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    server = Base64.decode(phint, Base64.URL_SAFE);

    int i = 0;// w  w w. jav  a 2s. co  m
    for (byte b : android) {
        password[i] = (byte) (android[i] ^ server[i]);
        i++;
    }
    byte[] pw = Base64.encode(password, Base64.URL_SAFE + Base64.NO_PADDING + Base64.NO_WRAP);
    String pass = new String(pw);

    if (storage == null) {
        try {
            KeyStore keystore = KeyStore.getInstance("PKCS12");
            keystore.load(r.openRawResource(R.raw.abelananew), pass.toCharArray());

            credential = new GoogleCredential.Builder().setTransport(httpTransport).setJsonFactory(jsonFactory)
                    .setServiceAccountId(r.getString(R.string.service_account))
                    .setServiceAccountScopes(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL))
                    .setServiceAccountPrivateKey((PrivateKey) keystore.getKey("privatekey", pass.toCharArray()))
                    .build();

            storage = new Storage.Builder(httpTransport, jsonFactory, credential)
                    .setApplicationName(r.getString(R.string.app_name) + "/1.0").build();

        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("loaded");
    }
}

From source file:com.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java

protected File generateCertificateKeystore(KeyStoreType keystoreType) throws Exception {
    KeyPair keyPair = generateKeyPair();
    X509Certificate cert = generateCertificate(keyPair);

    KeyStore keyStore = KeyStore.getInstance(keystoreType.getJavaValue());
    keyStore.load(null, KEYSTORE_PASSWORD.toCharArray());
    keyStore.setKeyEntry("foo", keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(),
            new Certificate[] { cert });
    File keystoreFile = keystoreFolder.newFile("keystore " + System.currentTimeMillis() + ".jks");
    try (FileOutputStream fos = new FileOutputStream(keystoreFile)) {
        keyStore.store(fos, KEYSTORE_PASSWORD.toCharArray());
    }//from  ww w  .j a v a  2s. c  o m
    return keystoreFile;
}