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.gw2InfoViewer.factories.HttpsConnectionFactory.java

public static HttpClient getHttpsClientWithProxy(byte[] sslCertificateBytes, String proxyAddress,
        int proxyPort) {
    DefaultHttpClient httpClient;/*from  ww  w  . ja v  a  2  s  . c  o m*/
    Certificate[] sslCertificate;
    HttpHost proxy;

    httpClient = new DefaultHttpClient();
    try {
        sslCertificate = convertByteArrayToCertificate(sslCertificateBytes);

        TrustManagerFactory tf = TrustManagerFactory.getInstance("X509");
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null);
        for (int i = 0; i < sslCertificate.length; i++) {
            ks.setCertificateEntry("StartCom" + i, sslCertificate[i]);
        }

        tf.init(ks);
        TrustManager[] tm = tf.getTrustManagers();

        SSLContext sslCon = SSLContext.getInstance("SSL");
        sslCon.init(null, tm, new SecureRandom());
        SSLSocketFactory socketFactory = new SSLSocketFactory(ks);
        Scheme sch = new Scheme("https", 443, socketFactory);

        proxy = new HttpHost(proxyAddress, proxyPort, "https");
        httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

        httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException | UnrecoverableKeyException ex) {
        Logger.getLogger(HttpsConnectionFactory.class.getName()).log(Level.SEVERE, null, ex);
    }

    return httpClient;
}

From source file:org.viafirma.nucleo.validacion.KeyStoreLoader.java

/**
 * Load keystore of the default type from the specified file, using the
 * specified password.//from w  w w.j  a v  a 2s  .co  m
 * 
 * @param file
 *            file to read keystore from
 * @param passwd
 *            keystore password
 * 
 * @return keystore loaded from the file
 * @throws IOException
 *             if there is an I/O or format problem with the keystore data
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 * @throws NoSuchAlgorithmException
 *             if the algorithm used to check the integrity of the keystore
 *             cannot be found
 */
private static KeyStore loadKeystore(File file, char[] passwd)
        throws IOException, CertificateException, NoSuchAlgorithmException {
    try {
        return loadKeystore(file, passwd, KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        throw new RuntimeException("FATAL: keystore type \"" + KeyStore.getDefaultType() + "\" not supported");
    }
}

From source file:org.hawkular.client.RestFactory.java

public HttpClient getHttpClient() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {//from  w w  w.  ja  v a  2 s .  com
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;

    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        return null;
    }
}

From source file:com.rumblefish.friendlymusic.api.WebRequest.java

public static HttpClient getNewHttpClient(int timelimit) {
    try {/* ww w .j av a2  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);
        HttpConnectionParams.setConnectionTimeout(params, timelimit);
        HttpConnectionParams.setSoTimeout(params, timelimit);

        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) {
        e.printStackTrace();
        return new DefaultHttpClient();
    }
}

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

public void executePut(String putURL, RequestParams params, String filename) {
    try {//w  w w  . ja  v a2 s .  c  o m
        AsyncHttpClient client = new AsyncHttpClient();
        FileEntity fe = null;
        fe = new FileEntity(new File(filename), "audio/wav");

        // 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(), fe, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:oauth.commons.http.CommonsHttpOAuthProvider.java

public HttpClient getNewHttpClient() {
    try {/*from   ww w  . j  a v  a 2s  .c o m*/
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new SSLSocketFactoryEx(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:ws.argo.responder.configuration.ResponderConfiguration.java

/**
 * The initializeSecurity method will setup the necessary values from either the config file
 * or the system properties (so you can override the config file with the -D switch I guess).
 * None of this is actually used unless the "allowHTTPS" flag is set to true in the config file.
 *///ww w  .  jav  a 2  s  .  c  o  m
private void initializeSecurity() {
    _allowHTTPS = Boolean.parseBoolean(_config.getString("allowHTTPS", "false"));
    _truststoreType = _config.getString("truststoreType", KeyStore.getDefaultType());

    String defaultTruststore = System.getProperty("javax.net.ssl.trustStore");
    String defaultTruststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");

    _truststoreFilename = _config.getString("truststoreFilename", defaultTruststore);
    _truststorePassword = _config.getString("truststorePassword", defaultTruststorePassword);

    if (_truststoreFilename != null && _truststoreFilename.isEmpty())
        _truststoreFilename = null;
    if (_truststorePassword != null && _truststorePassword.isEmpty())
        _truststorePassword = null;

}

From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java

/**
 * Loads keystore in the given file using passphrase as keystore password.
 * /*from   w ww  . ja  v a 2  s. c om*/
 * @param keystore
 * @param pass
 * @return
 * @throws Exception will be a IOExecption if the given password is a wrong
 *         one
 */
public static KeyStore loadKeyStore(File keystore, char[] pass) throws Exception {

    Validate.notNull(keystore, "keystore must be a vaild keystore file");
    InputStream in = new FileInputStream(keystore);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, pass);
    in.close();

    return ks;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert)
        throws GeneralSecurityException, IOException {
    // Create a new empty key store.
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*  ww  w. j a va 2s.  c  o m*/

    Certificate[] chain = { clientCert };

    // The KeyStore requires a password for key entries.
    char[] password = { ' ' };

    // Since we never write out the key store, we don't bother protecting
    // the key.
    ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain),
            new KeyStore.PasswordProtection(password));

    // Shove the key store in a KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password);
    return kmf.getKeyManagers();
}

From source file:org.forgerock.json.crypto.cli.Main.java

public void exec() throws Exception {
    if (cmd.hasOption(PROPERTIES_ENCRYPT_COMMAND)) {
        Key key = getSimpleKeySelector(cmd.getOptionValue(PROPERTIES_KEYSTORE_OPTION),
                cmd.getOptionValue(PROPERTIES_STORETYPE_OPTION, KeyStore.getDefaultType()),
                cmd.getOptionValue(PROPERTIES_STOREPASS_OPTION),
                cmd.getOptionValue(PROPERTIES_PROVIDERNAME_OPTION))
                        .select(cmd.getOptionValue(PROPERTIES_ALIAS_OPTION));
        if (key == null) {
            throw new JsonCryptoException("key not found: " + cmd.getOptionValue(PROPERTIES_ALIAS_OPTION));
        }// w w w. java2 s . com
        SimpleEncryptor encryptor = new SimpleEncryptor(
                cmd.getOptionValue(PROPERTIES_CIPHER_OPTION, DEFAULT_CIPHER), key,
                cmd.getOptionValue(PROPERTIES_ALIAS_OPTION));
        JsonValue value = getSourceValue(cmd.getOptionValue(PROPERTIES_SRCJSON_OPTION), true);
        value = new JsonCrypto(encryptor.getType(), encryptor.encrypt(value)).toJsonValue();
        setDestinationValue(cmd.getOptionValue(PROPERTIES_DESTJSON_OPTION), value);
    } else if (cmd.hasOption(PROPERTIES_DECRYPT_COMMAND)) {
        final ArrayList<JsonTransformer> decryptionTransformers = new ArrayList<JsonTransformer>(1);
        decryptionTransformers.add(new JsonCryptoTransformer(
                new SimpleDecryptor(getSimpleKeySelector(cmd.getOptionValue(PROPERTIES_KEYSTORE_OPTION),
                        cmd.getOptionValue(PROPERTIES_STORETYPE_OPTION, KeyStore.getDefaultType()),
                        cmd.getOptionValue(PROPERTIES_STOREPASS_OPTION),
                        cmd.getOptionValue(PROPERTIES_PROVIDERNAME_OPTION)))));
        JsonValue value = getSourceValue(cmd.getOptionValue(PROPERTIES_SRCJSON_OPTION), true);
        setDestinationValue(cmd.getOptionValue(PROPERTIES_DESTJSON_OPTION),
                new JsonValue(value.getObject(), new JsonPointer(), decryptionTransformers));
    } else {
        usage();
    }
}