Example usage for java.security KeyStore getDefaultType

List of usage examples for java.security KeyStore getDefaultType

Introduction

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

Prototype

public static final String getDefaultType() 

Source Link

Document

Returns the default keystore type as specified by the keystore.type security property, or the string "jks" (acronym for "Java keystore" ) if no such property exists.

Usage

From source file:net.solarnetwork.node.setup.test.DefaultSetupServiceTest.java

private synchronized KeyStore loadKeyStore() throws Exception {
    File ksFile = new File(KEYSTORE_PATH);
    InputStream in = null;//  w w  w. j a  v a2 s  . co  m
    String passwd = TEST_PW_VALUE;
    try {
        if (ksFile.isFile()) {
            in = new BufferedInputStream(new FileInputStream(ksFile));
        }
        return loadKeyStore(KeyStore.getDefaultType(), in, passwd);
    } catch (IOException e) {
        throw new CertificateException("Error opening file " + KEYSTORE_PATH, e);
    }
}

From source file:org.springframework.vault.config.ClientHttpRequestFactoryFactory.java

private static TrustManagerFactory createTrustManagerFactory(Resource trustFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    loadKeyStore(trustFile, storePassword, trustStore);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return trustManagerFactory;
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from   w  w  w . j  a v a  2 s . c  o m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.whitesource.agent.client.WssServiceClientImpl.java

/**
 * Constructor//from   ww  w .  j a v a2 s .  c o  m
 *
 * @param serviceUrl WhiteSource service URL to use.
 * @param setProxy WhiteSource set proxy, whether the proxy settings is defined or not.
 * @param connectionTimeoutMinutes WhiteSource connection timeout, whether the connection timeout is defined or not (default to 60 minutes).
 */
public WssServiceClientImpl(String serviceUrl, boolean setProxy, int connectionTimeoutMinutes,
        boolean ignoreCertificateCheck) {
    gson = new Gson();

    if (serviceUrl == null || serviceUrl.length() == 0) {
        this.serviceUrl = ClientConstants.DEFAULT_SERVICE_URL;
    } else {
        this.serviceUrl = serviceUrl;
    }

    if (connectionTimeoutMinutes <= 0) {
        this.connectionTimeout = ClientConstants.DEFAULT_CONNECTION_TIMEOUT_MINUTES * TO_MILLISECONDS;
    } else {
        this.connectionTimeout = connectionTimeoutMinutes * TO_MILLISECONDS;
    }

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, this.connectionTimeout);
    HttpConnectionParams.setSoTimeout(params, this.connectionTimeout);
    HttpClientParams.setRedirecting(params, true);

    httpClient = new DefaultHttpClient();

    if (ignoreCertificateCheck) {
        try {
            logger.warn("Security Warning - Trusting all certificates");

            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            char[] password = SOME_PASSWORD.toCharArray();
            keystore.load(null, password);

            WssSSLSocketFactory sf = new WssSSLSocketFactory(keystore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

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

            httpClient = new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    if (setProxy) {
        findDefaultProxy();
    }
}

From source file:org.ulyssis.ipp.publisher.HttpServerPublisher.java

private SSLContext sslContext() {
    try {// ww  w  .  j a  va2  s .c o m
        KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType());
        cks.load(new FileInputStream(options.getKeystore().get().toFile()),
                options.getKeystorePass().toCharArray());
        SSLContextBuilder builder = SSLContexts.custom();
        if (options.getTruststore().isPresent()) {
            KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
            tks.load(new FileInputStream(options.getTruststore().get().toFile()),
                    options.getTruststorePass().toCharArray());
            builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy());
        }
        return builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray()).build();
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
    return null;
}

From source file:com.netflix.spinnaker.orca.webhook.config.WebhookConfiguration.java

private Optional<KeyStore> getCustomKeyStore() {
    WebhookProperties.TrustSettings trustSettings = webhookProperties.getTrust();
    if (trustSettings == null || !trustSettings.isEnabled()
            || StringUtils.isEmpty(trustSettings.getTrustStore())) {
        return Optional.empty();
    }/*from  ww  w . j a v  a 2 s  .  c  o  m*/

    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }

    try (FileInputStream file = new FileInputStream(trustSettings.getTrustStore())) {
        keyStore.load(file, trustSettings.getTrustStorePassword().toCharArray());
    } catch (CertificateException | IOException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    return Optional.of(keyStore);
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTPs connection// w  w w  .  j  a va 2 s. com
 * 
 * @param sslPort
 *            the number of the port the server should be listening for
 *            SSL/TLS connections
 */
public void InitializeSecure(int sslPort) {
    if (sslPort != -1) {
        SSLSocketFactory sslf = null;
        SSLSocket s = null;
        port = sslPort;
        try {
            // notifyOfProggress(false);
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
            trusted.load(null, null);

            sslf = new MySSLSocketFactory(trusted);
            Log.w("Android mobile voting", "1");
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Log.w("Android mobile voting", "2");
            BasicHttpParams params = new BasicHttpParams();
            Log.w("Android mobile voting", "3");
            HttpConnectionParams.setConnectionTimeout(params, 500);
            Log.w("Android mobile voting", "4");
            s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0,
                    params);
            if (exc) {
                SSLSession ssls = null;
                ssls = s.getSession();
                final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain();

                for (int i = 0; i < x.length; i++) {

                    parent.mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            try {
                                parent.askForTrust(getThumbPrint(x[0]), instance);
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (CertificateEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (final Exception ex) {
                                parent.mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        parent.showToast(ex.toString());

                                    }

                                });
                                Log.w("Android Mobile Voting", "400 Error");
                                parent.finish();
                            }

                        }
                    });

                }

            }

            s.startHandshake();

            Scheme https = new Scheme("https", sslf, sslPort);

            schemeRegistry.register(https);
            usingScheme = "https";
            port = sslPort;
            if (!exc)
                retrieveQuestions();
        } catch (final Exception ex) {
            parent.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    parent.showToast(ex.toString());

                }

            });
            // Log.w("Android Mobile Voting", "400 Error");
            parent.finish();

        }
    } else {
        parent.mHandler.post(new Runnable() {

            @Override
            public void run() {
                parent.showNoSSLDialog(instance);

            }

        });
    }

}

From source file:edu.washington.iam.tools.IamConnectionManager.java

protected void initManagers() {

    // trust managers
    /**/*  w  w  w. j av  a 2  s  .  com*/
           try {
               TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            
               X509Certificate cert = null;
               if (caFilename!=null) cert = readCertificate(caFilename);
               log.debug("init trust mgr " + cert);
               trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
               trustStore.load(null, null);
               trustStore.setCertificateEntry("CACERT", cert);
               tmf.init(trustStore);
               trustManagers = tmf.getTrustManagers();
           } catch (Exception e) {
               log.error("cacert error: " + e);
           }
     **/
    trustManagers = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
            return;
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
            return;
        }
    } };

    // key managers
    if (certFilename != null && keyFilename != null) {
        try {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);

            X509Certificate cert = readCertificate(certFilename);
            PKCS1 pkcs = new PKCS1();
            PrivateKey key = pkcs.readKey(keyFilename);

            X509Certificate[] chain = new X509Certificate[1];
            chain[0] = cert;
            keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain);

            kmf.init(keyStore, "pw".toCharArray());
            keyManagers = kmf.getKeyManagers();
        } catch (Exception e) {
            log.error("cert/key error: " + e);
        }
    }

}

From source file:org.seedstack.seed.crypto.internal.EncryptionServiceFactoryTest.java

/**
 * Test method for/*from ww w  .  ja  v a  2s  .  c  o m*/
 * {@link org.seedstack.seed.crypto.internal.EncryptionServiceFactory#createEncryptionService(org.seedstack.seed.crypto.internal.KeyStoreDefinition, org.seedstack.seed.crypto.internal.CertificateDefinition)}
 * . Test a {@link KeyStoreException} if no Provider supports a KeyStoreSpi implementation for the specified type.
 *
 * @throws Exception if an error occurred
 */
@Test(expected = RuntimeException.class)
public void testCreateEncryptionServiceWithKeystoreException(
        @Mocked final KeyStoreDefinition keyStoreDefinition,
        @Mocked final CertificateDefinition certificateDefinition,
        @SuppressWarnings("unused") @Mocked final KeyStore keyStore) throws Exception {
    new Expectations() {
        final String pathToKeystore = "pathToKeystore";

        {
            keyStoreDefinition.getPath();
            returns(pathToKeystore);

            KeyStore.getInstance(KeyStore.getDefaultType());
            result = new KeyStoreException("dummy exception");
        }
    };

    EncryptionServiceFactory factory = new EncryptionServiceFactory();
    factory.createEncryptionService(keyStoreDefinition, certificateDefinition);

}

From source file:com.hybris.datahub.outbound.utils.RestTemplateUtil.java

private LayeredConnectionSocketFactory setUpSSL() {
    LayeredConnectionSocketFactory sslSF = null;
    try {/*from w w w.  ja  va2  s .c  o m*/
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        final SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
        sslSF = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    } catch (final Exception e) {
        LOGGER.error(e.getMessage());
    }
    return sslSF;
}