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.qpark.eip.core.spring.security.https.EipX509TrustManager.java

/**
 * Initialize.//w w w. j  av a 2s.  co  m
 * 
 * @throws Exception
 */
@PostConstruct
public void init() throws Exception {
    // create a "default" JSSE X509TrustManager.
    this.ks = KeyStore.getInstance("JKS");
    if (this.keystore != null) {
        this.ks.load(this.keystore.getInputStream(), this.keystorePassword);
    }

    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
    tmf.init(this.ks);

    TrustManager tms[] = tmf.getTrustManagers();

    /*
     * Iterate over the returned trust managers, look for an instance of
     * X509TrustManager. If found, use that as our "default" trust manager.
     */
    for (TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            this.sunJSSEX509TrustManager = (X509TrustManager) tm;
            return;
        }
    }

    /*
     * Find some other way to initialize, or else we have to fail the
     * constructor.
     */
    throw new Exception("Couldn't initialize");
}

From source file:com.peopleapi.RegisterWithApi.java

private DefaultHttpClient getNewHttpClient() {
    //I mocked out a key store, you will want to generate a real store. this is for testing only!
    try {//w w w.jav a  2s.com
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(MySSLSocketFactory.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.ecs.sync.filter.DecryptionFilter.java

@Override
public void configure(SyncSource source, Iterator<SyncFilter> filters, SyncTarget target) {
    try {//from  www. j  av  a 2  s .c  o m
        if (keystore == null) {
            if (keystoreFile == null)
                throw new ConfigurationException("Must specify a keystore");

            // Init keystore
            keystore = KeyStore.getInstance("jks");
            keystore.load(new FileInputStream(keystoreFile), keystorePass.toCharArray());
            log.info("Keystore Loaded");
        }

        // TODO: remove alias logic when decryption factory no longer requires an alias
        Enumeration<String> aliases = keystore.aliases();
        if (aliases == null || !aliases.hasMoreElements())
            throw new ConfigurationException("keystore has no aliases");
        transformFactory = new KeyStoreEncryptionFactory(keystore, aliases.nextElement(),
                keystorePass.toCharArray());

    } catch (Exception e) {
        throw new ConfigurationException(e);
    }
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>// w w w  .j  av  a  2 s  .c o m
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:davmail.util.ClientCertificateTest.java

public void testWindowsSmartCard() {
    try {//from   w ww . j av  a2  s .  co  m
        KeyStore ks = KeyStore.getInstance("Windows-MY");
        ks.load(null, null);
        java.util.Enumeration en = ks.aliases();

        while (en.hasMoreElements()) {
            String aliasKey = (String) en.nextElement();
            X509Certificate c = (X509Certificate) ks.getCertificate(aliasKey);
            System.out.println("---> alias : " + aliasKey + " " + c.getSubjectDN());

            //PrivateKey key = (PrivateKey) ks.getKey(aliasKey, "Passw0rd".toCharArray());
            Certificate[] chain = ks.getCertificateChain(aliasKey);
        }

    } catch (Exception ioe) {
        System.err.println(ioe.getMessage());
    }
}

From source file:com.jonbanjo.cupsprint.CertificateActivity.java

private KeyStore loadTrustStore() {
    KeyStore ts = null;/*  w  w w .ja  v a2s.  co  m*/

    try {
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (Exception e) {
        System.out.println(e.toString());
        return null;
    }

    FileInputStream fis = null;
    try {
        fis = openFileInput(JfSSLScheme.trustfile);
        ts.load(fis, JfSSLScheme.password.toCharArray());
    } catch (Exception e) {
        try {
            ts.load(null, JfSSLScheme.password.toCharArray());
        } catch (Exception e1) {
            System.out.println(e.toString());
            return null;
        }
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (Exception e1) {
            }
        }
    }
    return ts;
}

From source file:br.com.ararati.operacoes.SocketFactory.java

public TrustManager[] createTrustManagers()
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    KeyStore trustStore = KeyStore.getInstance("JKS");

    trustStore.load(new FileInputStream(fileCacerts), "changeit".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory.getTrustManagers();
}

From source file:org.opcfoundation.ua.transport.https.HttpsSettings.java

/**
 * Set keypair of a https application. This replaces a keyManager.
 * Additional CA certifications can be attached. 
 * // w  ww . ja  v  a  2s. co m
 * @param keypair
 * @param caCerts
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 */
public void setKeyPair(KeyPair keypair, Cert... caCerts) {
    if (keypair != null)
        try {
            KeyStore keystore = KeyStore.getInstance("jks");
            Certificate[] certs = new Certificate[] { keypair.certificate.certificate };
            PrivateKeyEntry entry = new PrivateKeyEntry(keypair.privateKey.getPrivateKey(), certs);
            String password = "";
            keystore.load(null);
            keystore.setEntry("myentry-" + keypair.hashCode(), entry,
                    new PasswordProtection(password.toCharArray()));
            int count = caCerts.length;
            for (int i = 0; i < count; i++) {
                String id = "cacert-" + (i + 1);
                keystore.setEntry(id, new TrustedCertificateEntry(caCerts[i].certificate), null);
            }
            setKeyStore(keystore, "");
        } catch (KeyStoreException e) {
            // Expected if JKS is not available (e.g. in Android)

        } catch (NoSuchAlgorithmException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (CertificateException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (IOException e) {
            // Unexpected
            throw new RuntimeException(e);
        } catch (ServiceResultException e) {
            // Unexpected
            throw new RuntimeException(e);
        }
}

From source file:talkeeg.httpserver.HttpServer.java

private NHttpConnectionFactory<DefaultNHttpServerConnection> createConnectionFactory() {
    NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
    if (config.isUseTLS()) {
        try {/*  ww w .  j a  v  a  2s. c  o m*/
            KeyStore keystore = KeyStore.getInstance("jks");
            char[] password = new char[0];
            keystore.load(null, password);
            final X509Certificate certificate = certManager.getCertificate(OwnedKeyType.USER);
            KeyStore.PrivateKeyEntry entry = new KeyStore.PrivateKeyEntry(
                    ownedKeysManager.getPrivateKey(OwnedKeyType.USER), new Certificate[] { certificate });

            keystore.setEntry("", entry, new KeyStore.PasswordProtection(password));
            KeyManagerFactory kmfactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmfactory.init(keystore, password);
            final KeyManager[] keymanagers = kmfactory.getKeyManagers();
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(keymanagers, null, null);
            connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, ConnectionConfig.DEFAULT);
        } catch (Exception e) {
            throw new RuntimeException("Can not initialise SSL.", e);
        }
    } else {
        connFactory = new DefaultNHttpServerConnectionFactory(ConnectionConfig.DEFAULT);
    }
    return connFactory;
}

From source file:com.github.mrstampy.gameboot.otp.OtpTestConfiguration.java

private KeyStore getKeyStore() throws KeyStoreException {
    return KeyStore.getInstance(KeyStore.getDefaultType());
}