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:br.ufsc.das.gtscted.shibbauth.Connection.java

public Connection() throws ClientProtocolException, IOException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    SSLSocketFactory socketFactory;
    httpClient = new DefaultHttpClient();
    KeyStore trustStore;/*from   www . j ava2  s . c  om*/
    trustStore = KeyStore.getInstance(KeyStore.getDefaultType());

    // usando a nova SSLSocketFactory. Ver links abaixo:
    // http://groups.google.com/group/android-developers/browse_thread/thread/d9b914c0dca5a702
    // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4523989
    // http://exampledepot.com/egs/javax.net.ssl/TrustAll.html
    // http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
    // http://stackoverflow.com/questions/2899079/custom-ssl-handling-stopped-working-on-android-2-2-froyo
    socketFactory = new MySSLSocketFactory(trustStore);
    Scheme scheme = new Scheme("https", socketFactory, 443);
    httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
}

From source file:at.gv.egovernment.moa.id.demoOA.Configuration.java

public KeyStore getPVP2KeyStore() throws ConfigurationException {

    try {//www  .j  a  v a 2s. c  om
        if (keyStore == null) {
            String keystoretype = getPVP2MetadataKeystoreType();
            if (MiscUtil.isEmpty(keystoretype)) {
                keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            } else {
                keyStore = KeyStore.getInstance(keystoretype);

            }

            String file = getPVP2MetadataKeystoreURL();
            if (MiscUtil.isEmpty(file)) {
                throw new ConfigurationException("KeyStoreURL is empty");
            }

            FileInputStream inputStream = new FileInputStream(file);
            keyStore.load(inputStream, getPVP2MetadataKeystorePassword().toCharArray());
            inputStream.close();
        }

        return keyStore;

    } catch (Exception e) {
        throw new ConfigurationException("KeyStore intialization FAILED", e);

    }

}

From source file:com.wso2telco.gsma.shorten.BitlyUrlShorten.java

/**
 * Gets the new http client.//w  ww  .  j a  v a  2 s .  c om
 *
 * @return the new http client
 */
@SuppressWarnings("deprecation")
public CloseableHttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        org.apache.http.conn.ssl.SSLSocketFactory sf = new SSLSocket(trustStore);
        sf.setHostnameVerifier(org.apache.http.conn.ssl.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:me.xiaopan.android.gohttp.httpclient.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore/* ww w. j a  v a2s  .c  o m*/
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = (Certificate) cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            caInput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", (Certificate) ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {/*from  www  .  ja v  a2s. c o  m*/
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

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

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

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

private static KeyManagerFactory createKeyManagerFactory(Resource keystoreFile, String storePassword)
        throws GeneralSecurityException, IOException {

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

    try (InputStream inputStream = keystoreFile.getInputStream()) {
        keyStore.load(inputStream, StringUtils.hasText(storePassword) ? storePassword.toCharArray() : null);
    }/*www .ja  va  2 s.co m*/

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,
            StringUtils.hasText(storePassword) ? storePassword.toCharArray() : new char[0]);

    return keyManagerFactory;
}

From source file:org.commonjava.indy.httprox.ProxyHttpsWildcardHostCertTest.java

private KeyStore getTrustStore(File jks) throws Exception {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (FileInputStream instream = new FileInputStream(jks)) {
        trustStore.load(instream, "passwd".toCharArray());
    }//from  w ww .j  a va  2s  .c  om
    return trustStore;
}

From source file:cn.com.loopj.android.http.MySSLSocketFactory.java

/**
 * Gets a KeyStore containing the Certificate
 *
 * @param cert InputStream of the Certificate
 * @return KeyStore/*www  .j  ava2s. c  o  m*/
 */
public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        caInput = new BufferedInputStream(cert);
        ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
        e1.printStackTrace();
    } finally {
        try {
            if (caInput != null) {
                caInput.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance(keyStoreType);
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return keyStore;
}

From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java

private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception {
    X509Certificate certHolder = readCertFile(cert);
    Object keyObject = readPrivateKeyFile(privateKey);
    char[] passwordCharArray = "".toCharArray();
    if (!StringUtils.isEmpty(password)) {
        passwordCharArray = password.toCharArray();
    }//  w ww. j  a  v  a2 s .co m

    JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC");

    PrivateKey privateKey;
    if (keyObject instanceof PEMEncryptedKeyPair) {
        PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
        KeyPair key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider));
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PEMKeyPair) {
        KeyPair key = keyConverter.getKeyPair((PEMKeyPair) keyObject);
        privateKey = key.getPrivate();
    } else if (keyObject instanceof PrivateKey) {
        privateKey = (PrivateKey) keyObject;
    } else {
        throw new RuntimeException("Unable to get private key from object: " + keyObject.getClass());
    }

    KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    clientKeyStore.load(null, null);
    clientKeyStore.setCertificateEntry("cert", certHolder);
    clientKeyStore.setKeyEntry("private-key", privateKey, passwordCharArray, new Certificate[] { certHolder });

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(clientKeyStore, passwordCharArray);
    return keyManagerFactory;
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints.
 *
 * @throws IOException/*from   w  w w  . ja v  a 2 s .  c  om*/
 *             if there are any issues with the keystore processing.
 */
private synchronized void getKeyStoreInfo() throws IOException {
    try {
        // load up the keystore..
        FileInputStream is = new FileInputStream(keyStore);
        KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType());
        signingKeystore.load(is, keyStorePW.toCharArray());

        // grab the key we'll use to sign
        signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray());

    } catch (KeyStoreException e) {
        throw new IOException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    } catch (CertificateException e) {
        throw new IOException(e);
    } catch (UnrecoverableKeyException e) {
        throw new IOException(e);
    }

}