Example usage for java.security KeyStore getInstance

List of usage examples for java.security KeyStore getInstance

Introduction

In this page you can find the example usage for java.security KeyStore getInstance.

Prototype

public static KeyStore getInstance(String type) throws KeyStoreException 

Source Link

Document

Returns a keystore object of the specified type.

Usage

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   ww w . j  a  v  a  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. j  av  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:com.springcryptoutils.core.keystore.Base64EncodedKeyStoreFactoryBean.java

public void afterPropertiesSet() throws KeyStoreException, IOException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateException {
    if ((provider == null) || (provider.length() == 0)) {
        keystore = KeyStore.getInstance(type);
    } else {//from  w ww  . j a v  a 2s.  c  o  m
        keystore = KeyStore.getInstance(type, provider);
    }
    ByteArrayInputStream in = new ByteArrayInputStream(
            Base64.decodeBase64(base64EncodedKeyStoreFile.getBytes()));
    keystore.load(in, password.toCharArray());
}

From source file:org.kuali.mobility.push.factory.iOSConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    SSLSocket socket = null;/* w w  w  .  j  av  a  2 s  .  c  o  m*/
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:org.kuali.mobility.push.factory.iOSFeedbackConnectionFactory.java

@Override
public SSLSocket makeObject() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(certPath.getInputStream(), certPassword.toCharArray());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("sunx509");
    keyManagerFactory.init(keyStore, certPassword.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("sunx509");
    trustManagerFactory.init(keyStore);/*from  ww w .  j  a  va 2s.  c  om*/
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslCtx.getSocketFactory();
    SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(host, port);
    socket.startHandshake();
    return socket;
}

From source file:com.cloud.utils.security.CertificateHelper.java

public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException,
        IOException {//from ww  w  .  j ava2 s.  c  o m

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, storePassword != null ? storePassword.toCharArray() : null);
    Certificate[] certs = new Certificate[1];
    certs[0] = buildCertificate(cert);
    ks.setKeyEntry(alias, buildPrivateKey(privateKey),
            storePassword != null ? storePassword.toCharArray() : null, certs);
    return ks;
}

From source file:com.cloudbees.tftwoway.Client.java

public static KeyManager[] getKeyManager() throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore store = KeyStore.getInstance("JKS");

    PrivateKey clientKey = loadRSAKey(PRIVATE_KEY);
    X509Certificate clientCert = loadX509Key(CERTIFICATE);

    store.load(null);//from   www  .j  ava  2  s .  c om
    store.setKeyEntry("key", clientKey, "123123".toCharArray(), new Certificate[] { clientCert });

    keyManagerFactory.init(store, "123123".toCharArray());

    return keyManagerFactory.getKeyManagers();
}

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

/**
 * https?/*from   w  w  w . jav a  2 s .c o  m*/
 * @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:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java

private static KeyStore createKeyStore(KeyPair keyPair) throws KeyStoreException, CertificateException,
        NoSuchAlgorithmException, IOException, OperatorCreationException, NoSuchProviderException {
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null, null);/*from w w  w .j  av a  2  s.  c  o  m*/
    keyStore.setKeyEntry(DEFAULT_P12_ALIAS, keyPair.getPrivate(), DEFAULT_P12_SECRET.toCharArray(),
            new Certificate[] { generateCertificate(keyPair) });
    return keyStore;
}

From source file:com.alliander.osgp.shared.usermanagement.UserManagementClient.java

/**
 * Construct a UserManagementClient instance.
 *
 * @param keystoreLocation//from  w  w  w  .  ja v  a  2 s.  c o m
 *            The location of the key store.
 * @param keystorePassword
 *            The password for the key store.
 * @param keystoreType
 *            The type of the key store.
 * @param baseAddress
 *            The base address or URL for the UserManagementClient.
 *
 * @throws UserManagementClientException
 *             In case the construction fails, a
 *             UserManagmentClientException will be thrown.
 */
public UserManagementClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws UserManagementClientException {

    InputStream stream = null;
    boolean isClosed = false;
    Exception exception = null;

    try {
        // Create the KeyStore.
        final KeyStore keystore = KeyStore.getInstance(keystoreType.toUpperCase());

        stream = new FileInputStream(keystoreLocation);
        keystore.load(stream, keystorePassword.toCharArray());

        // Create TrustManagerFactory and initialize it using the KeyStore.
        final TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystore);

        // Create Apache CXF WebClient with JSON provider.
        final List<Object> providers = new ArrayList<Object>();
        providers.add(new JacksonJaxbJsonProvider());

        this.webClient = WebClient.create(baseAddress, providers);
        if (this.webClient == null) {
            throw new UserManagementClientException("webclient is null");
        }

        // Set up the HTTP Conduit to use the TrustManagers.
        final ClientConfiguration config = WebClient.getConfig(this.webClient);
        final HTTPConduit conduit = config.getHttpConduit();

        conduit.setTlsClientParameters(new TLSClientParameters());
        conduit.getTlsClientParameters().setTrustManagers(tmf.getTrustManagers());
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new UserManagementClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

    if (!isClosed) {
        throw new UserManagementClientException(CONSTRUCTION_FAILED, exception);
    }
}