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:org.apache.geode.internal.net.SocketCreator.java

private TrustManager[] getTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    TrustManager[] trustManagers = null;
    GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();

    String trustStoreType = sslConfig.getTruststoreType();
    if (StringUtils.isEmpty(trustStoreType)) {
        // read from console, default on empty
        if (consoleReader.isSupported()) {
            trustStoreType = consoleReader
                    .readLine("Please enter the trustStoreType (javax.net.ssl.trustStoreType) : ");
        } else {/*from w  w  w .ja v a 2 s .  c  o m*/
            trustStoreType = KeyStore.getDefaultType();
        }
    }

    KeyStore ts = KeyStore.getInstance(trustStoreType);
    String trustStorePath = sslConfig.getTruststore();
    if (StringUtils.isEmpty(trustStorePath)) {
        if (consoleReader.isSupported()) {
            trustStorePath = consoleReader
                    .readLine("Please enter the trustStore location (javax.net.ssl.trustStore) : ");
        }
    }
    FileInputStream fis = new FileInputStream(trustStorePath);
    String passwordString = sslConfig.getTruststorePassword();
    char[] password = null;
    if (passwordString != null) {
        if (passwordString.trim().equals("")) {
            if (!StringUtils.isEmpty(passwordString)) {
                String toDecrypt = "encrypted(" + passwordString + ")";
                passwordString = PasswordUtil.decrypt(toDecrypt);
                password = passwordString.toCharArray();
            }
            // read from the console
            if (StringUtils.isEmpty(passwordString) && consoleReader.isSupported()) {
                password = consoleReader.readPassword(
                        "Please enter password for trustStore (javax.net.ssl.trustStorePassword) : ");
            }
        } else {
            password = passwordString.toCharArray();
        }
    }
    ts.load(fis, password);

    // default algorithm can be changed by setting property "ssl.TrustManagerFactory.algorithm" in
    // security properties
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);
    trustManagers = tmf.getTrustManagers();
    // follow the security tip in java doc
    if (password != null) {
        java.util.Arrays.fill(password, ' ');
    }

    return trustManagers;
}

From source file:de.uni_koblenz_landau.apow.helper.SyncHelper.java

/**
 * Creates a HTTPClient for usage with self signed SSL certificates.
 * // w  w  w. j  av  a  2 s.  com
 * Sources:
 * http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
 * http://havrl.blogspot.de/2013/08/synchronization-algorithm-for.html 
 * 
 * @return HTTPClient
 */
private static HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SelfSignedSSLSocketFactory(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:org.hyperledger.fabric.sdk.security.CryptoPrimitivesTest.java

@Test
public void testSetTrustStore() throws Throwable {

    try {/*from   ww w . j  ava2  s  .  c o m*/
        CryptoPrimitives myCrypto = new CryptoPrimitives();
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        //     myCrypto.setTrustStore(keyStore);
        TestUtils.invokeMethod(myCrypto, "setTrustStore", keyStore);
        assertSame(keyStore, myCrypto.getTrustStore());
    } catch (CryptoException | KeyStoreException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        fail("testSetTrustStore() should not have thrown Exception. Error: " + e.getMessage());
    }
}

From source file:org.miloss.fgsms.bueller.Bueller.java

protected void Init(boolean pooled) throws Exception {
    if ((System.currentTimeMillis() - 30000) < LastConfiguredAt && Configured) {
        log.log(Level.DEBUG, "already configured, using last known config");
        return;//  w ww .  j  a v  a2  s  . c  om
    }
    log.log(Level.INFO, "Refreshing configuration");
    LastConfiguredAt = System.currentTimeMillis();
    Configured = true;

    String tmp = System.getProperty("jboss.server.config.url");

    if (Utility.stringIsNullOrEmpty(tmp)) {
        //FIX for Jboss 7
        try {
            tmp = System.getProperty("jboss.server.config.dir");
            if (tmp != null && !tmp.equalsIgnoreCase("null")) {
                File f = new File(tmp);
                tmp = f.toURI().toURL().toString();
                tmp += File.separator;
            }
        } catch (Exception e) {
        }
    }
    //fix for tomcat
    if (Utility.stringIsNullOrEmpty(tmp)) {
        tmp = System.getProperty("catalina.home");
        if (tmp != null) {
            tmp = tmp + File.separator + "conf" + File.separator;
        }
    }
    //fix for OpenJDK/linux issues
    if (tmp != null) {
        String os = System.getProperty("os.name");
        if (os.toLowerCase().indexOf("win") == -1) {
            tmp = File.separator + tmp;
        }

    }
    X509HostnameVerifier hostnameVerifier = new org.apache.http.conn.ssl.StrictHostnameVerifier();
    KeyNameValueEnc d = DBSettingsLoader.GetPropertiesFromDB(pooled, "Bueller", "IgnoreSSLErrors");
    if (d != null && d.getKeyNameValue() != null) {
        try {
            ignoreSSL = Boolean.parseBoolean(d.getKeyNameValue().getPropertyValue());
        } catch (Exception ex) {
            ignoreSSL = false;
        }
    }
    if (ignoreSSL) {
        log.log(Level.WARN, "SSL Hostname verification turned off");
        hostnameVerifier = new AllowAllHostnameVerifier();
    }

    if (!Utility.stringIsNullOrEmpty(tmp)) {

        d = DBSettingsLoader.GetPropertiesFromDB(pooled, "defaults", "truststore");
        if (d != null && d.getKeyNameValue() != null) {
            truststore = tmp + d.getKeyNameValue().getPropertyValue();
        }
        d = DBSettingsLoader.GetPropertiesFromDB(pooled, "defaults", "truststorepass");
        if (d != null && d.getKeyNameValue() != null) {
            truststorepass = d.getKeyNameValue().getPropertyValue();
        }
        d = DBSettingsLoader.GetPropertiesFromDB(pooled, "defaults", "keystore");
        if (d != null && d.getKeyNameValue() != null) {
            keystore = tmp + d.getKeyNameValue().getPropertyValue();
        }
        d = DBSettingsLoader.GetPropertiesFromDB(pooled, "defaults", "keystorepass");
        if (d != null && d.getKeyNameValue() != null) {
            keystorepass = d.getKeyNameValue().getPropertyValue();
        }

        if (!(Utility.stringIsNullOrEmpty(truststore) && !Utility.stringIsNullOrEmpty(truststorepass)) && !Utility.stringIsNullOrEmpty(keystore) && !Utility.stringIsNullOrEmpty(keystorepass)) {

            KeyStore trustStore = null;
            FileInputStream instream = null;
            try {
                log.log(Level.INFO, "loading trust store from " + truststore);
                instream = new FileInputStream(new File(truststore.replace("file:/", "")));
                trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(instream, Utility.DE(truststorepass).toCharArray());
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
                trustStore = null;
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (Exception ex) {
                        log.log(Level.DEBUG, null, ex);
                    }
                }
            }
            KeyStore keyStore = null;

            try {
                log.log(Level.INFO, "loading key store from " + keystore);
                instream = new FileInputStream(new File(keystore.replace("file:/", "")));
                keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                keyStore.load(instream, Utility.DE(keystorepass).toCharArray());
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
                keyStore = null;
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (Exception ex) {
                        log.log(Level.DEBUG, null, ex);
                    }
                }
            }
            if (trustStore != null && keyStore != null) {
                sfpki = new org.apache.http.conn.ssl.SSLSocketFactory(org.apache.http.conn.ssl.SSLSocketFactory.TLS, keyStore, Utility.DE(keystorepass), trustStore, new SecureRandom(),
                        hostnameVerifier);
                //sf = new org.apache.http.conn.ssl.SSLSocketFactory(asdasdtrustStore, Utility.DE(truststorepass));
            } else if (trustStore != null) {
                sf = new org.apache.http.conn.ssl.SSLSocketFactory(trustStore, Utility.DE(truststorepass));
            }
        } else if (!(Utility.stringIsNullOrEmpty(truststore) && !Utility.stringIsNullOrEmpty(truststorepass))) {
            KeyStore trustStore = null;
            FileInputStream instream = new FileInputStream(new File(truststore.replace("file:/", "")));
            try {
                log.log(Level.INFO, "loading trust store from " + truststore);
                trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                trustStore.load(instream, Utility.DE(truststorepass).toCharArray());
            } catch (Exception ex) {
                log.log(Level.WARN, null, ex);
                trustStore = null;
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (Exception ex) {
                        log.log(Level.DEBUG, null, ex);
                    }
                }
            }
            if (trustStore != null) {
                sf = new org.apache.http.conn.ssl.SSLSocketFactory(trustStore, Utility.DE(truststorepass));
                sf.setHostnameVerifier(hostnameVerifier);
            }
        }

        //check system.properties for javax.net.ssl
        //load trust store and keystore from jboss?
        //setup ssl 
    } else {
        log.log(Level.WARN, "unable to determine the location to the key/trust stores because the environment variable jboss.server.config.url, jboss.server.config.dir and catalina.home are not defined. At least one must be set for SSL to function");
    }
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
   This method provides initializing connection. 
   If is installCert set to true - downloads server certificate and adds to truststore.
 *///w  w  w.  j  a  va2s  .c  o  m
private void init() throws InstallCertException, InitKeystoreException {
    try {
        KeyStore trustStore;
        FileInputStream instream;

        if (installCert) {
            trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InstallCert.install(servername, port, keystorePass);
            instream = new FileInputStream(new File(defKeystoreLocation));
            trustStore.load(instream, keystorePass.toCharArray());
            instream.close();
        } else {
            trustStore = loadJavaDefaultTruststore();
        }

        SSLSocketFactory socketFactory = new SSLSocketFactory(null, null, null, trustStore, null, null,
                SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme(SCHEME_HTTPS, port, socketFactory);
        client.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Exception e) {
        throw new InitKeystoreException();
    }
}

From source file:com.danielme.muspyforandroid.services.MuspyClient.java

private DefaultHttpClient getDefaultHttpClient() throws Exception {
    if (defaultHttpClient == null) {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);//from   w w w .j a v  a 2  s.  c om

        SSLSocketFactory sslSocketFactory = new MySSLSocketFactory(trustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sslSocketFactory, 443));

        defaultHttpClient = new DefaultHttpClient(
                new ThreadSafeClientConnManager(new BasicHttpParams(), registry), new BasicHttpParams());
    }

    return defaultHttpClient;
}

From source file:com.networknt.client.Client.java

private SSLContext sslContext()
        throws ClientException, IOException, NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = null;
    Map<String, Object> tlsMap = (Map) config.get(TLS);
    if (tlsMap != null) {
        SSLContextBuilder builder = SSLContexts.custom();
        // load trust store, this is the server public key certificate
        // first check if javax.net.ssl.trustStore system properties is set. It is only necessary if the server
        // certificate doesn't have the entire chain.
        Boolean loadTrustStore = (Boolean) tlsMap.get(LOAD_TRUST_STORE);
        if (loadTrustStore != null && loadTrustStore == true) {
            String trustStoreName = System.getProperty(TRUST_STORE_PROPERTY);
            String trustStorePass = System.getProperty(TRUST_STORE_PASSWORD_PROPERTY);
            if (trustStoreName != null && trustStorePass != null) {
                logger.info("Loading trust store from system property at " + Encode.forJava(trustStoreName));
            } else {
                trustStoreName = (String) tlsMap.get(TRUST_STORE);
                trustStorePass = (String) tlsMap.get(TRUST_PASS);
                logger.info("Loading trust store from config at " + Encode.forJava(trustStoreName));
            }/*from w w  w  .j a v  a  2 s  . c  om*/

            KeyStore trustStore = null;
            if (trustStoreName != null && trustStorePass != null) {
                InputStream trustStream = Config.getInstance().getInputStreamFromFile(trustStoreName);
                if (trustStream != null) {
                    try {
                        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        trustStore.load(trustStream, trustStorePass.toCharArray());
                        builder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
                    } catch (CertificateException ce) {
                        logger.error("CertificateException: Unable to load trust store.", ce);
                        throw new ClientException("CertificateException: Unable to load trust store.", ce);
                    } catch (KeyStoreException kse) {
                        logger.error("KeyStoreException: Unable to load trust store.", kse);
                        throw new ClientException("KeyStoreException: Unable to load trust store.", kse);
                    } finally {
                        trustStream.close();
                    }
                }
            }
        }

        // load key store for client certificate if two way ssl is used.
        Boolean loadKeyStore = (Boolean) tlsMap.get(LOAD_KEY_STORE);
        if (loadKeyStore != null && loadKeyStore == true) {
            String keyStoreName = (String) tlsMap.get(KEY_STORE);
            String keyStorePass = (String) tlsMap.get(KEY_PASS);
            KeyStore keyStore = null;
            if (keyStoreName != null && keyStorePass != null) {
                InputStream keyStream = Config.getInstance().getInputStreamFromFile(keyStoreName);
                if (keyStream != null) {
                    try {
                        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
                        keyStore.load(keyStream, keyStorePass.toCharArray());
                        builder.loadKeyMaterial(keyStore, keyStorePass.toCharArray());
                    } catch (CertificateException ce) {
                        logger.error("CertificateException: Unable to load key store.", ce);
                        throw new ClientException("CertificateException: Unable to load key store.", ce);
                    } catch (KeyStoreException kse) {
                        logger.error("KeyStoreException: Unable to load key store.", kse);
                        throw new ClientException("KeyStoreException: Unable to load key store.", kse);
                    } catch (UnrecoverableKeyException uke) {
                        logger.error("UnrecoverableKeyException: Unable to load key store.", uke);
                        throw new ClientException("UnrecoverableKeyException: Unable to load key store.", uke);
                    } finally {
                        keyStream.close();
                    }
                }
            }
        }
        sslContext = builder.build();
    }
    return sslContext;
}

From source file:com.basistech.ReleaseNoteMojo.java

private KeyStore readTrustStore(File trustStore) throws IOException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, KeyManagementException {
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    ByteSource keystoreByteSource = Files.asByteSource(trustStore);
    InputStream keystoreStream = null;
    try {//  w  w  w  .  ja  v a  2  s . c om
        keystoreStream = keystoreByteSource.openStream();
        //TODO: deal with the actual password whatever it is.
        // there's no good reason to use a fancy password on a trust store.
        keystore.load(keystoreStream, "changeit".toCharArray());
    } finally {
        IOUtils.closeQuietly(keystoreStream);
    }
    return keystore;
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslNeedsClientAuthenticationSucceedsWithClientCertificate() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    addTestTxtFile(factory);/*from  w w  w .ja  va  2s  .  c  om*/
    factory.setSsl(getSsl(ClientAuth.NEED, "password", "classpath:test.jks", "classpath:test.jks", null, null));
    this.webServer = factory.getWebServer();
    this.webServer.start();
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(new File("src/test/resources/test.jks")), "secret".toCharArray());
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                    .loadKeyMaterial(keyStore, "password".toCharArray()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    assertThat(getResponse(getLocalUrl("https", "/test.txt"), requestFactory)).isEqualTo("test");
}

From source file:zswi.protocols.communication.core.HTTPSConnection.java

/**
 * Provides Keystore object with integrated Java truststore.
 * @return Java truststore/*ww w . j a  va  2  s  .c  o m*/
 * @throws InitKeystoreException exception during keystore initialize
 */
private KeyStore loadJavaDefaultTruststore() throws InitKeystoreException {
    char SEP = File.separatorChar;
    File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security");
    File file = new File(dir, "jssecacerts");
    if (file.isFile() == false) {
        file = new File(dir, "cacerts");
    }

    try {
        InputStream in = new FileInputStream(file);
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(in, DEF_KS_PASS.toCharArray());
        in.close();
        return ks;
    } catch (Exception e) {
        throw new InitKeystoreException();
    }
}