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:com.corebase.android.framework.http.client.AsyncHttpClient.java

/**
 * ?SSLSocketFactory?https?/* ww  w.  ja  va 2 s  . com*/
 * 
 * @return
 * @throws KeyStoreException
 * @throws NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
private CustomSSLSocketFactory initCustomSSLSocketFactory()
        throws KeyStoreException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException {

    KeyStore keyStore = null;
    try {
        InputStream ins = context.getAssets().open("app_pay.cer"); // ?assets
        if (ins != null) {
            CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
            Certificate cer = cerFactory.generateCertificate(ins);
            keyStore = KeyStore.getInstance("PKCS12", "BC");
            keyStore.load(null, null);
            keyStore.setCertificateEntry("trust", cer);
        } else {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null, null);
        }
        CustomSSLSocketFactory customSSLSocketFactory = new CustomSSLSocketFactory(keyStore);
        customSSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        return customSSLSocketFactory;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.wikilab.android.friendica01.TwAjax.java

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

            SSLSocketFactory sf = new IgnoreCertsSSLSocketFactory(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();
        }
    } else {
        return new DefaultHttpClient();
    }
}

From source file:com.lgallardo.qbittorrentclient.RSSFeedParser.java

public DefaultHttpClient getNewHttpClient() {
    try {//w  w w .  ja  va2  s .  c om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        MySSLSocketFactory sf = new MySSLSocketFactory(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:org.hyperic.hq.hqapi1.HQConnection.java

private KeyStore getKeyStore(String keyStorePath, String keyStorePassword)
        throws KeyStoreException, IOException {
    FileInputStream keyStoreFileInputStream = null;

    try {// www. j  a  va  2s.  c  o  m
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        File file = new File(keyStorePath);
        char[] password = null;

        if (!file.exists()) {
            // ...if file doesn't exist, and path was user specified throw IOException...
            if (StringUtils.hasText(keyStorePath)) {
                throw new IOException("User specified keystore [" + keyStorePath + "] does not exist.");
            }

            password = keyStorePassword.toCharArray();
        }

        // ...keystore file exist, so init the file input stream...
        keyStoreFileInputStream = new FileInputStream(file);

        keystore.load(keyStoreFileInputStream, password);

        return keystore;
    } catch (NoSuchAlgorithmException e) {
        // can't check integrity of keystore, if this happens we're kind of screwed
        // is there anything we can do to self heal this problem?
        throw new KeyStoreException(e);
    } catch (CertificateException e) {
        // there are some corrupted certificates in the keystore, a bad thing
        // is there anything we can do to self heal this problem?
        throw new KeyStoreException(e);
    } finally {
        if (keyStoreFileInputStream != null) {
            keyStoreFileInputStream.close();
            keyStoreFileInputStream = null;
        }
    }
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

@Override
protected final KeyStore getKeystore(final String password)
        throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException {
    return getKeystore(password, KeyStore.getDefaultType());
}

From source file:org.cloudifysource.restclient.RestClient.java

/**
 * Returns a HTTP client configured to use SSL.
 * /* w  ww.j  a v  a2s . c  om*/
 * @param url
 * 
 * @return HTTP client configured to use SSL
 * @throws org.cloudifysource.restclient.exceptions.RestClientException
 *             Reporting different failures while creating the HTTP client
 */
private DefaultHttpClient getSSLHttpClient(final URL url) throws RestClientException {
    try {
        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // TODO : support self-signed certs if configured by user upon "connect"
        trustStore.load(null, null);

        final SSLSocketFactory sf = new RestSSLSocketFactory(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(HTTPS, sf, url.getPort()));

        final ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (final Exception e) {
        throw new RestClientException(FAILED_CREATING_CLIENT, "Failed creating http client",
                ExceptionUtils.getFullStackTrace(e));
    }
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

/**
 * Generates a self-signed certificate based on the keypair and saves it in the keystore.
 * Should only be used to init the CA./*w ww . j a  v  a  2 s .c  om*/
 */
public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl,
        String outputCaCrlPath) {
    if (KEYSTORE_PASSWORD == null) {
        KEYSTORE_PASSWORD = "changeit";
    }
    if (ROOT_KEYSTORE_PATH == null) {
        ROOT_KEYSTORE_PATH = "mc-root-keystore.jks";
    }
    if (INTERMEDIATE_KEYSTORE_PATH == null) {
        INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks";
    }
    if (TRUSTSTORE_PASSWORD == null) {
        TRUSTSTORE_PASSWORD = "changeit";
    }
    if (TRUSTSTORE_PATH == null) {
        TRUSTSTORE_PATH = "mc-truststore.jks";
    }
    if (CRL_URL == null) {
        CRL_URL = crlUrl;
    }
    if (OCSP_URL == null) {
        OCSP_URL = ocspUrl;
    }
    KeyPair cakp = generateKeyPair();
    KeyPair imkp = generateKeyPair();
    KeyStore rootks = null;
    KeyStore itks;
    KeyStore ts;
    FileOutputStream rootfos = null;
    FileOutputStream itfos = null;
    FileOutputStream tsfos = null;
    try {
        rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() 
        rootks.load(null, KEYSTORE_PASSWORD.toCharArray());
        itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() 
        itks.load(null, KEYSTORE_PASSWORD.toCharArray());
        // Store away the keystore.
        rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH);
        itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH);
        X509Certificate cacert;
        try {
            cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(),
                    cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null,
                    "ROOTCA");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        X509Certificate imcert;
        try {
            imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(),
                    imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null,
                    "INTERMEDIATE");
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        Certificate[] certChain = new Certificate[1];
        certChain[0] = cacert;
        rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain);
        rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray());
        rootks = KeyStore.getInstance(KeyStore.getDefaultType());
        rootks.load(null, KEYSTORE_PASSWORD.toCharArray());

        certChain = new Certificate[2];
        certChain[0] = imcert;
        certChain[1] = cacert;
        itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(),
                certChain);
        itks.store(itfos, KEYSTORE_PASSWORD.toCharArray());

        // Store away the truststore.
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
        ts.load(null, TRUSTSTORE_PASSWORD.toCharArray());
        tsfos = new FileOutputStream(TRUSTSTORE_PATH);
        ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert);
        ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert);
        ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray());
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        safeClose(rootfos);
        safeClose(itfos);
        safeClose(tsfos);

        KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(
                KEYSTORE_PASSWORD.toCharArray());
        PrivateKeyEntry rootCertEntry;
        try {
            rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam);
            generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath);
        } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) {
            // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block
            log.error("unable to generate RootCACRL", e);
        }

    }
}

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

private SSLSocketFactory getSSLSocketFactory(SSLContextModel sslContextConfig) {
    SSLSocketFactory sslFactory = null;
    if (sslContextConfig != null) {
        X509HostnameVerifier verifier = null;
        if (sslContextConfig.getVerifier() != null) {
            if (sslContextConfig.getVerifier().equals(ANY)) {
                verifier = new AllowAllHostnameVerifier();
            } else if (sslContextConfig.getVerifier().equals(BROWSER)) {
                verifier = new BrowserCompatHostnameVerifier();
            } else if (sslContextConfig.getVerifier().equals(STRICT)) {
                verifier = new StrictHostnameVerifier();
            }// ww  w . j  av  a  2s  .  co  m
        }
        KeyStore truststore = null;
        KeyStore keystore = null;
        if (sslContextConfig.getTruststore() != null) {
            FileInputStream instream = null;
            try {
                truststore = KeyStore.getInstance(KeyStore.getDefaultType());
                instream = new FileInputStream(new File(sslContextConfig.getTruststore()));
                truststore.load(instream, sslContextConfig.getTruststorePass().toCharArray());
            } catch (Exception e) {
                throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingTruststore(e);
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException ioe) {
                        throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingTruststore(ioe);
                    }
                }
            }
        }
        if (sslContextConfig.getKeystore() != null) {
            FileInputStream instream = null;
            try {
                keystore = KeyStore.getInstance(KeyStore.getDefaultType());
                instream = new FileInputStream(new File(sslContextConfig.getKeystore()));
                keystore.load(instream, sslContextConfig.getKeystorePass().toCharArray());
            } catch (Exception e) {
                throw RestEasyMessages.MESSAGES.unexpectedExceptionLoadingKeystore(e);
            } finally {
                if (instream != null) {
                    try {
                        instream.close();
                    } catch (IOException ioe) {
                        throw RestEasyMessages.MESSAGES.unexpectedExceptionClosingKeystore(ioe);
                    }
                }
            }
        }
        try {
            sslFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keystore,
                    sslContextConfig.getKeystorePass(), truststore, null, verifier);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return sslFactory;
}

From source file:com.haoqee.chat.net.Utility.java

public static HttpClient getNewHttpClient(long timeout) {
    try {/*from   w w w  .j  av a2  s  .  c  om*/
        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();

        // HttpConnectionParams.setConnectionTimeout(params, 10000);
        // HttpConnectionParams.setSoTimeout(params, 10000);

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        // HttpProtocolParams.setContentCharset(params, HTTP.);

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

        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Utility.SET_CONNECTION_TIMEOUT);
        long soc_time = Utility.SET_SOCKET_TIMEOUT + timeout;
        HttpConnectionParams.setSoTimeout(params, (int) soc_time);
        HttpClient client = new DefaultHttpClient(ccm, params);
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:ddf.security.realm.sts.StsRealm.java

/**
 * Setup key store for SSL client.//  w  ww  . ja v  a 2  s . c om
 */
private void setupKeyStore(TLSClientParameters tlsParams, String keyStorePath, String keyStorePassword) {
    File keyStoreFile = new File(keyStorePath);

    if (keyStoreFile.exists() && keyStorePassword != null) {
        FileInputStream fis = null;
        KeyStore keyStore = null;

        try {
            keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            fis = new FileInputStream(keyStoreFile);

            LOGGER.debug("Loading keyStore");
            keyStore.load(fis, keyStorePassword.toCharArray());

            KeyManagerFactory keyFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyFactory.init(keyStore, keyStorePassword.toCharArray());
            LOGGER.debug("key manager factory initialized");
            KeyManager[] km = keyFactory.getKeyManagers();
            tlsParams.setKeyManagers(km);
        } catch (FileNotFoundException e) {
            LOGGER.error("Unable to find SSL store: " + keyStorePath, e);
        } catch (IOException e) {
            LOGGER.error("Unable to load key store. " + keyStoreFile, e);
        } catch (CertificateException e) {
            LOGGER.error("Unable to load certificates from key store. " + keyStoreFile, e);
        } catch (KeyStoreException e) {
            LOGGER.error("Unable to read key store: ", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("Problems creating SSL socket. Usually this is "
                    + "referring to the certificate sent by the server not being trusted by the client.", e);
        } catch (UnrecoverableKeyException e) {
            LOGGER.error("Unable to read key store: ", e);
        } finally {
            IOUtils.closeQuietly(fis);
        }

    }
}