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.SAMLIDPInitiatedSSLAuthenticationTestCase.java

@Test
@OperateOnDeployment("identity-provider")
public void testIdPInitiatedSSO() 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/idp-ssl");

    WebConversation conversation = new WebConversation();

    WebResponse response = conversation.getResponse(request);

    assertTrue(response.getText().contains("SAML 2.0 IdP-Initiated SSO"));
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

private void initKeyStore() throws SignerException {

    FileInputStream is = null;//from w w w.  j  av  a 2s  .c o  m

    try {
        is = new FileInputStream(keyStoreFile);
    } catch (FileNotFoundException ex) {
        throw new SignerException("Could not find keystore", ex);
    }

    try {
        keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException ex) {
        throw new SignerException("Could not instantiate keystore", ex);
    }

    char[] passwd = password.toCharArray();

    try {
        keyStore.load(is, passwd);
    } catch (IOException | NoSuchAlgorithmException | CertificateException ex) {
        throw new SignerException("Could not load keystore", ex);
    }

    close(is);
}

From source file:com.microsoft.office.core.auth.AbstractAuthenticationFactory.java

/**
 * Creates HttpClient instance for given method and URI.
 *
 * @param method Http method.//from   www  . j a va2 s.c o m
 * @param uri Target URI.
 * @return HttpClient instance prepared to make request.
 */
@SuppressWarnings("deprecation")
public HttpClient createHttpClient(HttpMethod method, URI uri) {
    HttpClient httpclient = super.createHttpClient(method, uri);

    final IAuthenticator creds = Configuration.getAuthenticator();
    if (creds != null) {
        creds.prepareClient(httpclient);
    }

    httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getConnectionTimeout());
    httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, getSocketTimeout());

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

            SSLSocketFactory sf = new TrustAllSSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));
            ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
            httpclient = new DefaultHttpClient(ccm, httpclient.getParams());
        } catch (Exception e) {
        }
    }

    return httpclient;
}

From source file:com.supremainc.biostar2.sdk.volley.toolbox.HttpClientStack.java

public HttpClient getNewHttpClient() {
    try {/*w w w.  j  a v 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);

        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:com.emc.cto.ridagent.rid.util.HTTPSender.java

public static Map<String, Object> httpSend(PipelineOutput output, String destURL) {

    /* Set up TLS mutual authentication */

    KeyStore keystore = null;/*from   w  w  w  .j ava  2  s . c  o m*/
    try {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    InputStream keystoreInput = null;
    try {
        keystoreInput = new FileInputStream(m_keystorePath);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        keystore.load(keystoreInput, m_keystorePassword.toCharArray());
    } 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();
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Keystore has " + keystore.size() + " keys");
        }
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    KeyStore truststore = null;
    try {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    InputStream truststoreInput = null;
    try {
        truststoreInput = new FileInputStream(m_truststorePath);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        truststore.load(truststoreInput, m_truststorePassword.toCharArray());
    } catch (NoSuchAlgorithmException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (CertificateException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Truststore has " + truststore.size() + " keys");
        }
    } catch (KeyStoreException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    SSLSocketFactory schemeSocketFactory = null;

    try {
        schemeSocketFactory = new SSLSocketFactory(keystore, m_keystorePassword, truststore);
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    schemeRegistry.register(new Scheme(m_protocol, m_port, schemeSocketFactory));
    final HttpParams httpParams = new BasicHttpParams();
    DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(schemeRegistry),
            httpParams);

    /* Prepare the request to send */

    String body = null;
    Map<String, Object> responseMap = new HashMap<String, Object>();
    List<com.emc.documentum.xml.xproc.io.Source> sources = output.getSources(output.getPrimaryOutputPort());

    if (sources != null && !sources.isEmpty()) {
        // pipeline should only return a single value - we return the first as the output
        Node node = sources.get(0).getNode();
        InputStream is = sources.get(0).getInputStream();
        Reader rdr = sources.get(0).getReader();

        //For now we implement node only since we assume content is in the node
        if (node != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Node has content");
            }
            body = Utilities.nodeToString(node);

        } else if (is != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Input stream has content");
            }

        } else if (rdr != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Reader has content");
            }
        }
    }

    HttpEntity request = new StringEntity(body, ContentType.TEXT_XML);

    //Create POST method
    HttpPost postMethod = new HttpPost(destURL);
    postMethod.setHeader("User-Agent", "EMC RID System");
    postMethod.setHeader("Content-Type", "text/xml");
    postMethod.setEntity(request);

    /* POST the request and process the response */
    HttpResponse httpResponse = null;
    int code;
    String responseBody = null;

    try {
        httpResponse = httpClient.execute(postMethod);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (httpResponse.getEntity() != null) {

        code = httpResponse.getStatusLine().getStatusCode();

        try {
            responseBody = EntityUtils.toString(httpResponse.getEntity());
        } catch (ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        if (logger.isDebugEnabled()) {
            logger.debug("Response status code: " + code);
            logger.debug("Reponse body =" + responseBody);
        }

        responseMap.put("success", true);
        responseMap.put("statusCode", code);
        responseMap.put("responseBody", responseBody);

    } else {
        responseMap.put("success", false);
        responseMap.put("errorMessage", "Send failed (fill in exception)");
    }

    return responseMap;
}

From source file:io.specto.hoverfly.junit.HoverflyRuleUtils.java

static void setHoverflyTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException,
        IOException, KeyManagementException, URISyntaxException {
    // load your key store as a stream and initialize a KeyStore
    InputStream trustStream = findResourceOnClasspath("hoverfly.jks").toURL().openStream();

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

    // load the stream to your store
    trustStore.load(trustStream, "hoverfly".toCharArray());

    // initialize a trust manager factory with the trusted store
    TrustManagerFactory trustFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init(trustStore);// w w w  .  jav a 2  s . co  m

    // get the trust managers from the factory
    TrustManager[] trustManagers = trustFactory.getTrustManagers();

    // initialize an ssl context to use these managers and set as default
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagers, null);
    SSLContext.setDefault(sslContext);
}

From source file:org.candlepin.client.CustomSSLProtocolSocketFactory.java

private SSLContext createCustomSSLContext() {
    try {// w  w w .  java  2s .c o m
        KeyManager[] keyManagers = null;
        // Generate key managers off of the identity certificates if
        // doing client auth.
        if (clientAuth) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            String[] keyCert = FileUtil.readKeyAndCert(configuration.getConsumerIdentityFilePath());
            kmf.init(PemUtil.pemToKeyStore(keyCert[1], keyCert[0], "password"), "password".toCharArray());
            keyManagers = kmf.getKeyManagers();
        }
        /* and provide them for the SSLContext */
        SSLContext ctx = SSLContext.getInstance("TLS");
        if (configuration.isIgnoreTrustManagers()) {
            ctx.init(keyManagers, Utils.DUMMY_TRUST_MGRS, new SecureRandom());
        } else {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            KeyStore ks2 = KeyStore.getInstance(KeyStore.getDefaultType());
            ks2.load(null, null);

            ks2.setCertificateEntry("candlepin", PemUtil.readCert("/etc/candlepin/certs/candlepin-ca.crt"));
            // ks2.load(
            // new FileInputStream(configuration.getKeyStoreFileLocation()),
            // passwd);
            tmf.init(ks2);
            ctx.init(keyManagers, tmf.getTrustManagers(), new SecureRandom());
        }

        return ctx;
    } catch (Exception e) {
        e.printStackTrace();
        throw new HttpClientError(e.getMessage());
    }
}

From source file:org.apache.ranger.authorization.kafka.authorizer.KafkaRangerAuthorizerTest.java

@org.junit.BeforeClass
public static void setup() throws Exception {
    // Create keys
    String serviceDN = "CN=Service,O=Apache,L=Dublin,ST=Leinster,C=IE";
    String clientDN = "CN=Client,O=Apache,L=Dublin,ST=Leinster,C=IE";

    // Create a truststore
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, "security".toCharArray());

    serviceKeystorePath = KafkaTestUtils.createAndStoreKey(serviceDN, serviceDN, BigInteger.valueOf(30),
            "sspass", "myservicekey", "skpass", keystore);
    clientKeystorePath = KafkaTestUtils.createAndStoreKey(clientDN, clientDN, BigInteger.valueOf(31), "cspass",
            "myclientkey", "ckpass", keystore);

    File truststoreFile = File.createTempFile("kafkatruststore", ".jks");
    try (OutputStream output = new FileOutputStream(truststoreFile)) {
        keystore.store(output, "security".toCharArray());
    }//  w w w  . jav a  2s .  c o  m
    truststorePath = truststoreFile.getPath();

    zkServer = new TestingServer();

    // Get a random port
    ServerSocket serverSocket = new ServerSocket(0);
    port = serverSocket.getLocalPort();
    serverSocket.close();

    tempDir = Files.createTempDirectory("kafka");

    final Properties props = new Properties();
    props.put("broker.id", 1);
    props.put("host.name", "localhost");
    props.put("port", port);
    props.put("log.dir", tempDir.toString());
    props.put("zookeeper.connect", zkServer.getConnectString());
    props.put("replica.socket.timeout.ms", "1500");
    props.put("controlled.shutdown.enable", Boolean.TRUE.toString());
    // Enable SSL
    props.put("listeners", "SSL://localhost:" + port);
    props.put("ssl.keystore.location", serviceKeystorePath);
    props.put("ssl.keystore.password", "sspass");
    props.put("ssl.key.password", "skpass");
    props.put("ssl.truststore.location", truststorePath);
    props.put("ssl.truststore.password", "security");
    props.put("security.inter.broker.protocol", "SSL");
    props.put("ssl.client.auth", "required");

    // Plug in Apache Ranger authorizer
    props.put("authorizer.class.name",
            "org.apache.ranger.authorization.kafka.authorizer.RangerKafkaAuthorizer");

    // Create users for testing
    UserGroupInformation.createUserForTesting(clientDN, new String[] { "public" });
    UserGroupInformation.createUserForTesting(serviceDN, new String[] { "IT" });

    KafkaConfig config = new KafkaConfig(props);
    kafkaServer = new KafkaServerStartable(config);
    kafkaServer.startup();

    // Create some topics
    ZkClient zkClient = new ZkClient(zkServer.getConnectString(), 30000, 30000, ZKStringSerializer$.MODULE$);

    final ZkUtils zkUtils = new ZkUtils(zkClient, new ZkConnection(zkServer.getConnectString()), false);
    AdminUtils.createTopic(zkUtils, "test", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
    AdminUtils.createTopic(zkUtils, "dev", 1, 1, new Properties(), RackAwareMode.Enforced$.MODULE$);
}

From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java

public static KeyStore readCerts(final String pemContent, final String aliasPrefix)
        throws IOException, CertificateException, KeyStoreException, NoSuchAlgorithmException {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);/*from   w w w .ja  v  a 2 s  .c o m*/

    final CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

    final List<String> lines = readLines(pemContent);

    final StringBuilder current = new StringBuilder();
    final List<String> entries = new ArrayList<String>();
    for (final String line : lines) {
        if (line == null) {
            continue;
        }

        if (line.startsWith("-----BEGIN")) {
            current.setLength(0);
        } else if (line.startsWith("-----END")) {
            entries.add(current.toString());
        } else {
            current.append(line.trim());
        }
    }

    int i = 0;
    for (final String entry : entries) {
        final byte[] data = decodeBase64(entry);

        final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data));

        ks.setCertificateEntry(aliasPrefix + i, c);
        i++;
    }

    return ks;
}

From source file:org.apache.juddi.v3.client.cryptor.TransportSecurityHelper.java

public static boolean applyTransportSecurity(BindingProvider webServicePort) {
    try {/*from   www.  jav  a  2  s. c o m*/
        File currentdir = new File(".");
        String s = System.getProperty("javax.net.ssl.keyStore");
        String st = System.getProperty("javax.net.ssl.trustStore");
        log.info("Attempting to initialize keystore and truststore from " + s + " " + st);
        if (s == null) {
            log.warn("keystore isn't defined! " + s);
            return false;
        } else if (st == null) {
            log.warn("truststore isn't defined! " + s);
            return false;
        } else {
            File keystore = new File(s);
            if (keystore == null || !keystore.exists()) {
                log.warn("keystore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwd = System.getProperty("javax.net.ssl.keyStorePassword");
            if (pwd == null) {
                log.warn("keystore password isn't defined!");
                return false;
            }

            File truststore = new File(st);
            if (truststore == null || !truststore.exists()) {
                log.warn("truststore doesn't exist! input was " + s + " working dir is "
                        + currentdir.getAbsolutePath());
                return false;
            }
            //File truststore =new File(System.getProperty("javax.net.ssl.trustStore"));
            String pwdt = System.getProperty("javax.net.ssl.trustStorePassword");
            if (pwdt == null) {
                log.warn("truststore password isn't defined!");
                return false;
            }

            if (keystore.exists()) {
                try {
                    log.info("Using keystore from " + keystore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());

                    log.info("Using truststore from " + truststore.getAbsolutePath() + " current dir is "
                            + currentdir.getAbsolutePath());
                    //log.info("Using truststure from " + truststore.getAbsolutePath() + " current dir is " + currentdir.getAbsolutePath());
                    SSLContext sc = SSLContext.getInstance("SSLv3");

                    KeyManagerFactory kmf = KeyManagerFactory
                            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

                    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
                    ks.load(new FileInputStream(keystore), pwd.toCharArray());

                    kmf.init(ks, pwd.toCharArray());

                    String alg = TrustManagerFactory.getDefaultAlgorithm();
                    TrustManagerFactory tmFact = TrustManagerFactory.getInstance(alg);

                    FileInputStream fis = new FileInputStream(st);
                    KeyStore kst = KeyStore.getInstance("jks");
                    kst.load(fis, pwdt.toCharArray());
                    fis.close();

                    tmFact.init(kst);

                    TrustManager[] tms = tmFact.getTrustManagers();

                    sc.init(kmf.getKeyManagers(), null, null);
                    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
                            sc.getSocketFactory());
                    ((BindingProvider) webServicePort).getRequestContext().put(
                            "com.sun.xml.ws.transport.https.client.SSLSocketFactory", sc.getSocketFactory());
                    return true;
                } catch (Exception ex) {
                    log.warn("unable to establish ssl settings", ex);
                }
            }
        }
        return false;
    } catch (Exception x) {
        log.error("unexpected error", x);
    }
    return false;
}