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.spacetimeinsight.webservice.ssl.EasySSLProtocolSocketFactory.java

public static SSLContext getContext(File pKeyFile, String pKeyPassword)
        throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");

    InputStream keyInput = new FileInputStream(pKeyFile);
    try {// www  .  j a v a 2s  .  com
        keyStore.load(keyInput, pKeyPassword.toCharArray());
    } catch (java.security.cert.CertificateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    keyInput.close();

    keyManagerFactory.init(keyStore, pKeyPassword.toCharArray());

    TrustManager[] trustAllCerts = new TrustManager[] {
            (X509TrustManager) new EasyX509SSLTrustManager(keyStore) };

    // javax.net.ssl.SSLContext context =  javax.net.ssl.getInstance("SSL");
    SSLContext context = SSLContext.getInstance("SSL");
    context.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom());

    return context;
}

From source file:com.adito.install.actions.UploadExistingCertificateAction.java

private boolean validateKeyStore(String keyStoreType, String password, File keystoreFile) {
    InputStream inputStream = null;
    try {//from w  w w  .j  a  va  2s.  c  o  m
        KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        inputStream = new FileInputStream(keystoreFile);
        keyStore.load(inputStream, password.toCharArray());
        return true;
    } catch (Exception e) {
        log.error("Validation of key store failed", e);
        return false;
    } finally {
        Util.closeStream(inputStream);
    }
}

From source file:common.rest.client.transport.HttpClientSSLKeyStore.java

private KeyStore loadKeyStore(final InputStream input, final String password) throws Exception {
    final KeyStore keystore = KeyStore.getInstance("jks");
    keystore.load(input, password.toCharArray());
    return keystore;
}

From source file:dk.itst.oiosaml.sp.IntegrationTests.java

@Before
public final void setUpServer() throws Exception {
    tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random());
    tmpdir.mkdir();//from w  ww  .  j a v  a 2 s .c  om
    FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP"));
    FileUtils.forceMkdir(new File(tmpdir, "metadata/SP"));

    credential = TestHelper.getCredential();
    EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential);
    FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos);
    fos.close();

    EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil
            .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml"));
    fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml"));
    IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos);
    fos.close();

    spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS);
    idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor);

    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml"));
    IOUtils.write(
            "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>",
            fos);
    fos.close();

    Properties props = new Properties();
    props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore");
    props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password");
    props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml");
    props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(),
            new Certificate[] { TestHelper.getCertificate(credential) });
    OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore"));
    ks.store(bos, "password".toCharArray());
    bos.close();

    props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2");
    props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true");
    fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties"));
    props.store(fos, "Generated");
    fos.close();

    SAMLConfiguration.setSystemConfiguration(null);
    IdpMetadata.setMetadata(null);
    SPMetadata.setMetadata(null);
    System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath());
    server = new Server(8808);
    WebAppContext wac = new WebAppContext();
    wac.setClassLoader(Thread.currentThread().getContextClassLoader());
    wac.setContextPath("/saml");
    wac.setWar("webapp/");

    server.setHandler(wac);
    server.start();

    client = new WebClient();
    client.setRedirectEnabled(false);
    client.setThrowExceptionOnFailingStatusCode(false);
    handler = new RedirectRefreshHandler();
    client.setRefreshHandler(handler);
}

From source file:org.gvnix.service.roo.addon.addon.security.GvNix509TrustManager.java

/**
 * Loads keystore in the given file using passphrase as keystore password.
 * // ww  w  .  j a v a 2  s .c o m
 * @param keystore
 * @param pass
 * @return
 * @throws Exception will be a IOExecption if the given password is a wrong
 *         one
 */
public static KeyStore loadKeyStore(File keystore, char[] pass) throws Exception {

    Validate.notNull(keystore, "keystore must be a vaild keystore file");
    InputStream in = new FileInputStream(keystore);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(in, pass);
    in.close();

    return ks;
}

From source file:gov.niem.ws.util.SecurityUtil.java

public static KeyManager[] createKeyManagers(KeyPair clientKey, X509Certificate clientCert)
        throws GeneralSecurityException, IOException {
    // Create a new empty key store.
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null);//from   www.  j  av  a 2s  . c  om

    Certificate[] chain = { clientCert };

    // The KeyStore requires a password for key entries.
    char[] password = { ' ' };

    // Since we never write out the key store, we don't bother protecting
    // the key.
    ks.setEntry("client-key", new KeyStore.PrivateKeyEntry(clientKey.getPrivate(), chain),
            new KeyStore.PasswordProtection(password));

    // Shove the key store in a KeyManager.
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, password);
    return kmf.getKeyManagers();
}

From source file:com.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Gets the http client.//from   w  w  w .  j a  v a 2  s . com
 *
 * @param certificate the certificate
 * @param password the password
 * @return the http client
 */
public static CloseableHttpClient getPKCSKeyHttpClient(final String certificate, final String password) {

    try {
        final KeyStore keystore = KeyStore.getInstance("pkcs12");
        keystore.load(HTTPSClient.class.getClassLoader().getResourceAsStream(certificate),
                password.toCharArray());
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadKeyMaterial(keystore, password.toCharArray());
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setHostnameVerifier(new AllowAllHostnameVerifier()).build();
        return httpClient;
    } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException
            | CertificateException | IOException e) {
        LOGGER.error("Error processing SSL certificates in HTTPS method. Reason ::: " + e);
        return null;
    }
}

From source file:de.cellular.lib.lightlib.backend.LLRequest.java

/**
 * Creates a {@link DefaultHttpClient} object.
 * /*  ww w  .ja v a2s .c  om*/
 * @since 1.0
 * @param _credsProvider
 *            the object contains connect credential info like: User, Pwd, Host etc.
 * @param _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL
 *            true allow all hostname verifier for ssl.
 * @return the {@link DefaultHttpClient} object
 */
public static DefaultHttpClient createHttpClient(CredentialsProvider _credsProvider,
        boolean _ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
    // -------------------------------------------------------------------
    // Example for _credsProvider
    //
    // String usr = getUser();
    // String pwd = getPassword();
    // DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    // CredentialsProvider credsProvider = new BasicCredentialsProvider();
    // credsProvider.setCredentials(new AuthScope(host, port), new UsernamePasswordCredentials(usr, pwd));
    // -------------------------------------------------------------------

    HttpParams params = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(params, TIME_OUT);
    HttpConnectionParams.setSoTimeout(params, TIME_OUT);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
    HttpProtocolParams.setUseExpectContinue(params, true);

    SchemeRegistry schReg = new SchemeRegistry();
    PlainSocketFactory plainSocketFactory = PlainSocketFactory.getSocketFactory();
    SSLSocketFactory sslSocketFactory = null;

    if (_ALLOW_ALL_HOSTNAME_VERIFIER_FOR_SSL) {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sslSocketFactory = new EasySSLSocketFactory(trustStore);
        } catch (Exception _e) {
            LL.e(_e.toString());
            sslSocketFactory = SSLSocketFactory.getSocketFactory();
        }
        sslSocketFactory
                .setHostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        sslSocketFactory = SSLSocketFactory.getSocketFactory();
    }
    schReg.register(new Scheme("http", plainSocketFactory, 80));
    schReg.register(new Scheme("https", sslSocketFactory, 443));
    ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);

    DefaultHttpClient httpclient = new DefaultHttpClient(conMgr, params);
    if (_credsProvider != null) {
        httpclient.setCredentialsProvider(_credsProvider);
    }
    return httpclient;
}

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

private HttpClient getHttpClient() {
    CloseableHttpClient httpclient = null;

    try {//from   w w  w.  j  av  a2 s.c o  m
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        _logger.error("Failed to create HTTPClient: {}", e);
    }

    return httpclient;
}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Return the KeyStore by given URL and password
 * //from  w  ww  .  j  ava 2 s. com
 * @param url
 * @param password
 * @return KeyStore
 * @throws Exception
 */
public static KeyStore getKeyStore(final URL url, final String password) throws Exception {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }
    KeyStore keystore = KeyStore.getInstance("jks");
    InputStream is = null;
    try {
        is = url.openStream();
        keystore.load(is, password != null ? password.toCharArray() : null);
    } finally {
        if (is != null)
            is.close();
    }
    return keystore;
}