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.ws.security.components.crypto.MerlinDevice.java

@Override
public void loadProperties(Properties properties, ClassLoader loader) throws CredentialException, IOException {
    if (properties == null) {
        return;//from w ww  .  j ava2  s.c o  m
    }
    this.properties = properties;
    //
    // Load the provider(s)
    //
    String provider = properties.getProperty(CRYPTO_KEYSTORE_PROVIDER);
    if (provider != null) {
        provider = provider.trim();
    }
    String certProvider = properties.getProperty(CRYPTO_CERT_PROVIDER);
    if (certProvider != null) {
        setCryptoProvider(certProvider);
    }
    //
    // Load the KeyStore
    //
    String alias = properties.getProperty(KEYSTORE_ALIAS);
    if (alias != null) {
        alias = alias.trim();
        defaultAlias = alias;
    }
    String keyStoreLocation = properties.getProperty(KEYSTORE_FILE);
    if (keyStoreLocation == null) {
        keyStoreLocation = properties.getProperty(OLD_KEYSTORE_FILE);
    }
    String keyStorePassword = properties.getProperty(KEYSTORE_PASSWORD, "security");
    if (keyStorePassword != null) {
        keyStorePassword = keyStorePassword.trim();
    }
    String keyStoreType = properties.getProperty(KEYSTORE_TYPE, KeyStore.getDefaultType());
    if (keyStoreType != null) {
        keyStoreType = keyStoreType.trim();
    }
    if (keyStoreLocation != null) {
        keyStoreLocation = keyStoreLocation.trim();
        InputStream is = loadInputStream(loader, keyStoreLocation);

        try {
            keystore = load(is, keyStorePassword, provider, keyStoreType);
            if (DO_DEBUG) {
                LOG.debug("The KeyStore " + keyStoreLocation + " of type " + keyStoreType + " has been loaded");
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        keystore = load(null, keyStorePassword, provider, keyStoreType);
    }

    //
    // Load the TrustStore
    //
    String trustStorePassword = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
    if (trustStorePassword != null) {
        trustStorePassword = trustStorePassword.trim();
    }
    String trustStoreType = properties.getProperty(TRUSTSTORE_TYPE, KeyStore.getDefaultType());
    if (trustStoreType != null) {
        trustStoreType = trustStoreType.trim();
    }
    String loadCacerts = properties.getProperty(LOAD_CA_CERTS, "false");
    if (loadCacerts != null) {
        loadCacerts = loadCacerts.trim();
    }
    String trustStoreLocation = properties.getProperty(TRUSTSTORE_FILE);
    if (trustStoreLocation != null) {
        trustStoreLocation = trustStoreLocation.trim();
        InputStream is = loadInputStream(loader, trustStoreLocation);

        try {
            truststore = load(is, trustStorePassword, provider, trustStoreType);
            if (DO_DEBUG) {
                LOG.debug("The TrustStore " + trustStoreLocation + " of type " + trustStoreType
                        + " has been loaded");
            }
            loadCACerts = false;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else if (Boolean.valueOf(loadCacerts).booleanValue()) {
        String cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
        if (cacertsPath != null) {
            cacertsPath = cacertsPath.trim();
        }
        InputStream is = new FileInputStream(cacertsPath);
        try {
            String cacertsPasswd = properties.getProperty(TRUSTSTORE_PASSWORD, "changeit");
            if (cacertsPasswd != null) {
                cacertsPasswd = cacertsPasswd.trim();
            }
            truststore = load(is, cacertsPasswd, null, KeyStore.getDefaultType());
            if (DO_DEBUG) {
                LOG.debug("CA certs have been loaded");
            }
            loadCACerts = true;
        } finally {
            if (is != null) {
                is.close();
            }
        }
    } else {
        truststore = load(null, trustStorePassword, provider, trustStoreType);
    }
    //
    // Load the CRL file
    //
    String crlLocation = properties.getProperty(X509_CRL_FILE);
    if (crlLocation != null) {
        crlLocation = crlLocation.trim();
        InputStream is = loadInputStream(loader, crlLocation);

        try {
            CertificateFactory cf = getCertificateFactory();
            X509CRL crl = (X509CRL) cf.generateCRL(is);

            if (provider == null || provider.length() == 0) {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)));
            } else {
                crlCertStore = CertStore.getInstance("Collection",
                        new CollectionCertStoreParameters(Collections.singletonList(crl)), provider);
            }
            if (DO_DEBUG) {
                LOG.debug("The CRL " + crlLocation + " has been loaded");
            }
        } catch (Exception e) {
            if (DO_DEBUG) {
                LOG.debug(e.getMessage(), e);
            }
            throw new CredentialException(CredentialException.IO_ERROR, "ioError00", e);
        } finally {
            if (is != null) {
                is.close();
            }
        }
    }
}

From source file:com.netflix.spinnaker.halyard.config.validate.v1.security.SamlValidator.java

@Override
public void validate(ConfigProblemSetBuilder p, Saml saml) {
    if (!saml.isEnabled()) {
        return;/* ww w .ja  v  a2 s  .  co  m*/
    }

    if (StringUtils.isEmpty(saml.getMetadataLocal()) && StringUtils.isEmpty(saml.getMetadataRemote())) {
        p.addProblem(Problem.Severity.ERROR, "No metadata file specified.");
    }

    if (StringUtils.isNotEmpty(saml.getMetadataLocal())) {
        try {
            new File(new URI("file:" + saml.getMetadataLocal()));
        } catch (Exception f) {
            p.addProblem(Problem.Severity.ERROR, f.getMessage());
        }
    }

    if (StringUtils.isNotEmpty(saml.getMetadataRemote())) {
        try {
            HttpClientBuilder.create().build().execute(new HttpGet(saml.getMetadataRemote()));
        } catch (IOException e) {
            p.addProblem(Problem.Severity.WARNING, "Cannot access remote metadata.xml file: " + e.getMessage());
        }
    }

    if (StringUtils.isEmpty(saml.getIssuerId())) {
        p.addProblem(Problem.Severity.ERROR, "No issuerId specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStore())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStorePassword())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore password specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStoreAliasName())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore alias specified.");
    }

    InputStream is = null;
    try {
        File f = new File(new URI("file:" + saml.getKeyStore()));
        is = new FileInputStream(f);
        val keystore = KeyStore.getInstance(KeyStore.getDefaultType());

        // will throw an exception if `keyStorePassword` is invalid
        keystore.load(is, saml.getKeyStorePassword().toCharArray());

        Collections.list(keystore.aliases()).stream()
                .filter(alias -> alias.equalsIgnoreCase(saml.getKeyStoreAliasName())).findFirst()
                .orElseThrow(() -> new RuntimeException(
                        "Keystore does not contain alias " + saml.getKeyStoreAliasName()));

    } catch (Exception e) {
        p.addProblem(Problem.Severity.ERROR, "Keystore validation problem: " + e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                // ignored.
            }
        }
    }

    if (saml.getServiceAddress() == null) {
        p.addProblem(Problem.Severity.ERROR, "No service address specified.");
    } else if (!saml.getServiceAddress().getProtocol().equalsIgnoreCase("https")) {
        p.addProblem(Problem.Severity.WARNING, "Gate should operate on HTTPS");
    }
}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java

private synchronized KeyStore getKeystore() throws IOException {
    String type = null;/*from  w  w  w  .ja  v a 2 s .  c o m*/
    try {
        if (null == _keystore) {
            // Get the key manager factory for the default algorithm.
            final Preferences preferences = PreferencesFactory.get();
            type = preferences.getProperty("connection.ssl.keystore.type");
            if (log.isInfoEnabled()) {
                log.info(String.format("Load default store of type %s", type));
            }
            if (null == type) {
                type = KeyStore.getDefaultType();
            }
            final String provider = preferences.getProperty("connection.ssl.keystore.provider");
            if (StringUtils.isBlank(provider)) {
                _keystore = KeyStore.getInstance(type);
            } else {
                _keystore = KeyStore.getInstance(type, provider);
            }
            // Load default key store
            _keystore.load(null, null);
        }
    } catch (Exception e) {
        try {
            log.error(String.format("Could not load default store of type %s", type), e);
            if (log.isInfoEnabled()) {
                log.info("Load default store of default type");
            }
            _keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            _keystore.load(null, null);
        } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException ex) {
            log.error(String.format("Initialization of key store failed. %s", e.getMessage()));
            throw new IOException(e);
        }
    }
    return _keystore;
}

From source file:com.tlabs.eve.HttpClientTest.java

@BeforeClass
public static final void setHttpClient() throws Exception {
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    //FIXME check about the deprecated
    try {/*from ww w .  j  a va2s. c  om*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sslf = new NoCheckSSLSocketFactory(trustStore);
        sslf.setHostnameVerifier(new AllowAllHostnameVerifier());
        schemeRegistry.register(new Scheme("https", sslf, 443));
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    connectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
}

From source file:org.structr.util.StructrLicenseVerifier.java

private StructrLicenseVerifier(final String keystoreFileName, final String password) {

    logger.info("Starting license server..");

    try {/*from www  . ja va2  s  .  c  om*/

        logger.info("Loading key store, initializing ciphers..");

        this.gson = new GsonBuilder().setPrettyPrinting().create();
        this.keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        this.blockCipher = Cipher.getInstance(StructrLicenseManager.KeyEncryptionAlgorithm);
        this.streamCipher = Cipher.getInstance(StructrLicenseManager.DataEncryptionAlgorithm);
        this.signer = Signature.getInstance(StructrLicenseManager.SignatureAlgorithm);

        try (final InputStream is = new FileInputStream(keystoreFileName)) {

            keyStore.load(is, password.toCharArray());

            this.key = keyStore.getKey("structr", password.toCharArray());

            blockCipher.init(Cipher.DECRYPT_MODE, key);
        }

    } catch (Throwable t) {
        logger.warn("Unable to initialize key store or ciphers: {}", t.getMessage());
    }
}

From source file:org.rhq.modules.plugins.jbossas7.SchemeRegistryBuilder.java

public SchemeRegistry buildSchemeRegistry() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (asConnectionParams.isSecure()) {
        SSLSocketFactory sslSocketFactory;
        try {//from   w w w .j a  v  a  2s  .co m
            KeyStore truststore = null;
            if (asConnectionParams.getTruststore() != null) {
                truststore = loadKeystore( //
                        asConnectionParams.getTruststoreType(), //
                        asConnectionParams.getTruststore(), //
                        asConnectionParams.getTruststorePassword() //
                );
            }
            KeyStore keystore = null;
            String keyPassword = null;
            if (asConnectionParams.isClientcertAuthentication()) {
                if (asConnectionParams.getKeystore() == null) {
                    keystore = loadKeystore( //
                            System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()), //
                            System.getProperty("javax.net.ssl.keyStore"), //
                            System.getProperty("javax.net.ssl.keyStorePassword") //
                    );
                } else {
                    keystore = loadKeystore( //
                            asConnectionParams.getKeystoreType(), //
                            asConnectionParams.getKeystore(), //
                            asConnectionParams.getKeystorePassword() //
                    );
                    keyPassword = asConnectionParams.getKeyPassword();
                }
            }
            sslSocketFactory = new SSLSocketFactory(null, keystore, keyPassword, truststore, null,
                    getTrustStrategy(), getHostnameVerifier());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        schemeRegistry.register(new Scheme(HTTPS_SCHEME, asConnectionParams.getPort(), sslSocketFactory));
    } else {
        schemeRegistry.register(
                new Scheme(HTTP_SCHEME, asConnectionParams.getPort(), PlainSocketFactory.getSocketFactory()));
    }
    return schemeRegistry;
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, JSONObject json) {
    try {/*from   ww  w.j  a  v a2  s .  co m*/
        AsyncHttpClient client = new AsyncHttpClient();
        StringEntity se = null;
        try {
            se = new StringEntity(json.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), se, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:org.bigmouth.nvwa.network.http.HttpClientHelper.java

@SuppressWarnings("deprecation")
private static HttpClient getHttpClient(File keystore, char[] pwd, ClientConnectionManager ccm, int port,
        int timeout) throws Exception {
    SchemeRegistry sr = ccm.getSchemeRegistry();
    KeyStore truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    truststore.load(new FileInputStream(keystore), pwd);
    SSLSocketFactory socketFactory = new SSLSocketFactory(truststore);
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sr.register(new Scheme("https", port, socketFactory));
    HttpClient httpClient = new DefaultHttpClient(ccm);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_KEEPALIVE, true);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
    return httpClient;
}

From source file:com.screenslicer.common.LenientHttpsConfig.java

private LenientHttpsConfig() {
    AsyncHttpClientConfig configTmp = null;
    SSLContext sslContextTmp = null;
    try {//from   w  ww  .j a  v  a 2 s . c  o  m
        AsyncHttpClient client = new AsyncHttpClient();
        configTmp = client.getConfig();
        IOUtils.closeQuietly(client);
        client = null;

        X509Certificate cert = (X509Certificate) CertificateFactory.getInstance("X.509")
                .generateCertificate(CommonUtil.class.getResourceAsStream("screenslicer.internal.cert"));
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        keyStore.setCertificateEntry(cert.getSubjectX500Principal().getName(), cert);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance("SunX509");
        keyManager.init(keyStore, null);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance("X509");
        trustManager.init(keyStore);
        sslContextTmp = SSLContext.getInstance("TLS");
        sslContextTmp.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
    } catch (Throwable t) {
    }
    config = configTmp;
    sslContext = sslContextTmp;
}

From source file:com.cellobject.oikos.util.NetworkHelper.java

public HttpClient createHttpClient() {
    try {//from  w w w.  j  a va 2s  .  co  m
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        final SSLSocketFactory sf = new IISSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        final HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));
        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        return new DefaultHttpClient();
    }
}