Example usage for javax.net.ssl TrustManagerFactory getInstance

List of usage examples for javax.net.ssl TrustManagerFactory getInstance

Introduction

In this page you can find the example usage for javax.net.ssl TrustManagerFactory getInstance.

Prototype

public static final TrustManagerFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a TrustManagerFactory object that acts as a factory for trust managers.

Usage

From source file:org.wildfly.security.sasl.entity.EntityTest.java

private X509TrustManager getX509TrustManager(final KeyStore trustStore)
        throws GeneralSecurityException, IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }/*from   ww  w  . ja v a2  s .c  om*/
    }
    return null;
}

From source file:org.deviceconnect.android.message.DevicePluginContext.java

/**
 * SSLContext ?????.//from   w ww .ja v a  2s  .  c o  m
 * <p>
 * ? Web ?????Manager???????????SSLContext ???
 * </p>
 * @param keyStore 
 * @return SSLContext?
 * @throws GeneralSecurityException SSLContext???????
 */
protected SSLContext createSSLContext(final KeyStore keyStore) throws GeneralSecurityException {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, "0000".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new SecureRandom());
    return sslContext;
}

From source file:me.mneri.rice.Connection.java

public void start() {
    if (mState != State.CLOSED)
        return;//from  w  w w .j  a v a2 s  .  c  o  m

    mState = State.STARTED;
    emit(new Event(START, this));

    new Thread(() -> {
        try {
            if (mSecure) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                String algorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(algorithm);
                tmFactory.init((KeyStore) null);
                sslContext.init(null, tmFactory.getTrustManagers(), null);
                SSLSocketFactory sslFactory = sslContext.getSocketFactory();
                SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(mHost, mPort);
                sslSocket.startHandshake();
                mSocket = sslSocket;
            } else {
                mSocket = new Socket(mHost, mPort);
            }

            mSocket.setSoTimeout(mSoTimeout);
            mInputThread = new InputThread(mSocket.getInputStream(), mEncoding, new InputThreadObserver());
            mInputThread.start();
            OutputInterfaceFactory outFactory = OutputInterfaceFactory.instance();
            OutputStreamWriter outWriter = new OutputStreamWriter(mSocket.getOutputStream(), mEncoding);
            mOutputInterface = outFactory.createInterface(outWriter);

            mState = State.CONNECTED;
            emit(new Event(CONNECT, this));
            cap("LS");

            if (!TextUtils.isEmpty(mPass))
                pass(mPass);

            nick(mWantedNick);
            user(mUser, mLoginMode, "*", mReal);
        } catch (Exception e) {
            onDisconnection();
        }
    }).start();
}

From source file:com.vmware.photon.controller.deployer.xenon.workflow.BatchCreateManagementWorkflowService.java

private void generateCertificate(DeploymentService.State deploymentState) {
    if (!deploymentState.oAuthEnabled) {
        sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
        return;/*ww w. j a va  2s. com*/
    }

    List<String> command = new ArrayList<>();
    command.add("./" + GENERATE_CERTIFICATE_SCRIPT_NAME);
    command.add(deploymentState.oAuthServerAddress);
    command.add(deploymentState.oAuthPassword);
    command.add(deploymentState.oAuthTenantName);
    command.add(PhotonControllerXenonHost.KEYSTORE_FILE);
    command.add(PhotonControllerXenonHost.KEYSTORE_PASSWORD);

    DeployerContext deployerContext = HostUtils.getDeployerContext(this);
    File scriptLogFile = new File(deployerContext.getScriptLogDirectory(),
            GENERATE_CERTIFICATE_SCRIPT_NAME + ".log");

    ScriptRunner scriptRunner = new ScriptRunner.Builder(command, deployerContext.getScriptTimeoutSec())
            .directory(deployerContext.getScriptDirectory())
            .redirectOutput(ProcessBuilder.Redirect.to(scriptLogFile)).build();

    ListenableFutureTask<Integer> futureTask = ListenableFutureTask.create(scriptRunner);
    HostUtils.getListeningExecutorService(this).submit(futureTask);

    Futures.addCallback(futureTask, new FutureCallback<Integer>() {
        @Override
        public void onSuccess(@javax.validation.constraints.NotNull Integer result) {
            try {
                if (result != 0) {
                    logScriptErrorAndFail(result, scriptLogFile);
                } else {
                    // Set the inInstaller flag to true which would allow us to override the xenon service client to talk
                    // to the auth enabled newly deployed management plane using https with two way SSL.
                    ((PhotonControllerXenonHost) getHost()).setInInstaller(true);

                    // need to switch the ssl context for the thrift clients to use
                    // the generated certs to be able to talk to the authenticated
                    // agents
                    try {
                        SSLContext sslContext = SSLContext.getInstance(KeyStoreUtils.THRIFT_PROTOCOL);
                        TrustManagerFactory tmf = null;

                        tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        KeyStore keyStore = KeyStore.getInstance("JKS");
                        InputStream in = FileUtils
                                .openInputStream(new File(PhotonControllerXenonHost.KEYSTORE_FILE));
                        keyStore.load(in, PhotonControllerXenonHost.KEYSTORE_PASSWORD.toCharArray());
                        tmf.init(keyStore);
                        sslContext.init(null, tmf.getTrustManagers(), null);
                        ((PhotonControllerXenonHost) getHost()).regenerateThriftClients(sslContext);

                        KeyStoreUtils.acceptAllCerts(KeyStoreUtils.THRIFT_PROTOCOL);
                    } catch (Throwable t) {
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this,
                                "Regenerating the SSL Context for thrift failed, ignoring to make tests pass, it fail later");
                        ServiceUtils.logSevere(BatchCreateManagementWorkflowService.this, t);
                    }
                    sendStageProgressPatch(TaskStage.STARTED, TaskState.SubStage.CREATE_VMS);
                }
            } catch (Throwable t) {
                failTask(t);
            }
        }

        @Override
        public void onFailure(Throwable throwable) {
            failTask(throwable);
        }
    });
}

From source file:org.wso2.carbon.device.mgt.jaxrs.util.DeviceMgtAPIUtils.java

/**
 * Initializes the SSL Context//from   w ww.  j a  v a 2s .  c om
 */
private static void initSSLConnection()
        throws NoSuchAlgorithmException, UnrecoverableKeyException, KeyStoreException, KeyManagementException {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
    keyManagerFactory.init(keyStore, keyStorePassword);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
    trustManagerFactory.init(trustStore);

    // Create and initialize SSLContext for HTTPS communication
    sslContext = SSLContext.getInstance(SSLV3);
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
    SSLContext.setDefault(sslContext);
}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private javax.net.ssl.SSLSocketFactory getProviderSSLSocketFactory() throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException, IOException, KeyManagementException {
    String provider_cert_string = preferences.getString(Provider.CA_CERT, "");

    java.security.cert.Certificate provider_certificate = ConfigHelper
            .parseX509CertificateFromString(provider_cert_string);

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = KeyStore.getInstance(keyStoreType);
    keyStore.load(null, null);//from  w w  w. j  a  v  a  2s .  c  om
    keyStore.setCertificateEntry("provider_ca_certificate", provider_certificate);

    // Create a TrustManager that trusts the CAs in our KeyStore
    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keyStore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:com.wwpass.connection.WWPassConnection.java

public WWPassConnection(X509Certificate cert, PKCS8EncodedKeySpec key, int timeoutSec, String spfeAddr)
        throws IOException, GeneralSecurityException {
    timeoutMs = timeoutSec * 1000;//from  w w  w. java 2  s  .c o  m
    SpfeURL = "https://" + spfeAddr + "/";
    // Setting up client certificate and key

    X509Certificate[] chain = { cert };

    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey privKey = kf.generatePrivate(key);

    KeyStore.PrivateKeyEntry pke = new KeyStore.PrivateKeyEntry(privKey, chain);

    //This adds no security but Java requires to password-protect the key
    byte[] password_bytes = new byte[16];
    (new java.security.SecureRandom()).nextBytes(password_bytes);
    // String password = (new BASE64Encoder()).encode(password_bytes);
    String password = (new Base64()).encodeToString(password_bytes);

    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(null);

    keyStore.setEntry("WWPass client key", pke, new KeyStore.PasswordProtection(password.toCharArray()));
    keyManagerFactory.init(keyStore, password.toCharArray());

    SPFEContext = SSLContext.getInstance("TLS");

    // Making rootCA certificate
    InputStream is = null;
    CertificateFactory cf;
    X509Certificate rootCA = null;
    try {
        is = new ByteArrayInputStream(WWPassCA_DER);
        cf = CertificateFactory.getInstance("X.509");
        rootCA = (X509Certificate) cf.generateCertificate(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }

    //Creating TrustManager for this CA
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);
    ks.setCertificateEntry("WWPass Root CA", rootCA);

    trustManagerFactory.init(ks);

    SPFEContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(),
            new java.security.SecureRandom());
}

From source file:de.stklcode.jvault.connector.HTTPVaultConnector.java

/**
 * Create a custom socket factory from trusted CA certificate.
 *
 * @return The factory.//  w  w  w.j ava 2s  .c o m
 * @throws TlsException An error occured during initialization of the SSL context.
 * @since 0.8.0
 */
private SSLConnectionSocketFactory createSSLSocketFactory() throws TlsException {
    try {
        // Create Keystore with trusted certificate.
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("trustedCert", trustedCaCert);

        // Initialize TrustManager.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        // Create context usint this TrustManager.
        SSLContext context = SSLContext.getInstance(tlsVersion);
        context.init(null, tmf.getTrustManagers(), new SecureRandom());

        return new SSLConnectionSocketFactory(context, null, null,
                SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException
            | KeyManagementException e) {
        throw new TlsException(Error.INIT_SSL_CONTEXT, e);
    }
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();/*from w w w .  j  a  v  a 2 s.c om*/
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}