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:it.macisamuele.network.WebApplicationClient.java

public boolean acceptAnyCertificate() {
    try {//  ww  w  .j av  a2 s .c  o  m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        asyncHttpClient.setSSLSocketFactory(socketFactory);
        return true;
    } catch (IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException
            | KeyStoreException | KeyManagementException e) {
        e.printStackTrace();
        return false;
    }
}

From source file:keywhiz.TestClients.java

private static KeyStore keyStoreFromResource(String path, String password) {
    KeyStore keyStore;//from w ww  . java2s .c  o  m
    try (InputStream stream = Resources.getResource(path).openStream()) {
        keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(stream, password.toCharArray());
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException e) {
        throw new AssertionError(e);
    }
    return keyStore;
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/*from   w w  w  . ja  v  a 2s . co m*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:cloud.google.oauth2.MyWayAuthentication.java

/**
 * Load p12 file get private key/*from w  w w  .  j  av  a 2s . c o m*/
 * */
private PrivateKey getPrivateKey(String keyFile, String password) throws KeyStoreException, IOException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(new FileInputStream(keyFile), password.toCharArray());
    PrivateKey privateKey = (PrivateKey) keystore.getKey(GCDStatic.getKeyAlias(), password.toCharArray());

    return privateKey;
}

From source file:com.guster.skywebservice.library.webservice.SkyHttp.java

public static void setSSLCertificate(InputStream certificateFile) throws CertificateException, IOException,
        KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    Certificate cert = cf.generateCertificate(certificateFile);

    certificateFile.close();/*w w w  .  j a v a2s  .  c om*/

    // create a keystore containing the certificate
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("ca", cert);

    // create a trust manager for our certificate
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);

    // create a SSLContext that uses our trust manager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    // set socket factory
    setSSLSocketFactory(context.getSocketFactory());
}

From source file:org.openiot.gsn.http.rest.PushRemoteWrapper.java

public boolean initialize() {

    try {// w ww .j  a  v  a2s .co  m
        initParams = new RemoteWrapperParamParser(getActiveAddressBean(), true);
        uid = Math.random();

        postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair(PushDelivery.NOTIFICATION_ID_KEY, Double.toString(uid)));
        postParameters.add(
                new BasicNameValuePair(PushDelivery.LOCAL_CONTACT_POINT, initParams.getLocalContactPoint()));
        // Init the http client
        if (initParams.isSSLRequired()) {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(new FileInputStream(new File("conf/servertestkeystore")),
                    Main.getContainerConfig().getSSLKeyStorePassword().toCharArray());
            SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
            socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            int sslPort = Main.getContainerConfig().getSSLPort() > 0 ? Main.getContainerConfig().getSSLPort()
                    : ContainerConfig.DEFAULT_SSL_PORT;
            Scheme sch = new Scheme("https", socketFactory, sslPort);
            httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        }
        Scheme plainsch = new Scheme("http", PlainSocketFactory.getSocketFactory(),
                Main.getContainerConfig().getContainerPort());
        httpclient.getConnectionManager().getSchemeRegistry().register(plainsch);
        //
        lastReceivedTimestamp = initParams.getStartTime();
        structure = registerAndGetStructure();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        NotificationRegistry.getInstance().removeNotification(uid);
        return false;
    }

    return true;
}

From source file:com.youTransactor.uCube.mdm.MDMManager.java

public void initialize(Context context) {
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);

    onSharedPreferenceChanged(settings, null);

    settings.registerOnSharedPreferenceChangeListener(this);

    try {/*from ww  w  .j  av  a2s . c o m*/
        KeyStore keystoreCA = KeyStore.getInstance(KEYSTORE_TYPE);
        keystoreCA.load(context.getResources().openRawResource(R.raw.keystore), PWD);

        KeyStore keystoreClient = null;

        File file = context.getFileStreamPath(KEYSTORE_CLIENT_FILENAME);

        if (file.exists()) {
            keystoreClient = KeyStore.getInstance(KEYSTORE_TYPE);
            InputStream in = new FileInputStream(file);
            keystoreClient.load(in, PWD);
        }

        ready = keystoreClient != null && keystoreClient.getKey(MDM_CLIENT_CERT_ALIAS, PWD) != null;

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keystoreCA);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
        kmf.init(keystoreClient, PWD);

        sslContext = SSLContext.getInstance("TLS");

        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

    } catch (Exception e) {
        LogManager.debug(MDMManager.class.getSimpleName(), "load keystore error", e);
    }
}

From source file:AuthSSLProtocolSocketFactory.java

private static KeyStore createKeyStore(final URL url, final String password)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url may not be null");
    }//from  w w w. j av  a2s  . c  o m
    System.out.println("Initializing key store");
    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;
}

From source file:com.cloudera.nav.sdk.client.SSLUtils.java

private static X509TrustManager loadTrustManager(String type, String file, String password)
        throws IOException, GeneralSecurityException {
    X509TrustManager trustManager = null;
    KeyStore ks = KeyStore.getInstance(type);
    try (FileInputStream in = new FileInputStream(file)) {
        ks.load(in, password.toCharArray());
        LOG.debug("Loaded truststore '" + file + "'");
    }/*w ww.  jav a  2  s .co m*/

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SSLCERTIFICATE);
    trustManagerFactory.init(ks);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    for (TrustManager trustManager1 : trustManagers) {
        if (trustManager1 instanceof X509TrustManager) {
            trustManager = (X509TrustManager) trustManager1;
            break;
        }
    }
    return trustManager;
}

From source file:com.cloudbees.jenkins.support.impl.RootCAs.java

public static void getRootCAList(StringWriter writer) {
    KeyStore instance = null;/*ww w . j  a  v  a 2 s .  c  o m*/
    try {
        instance = KeyStore.getInstance(KeyStore.getDefaultType());
        Enumeration<String> aliases = instance.aliases();
        while (aliases.hasMoreElements()) {
            String s = aliases.nextElement();
            writer.append("========");
            writer.append("Alias: " + s);
            writer.append(instance.getCertificate(s).getPublicKey().toString());
            writer.append("Trusted certificate: " + instance.isCertificateEntry(s));
        }
    } catch (KeyStoreException e) {
        writer.write(Functions.printThrowable(e));
    }
}