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.picketlink.test.integration.federation.saml.SAMLSPInitiatedFallbackFormSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("service-provider")
public void testSPInitiatedSSOWithoutClientCert() throws Exception {
    KeyStore trustStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.truststore",
            KeyStore.getDefaultType());

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();//from  w w w . ja  v a2 s.  c om

    SSLContext.setDefault(sslcontext);

    WebRequest request = new GetMethodWebRequest("https://localhost:8443/sales-post-ssl");

    WebConversation conversation = new WebConversation();

    conversation.setExceptionsThrownOnErrorStatus(false);

    WebResponse response = conversation.getResponse(request);

    assertEquals("https://localhost:8443/idp-ssl/", response.getURL().toString());

    assertTrue(response.getText().contains("login_form"));
}

From source file:com.base.net.volley.toolbox.HttpClientStack.java

/**
 * https?//from  w ww .jav  a 2s. c om
 * @param client
 */
private void setClientHttps(HttpClient client) {

    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); // ??
        ClientConnectionManager conManager = client.getConnectionManager();
        SchemeRegistry schReg = conManager.getSchemeRegistry();
        if (schReg == null) {
            schReg = new SchemeRegistry();
        }
        schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        schReg.register(new Scheme("https", sf, 443));

    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsWithCertificate(final URL url) throws KeyStoreException, NoSuchAlgorithmException,
        CertificateException, IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null);// Make an empty store

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    FileInputStream fis = new FileInputStream(BeeConstants.BEE_HTTPS_CERTIFICATE_DEFAULT_PATH);
    BufferedInputStream bis = new BufferedInputStream(fis);
    while (bis.available() > 0) {
        Certificate cert = cf.generateCertificate(bis);
        // System.out.println(cert.getPublicKey().toString());
        trustStore.setCertificateEntry("jetty" + bis.available(), cert);
    }//from ww  w .jav  a  2  s.  co  m

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(trustStore);
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(null, tmf.getTrustManagers(), null);
    SSLSocketFactory sslFactory = ctx.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            if (0 == hostname.compareToIgnoreCase(url.getHost())) {
                return true;
            }
            return false;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(sslFactory);

    return urlConnection.getInputStream();
}

From source file:org.picketlink.test.integration.federation.saml.SAMLSPInitiatedSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("service-provider")
public void testSPInitiatedSSO() throws Exception {
    KeyStore keyStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.keystore", "PKCS12");
    KeyStore trustStore = getKeyStore(System.getProperty("jboss.config.dir") + "/client.truststore",
            KeyStore.getDefaultType());

    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .loadKeyMaterial(keyStore, "change_it".toCharArray()).build();

    SSLContext.setDefault(sslcontext);

    WebRequest request = new GetMethodWebRequest("https://localhost:8443/sales-post-ssl");

    WebConversation conversation = new WebConversation();

    WebResponse response = conversation.getResponse(request);

    assertTrue(response.getText().contains("Welcome to the Sales Tool"));
}

From source file:io.pivotal.springcloud.ssl.CloudFoundryCertificateTruster.java

/**
 * import trust from truststore file/*from  w  ww  .j  a v  a2  s.co m*/
 *
 * @param applicationContext
 * @param trustStore
 * @param trustStorePassword
 */
private void trustCertificatesFromStoreInternal(ConfigurableApplicationContext applicationContext,
        String trustStore, String trustStorePassword) {
    if (trustStore != null) {
        try {
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(applicationContext.getResource(trustStore).getInputStream(),
                    trustStorePassword.toCharArray());
            Enumeration<String> aliases = keystore.aliases();

            List<X509Certificate> certCollect = new ArrayList<X509Certificate>();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();

                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null && certs.length > 0)
                    for (Certificate cert : certs)
                        if (cert instanceof X509Certificate)
                            certCollect.add((X509Certificate) cert);

                Certificate cert = keystore.getCertificate(alias);
                if (cert != null && cert instanceof X509Certificate) {
                    certCollect.add((X509Certificate) cert);
                }
            }

            if (certCollect.size() > 0)
                sslCertificateTruster.appendToTruststoreInternal(certCollect.toArray(new X509Certificate[0]));

        } catch (Exception e) {
            log.error("trusting trustore at {}:{} failed", trustStore, trustStorePassword, e);
        }
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.jwks.JwksEndpoint.java

@GET
@Path(value = "/jwks")
@Produces(MediaType.APPLICATION_JSON)//from   w w  w  . java  2  s  .  c om
public String jwks() {

    String tenantDomain = null;
    int tenantId = -1;
    Object tenantObj = IdentityUtil.threadLocalProperties.get().get(OAuthConstants.TENANT_NAME_FROM_CONTEXT);
    if (tenantObj != null) {
        tenantDomain = (String) tenantObj;
    }
    if (StringUtils.isEmpty(tenantDomain)) {
        tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
    }

    RSAPublicKey publicKey = null;
    JSONObject jwksJson = new JSONObject();
    FileInputStream file = null;
    try {
        tenantId = IdentityTenantUtil.getTenantId(tenantDomain);
        if (tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
            file = new FileInputStream(
                    CarbonUtils.getServerConfiguration().getFirstProperty("Security.KeyStore.Location"));
            KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            String password = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.Password");
            keystore.load(file, password.toCharArray());
            String alias = CarbonUtils.getServerConfiguration().getInstance()
                    .getFirstProperty("Security.KeyStore.KeyAlias");
            // Get certificate of public key
            Certificate cert = keystore.getCertificate(alias);
            // Get public key
            publicKey = (RSAPublicKey) cert.getPublicKey();
        } else {

            if (tenantId < 1 && tenantId != -1234) {
                String errorMesage = "The tenant is not existing";
                log.error(errorMesage);
                return errorMesage;
            }
            KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
            KeyStore keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            // Get certificate of public key
            Certificate cert = keyStore.getCertificate(tenantDomain);
            publicKey = (RSAPublicKey) cert.getPublicKey();

        }
        String modulus = base64EncodeUint(publicKey.getModulus());
        String exponent = base64EncodeUint(publicKey.getPublicExponent());
        String kty = publicKey.getAlgorithm();
        JSONArray jwksKeyArray = new JSONArray();
        JSONObject jwksKeys = new JSONObject();
        jwksKeys.put("kty", kty);
        jwksKeys.put("alg", alg);
        jwksKeys.put("use", use);
        jwksKeys.put("kid", OAuth2Util.getThumbPrint(tenantDomain, tenantId));
        jwksKeys.put("n", modulus);
        jwksKeys.put("e", exponent);
        jwksKeyArray.put(jwksKeys);
        jwksJson.put("keys", jwksKeyArray);
    } catch (Exception e) {
        String errorMesage = "Error while generating the keyset for " + tenantDomain + " tenant domain.";
        log.error(errorMesage, e);
        return errorMesage;
    } finally {
        IdentityIOStreamUtils.closeInputStream(file);
    }

    return jwksJson.toString();
}

From source file:com.spotify.docker.client.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//from  www .  j  av  a2s . co m
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

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

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.loopj.android.http.sample.CustomCASample.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {//from w  ww  .j av a  2  s .  c om
        InputStream is = null;
        try {
            // Configure the library to use a custom 'bks' file to perform
            // SSL negotiation.
            KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
            is = getResources().openRawResource(R.raw.store);
            store.load(is, STORE_PASS.toCharArray());
            getAsyncHttpClient().setSSLSocketFactory(new SecureSocketFactory(store, STORE_ALIAS));
        } catch (IOException e) {
            throw new KeyStoreException(e);
        } catch (CertificateException e) {
            throw new KeyStoreException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new KeyStoreException(e);
        } catch (KeyManagementException e) {
            throw new KeyStoreException(e);
        } catch (UnrecoverableKeyException e) {
            throw new KeyStoreException(e);
        } finally {
            AsyncHttpClient.silentCloseInputStream(is);
        }
    } catch (KeyStoreException e) {
        Log.e(LOG_TAG, "Unable to initialize key store", e);
        showCustomCAHelp();
    }
}

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

public SchemeRegistry buildSchemeRegistry() {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    if (asConnectionParams.isSecure()) {
        SSLSocketFactory sslSocketFactory;
        try {//from  w  ww.j  a  v  a 2s  .c  om
            KeyStore truststore = null;
            if (asConnectionParams.getTruststore() != null) {
                truststore = SecurityUtil.loadKeystore( //
                        asConnectionParams.getTruststoreType(), //
                        asConnectionParams.getTruststore(), //
                        asConnectionParams.getTruststorePassword() //
                );
            }
            KeyStore keystore = null;
            String keyPassword = null;
            if (asConnectionParams.isClientcertAuthentication()) {
                if (asConnectionParams.getKeystore() == null) {
                    keystore = SecurityUtil.loadKeystore( //
                            System.getProperty("javax.net.ssl.keyStoreType", KeyStore.getDefaultType()), //
                            System.getProperty("javax.net.ssl.keyStore"), //
                            System.getProperty("javax.net.ssl.keyStorePassword") //
                    );
                } else {
                    keystore = SecurityUtil.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(ASConnection.HTTPS_SCHEME, asConnectionParams.getPort(), sslSocketFactory));
    } else {
        schemeRegistry.register(new Scheme(ASConnection.HTTP_SCHEME, asConnectionParams.getPort(),
                PlainSocketFactory.getSocketFactory()));
    }
    return schemeRegistry;
}

From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java

private DefaultHttpClient newClient() {
    DefaultHttpClient client = 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 2 s  .  co  m
        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,
            client.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));
    }

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

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

    return client;
}