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.openmeap.util.SSLUtils.java

static public HttpClient getRelaxedSSLVerificationHttpClient() {
    try {/*w  ww .ja v  a 2 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();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, FormConstants.CHAR_ENC_DEFAULT);

        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.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*w  w w  .ja v  a2  s .c om*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:io.restassured.authentication.CertificateAuthSettings.java

/**
 * Create a new instance of the Certificate Authentication Options with the default settings of:
 * <ul>/* w  w  w. j a  v a 2 s.  com*/
 * <li>keystoreType = {@link java.security.KeyStore#getDefaultType()}</li>
 * <li>trustStoreType = {@link java.security.KeyStore#getDefaultType()}</li>
 * <li>port = 443</li>
 * <li>trustStore = null</li>
 * <li>keyStore = null</li>
 * <li>x509HostnameVerifier = {@link org.apache.http.conn.ssl.SSLSocketFactory#STRICT_HOSTNAME_VERIFIER}</li>
 * <li>SSLSocketFactory = null</li>
 * </ul>
 *
 * @see #certAuthSettings()
 */
public CertificateAuthSettings() {
    this(KeyStore.getDefaultType(), KeyStore.getDefaultType(), UNDEFINED_PORT, null, null,
            STRICT_HOSTNAME_VERIFIER, null);
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@BeforeClass
public static void setUp() throws Exception {
    SharedUtils.bootstrap(false); // use real data
    String tenantName = ServerConfig.getTenant(0);
    String rpName = ServerConfig.getRelyingParty(tenantName, 0);
    String issuerUrl = ServerConfig.getRelyingPartyUrl(rpName);
    String acsName = ServerConfig.getAssertionConsumerService(rpName, 0);
    acsUrl = ServerConfig.getServiceEndpoint(acsName);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(SamlServiceTest.class.getResource("/sts-store.jks").getFile());
    char[] stsKeystorePassword = "ca$hc0w".toCharArray();
    ks.load(is, stsKeystorePassword);//from ww w . j  a va 2  s  .  c o m

    String stsAlias = "stskey";
    Certificate certificate = ks.getCertificate(stsAlias);
    Key key = ks.getKey(stsAlias, stsKeystorePassword);

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    certificates.add((X509Certificate) certificate);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(certificates);

    privateKey = (PrivateKey) key;
    x509Certificate = (X509Certificate) certificate;

    SamlServiceFactory factory = new DefaultSamlServiceFactory();
    service = factory.createSamlService(privateKey, SignatureAlgorithm.RSA_SHA256,
            SignatureAlgorithm.RSA_SHA256, issuerUrl, certPath);
}

From source file:edu.rit.csh.androidwebnews.WebnewsHttpClient.java

/**
 * Makes the SSL cert work correctly./*from   ww  w  .ja v a2s.co m*/
 *
 * @return SSLSocketFactory - provides the SSLFactory for communicating
 *         with the scheme
 */
private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
        trusted.load(null, null);
        // Pass the keystore to the SSLSocketFactory. The factory is responsible
        // for the verification of the server certificate.
        SSLSocketFactory sf = new WebnewsSocketFactory(trusted);
        // Hostname verification from certificate
        // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
        sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}

From source file:com.splunk.shuttl.archiver.http.InsecureHttpClientFactory.java

private static KeyStore getTrustStore() {
    try {// ww  w  . jav a 2 s  .c om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        return trustStore;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.trentorise.smartcampus.ac.network.HttpsClientBuilder.java

private static HttpClient getAcceptAllHttpClient(HttpParams inParams) {
    HttpClient client = null;/*from w ww .  ja  va2s  .  c o m*/

    HttpParams params = inParams != null ? inParams : new BasicHttpParams();

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

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

        // IMPORTANT: use CustolSSLSocketFactory for 2.2
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(trustStore);
        if (android.os.Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.FROYO) {
            sslSocketFactory = new CustomSSLSocketFactory(trustStore);
        }

        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme("https", sslSocketFactory, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        client = new DefaultHttpClient(params);
    }

    return client;
}

From source file:com.mobicage.rogerthat.util.http.HTTPUtil.java

private static KeyStore loadTrustStore() {
    if (sTrustStore == null) {
        String keyStorePassword = "rogerthat";
        try {//from   ww  w  .  ja  v a 2  s .c om
            final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            InputStream instream = App.getContext().getAssets().open("truststore.bks");
            try {
                keyStore.load(instream, keyStorePassword.toCharArray());
            } finally {
                instream.close();
            }
            sTrustStore = keyStore;
        } catch (Exception e) {
            throw new RuntimeException("Could not load keyStore from assets dir", e);
        }
    }
    return sTrustStore;
}

From source file:hu.javaforum.android.soap.ssl.HttpsClientFactory.java

/**
 * Creates a DefaultHttpClient implementation with trusts all certificate.
 * /*from   ww  w  .  ja va 2 s  .  c om*/
 * @param params
 *            The HttpParams
 * @return The DefaultHttpClient implementation
 * @throws KeyManagementException
 *             KeyManagementException
 * @throws KeyStoreException
 *             KeyStoreException
 * @throws NoSuchAlgorithmException
 *             NoSuchAlgorithmException
 * @throws UnrecoverableKeyException
 *             UnrecoverableKeyException
 */
public static HttpClient createTrustAllInstance(final HttpParams params)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    try {
        return createClient(new AllTrustSSLSocketFactory(KeyStore.getInstance(KeyStore.getDefaultType())),
                params);
    } finally {
    }
}

From source file:neembuu.release1.httpclient.NHttpClient.java

public static DefaultHttpClient getNewInstance() {
    DefaultHttpClient new_httpClient = null;
    new_httpClient = new DefaultHttpClient();
    GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings();
    HttpContext context = new BasicHttpContext();
    SchemeRegistry schemeRegistry = new SchemeRegistry();

    schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80));

    try {//from ww w  .  j  a v a 2s. c  om
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080));
    } catch (Exception a) {
        a.printStackTrace(System.err);
    }

    context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry);
    context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY,
            new BasicScheme()/*file.httpClient.getAuthSchemes()*/);

    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY,
            new_httpClient.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/
    );

    BasicCookieStore basicCookieStore = new BasicCookieStore();

    context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/);
    context.setAttribute(ClientContext.CREDS_PROVIDER,
            new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/);

    HttpConnection hc = new DefaultHttpClientConnection();
    context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc);

    //System.out.println(file.httpClient.getParams().getParameter("http.useragent"));
    HttpParams httpParams = new BasicHttpParams();

    if (proxySettings != null) {
        AuthState as = new AuthState();
        as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
        as.setAuthScope(AuthScope.ANY);
        as.setAuthScheme(new BasicScheme());
        httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as);
        httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port));
    }

    new_httpClient = new DefaultHttpClient(
            new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry),
            httpParams/*file.httpClient.getParams()*/);

    if (proxySettings != null) {
        new_httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password));
    }

    return new_httpClient;
}