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.netflix.spinnaker.halyard.config.validate.v1.security.SamlValidator.java

@Override
public void validate(ConfigProblemSetBuilder p, Saml saml) {
    if (!saml.isEnabled()) {
        return;//from w  ww . j a va 2 s.c o m
    }

    if (StringUtils.isEmpty(saml.getMetadataLocal()) && StringUtils.isEmpty(saml.getMetadataRemote())) {
        p.addProblem(Problem.Severity.ERROR, "No metadata file specified.");
    }

    if (StringUtils.isNotEmpty(saml.getMetadataLocal())) {
        try {
            new File(new URI("file:" + saml.getMetadataLocal()));
        } catch (Exception f) {
            p.addProblem(Problem.Severity.ERROR, f.getMessage());
        }
    }

    if (StringUtils.isNotEmpty(saml.getMetadataRemote())) {
        try {
            HttpClientBuilder.create().build().execute(new HttpGet(saml.getMetadataRemote()));
        } catch (IOException e) {
            p.addProblem(Problem.Severity.WARNING, "Cannot access remote metadata.xml file: " + e.getMessage());
        }
    }

    if (StringUtils.isEmpty(saml.getIssuerId())) {
        p.addProblem(Problem.Severity.ERROR, "No issuerId specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStore())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStorePassword())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore password specified.");
    }

    if (StringUtils.isEmpty(saml.getKeyStoreAliasName())) {
        p.addProblem(Problem.Severity.ERROR, "No keystore alias specified.");
    }

    InputStream is = null;
    try {
        File f = new File(new URI("file:" + saml.getKeyStore()));
        is = new FileInputStream(f);
        val keystore = KeyStore.getInstance(KeyStore.getDefaultType());

        // will throw an exception if `keyStorePassword` is invalid
        keystore.load(is, saml.getKeyStorePassword().toCharArray());

        Collections.list(keystore.aliases()).stream()
                .filter(alias -> alias.equalsIgnoreCase(saml.getKeyStoreAliasName())).findFirst()
                .orElseThrow(() -> new RuntimeException(
                        "Keystore does not contain alias " + saml.getKeyStoreAliasName()));

    } catch (Exception e) {
        p.addProblem(Problem.Severity.ERROR, "Keystore validation problem: " + e.getMessage());
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (Exception e) {
                // ignored.
            }
        }
    }

    if (saml.getServiceAddress() == null) {
        p.addProblem(Problem.Severity.ERROR, "No service address specified.");
    } else if (!saml.getServiceAddress().getProtocol().equalsIgnoreCase("https")) {
        p.addProblem(Problem.Severity.WARNING, "Gate should operate on HTTPS");
    }
}

From source file:com.tlabs.eve.HttpClientTest.java

@BeforeClass
public static final void setHttpClient() throws Exception {
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    //FIXME check about the deprecated
    try {//from   w w  w  .ja  va  2s. com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sslf = new NoCheckSSLSocketFactory(trustStore);
        sslf.setHostnameVerifier(new AllowAllHostnameVerifier());
        schemeRegistry.register(new Scheme("https", sslf, 443));
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
    connectionManager = new ThreadSafeClientConnManager(new BasicHttpParams(), schemeRegistry);
}

From source file:mitm.common.security.keystore.KeyStoreLoader.java

public KeyStore loadKeyStore(File file, char[] password) throws IOException, KeyStoreException,
        NoSuchProviderException, NoSuchAlgorithmException, CertificateException {
    if (file == null) {
        throw new IOException("file cannot be null");
    }// w  w w.j  a v  a2s.c o  m

    if (!file.exists()) {
        throw new FileNotFoundException("file does not exist");
    }

    if (StringUtils.isEmpty(keyStoreType)) {
        determineKeyStoreTypeFromFile(file);
    }

    KeyStore keyStore = KeyStore.getInstance(keyStoreType);

    InputStream input = new FileInputStream(file);

    try {
        keyStore.load(input, password);
    } finally {
        IOUtils.closeQuietly(input);
    }

    return keyStore;
}

From source file:com.amalto.workbench.utils.SSLContextProvider.java

private static TrustManager[] buildTrustManagers(String path, String storePass, String trusttype)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException {
    InputStream stream = null;/*w w w.  j  a v  a 2s  . c o m*/
    try {
        if (StringUtils.isEmpty(path)) {
            return new TrustManager[] { TRUST_ALL };
        }
        if (!new File(path).exists()) {
            throw new KeyStoreException(Messages.bind(Messages.noKeystoreFile_error, path));
        }
        stream = new FileInputStream(path);

        KeyStore tks = KeyStore.getInstance(trusttype);
        tks.load(stream, storePass.toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$
        tmf.init(tks);

        return tmf.getTrustManagers();
    } finally {
        IOUtils.closeQuietly(stream);
    }
}

From source file:com.github.restdriver.clientdriver.integration.SecureClientDriverTest.java

static KeyStore getKeystore()
        throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
    ClassLoader loader = SecureClientDriverTest.class.getClassLoader();
    byte[] binaryContent = IOUtils.toByteArray(loader.getResourceAsStream("keystore.jks"));
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new ByteArrayInputStream(binaryContent), "password".toCharArray());
    return keyStore;

}

From source file:learn.encryption.ssl.SSLContext_Https.java

public static SSLContext getSSLContext2(String servercerfile, String clientkeyStore, String clientPass) {
    if (sslContext != null) {
        return sslContext;
    }/*from  ww w.  j a  va 2 s .  c  o  m*/
    try {
        // ??, ??assets
        //InputStream inputStream = App.getInstance().getAssets().open("serverkey.cer");
        InputStream inputStream = new FileInputStream(new File(servercerfile));
        // ??
        CertificateFactory cerFactory = CertificateFactory.getInstance("X.509");
        Certificate cer = cerFactory.generateCertificate(inputStream);
        // ?KeyStore
        KeyStore keyStore = KeyStore.getInstance("PKCS12");//eclipse?jksandroidPKCS12??
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trust", cer);

        // KeyStoreTrustManagerFactory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);

        sslContext = SSLContext.getInstance("TLS");

        //?clientKeyStore(android??bks)
        //KeyStore clientKeyStore = KeyStore.getInstance("BKS");
        KeyStore clientKeyStore = KeyStore.getInstance("jks");
        //clientKeyStore.load(App.getInstance().getAssets().open("clientkey.bks"), "123456".toCharArray());
        clientKeyStore.load(new FileInputStream(new File(clientkeyStore)), clientPass.toCharArray());

        // ?clientKeyStorekeyManagerFactory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, clientPass.toCharArray());

        // ?SSLContext  trustManagerFactory.getTrustManagers()
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
                new SecureRandom());//new TrustManager[]{trustManagers}??
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sslContext;
}

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

/**
 * Construct an AuthenticationClient instance.
 *
 * @param keystoreLocation//  www  . j ava2s.co 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 AuthenticationClient.
 *
 * @throws AuthenticationClientException
 *             In case the construction fails, an
 *             AuthenticationClientException will be thrown.
 */
public AuthenticationClient(final String keystoreLocation, final String keystorePassword,
        final String keystoreType, final String baseAddress) throws AuthenticationClientException {

    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, true);
        if (this.webClient == null) {
            throw new AuthenticationClientException("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());

        this.jacksonObjectMapper = new ObjectMapper();
    } catch (final Exception e) {
        LOGGER.error(CONSTRUCTION_FAILED, e);
        throw new AuthenticationClientException(CONSTRUCTION_FAILED, e);
    } finally {
        try {
            stream.close();
            isClosed = true;
        } catch (final Exception streamCloseException) {
            LOGGER.error(CONSTRUCTION_FAILED, streamCloseException);
            exception = streamCloseException;
        }
    }

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

From source file:org.appenders.log4j2.elasticsearch.jest.JKSCertInfo.java

@Override
public void applyTo(HttpClientConfig.Builder clientConfigBuilder) {

    try (FileInputStream keystoreFile = new FileInputStream(new File(keystorePath));
            FileInputStream truststoreFile = new FileInputStream(new File(truststorePath))) {
        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(keystoreFile, keystorePassword.toCharArray());
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, keystorePassword.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("jks");
        trustStore.load(truststoreFile, truststorePassword.toCharArray());

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        // TODO: add support for hostname verification modes
        clientConfigBuilder.sslSocketFactory(new SSLConnectionSocketFactory(sslContext));
        clientConfigBuilder/*from   www . jav a  2  s.  co  m*/
                .httpsIOSessionStrategy(new SSLIOSessionStrategy(sslContext, new NoopHostnameVerifier()));

    } catch (IOException | GeneralSecurityException e) {
        throw new ConfigurationException(configExceptionMessage, e);
    }
}

From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java

public void executePut(String putURL, RequestParams params, JSONObject json) {
    try {//from ww  w  .  java  2 s .c  o m
        AsyncHttpClient client = new AsyncHttpClient();
        StringEntity se = null;
        try {
            se = new StringEntity(json.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return;
        }
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        // Add SSL
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray());
        SSLSocketFactory sf = new SSLSocketFactory(trustStore);
        client.setSSLSocketFactory(sf);

        client.setTimeout(30000);

        client.put(null, putURL + "?" + params.toString(), se, null, this);
    } catch (Exception e) {
        e.printStackTrace();
    }
    Log.i("executePut", "done");
}

From source file:org.apache.axis2.transport.nhttp.HttpCoreNIOSSLSender.java

protected SSLContext getSSLContext(TransportOutDescription transportOut) throws AxisFault {

    KeyManager[] keymanagers = null;
    TrustManager[] trustManagers = null;

    Parameter keyParam = transportOut.getParameter("keystore");
    Parameter trustParam = transportOut.getParameter("truststore");

    if (keyParam != null) {
        OMElement ksEle = keyParam.getParameterElement().getFirstElement();
        String location = ksEle.getFirstChildWithName(new QName("Location")).getText();
        String type = ksEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = ksEle.getFirstChildWithName(new QName("Password")).getText();
        String keyPassword = ksEle.getFirstChildWithName(new QName("KeyPassword")).getText();

        try {//from   w  w w .ja va  2s .c o  m
            KeyStore keyStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Key Store from URL : " + url);

            keyStore.load(url.openStream(), storePassword.toCharArray());
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keyStore, keyPassword.toCharArray());
            keymanagers = kmfactory.getKeyManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        }
    }

    if (trustParam != null) {
        OMElement tsEle = trustParam.getParameterElement().getFirstElement();
        String location = tsEle.getFirstChildWithName(new QName("Location")).getText();
        String type = tsEle.getFirstChildWithName(new QName("Type")).getText();
        String storePassword = tsEle.getFirstChildWithName(new QName("Password")).getText();

        try {
            KeyStore trustStore = KeyStore.getInstance(type);
            URL url = getClass().getClassLoader().getResource(location);
            log.debug("Loading Trust Key Store from URL : " + url);

            trustStore.load(url.openStream(), storePassword.toCharArray());
            TrustManagerFactory trustManagerfactory = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            trustManagerfactory.init(trustStore);
            trustManagers = trustManagerfactory.getTrustManagers();

        } catch (GeneralSecurityException gse) {
            log.error("Error loading Key store : " + location, gse);
            throw new AxisFault("Error loading Key store : " + location, gse);
        } catch (IOException ioe) {
            log.error("Error opening Key store : " + location, ioe);
            throw new AxisFault("Error opening Key store : " + location, ioe);
        }
    }

    try {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustManagers, null);
        return sslcontext;

    } catch (GeneralSecurityException gse) {
        log.error("Unable to create SSL context with the given configuration", gse);
        throw new AxisFault("Unable to create SSL context with the given configuration", gse);
    }
}