Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

In this page you can find the example usage for java.security KeyStore getInstance.

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

From source file:com.mobiaware.auction.notify.impl.PushNotificationService.java

private PushNotificationService() {
    PropertyManager pm = new PropertyManager("notification.properties",
            System.getProperty("NOTIFICATION_CONFIG"));

    String keystore = pm.getString("apns.keystore");
    String password = pm.getString("apns.password");
    boolean sandbox = Boolean.parseBoolean(pm.getString("apns.sandbox"));

    InputStream is = null;//from w  w  w . jav  a 2s . com

    try {
        is = new FileInputStream(keystore);

        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(is, password.toCharArray());

        ApnsEnvironment environment = sandbox ? ApnsEnvironment.getSandboxEnvironment()
                : ApnsEnvironment.getProductionEnvironment();

        SSLContext context = PushManagerFactory.createDefaultSSLContext(keyStore, password.toCharArray());

        PushManagerFactory<SimpleApnsPushNotification> pushManagerFactory = new PushManagerFactory<SimpleApnsPushNotification>(
                environment, context);

        _pushManager = pushManagerFactory.buildPushManager();
        _pushManager.registerRejectedNotificationListener(new PushManagerRejectedNotificationListener());
    } catch (NoSuchAlgorithmException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (CertificateException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (IOException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (KeyStoreException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (UnrecoverableKeyException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } catch (KeyManagementException e) {
        LOG.error(Throwables.getStackTraceAsString(e));
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java

/**
 * import trust from truststore file/*from  w w w .  j a  v  a 2  s. c om*/
 *
 * @param applicationContext
 * @param trustStore
 * @param trustStorePassword
 */
private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext,
        String trustStore, String trustStorePassword) {
    if (trustStore != null) {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(applicationContext.getResource(trustStore).getInputStream(),
                    trustStorePassword.toCharArray());
            Enumeration<String> aliases = keystore.aliases();

            List<X509Certificate> certCollect = new ArrayList<X509Certificate>();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();

                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null && certs.length > 0)
                    for (Certificate cert : certs)
                        if (cert instanceof X509Certificate)
                            certCollect.add((X509Certificate) cert);

                Certificate cert = keystore.getCertificate(alias);
                if (cert != null && cert instanceof X509Certificate) {
                    certCollect.add((X509Certificate) cert);
                }
            }

            if (certCollect.size() > 0)
                sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0]));

        } catch (Exception e) {
            log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e);
        }
    }
}

From source file:com.spotify.docker.client.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//from ww  w . ja va 2s.com
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:es.mityc.firmaJava.libreria.utilidades.GetPKCS12Keys.java

/** Crea una nueva instancia de GetPKCS12Keys
 *  @param fichero//from w w  w.j  av a2  s  . c om
 *  @param contrasea
 */
public GetPKCS12Keys(String fichero, String contrasenia) throws PKCS12Error {
    InputStream fis = null;
    try {
        //Carga la configuracin
        configuracion.cargarConfiguracion();
        //Establece el idioma segn la configuracin
        String locale = configuracion.getValor(LOCALE);
        // Configura el idioma
        I18n.setLocale(locale, locale.toUpperCase());
        if (contrasenia == null) {
            throw new PKCS12Error(I18n.getResource(LIBRERIAXADES_GETPKCS12KEYS_TEXTO_1));
        }
        if (fichero == null || fichero.trim().equals(CADENA_VACIA)) {
            throw new PKCS12Error(I18n.getResource(LIBRERIAXADES_GETPKCS12KEYS_TEXTO_2));
        }

        this.contrasenia = contrasenia;
        this.fichero = fichero;
        ks = KeyStore.getInstance(PKCS12);
        fis = new FileInputStream(fichero);
        ks.load(fis, contrasenia.toCharArray());
        Enumeration e = ks.aliases();

        while (e.hasMoreElements()) {
            String alias = (String) e.nextElement();
            if (ks.isKeyEntry(alias)) {
                claveAlias = alias;
                break;
            }
        }
        if (claveAlias == null) {
            throw new PKCS12Error(I18n.getResource(LIBRERIAXADES_GETPKCS12KEYS_TEXTO_3));
        }

    } catch (KeyStoreException e) {
        throw new PKCS12Error(e.getMessage());
    } catch (FileNotFoundException e) {
        throw new PKCS12Error(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new PKCS12Error(e.getMessage());
    } catch (CertificateException e) {
        throw new PKCS12Error(e.getMessage());
    } catch (IOException e) {
        throw new PKCS12Error(e.getMessage());
    }

    finally {

        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error(e);
            }
        }

    }
}

From source file:net.ymate.framework.commons.HttpClientHelper.java

public static SSLConnectionSocketFactory createConnectionSocketFactory(String certType, URL certFilePath,
        char[] passwordChars) throws KeyStoreException, IOException, CertificateException,
        NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    if (StringUtils.isBlank(certType)) {
        throw new NullArgumentException("certType");
    }//w w  w  .  ja v a 2s .  c  o m
    if (certFilePath == null) {
        throw new NullArgumentException("certFilePath");
    }
    if (ArrayUtils.isEmpty(passwordChars)) {
        throw new NullArgumentException("passwordChars");
    }
    KeyStore _keyStore = KeyStore.getInstance(certType);
    InputStream _certFileStream = null;
    try {
        _certFileStream = certFilePath.openStream();
        _keyStore.load(_certFileStream, passwordChars);
    } finally {
        IOUtils.closeQuietly(_certFileStream);
    }
    SSLContext _sslContext = SSLContexts.custom().loadKeyMaterial(_keyStore, passwordChars).build();
    return new SSLConnectionSocketFactory(_sslContext, new String[] { "TLSv1" }, null,
            new DefaultHostnameVerifier());
}

From source file:com.loopj.android.http.sample.CustomCASample.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {//from w  ww .j a  v a  2 s .  com
        InputStream is = null;
        try {
            // Configure the library to use a custom 'bks' file to perform
            // SSL negotiation.
            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
            is = getResources().openRawResource(R.raw.store);
            store.load(is, STORE_PASS.toCharArray());
            getAsyncHttpClient().setSSLSocketFactory(new SecureSocketFactory(store, STORE_ALIAS));
        } catch (IOException e) {
            throw new KeyStoreException(e);
        } catch (CertificateException e) {
            throw new KeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new KeyStoreException(e);
        } catch (KeyManagementException e) {
            throw new KeyStoreException(e);
        } catch (UnrecoverableKeyException e) {
            throw new KeyStoreException(e);
        } finally {
            AsyncHttpClient.silentCloseInputStream(is);
        }
    } catch (KeyStoreException e) {
        Log.e(LOG_TAG, "Unable to initialize key store", e);
        showCustomCAHelp();
    }
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {/*  ww w.j a  v a  2s .co m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    client = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return client;
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

protected static TrustManager[] createTrustManager(JSONObject sslConf) {
    TrustManager[] tms = null;// w  w w .j av  a2 s . co  m
    try {

        String TRUST_STORE = "etc/conf/trust.jks";
        String TRUST_STORE_PASSWORD = "Changeme_123";
        String TRUST_STORE_TYPE = "jks";
        if (sslConf != null) {
            TRUST_STORE = sslConf.getString("trustStore");
            TRUST_STORE_PASSWORD = sslConf.getString("trustStorePass");
            TRUST_STORE_TYPE = sslConf.getString("trustStoreType");
        }
        FileInputStream f_trustStore = new FileInputStream(TRUST_STORE);
        KeyStore ks = KeyStore.getInstance(TRUST_STORE_TYPE);
        ks.load(f_trustStore, TRUST_STORE_PASSWORD.toCharArray());
        f_trustStore.close();

        String alg = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);
        tmFact.init(ks);
        tms = tmFact.getTrustManagers();

    } catch (Exception e) {
        LOG.error("create TrustManager fail!", e);
    }
    return tms;
}

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

public void run() {
    try {/* www.j a  v a2  s  .  com*/
        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();
    }
}