Java Examples for javax.net.ssl.TrustManagerFactory

The following java examples will help you to understand the usage of javax.net.ssl.TrustManagerFactory. These source code samples are taken from different open source projects.

Example 1
Project: Android-tcp-long-connection-based-on-Apache-mina-master  File: SslContextFactory.java View source code
public SSLContext newInstance() throws Exception {
    KeyManagerFactory kmf = this.keyManagerFactory;
    TrustManagerFactory tmf = this.trustManagerFactory;
    if (kmf == null) {
        String algorithm = keyManagerFactoryAlgorithm;
        if (algorithm == null && keyManagerFactoryAlgorithmUseDefault) {
            algorithm = KeyManagerFactory.getDefaultAlgorithm();
        }
        if (algorithm != null) {
            if (keyManagerFactoryProvider == null) {
                kmf = KeyManagerFactory.getInstance(algorithm);
            } else {
                kmf = KeyManagerFactory.getInstance(algorithm, keyManagerFactoryProvider);
            }
        }
    }
    if (tmf == null) {
        String algorithm = trustManagerFactoryAlgorithm;
        if (algorithm == null && trustManagerFactoryAlgorithmUseDefault) {
            algorithm = TrustManagerFactory.getDefaultAlgorithm();
        }
        if (algorithm != null) {
            if (trustManagerFactoryProvider == null) {
                tmf = TrustManagerFactory.getInstance(algorithm);
            } else {
                tmf = TrustManagerFactory.getInstance(algorithm, trustManagerFactoryProvider);
            }
        }
    }
    KeyManager[] keyManagers = null;
    if (kmf != null) {
        kmf.init(keyManagerFactoryKeyStore, keyManagerFactoryKeyStorePassword);
        keyManagers = kmf.getKeyManagers();
    }
    TrustManager[] trustManagers = null;
    if (tmf != null) {
        if (trustManagerFactoryParameters != null) {
            tmf.init(trustManagerFactoryParameters);
        } else {
            tmf.init(trustManagerFactoryKeyStore);
        }
        trustManagers = tmf.getTrustManagers();
    }
    SSLContext context = null;
    if (provider == null) {
        context = SSLContext.getInstance(protocol);
    } else {
        context = SSLContext.getInstance(protocol, provider);
    }
    context.init(keyManagers, trustManagers, secureRandom);
    if (clientSessionCacheSize >= 0) {
        context.getClientSessionContext().setSessionCacheSize(clientSessionCacheSize);
    }
    if (clientSessionTimeout >= 0) {
        context.getClientSessionContext().setSessionTimeout(clientSessionTimeout);
    }
    if (serverSessionCacheSize >= 0) {
        context.getServerSessionContext().setSessionCacheSize(serverSessionCacheSize);
    }
    if (serverSessionTimeout >= 0) {
        context.getServerSessionContext().setSessionTimeout(serverSessionTimeout);
    }
    return context;
}
Example 2
Project: Yarrn-master  File: SslCertificateHelper.java View source code
public static void trustGeotrustCertificate(final Context context) {
    try {
        final KeyStore trustStore = KeyStore.getInstance("BKS");
        final InputStream in = context.getResources().openRawResource(R.raw.geotrust_cert);
        trustStore.load(in, null);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        final SSLContext sslCtx = SSLContext.getInstance("TLS");
        sslCtx.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());
    } catch (final Exception e) {
        AQUtility.report(e);
        e.printStackTrace();
    }
}
Example 3
Project: Swinedroid-master  File: TrustManagerFactory.java View source code
public static void addCertificateChain(String alias, X509Certificate[] chain) throws CertificateException {
    try {
        javax.net.ssl.TrustManagerFactory tmf = javax.net.ssl.TrustManagerFactory.getInstance("X509");
        for (int i = 0; i < chain.length; i++) {
            keyStore.setCertificateEntry(chain[i].getSubjectDN().toString(), chain[i]);
        }
        tmf.init(keyStore);
        TrustManager[] tms = tmf.getTrustManagers();
        if (tms != null) {
            for (TrustManager tm : tms) {
                if (tm instanceof X509TrustManager) {
                    localTrustManager = (X509TrustManager) tm;
                    break;
                }
            }
        }
        java.io.FileOutputStream keyStoreStream;
        try {
            keyStoreStream = new java.io.FileOutputStream(keyStoreFile);
            keyStore.store(keyStoreStream, "".toCharArray());
            keyStoreStream.close();
        } catch (FileNotFoundException e) {
            throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
        } catch (CertificateException e) {
            throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
        } catch (IOException e) {
            throw new CertificateException("Unable to write KeyStore: " + e.getMessage());
        }
    } catch (NoSuchAlgorithmException e) {
        Log.e(LOG_TAG, "Unable to get X509 Trust Manager ", e);
    } catch (KeyStoreException e) {
        Log.e(LOG_TAG, "Key Store exception while initializing TrustManagerFactory ", e);
    }
}
Example 4
Project: coinbase-java-master  File: CoinbaseSSL.java View source code
public static synchronized SSLContext getSSLContext() {
    if (sslContext != null) {
        return sslContext;
    }
    KeyStore trustStore = null;
    InputStream trustStoreInputStream = null;
    try {
        if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) {
            trustStoreInputStream = CoinbaseSSL.class.getResourceAsStream("/com/coinbase/api/ca-coinbase.bks");
            trustStore = KeyStore.getInstance("BKS");
        } else {
            trustStoreInputStream = CoinbaseSSL.class.getResourceAsStream("/com/coinbase/api/ca-coinbase.jks");
            trustStore = KeyStore.getInstance("JKS");
        }
        trustStore.load(trustStoreInputStream, "changeit".toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, tmf.getTrustManagers(), null);
        sslContext = ctx;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (trustStoreInputStream != null) {
            try {
                trustStoreInputStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
    return sslContext;
}
Example 5
Project: ForgeEssentials-master  File: SSLContextHelper.java View source code
public void loadSSLCertificate(InputStream keystore, String storepass, String keypass) throws IOException, GeneralSecurityException {
    if (keystore == null)
        throw new IOException("Invalid keystore");
    // Load KeyStore
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(keystore, storepass.toCharArray());
    // Init KeyManager
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keypass.toCharArray());
    // Init TrustManager
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    // Init SSLContext
    SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    sslCtx = ctx;
}
Example 6
Project: geoserver-master  File: SSLUtilities.java View source code
public static void registerKeyStore(String keyStoreName) {
    try {
        ClassLoader classLoader = SSLUtilities.class.getClassLoader();
        InputStream keyStoreInputStream = classLoader.getResourceAsStream(keyStoreName);
        if (keyStoreInputStream == null) {
            throw new FileNotFoundException("Could not find file named '" + keyStoreName + "' in the CLASSPATH");
        }
        // load the keystore
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(keyStoreInputStream, null);
        // add to known keystore
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keystore);
        // default SSL connections are initialized with the keystore above
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustManagers, null);
        SSLContext.setDefault(sc);
    } catch (IOExceptionGeneralSecurityException |  e) {
        throw new RuntimeException(e);
    }
}
Example 7
Project: cos598b-master  File: TrustManagerFactory.java View source code
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // FIXME: Using a static field to store the certificate chain is a bad idea. Instead
    // create a CertificateException subclass and store the chain there.
    TrustManagerFactory.setLastCertChain(chain);
    try {
        defaultTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException e) {
        localTrustManager.checkServerTrusted(new X509Certificate[] { chain[0] }, authType);
    }
    if (!DomainNameChecker.match(chain[0], mHost)) {
        try {
            String dn = chain[0].getSubjectDN().toString();
            if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
                return;
            }
        } catch (KeyStoreException e) {
            throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
        }
        throw new CertificateException("Certificate domain name does not match " + mHost);
    }
}
Example 8
Project: k9mail-master  File: TrustManagerFactory.java View source code
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    TrustManagerFactory.setLastCertChain(chain);
    try {
        defaultTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException e) {
        localTrustManager.checkServerTrusted(new X509Certificate[] { chain[0] }, authType);
    }
    if (!DomainNameChecker.match(chain[0], mHost)) {
        try {
            String dn = chain[0].getSubjectDN().toString();
            if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
                return;
            }
        } catch (KeyStoreException e) {
            throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
        }
        throw new CertificateException("Certificate domain name does not match " + mHost);
    }
}
Example 9
Project: SVQCOM-master  File: TrustManagerFactory.java View source code
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    // FIXME: Using a static field to store the certificate chain is a
    // bad idea. Instead
    // create a CertificateException subclass and store the chain there.
    TrustManagerFactory.setLastCertChain(chain);
    try {
        defaultTrustManager.checkServerTrusted(chain, authType);
    } catch (CertificateException e) {
        localTrustManager.checkServerTrusted(new X509Certificate[] { chain[0] }, authType);
    }
    try {
        String dn = chain[0].getSubjectDN().toString();
        if ((dn != null) && (dn.equalsIgnoreCase(keyStore.getCertificateAlias(chain[0])))) {
            return;
        }
    } catch (KeyStoreException e) {
        throw new CertificateException("Certificate cannot be verified; KeyStore Exception: " + e);
    }
    throw new CertificateException("Certificate domain name does not match " + mHost);
}
Example 10
Project: groundhog-reader-master  File: TrustManagerFactory.java View source code
/**
     * Logging of certificates, to help debugging trust issues.  Logging strategy:
     *   Trusting a certificate:  Lightweight log about it
     *   Fully checking:  Silent if OK, verbose log it failure
     *
     * @param chain the certificate chain to dump
     * @param caller a prefix that will be added to each log
     * @param verbose if true, the issuer and dates will also be logged
     */
private static void logCertificates(X509Certificate[] chain, String caller, boolean verbose) {
    //if (Email.DEBUG) {
    if (true) {
        for (int i = 0; i < chain.length; ++i) {
            Log.d("Groundhog:TrustManagerFactory", caller + " Certificate #" + i);
            Log.d("Groundhog:TrustManagerFactory", "  subject=" + chain[i].getSubjectDN());
            if (verbose) {
                Log.d("Groundhog:TrustManagerFactory", "  issuer=" + chain[i].getIssuerDN());
                Log.d("Groundhog:TrustManagerFactory", "  dates=" + chain[i].getNotBefore() + " to " + chain[i].getNotAfter());
            }
        }
    }
}
Example 11
Project: JBossAS51-master  File: Context.java View source code
/*
    * Returns an initialized JSSE SSLContext that uses the KeyManagerFactory
    * and TrustManagerFactory objects encapsulated by a given JBossSX 
    * SecurityDomain.
    */
static SSLContext forDomain(SecurityDomain securityDomain) throws IOException {
    SSLContext sslCtx = null;
    try {
        sslCtx = SSLContext.getInstance("TLS");
        KeyManagerFactory keyMgr = securityDomain.getKeyManagerFactory();
        if (keyMgr == null)
            throw new IOException("KeyManagerFactory is null for security domain: " + securityDomain.getSecurityDomain());
        TrustManagerFactory trustMgr = securityDomain.getTrustManagerFactory();
        TrustManager[] trustMgrs = null;
        if (trustMgr != null)
            trustMgrs = trustMgr.getTrustManagers();
        sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
        return sslCtx;
    } catch (NoSuchAlgorithmException e) {
        log.error("Failed to get SSLContext for TLS algorithm", e);
        throw new IOException("Failed to get SSLContext for TLS algorithm");
    } catch (KeyManagementException e) {
        log.error("Failed to init SSLContext", e);
        throw new IOException("Failed to init SSLContext");
    } catch (SecurityException e) {
        log.error("Failed to init SSLContext", e);
        throw new IOException("Failed to init SSLContext");
    }
}
Example 12
Project: JBossAS_5_1_EDG-master  File: Context.java View source code
/*
    * Returns an initialized JSSE SSLContext that uses the KeyManagerFactory
    * and TrustManagerFactory objects encapsulated by a given JBossSX 
    * SecurityDomain.
    */
static SSLContext forDomain(SecurityDomain securityDomain) throws IOException {
    SSLContext sslCtx = null;
    try {
        sslCtx = SSLContext.getInstance("TLS");
        KeyManagerFactory keyMgr = securityDomain.getKeyManagerFactory();
        if (keyMgr == null)
            throw new IOException("KeyManagerFactory is null for security domain: " + securityDomain.getSecurityDomain());
        TrustManagerFactory trustMgr = securityDomain.getTrustManagerFactory();
        TrustManager[] trustMgrs = null;
        if (trustMgr != null)
            trustMgrs = trustMgr.getTrustManagers();
        sslCtx.init(keyMgr.getKeyManagers(), trustMgrs, null);
        return sslCtx;
    } catch (NoSuchAlgorithmException e) {
        log.error("Failed to get SSLContext for TLS algorithm", e);
        throw new IOException("Failed to get SSLContext for TLS algorithm");
    } catch (KeyManagementException e) {
        log.error("Failed to init SSLContext", e);
        throw new IOException("Failed to init SSLContext");
    } catch (SecurityException e) {
        log.error("Failed to init SSLContext", e);
        throw new IOException("Failed to init SSLContext");
    }
}
Example 13
Project: advanced-networking-master  File: CustomSSLSocketFactory.java View source code
public static SSLSocketFactory getInstance() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, KeyManagementException, IOException {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        String trustStore = System.getProperty("javax.net.ssl.trustStore");
        String trustStorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
        if (trustStore == null || trustStorePassword == null) {
            throw new IOException("javax.net.ssl.trustStore/javax.net.ssl.trustStorePassword property - not set");
        }
        FileInputStream keystoreStream = new FileInputStream(trustStore);
        try {
            keystore = KeyStore.getInstance(KeyStore.getDefaultType());
            keystore.load(keystoreStream, trustStorePassword.toCharArray());
        } finally {
            keystoreStream.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    trustManagerFactory.init(keystore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLContext.setDefault(sslContext);
    return new SSLSocketFactory(sslContext, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
Example 14
Project: AFBaseLibrary-master  File: AFCertificateUtil.java View source code
public static SSLSocketFactory setCertificates(Context context, String... certificateNames) {
    InputStream[] certificates = getCertificatesByAssert(context, certificateNames);
    if (certificates == null) {
        return null;
    }
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(null, trustManagerFactory.getTrustManagers(), new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 15
Project: android-sdk-sources-for-api-level-23-master  File: TrustManagerFactorySpiTest.java View source code
/**
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
     */
public void test_engineInit_01() throws NoSuchAlgorithmException, KeyStoreException {
    factory.reset();
    Provider provider = new MyProvider();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", provider);
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        tmf.init(ks);
    } catch (Exception e) {
        fail("Unexpected exception " + e.toString());
    }
    assertTrue(factory.isEngineInitCalled());
    assertEquals(ks, factory.getKs());
    factory.reset();
    tmf.init((KeyStore) null);
    assertTrue(factory.isEngineInitCalled());
    assertNull(factory.getKs());
}
Example 16
Project: android-security-master  File: HttpClientProvider.java View source code
private static void setupTls(OkHttpClient.Builder builder) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init((KeyStore) null);
        for (TrustManager trustManager : factory.getTrustManagers()) {
            if (trustManager instanceof X509TrustManager) {
                builder.sslSocketFactory(new Tls12SslSocketFactory(), (X509TrustManager) trustManager);
                break;
            }
        }
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "Failed to initialize SSL Socket Factory", e);
    }
}
Example 17
Project: AndroidAsync-master  File: SSLTests.java View source code
public void testKeys() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    kmf.init(ks, "storepass".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
    ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    tmf.init(ts);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.listenSecure(8888, sslContext);
    httpServer.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("hello");
        }
    });
    Thread.sleep(1000);
    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setSSLContext(sslContext);
    AsyncHttpClient.getDefaultInstance().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
    AsyncHttpClient.getDefaultInstance().executeString(new AsyncHttpGet("https://localhost:8888/"), null).get();
}
Example 18
Project: android_frameworks_base-master  File: TestUtils.java View source code
public static SSLContext getSSLContext(ConfigSource source) throws Exception {
    ApplicationConfig config = new ApplicationConfig(source);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX", new NetworkSecurityConfigProvider());
    tmf.init(new RootTrustManagerFactorySpi.ApplicationConfigParameters(config));
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
}
Example 19
Project: Bingo-master  File: HttpsCoder.java View source code
private static SSLSocketFactory getSSLSocketFactory(InputStream keyStoreInputStream, String password) throws Exception {
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore keyStore = getKeyStore(keyStoreInputStream, password);
    keyManagerFactory.init(keyStore, password.toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    SSLContext context = SSLContext.getInstance(PROTOCOL);
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
    keyStoreInputStream.close();
    return context.getSocketFactory();
}
Example 20
Project: caelum-stella-master  File: CertificateAndPrivateKey.java View source code
public void enableSSLForServer(InputStream serverCertificateFile, String password) {
    try {
        KeyStore trustStore = KeyStore.getInstance("JKS");
        trustStore.load(serverCertificateFile, password.toCharArray());
        String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(defaultAlgorithm);
        trustManagerFactory.init(trustStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        KeyManager[] keyManagers = { new HSKeyManager(certificate, privateKey) };
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 21
Project: channelmanager2-master  File: MockSSLEngineFactory.java View source code
public SSLEngine createEngineForSocket() throws GeneralSecurityException, IOException {
    // Create/initialize the SSLContext with key material
    char[] passphrase = password.toCharArray();
    // First initialize the key and trust material.
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(clientKeystore), passphrase);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    //****************Client side specific*********************
    // TrustManager's decide whether to allow connections.
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    sslContext.init(null, tmf.getTrustManagers(), null);
    //****************Client side specific*********************
    SSLEngine engine = sslContext.createSSLEngine();
    engine.setUseClientMode(true);
    return engine;
}
Example 22
Project: dse_driver_examples-master  File: TestSSL.java View source code
private static SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws Exception {
    FileInputStream tsf = new FileInputStream(truststorePath);
    FileInputStream ksf = new FileInputStream(keystorePath);
    SSLContext ctx = SSLContext.getInstance("SSL");
    KeyStore ts = KeyStore.getInstance("JKS");
    ts.load(tsf, truststorePassword.toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ts);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(ksf, keystorePassword.toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, keystorePassword.toCharArray());
    ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
    return ctx;
}
Example 23
Project: gngr-master  File: TrustManager.java View source code
public static SSLSocketFactory makeSSLSocketFactory(final InputStream extraCertsStream) {
    final String sep = File.separator;
    final String hardDefaultPath = System.getProperty("java.home") + sep + "lib" + sep + "security" + sep + "cacerts";
    final String defaultStorePath = System.getProperty("javax.net.ssl.trustStore", hardDefaultPath);
    try (final FileInputStream defaultIS = new FileInputStream(defaultStorePath)) {
        final KeyStore defKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        defKeyStore.load(defaultIS, "changeit".toCharArray());
        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(extraCertsStream, null);
        // final KeyStore keyStore =  KeyStore.Builder.newInstance(defKeyStore, null).getKeyStore();
        final Enumeration<String> aliases = defKeyStore.aliases();
        while (aliases.hasMoreElements()) {
            final String alias = aliases.nextElement();
            if (defKeyStore.isCertificateEntry(alias)) {
                final Entry entry = defKeyStore.getEntry(alias, null);
                keyStore.setEntry(alias, entry, null);
            }
        }
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);
        final SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, tmf.getTrustManagers(), null);
        return sc.getSocketFactory();
    } catch (KeyManagementExceptionKeyStoreException | NoSuchAlgorithmException | IOException | CertificateException | UnrecoverableEntryException |  e) {
        throw new RuntimeException(e);
    }
}
Example 24
Project: instantcom-mm7-master  File: X509TrustManagerImpl.java View source code
private void initDefaultTrustManager() throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(certificateTrustStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            defaultTrustManager = (X509TrustManager) trustManager;
            break;
        }
    }
}
Example 25
Project: ion-master  File: SelfSignedCertificateTests.java View source code
public void testKeys() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    kmf.init(ks, "storepass".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
    ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    tmf.init(ts);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.listenSecure(8888, sslContext);
    httpServer.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("hello");
        }
    });
    Thread.sleep(1000);
    Ion ion = Ion.getInstance(getContext(), "CustomSSL");
    ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
    ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
    ion.build(getContext()).load("https://localhost:8888/").asString().get();
}
Example 26
Project: jetty-plugin-support-master  File: SslSocketServerTest.java View source code
@BeforeClass
public static void init() throws Exception {
    SslSocketConnector connector = new SslSocketConnector();
    String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore";
    SslContextFactory cf = connector.getSslContextFactory();
    cf.setKeyStorePath(keystorePath);
    cf.setKeyStorePassword("storepwd");
    cf.setKeyManagerPassword("keypwd");
    cf.setTrustStore(keystorePath);
    cf.setTrustStorePassword("storepwd");
    startServer(connector);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(new FileInputStream(connector.getKeystore()), "storepwd".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);
    __sslContext = SSLContext.getInstance("TLSv1");
    __sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
}
Example 27
Project: jetty-spdy-master  File: SslSocketServerTest.java View source code
@BeforeClass
public static void init() throws Exception {
    SslSocketConnector connector = new SslSocketConnector();
    String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore";
    SslContextFactory cf = connector.getSslContextFactory();
    cf.setKeyStorePath(keystorePath);
    cf.setKeyStorePassword("storepwd");
    cf.setKeyManagerPassword("keypwd");
    cf.setTrustStore(keystorePath);
    cf.setTrustStorePassword("storepwd");
    startServer(connector);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(new FileInputStream(connector.getKeystore()), "storepwd".toCharArray());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);
    __sslContext = SSLContext.getInstance("TLSv1");
    __sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
}
Example 28
Project: jetty.project-master  File: SslSelectChannelTimeoutTest.java View source code
@Before
public void init() throws Exception {
    String keystorePath = System.getProperty("basedir", ".") + "/src/test/resources/keystore";
    SslContextFactory sslContextFactory = new SslContextFactory();
    sslContextFactory.setKeyStorePath(keystorePath);
    sslContextFactory.setKeyStorePassword("storepwd");
    sslContextFactory.setKeyManagerPassword("keypwd");
    sslContextFactory.setTrustStorePath(keystorePath);
    sslContextFactory.setTrustStorePassword("storepwd");
    ServerConnector connector = new ServerConnector(_server, 1, 1, sslContextFactory);
    //250 msec max idle
    connector.setIdleTimeout(MAX_IDLE_TIME);
    startServer(connector);
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream stream = new FileInputStream(keystorePath)) {
        keystore.load(stream, "storepwd".toCharArray());
    }
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keystore);
    __sslContext = SSLContext.getInstance("SSL");
    __sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
}
Example 29
Project: keycloak-master  File: SslUtil.java View source code
public static SSLContext createSSLContext(final KeyStore keyStore, String password, final KeyStore trustStore) throws Exception {
    KeyManager[] keyManagers;
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    keyManagers = keyManagerFactory.getKeyManagers();
    TrustManager[] trustManagers = null;
    if (trustStore != null) {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        trustManagers = trustManagerFactory.getTrustManagers();
    }
    SSLContext sslContext;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    return sslContext;
}
Example 30
Project: kodex-master  File: SecurityConfigurationTestUtils.java View source code
protected Client createHttpClient() {
    OkHttpClient client = new OkHttpClient();
    client.setReadTimeout(0, TimeUnit.MILLISECONDS);
    client.setConnectTimeout(0, TimeUnit.MILLISECONDS);
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(Keystores.loadKeystoreFromResource("security/rhizome.jks", "rhizome".toCharArray()));
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        client.setSslSocketFactory(sslContext.getSocketFactory());
    } catch (NoSuchAlgorithmExceptionKeyManagementException | KeyStoreException | CertificateException | IOException |  e) {
        e.printStackTrace();
    }
    return new OkClient(client);
}
Example 31
Project: LittleProxy-mitm-master  File: MergeTrustManager.java View source code
private X509TrustManager defaultTrustManager(KeyStore trustStore) throws NoSuchAlgorithmException, KeyStoreException {
    String tma = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tma);
    tmf.init(trustStore);
    TrustManager[] trustManagers = tmf.getTrustManagers();
    for (TrustManager each : trustManagers) {
        if (each instanceof X509TrustManager) {
            return (X509TrustManager) each;
        }
    }
    throw new IllegalStateException("Missed X509TrustManager in " + Arrays.toString(trustManagers));
}
Example 32
Project: monsiaj-master  File: JarVerifier.java View source code
public static boolean verify(JarFile jar) throws Exception {
    X509Certificate[] certs = null;
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init((KeyStore) null);
    for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
        if (trustManager instanceof X509TrustManager) {
            X509TrustManager x509TrustManager = (X509TrustManager) trustManager;
            certs = x509TrustManager.getAcceptedIssuers();
        }
    }
    boolean result = false;
    Enumeration<JarEntry> entries = jar.entries();
    while (entries.hasMoreElements()) {
        JarEntry entry = entries.nextElement();
        try {
            InputStream iis = jar.getInputStream(entry);
        } catch (SecurityException se) {
            return false;
        }
        if (verifyCert(entry.getCertificates(), certs)) {
            result = true;
        }
    }
    return result;
}
Example 33
Project: Pin-Fever-Android-master  File: SelfSignedCertificateTests.java View source code
public void testKeys() throws Exception {
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509");
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    kmf.init(ks, "storepass".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = KeyStore.getInstance(KeyStore.getDefaultType());
    ts.load(getContext().getResources().openRawResource(R.raw.keystore), "storepass".toCharArray());
    tmf.init(ts);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    AsyncHttpServer httpServer = new AsyncHttpServer();
    httpServer.listenSecure(8888, sslContext);
    httpServer.get("/", new HttpServerRequestCallback() {

        @Override
        public void onRequest(AsyncHttpServerRequest request, AsyncHttpServerResponse response) {
            response.send("hello");
        }
    });
    Thread.sleep(1000);
    Ion ion = Ion.getInstance(getContext(), "CustomSSL");
    ion.getHttpClient().getSSLSocketMiddleware().setSSLContext(sslContext);
    ion.getHttpClient().getSSLSocketMiddleware().setTrustManagers(tmf.getTrustManagers());
    ion.build(getContext()).load("https://localhost:8888/").asString().get();
}
Example 34
Project: platform_frameworks_base-master  File: TestUtils.java View source code
public static SSLContext getSSLContext(ConfigSource source) throws Exception {
    ApplicationConfig config = new ApplicationConfig(source);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX", new NetworkSecurityConfigProvider());
    tmf.init(new RootTrustManagerFactorySpi.ApplicationConfigParameters(config));
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    return context;
}
Example 35
Project: property-db-master  File: X509TrustManagerExtensionsTest.java View source code
public void testNormalUseCase() throws Exception {
    String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
    String defaultKeystoreType = KeyStore.getDefaultType();
    tmf.init(KeyStore.getInstance(defaultKeystoreType));
    TrustManager[] tms = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            new X509TrustManagerExtensions((X509TrustManager) tm);
            return;
        }
    }
    fail();
}
Example 36
Project: ratpack-master  File: SslContexts.java View source code
public static TrustManagerFactory trustManagerFactory(InputStream trustStoreStream, char[] trustStorePassword) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
    TrustManagerFactory trustManagerFactory;
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(trustStoreStream, trustStorePassword);
    trustManagerFactory = TrustManagerFactory.getInstance(getAlgorithm());
    trustManagerFactory.init(trustStore);
    return trustManagerFactory;
}
Example 37
Project: rtmp-rtsp-stream-client-java-master  File: CreateSSLSocket.java View source code
/**
   *
   * @param keyStore created with createKeyStore()
   * @param host variable from RtspClient
   * @param port variable from RtspClient
   * @return
   */
public static Socket createSSlSocket(KeyStore keyStore, String host, int port) {
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory().createSocket(host, port);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmExceptionIOException |  e) {
        e.printStackTrace();
        return null;
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}
Example 38
Project: sissi-master  File: CertificateContextBuilder.java View source code
private TrustManager[] getTrustManagers(Certificate trust) throws Exception {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    InputStream certificate = trust.getFile().openStream();
    try {
        KeyStore ks = KeyStore.getInstance(this.keystore);
        ks.load(certificate, trust.getPassword());
        factory.init(ks);
    } finally {
        IOUtil.closeQuietly(certificate);
    }
    return factory.getTrustManagers();
}
Example 39
Project: tinify-java-master  File: SSLContext.java View source code
public static SSLSocketFactory getSocketFactory() {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(certificateStream());
        KeyStore keyStore = newEmptyKeyStore();
        int index = 0;
        for (Certificate certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificate);
        }
        if (keyStore.size() == 0) {
            /* The resource stream was empty, no certificates were found. */
            throw new ConnectionException("Unable to load any CA certificates.", null);
        }
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, null);
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        javax.net.ssl.SSLContext sslContext = javax.net.ssl.SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
        return sslContext.getSocketFactory();
    } catch (GeneralSecurityExceptionIOException |  e) {
        throw new ConnectionException("Error while loading trusted CA certificates.", e);
    }
}
Example 40
Project: TLSDemo-master  File: CustomSSLSocketFactory.java View source code
private TrustManager[] fetchTrustManager(InputStream in, String passwd) {
    KeyStore keyStore = null;
    try {
        keyStore = KeyStore.getInstance("BKS");
        keyStore.load(in, passwd.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(keyStore);
        return tmf.getTrustManagers();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
Example 41
Project: webbit-master  File: SslFactory.java View source code
public SSLContext getClientContext() throws WebbitException {
    try {
        SSLContext sslContext = SSLContext.getInstance(PROTOCOL);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509", "SunJSSE");
        tmf.init(ks);
        TrustManager[] trustManagers = tmf.getTrustManagers();
        sslContext.init(null, trustManagers, null);
        return sslContext;
    } catch (Exception e) {
        throw new WebbitException(e);
    }
}
Example 42
Project: webpie-master  File: SelfSignedSSLEngineFactory.java View source code
public SSLEngine createEngineForClient(String host, int port) {
    try {
        // Create/initialize the SSLContext with key material
        char[] passphrase = password.toCharArray();
        // First initialize the key and trust material.
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(clientKeystore), passphrase);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        //****************Client side specific*********************
        // TrustManager's decide whether to allow connections.
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);
        sslContext.init(null, tmf.getTrustManagers(), null);
        //****************Client side specific*********************
        SSLEngine engine = sslContext.createSSLEngine(host, port);
        engine.setUseClientMode(true);
        return engine;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Example 43
Project: wso2-synapse-master  File: TrustKeyStoreInformation.java View source code
/**
     * Returns the TrustManagerFactory instance
     *
     * @return TrustManagerFactory instance
     */
public TrustManagerFactory getTrustManagerFactoryInstance() {
    try {
        if (log.isDebugEnabled()) {
            log.debug("Creating a TrustManagerFactory instance");
        }
        KeyStore trustStore = this.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        return trustManagerFactory;
    } catch (Exception e) {
        handleException("Error getting TrustManagerFactory: ", e);
    }
    return null;
}
Example 44
Project: JamVM-PH-master  File: Jessie.java View source code
public Object run() {
    put("SSLContext.TLSv1.1", SSLContextImpl.class.getName());
    put("Alg.Alias.SSLContext.SSLv3", "TLSv1.1");
    put("Alg.Alias.SSLContext.TLSv1", "TLSv1.1");
    put("Alg.Alias.SSLContext.TLSv1.0", "TLSv1.1");
    put("Alg.Alias.SSLContext.TLS", "TLSv1.1");
    put("Alg.Alias.SSLContext.SSL", "TLSv1.1");
    put("KeyManagerFactory.JessieX509", X509KeyManagerFactory.class.getName());
    put("TrustManagerFactory.JessieX509", X509TrustManagerFactory.class.getName());
    put("KeyManagerFactory.JessiePSK", PreSharedKeyManagerFactoryImpl.class.getName());
    //put("TrustManagerFactory.SRP",        SRPTrustManagerFactory.class.getName());
    put("Mac.SSLv3HMac-MD5", SSLv3HMacMD5Impl.class.getName());
    put("Mac.SSLv3HMac-SHA", SSLv3HMacSHAImpl.class.getName());
    put("Signature.TLSv1.1-RSA", SSLRSASignatureImpl.class.getName());
    put("Alg.Alias.Signature.TLSv1-RSA", "TLSv1.1-RSA");
    put("Alg.Alias.Signature.SSLv3-RSA", "TLSv1.1-RSA");
    return null;
}
Example 45
Project: androidpn-master  File: SSLTrustManagerFactory.java View source code
public static TrustManager[] getTrustManagers(String storeType, String truststore, String trustpass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    TrustManager[] trustManagers;
    if (truststore == null) {
        trustManagers = null;
    } else {
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if (trustpass == null) {
            trustpass = "";
        }
        KeyStore keyStore = KeyStore.getInstance(storeType);
        keyStore.load(new FileInputStream(truststore), trustpass.toCharArray());
        trustFactory.init(keyStore);
        trustManagers = trustFactory.getTrustManagers();
    }
    return trustManagers;
}
Example 46
Project: androidpn-server-app-master  File: SSLTrustManagerFactory.java View source code
public static TrustManager[] getTrustManagers(String storeType, String truststore, String trustpass) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
    TrustManager[] trustManagers;
    if (truststore == null) {
        trustManagers = null;
    } else {
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        if (trustpass == null) {
            trustpass = "";
        }
        KeyStore keyStore = KeyStore.getInstance(storeType);
        keyStore.load(new FileInputStream(truststore), trustpass.toCharArray());
        trustFactory.init(keyStore);
        trustManagers = trustFactory.getTrustManagers();
    }
    return trustManagers;
}
Example 47
Project: apiman-master  File: KeyStoreUtil.java View source code
/**
     * Gets an array of trust managers for a given store+password.
     *
     * @param pathInfo
     * @return
     * @throws Exception
     */
public static TrustManager[] getTrustManagers(Info pathInfo) throws Exception {
    File trustStoreFile = new File(pathInfo.store);
    if (!trustStoreFile.isFile()) {
        throw new Exception("No TrustManager: " + pathInfo.store + " does not exist.");
    }
    String trustStorePassword = pathInfo.password;
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore truststore = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(pathInfo.store);
    truststore.load(fis, trustStorePassword.toCharArray());
    fis.close();
    tmf.init(truststore);
    return tmf.getTrustManagers();
}
Example 48
Project: arangodb-java-driver-master  File: ArangoSslTest.java View source code
@Test
@Ignore
public void connect() throws Exception {
    final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(this.getClass().getResourceAsStream(SSL_TRUSTSTORE), SSL_TRUSTSTORE_PASSWORD.toCharArray());
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, SSL_TRUSTSTORE_PASSWORD.toCharArray());
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    final SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    final ArangoDB arangoDB = new ArangoDB.Builder().port(8530).useSsl(true).sslContext(sc).build();
    final ArangoDBVersion version = arangoDB.getVersion();
    assertThat(version, is(notNullValue()));
}
Example 49
Project: armeria-master  File: SessionOptionsTest.java View source code
@Test
public void valueOverrideTest() {
    Duration connectionTimeout = Duration.ofMillis(10);
    Duration idleTimeout = Duration.ofMillis(200);
    EventLoop eventLoop = mock(EventLoop.class);
    TrustManagerFactory trustManagerFactory = mock(TrustManagerFactory.class);
    Integer maxConcurrency = 1;
    SessionOptions options = SessionOptions.of(CONNECT_TIMEOUT.newValue(connectionTimeout), IDLE_TIMEOUT.newValue(idleTimeout), EVENT_LOOP_GROUP.newValue(eventLoop), TRUST_MANAGER_FACTORY.newValue(trustManagerFactory));
    assertThat(options.get(CONNECT_TIMEOUT), is(Optional.of(connectionTimeout)));
    assertThat(options.get(IDLE_TIMEOUT), is(Optional.of(idleTimeout)));
    assertThat(options.get(EVENT_LOOP_GROUP), is(Optional.of(eventLoop)));
}
Example 50
Project: BansheeCore-master  File: SSLSocketFactoryGenerator.java View source code
private TrustManager[] getTrustManagers(InputStream trustStoreStream, String trustStorePassword) throws GeneralSecurityException, IOException {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(trustStoreStream, trustStorePassword.toCharArray());
        factory.init(keyStore);
        TrustManager[] managers = factory.getTrustManagers();
        return managers;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
Example 51
Project: bc-java-master  File: CipherSuitesTestCase.java View source code
public Exception call() throws Exception {
    try {
        TrustManagerFactory trustMgrFact = TrustManagerFactory.getInstance("PKIX", BouncyCastleJsseProvider.PROVIDER_NAME);
        trustMgrFact.init(config.clientTrustStore);
        SSLContext clientContext = SSLContext.getInstance("TLS", BouncyCastleJsseProvider.PROVIDER_NAME);
        clientContext.init(null, trustMgrFact.getTrustManagers(), SecureRandom.getInstance("DEFAULT", BouncyCastleProvider.PROVIDER_NAME));
        SSLSocketFactory fact = clientContext.getSocketFactory();
        SSLSocket cSock = (SSLSocket) fact.createSocket(HOST, port);
        cSock.setEnabledCipherSuites(new String[] { config.cipherSuite });
        this.tlsUnique = TestUtils.getChannelBinding(cSock, "tls-unique");
        TestProtocolUtil.doClientProtocol(cSock, "Hello");
    } finally {
        latch.countDown();
    }
    return null;
}
Example 52
Project: camel-master  File: AbstractJsseParametersTest.java View source code
protected CamelContext createPropertiesPlaceholderAwareContext() throws Exception {
    Properties supplementalProperties = new Properties();
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    SecureRandom sr = null;
    try {
        sr = SecureRandom.getInstance("SHA1PRNG");
    } catch (NoSuchAlgorithmException e) {
    }
    SSLContext sslc = SSLContext.getInstance("TLS");
    sslc.init(null, null, null);
    SSLSocket socket = (SSLSocket) sslc.getSocketFactory().createSocket();
    supplementalProperties.setProperty("keyStoreParameters.type", KeyStore.getDefaultType());
    supplementalProperties.setProperty("keyStoreParameters.provider", ks.getProvider().getName());
    supplementalProperties.setProperty("keyManagersParameters.algorithm", KeyManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty("keyManagersParameters.provider", kmf.getProvider().getName());
    supplementalProperties.setProperty("trustManagersParameters.algorithm", TrustManagerFactory.getDefaultAlgorithm());
    supplementalProperties.setProperty("trustManagersParameters.provider", tmf.getProvider().getName());
    if (sr != null) {
        supplementalProperties.setProperty("secureRandomParameters.algorithm", "SHA1PRNG");
        supplementalProperties.setProperty("secureRandomParameters.provider", sr.getProvider().getName());
    }
    supplementalProperties.setProperty("sslContextParameters.provider", sslc.getProvider().getName());
    supplementalProperties.setProperty("cipherSuite.0", socket.getSupportedCipherSuites()[0]);
    // Have to skip this guy because he doesn't work with TLS as the SSLContext protocol
    String ssp = "";
    for (String protocol : socket.getSupportedProtocols()) {
        if (!"SSLv2Hello".equals(protocol)) {
            ssp = protocol;
            break;
        }
    }
    supplementalProperties.setProperty("secureSocketProtocol.0", ssp);
    return this.createPropertiesPlaceholderAwareContext(supplementalProperties);
}
Example 53
Project: codedx-plugin-master  File: ReloadableX509TrustManager.java View source code
/* package-private */
void reloadTrustManager() throws GeneralSecurityException {
    KeyStore ks = certManager.asKeyStore();
    // initialize a new TMF with the KeyStore we just created
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    // acquire an X509 trust manager from the TMF
    // and update the `tmDelegate` to that value
    TrustManager[] tms = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            tmDelegate = (X509TrustManager) tm;
            return;
        }
    }
    // should have returned in the `for` loop above
    throw new NoSuchAlgorithmException("No X509TrustManager in TrustManagerFactory");
}
Example 54
Project: couchbase-jvm-core-master  File: SSLEngineFactory.java View source code
/**
     * Returns a new {@link SSLEngine} constructed from the config settings.
     *
     * @return a {@link SSLEngine} ready to be used.
     */
public SSLEngine get() {
    try {
        String pass = env.sslKeystorePassword();
        char[] password = pass == null || pass.isEmpty() ? null : pass.toCharArray();
        KeyStore ks = env.sslKeystore();
        if (ks == null) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            String ksFile = env.sslKeystoreFile();
            if (ksFile == null || ksFile.isEmpty()) {
                throw new IllegalArgumentException("Path to Keystore File must not be null or empty.");
            }
            ks.load(new FileInputStream(ksFile), password);
        }
        String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(defaultAlgorithm);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(defaultAlgorithm);
        kmf.init(ks, password);
        tmf.init(ks);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        SSLEngine engine = ctx.createSSLEngine();
        engine.setUseClientMode(true);
        return engine;
    } catch (Exception ex) {
        throw new SSLException("Could not create SSLEngine.", ex);
    }
}
Example 55
Project: countly-sdk-appcelerator-titanium-android-master  File: CertificateTrustManager.java View source code
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (chain == null) {
        throw new IllegalArgumentException("PublicKeyManager: X509Certificate array is null");
    }
    if (!(chain.length > 0)) {
        throw new IllegalArgumentException("PublicKeyManager: X509Certificate is empty");
    }
    if (!(null != authType && authType.equalsIgnoreCase("RSA"))) {
        throw new CertificateException("PublicKeyManager: AuthType is not RSA");
    }
    // Perform customary SSL/TLS checks
    TrustManagerFactory tmf;
    try {
        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init((KeyStore) null);
        for (TrustManager trustManager : tmf.getTrustManagers()) {
            ((X509TrustManager) trustManager).checkServerTrusted(chain, authType);
        }
    } catch (Exception e) {
        throw new CertificateException(e);
    }
    byte server[] = chain[0].getPublicKey().getEncoded();
    for (byte[] key : keys) {
        if (Arrays.equals(key, server)) {
            return;
        }
    }
    throw new CertificateException("Public keys didn't pass checks");
}
Example 56
Project: cyberduck-master  File: DefaultX509TrustManager.java View source code
protected void init(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
Example 57
Project: dc---master  File: HTTPSServerThread.java View source code
SSLContext createSSLContext() throws Exception {
    KeyManagerFactory mgrFact = KeyManagerFactory.getInstance("SunX509");
    KeyStore serverStore = KeyStore.getInstance("JKS");
    serverStore.load(new ByteArrayInputStream(KeyStores.server), SERVER_PASSWORD);
    mgrFact.init(serverStore, SERVER_PASSWORD);
    // set up a trust manager so we can recognize the server
    TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(new ByteArrayInputStream(KeyStores.trustStore), TRUST_STORE_PASSWORD);
    trustFact.init(trustStore);
    // create a context and set up a socket factory
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(mgrFact.getKeyManagers(), trustFact.getTrustManagers(), null);
    return sslContext;
}
Example 58
Project: dsys-snio-master  File: DemoSSLContext.java View source code
public static SSLContext getDemoContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException, IOException {
    final char[] password = "password".toCharArray();
    // First initialize the key and trust material.
    final KeyStore ksKeys = KeyStore.getInstance("JKS");
    try (final InputStream in = SSLEchoClient.class.getResourceAsStream("nodes.jks")) {
        ksKeys.load(in, password);
    }
    final KeyStore ksTrust = KeyStore.getInstance("JKS");
    try (final InputStream in = SSLEchoClient.class.getResourceAsStream("nodes.jks")) {
        ksTrust.load(in, password);
    }
    // KeyManager's decide which key material to use.
    final KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ksKeys, password);
    // TrustManager's decide whether to allow connections.
    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ksTrust);
    final SSLContext context = SSLContext.getInstance("TLS");
    context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return context;
}
Example 59
Project: dz-master  File: SSLContextFactory.java View source code
/**
     * Create an SSL context object.
     * 
     * @param protocol Secure protocol. Values that are known to work are:
     * {@code SSLv3}, {@code TLS}.
     * @param keyStoreName Keystore file name.
     * @param password Keystore password.
     * @return The SSL context.
     * @throws SSLException If there was an SSL related problem.
     */
public static SSLContext createContext(String protocol, String keyStoreName, String password) throws SSLException {
    try {
        SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
        SSLContext ctx = SSLContext.getInstance(protocol);
        if (password == null) {
            // Whatever...
            password = "";
        }
        char[] passwordArray = new char[password.length()];
        for (int idx = 0; idx < password.length(); idx++) {
            passwordArray[idx] = password.charAt(idx);
        }
        FileInputStream keyStoreFile = new FileInputStream(keyStoreName);
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(keyStoreFile, null);
        String keyManagementAlgorithm = "SunX509";
        KeyManagerFactory km = KeyManagerFactory.getInstance(keyManagementAlgorithm);
        km.init(ks, passwordArray);
        KeyManager[] keyManagerSet = km.getKeyManagers();
        for (int i = 0; i < keyManagerSet.length; i++) {
        // System.err.println("KeyManager " + keyManagerSet[i]);
        }
        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(keyManagementAlgorithm);
        tmFactory.init(ks);
        TrustManager[] trustManagerSet = tmFactory.getTrustManagers();
        for (int i = 0; i < trustManagerSet.length; i++) {
        // System.err.println("TrustManager " + trustManagerSet[i]);
        }
        ctx.init(keyManagerSet, trustManagerSet, random);
        return ctx;
    } catch (Throwable t) {
        SSLException ex = new SSLException("Can't create secure connection (SSLContext)");
        ex.initCause(t);
        throw ex;
    }
}
Example 60
Project: hazelcast-archive-master  File: BasicSSLContextFactory.java View source code
public void init(Properties properties) throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    KeyStore ts = KeyStore.getInstance("JKS");
    String keyStorePassword = properties.getProperty("keyStorePassword");
    if (keyStorePassword == null) {
        keyStorePassword = System.getProperty("javax.net.ssl.keyStorePassword");
    }
    String keyStore = properties.getProperty("keyStore");
    if (keyStore == null) {
        keyStore = System.getProperty("javax.net.ssl.keyStore");
    }
    if (keyStore == null || keyStorePassword == null) {
        throw new RuntimeException("SSL is enabled but keyStore[Password] properties aren't set!");
    }
    String keyManagerAlgorithm = getProperty(properties, "keyManagerAlgorithm", "SunX509");
    String trustManagerAlgorithm = getProperty(properties, "trustManagerAlgorithm", "SunX509");
    String protocol = getProperty(properties, "protocol", "TLS");
    final char[] passPhrase = keyStorePassword.toCharArray();
    final String keyStoreFile = keyStore;
    ks.load(new FileInputStream(keyStoreFile), passPhrase);
    ts.load(new FileInputStream(keyStoreFile), passPhrase);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerAlgorithm);
    kmf.init(ks, passPhrase);
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
    tmf.init(ts);
    sslContext = SSLContext.getInstance(protocol);
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
}
Example 61
Project: hudson.core-master  File: CertificateUtil.java View source code
/**
     * Loads the system default {@link X509TrustManager}.
     */
public static X509TrustManager getDefaultX509TrustManager() throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init((KeyStore) null);
    for (TrustManager tm : tmf.getTrustManagers()) {
        if (tm instanceof X509TrustManager) {
            return (X509TrustManager) tm;
        }
    }
    throw new IllegalStateException("X509TrustManager is not found");
}
Example 62
Project: irma_future_id-master  File: HTTPSServerThread.java View source code
SSLContext createSSLContext() throws Exception {
    KeyManagerFactory mgrFact = KeyManagerFactory.getInstance("SunX509");
    KeyStore serverStore = KeyStore.getInstance("JKS");
    serverStore.load(new ByteArrayInputStream(KeyStores.server), SERVER_PASSWORD);
    mgrFact.init(serverStore, SERVER_PASSWORD);
    // set up a trust manager so we can recognize the server
    TrustManagerFactory trustFact = TrustManagerFactory.getInstance("SunX509");
    KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(new ByteArrayInputStream(KeyStores.trustStore), TRUST_STORE_PASSWORD);
    trustFact.init(trustStore);
    // create a context and set up a socket factory
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(mgrFact.getKeyManagers(), trustFact.getTrustManagers(), null);
    return sslContext;
}
Example 63
Project: lightnio-master  File: SimpleSSLClient.java View source code
protected SSLContext createSSLContext() throws Exception {
    ClassLoader cl = getClass().getClassLoader();
    URL url = cl.getResource("test.keystore");
    KeyStore keystore = KeyStore.getInstance("jks");
    keystore.load(url.openStream(), "nopassword".toCharArray());
    TrustManagerFactory tmfactory = createTrustManagerFactory();
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, trustmanagers, null);
    return sslcontext;
}
Example 64
Project: logstash-gelf-master  File: GelfTCPSSLSenderIntegrationTests.java View source code
@BeforeAll
public static void setupClass() throws Exception {
    File file = new File("work/keystore.jks");
    assumeTrue(file.exists());
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(new FileInputStream(file), "changeit".toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(keyStore, "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    final SslContext sslContext = SslContextBuilder.forServer(kmf).build();
    GelfTCPSSLSenderIntegrationTests.sslContext = SSLContext.getInstance("TLSv1");
    GelfTCPSSLSenderIntegrationTests.sslContext.init(new KeyManager[0], tmf.getTrustManagers(), null);
    server.run(new ChannelInitializer<Channel>() {

        @Override
        protected void initChannel(Channel ch) throws Exception {
            ch.pipeline().addLast(sslContext.newHandler(ch.alloc()));
            ch.pipeline().addLast(server.getHandler());
        }
    });
}
Example 65
Project: mapfish-print-master  File: CertificateStore.java View source code
private SSLContext createSslContext() {
    try {
        SSLContext newSslContext = SSLContext.getInstance("TLS");
        KeyStore ks = KeyStore.getInstance("JKS");
        final byte[] bytes = this.configuration.loadFile(this.uri.toString());
        ks.load(new ByteArrayInputStream(bytes), this.password);
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, this.password);
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(ks);
        newSslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return newSslContext;
    } catch (Throwable t) {
        throw ExceptionUtils.getRuntimeException(t);
    }
}
Example 66
Project: MaritimeCloud-master  File: TransportSecurityUtils.java View source code
/**
     * Loads the trust-store from the given path
     * @param trustStorePath the path to the trust-store
     * @param pwd the trust store password
     * @return the trust-store managers
     */
public static TrustManager[] loadTrustStore(String trustStorePath, char[] pwd) throws Exception {
    Objects.requireNonNull(trustStorePath, "Trust-store path undefined");
    Objects.requireNonNull(pwd, "Trust-store password undefined");
    String defaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory instance = TrustManagerFactory.getInstance(defaultAlgorithm);
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    try (InputStream file = new FileInputStream(trustStorePath)) {
        trustStore.load(file, pwd);
    }
    instance.init(trustStore);
    return instance.getTrustManagers();
}
Example 67
Project: millipede-master  File: DefaultX509TrustManager.java View source code
protected void init(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(keystore);
    TrustManager[] trustmanagers = factory.getTrustManagers();
    if (trustmanagers.length == 0) {
        throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
    }
    this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
Example 68
Project: MobilSecurity-master  File: Client.java View source code
public void init(Context context) {
    try {
        SSLContext sslContext = SSLContext.getInstance(CLIENT_AGREEMENT);
        KeyManagerFactory keyManager = KeyManagerFactory.getInstance(CLIENT_KEY_MANAGER);
        TrustManagerFactory trustManager = TrustManagerFactory.getInstance(CLIENT_TRUST_MANAGER);
        KeyStore kks = KeyStore.getInstance(CLIENT_KEY_KEYSTORE);
        KeyStore tks = KeyStore.getInstance(CLIENT_TRUST_KEYSTORE);
        kks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_KET_PASSWORD.toCharArray());
        tks.load(context.getResources().openRawResource(R.raw.debug), CLIENT_TRUST_PASSWORD.toCharArray());
        keyManager.init(kks, CLIENT_KET_PASSWORD.toCharArray());
        trustManager.init(tks);
        sslContext.init(keyManager.getKeyManagers(), trustManager.getTrustManagers(), null);
        sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(SERVER_IP, SERVER_PORT);
    } catch (Exception e) {
        Log.v("TAG", e.toString());
    }
}
Example 69
Project: openflowjava-master  File: SslContextFactory.java View source code
/**
     * @return servercontext
     */
public SSLContext getServerContext() {
    String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
        algorithm = "SunX509";
    }
    SSLContext serverContext = null;
    try {
        KeyStore ks = KeyStore.getInstance(tlsConfig.getTlsKeystoreType().name());
        ks.load(SslKeyStore.asInputStream(tlsConfig.getTlsKeystore(), tlsConfig.getTlsKeystorePathType()), tlsConfig.getKeystorePassword().toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
        kmf.init(ks, tlsConfig.getCertificatePassword().toCharArray());
        KeyStore ts = KeyStore.getInstance(tlsConfig.getTlsTruststoreType().name());
        ts.load(SslKeyStore.asInputStream(tlsConfig.getTlsTruststore(), tlsConfig.getTlsTruststorePathType()), tlsConfig.getTruststorePassword().toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
        tmf.init(ts);
        serverContext = SSLContext.getInstance(PROTOCOL);
        serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (IOException e) {
        LOG.warn("IOException - Failed to load keystore / truststore." + " Failed to initialize the server-side SSLContext", e);
    } catch (NoSuchAlgorithmException e) {
        LOG.warn("NoSuchAlgorithmException - Unsupported algorithm." + " Failed to initialize the server-side SSLContext", e);
    } catch (CertificateException e) {
        LOG.warn("CertificateException - Unable to access certificate (check password)." + " Failed to initialize the server-side SSLContext", e);
    } catch (Exception e) {
        LOG.warn("Exception - Failed to initialize the server-side SSLContext", e);
    }
    return serverContext;
}
Example 70
Project: org.ops4j.pax.url-master  File: Util.java View source code
static void setupClientSSL() throws Exception {
    KeyStore store = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream storeInput = new FileInputStream(getTestKeystore());
    char[] storePass = getTestKeystorePassword().toCharArray();
    store.load(storeInput, storePass);
    TrustManagerFactory manager = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    manager.init(store);
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, manager.getTrustManagers(), null);
    SSLSocketFactory factory = context.getSocketFactory();
    HttpsURLConnection.setDefaultSSLSocketFactory(factory);
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        public //
        boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
}
Example 71
Project: QuakeInjector-master  File: CABundleLoader.java View source code
public static void loadCertificateAuthorities() throws GeneralSecurityException, IOException {
    KeyStore ks = getKeystore();
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init(ks);
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, factory.getTrustManagers(), null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
Example 72
Project: quickstarts-master  File: TCPClient.java View source code
public static void main(String[] args) throws Exception {
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream("users.jks"), "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(keystore);
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, "changeit".toCharArray());
    context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
    SSLSocketFactory sf = context.getSocketFactory();
    Socket clientSocket = sf.createSocket("localhost", 3939);
    DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    System.out.print("Message body to send over TCP: ");
    outputStream.write(reader.readLine().getBytes());
    Thread.sleep(50);
    clientSocket.close();
}
Example 73
Project: redmine-java-api-master  File: BetterSSLFactory.java View source code
/**
	 * Adds X509 keystore-backed trust manager into the list of managers. 
	 * @param managers list of the managers to add to.
	 * @param ks key store with target keys.
	 * @throws KeyStoreException if key store could not be accessed.
	 */
private static void addX509Managers(final Collection<X509TrustManager> managers, KeyStore ks) throws KeyStoreException, Error {
    try {
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ks);
        for (TrustManager tm : tmf.getTrustManagers()) {
            if (tm instanceof X509TrustManager) {
                managers.add((X509TrustManager) tm);
            }
        }
    } catch (NoSuchAlgorithmException e) {
        throw new Error("Default trust manager algorithm is not supported!", e);
    }
}
Example 74
Project: release-master  File: CamelNettyBindingQuickstartTest.java View source code
@Override
@Test
public void testDeployment() throws Exception {
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream(new File(SRC_DIR, "users.jks")), "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(keystore);
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, "changeit".toCharArray());
    context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
    SSLSocketFactory sf = context.getSocketFactory();
    Socket clientSocket = sf.createSocket("localhost", 3939);
    DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
    outputStream.write(getClass().getName().getBytes());
    outputStream.flush();
    Thread.sleep(1000);
    clientSocket.close();
}
Example 75
Project: Resteasy-master  File: SSLCerts.java View source code
public static SSLContext getContext(String keyStoreFileName, char[] keyStorePassword, String trustStoreFileName, char[] trustStorePassword) {
    try {
        KeyManager[] keyManagers = null;
        if (keyStoreFileName != null) {
            KeyStore ks = KeyStore.getInstance("JKS");
            loadKeyStore(ks, keyStoreFileName, keyStorePassword);
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(ks, keyStorePassword);
            keyManagers = kmf.getKeyManagers();
        }
        TrustManager[] trustManagers = null;
        if (trustStoreFileName != null) {
            KeyStore ks = KeyStore.getInstance("JKS");
            loadKeyStore(ks, trustStoreFileName, trustStorePassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            tmf.init(ks);
            trustManagers = tmf.getTrustManagers();
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);
        return sslContext;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
Example 76
Project: simple-java-mail-master  File: SSLConfiguration.java View source code
public SSLSocketFactory getSSLSocketFactory() throws SocksException {
    MiscUtil.checkNotNull(trustKeyStoreInfo, "trustKeyStoreInfo may not be null");
    FileInputStream s1 = null;
    FileInputStream s2 = null;
    try {
        final SSLContext context = SSLContext.getInstance("SSL");
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        final KeyStore trustKeyStore = KeyStore.getInstance(trustKeyStoreInfo.getType());
        trustKeyStore.load(s1 = new FileInputStream(trustKeyStoreInfo.getKeyStorePath()), trustKeyStoreInfo.getPassword().toCharArray());
        trustManagerFactory.init(trustKeyStore);
        KeyStore keyStore = null;
        if (keyStoreInfo != null && keyStoreInfo.getKeyStorePath() != null) {
            final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
            keyStore = KeyStore.getInstance(keyStoreInfo.getType());
            keyStore.load(s2 = new FileInputStream(keyStoreInfo.getKeyStorePath()), keyStoreInfo.getPassword().toCharArray());
            keyManagerFactory.init(keyStore, keyStoreInfo.getPassword().toCharArray());
            context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
        } else {
            context.init(null, trustManagerFactory.getTrustManagers(), null);
        }
        if (keyStore != null) {
            LOGGER.info("SSL: Key store:{}", keyStoreInfo.getKeyStorePath());
        }
        LOGGER.info("SSL: Trust key store:{}", trustKeyStoreInfo.getKeyStorePath());
        return context.getSocketFactory();
    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new SocksException(e.getMessage());
    } finally {
        tryCloseStream(s1);
        tryCloseStream(s2);
    }
}
Example 77
Project: spring-ws-master  File: TrustManagersFactoryBean.java View source code
@Override
public void afterPropertiesSet() throws Exception {
    String algorithm = StringUtils.hasLength(this.algorithm) ? this.algorithm : TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory trustManagerFactory = StringUtils.hasLength(this.provider) ? TrustManagerFactory.getInstance(algorithm, this.provider) : TrustManagerFactory.getInstance(algorithm);
    trustManagerFactory.init(keyStore);
    this.trustManagers = trustManagerFactory.getTrustManagers();
}
Example 78
Project: webofneeds-master  File: TrustManagerWrapperWithTrustService.java View source code
private static X509TrustManager getDefaultTrustManagerForKeyStore(KeyStore keyStore) throws NoSuchAlgorithmException, KeyStoreException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
    // initializing with null loads the system default keystore, will work only for the client
    tmf.init(keyStore);
    for (TrustManager t : tmf.getTrustManagers()) {
        if (t instanceof X509TrustManager) {
            return (X509TrustManager) t;
        }
    }
    return null;
}
Example 79
Project: ws.logv.trainmonitor-master  File: LogvSslRequestHandler.java View source code
private SSLSocketFactory newSslSocketFactory() {
    try {
        KeyStore trusted = KeyStore.getInstance("BKS");
        InputStream in = mContext.getResources().openRawResource(R.raw.keystore);
        try {
            trusted.load(in, "mysecret".toCharArray());
        } finally {
            in.close();
        }
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(trusted);
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);
        return context.getSocketFactory();
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}
Example 80
Project: yasme-android-master  File: HttpClient.java View source code
public static CloseableHttpClient createSSLClient() {
    SSLConnectionSocketFactory sslsf = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream caInput = context.getResources().openRawResource(R.raw.yasme_ca);
        Certificate ca = cf.generateCertificate(caInput);
        Log.d("HttpClient", "ca=" + ((X509Certificate) ca).getSubjectDN());
        caInput.close();
        trustStore.load(null, null);
        trustStore.setCertificateEntry("ca", ca);
        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trustStore);
        SSLContext context = SSLContext.getInstance("TLSv1");
        context.init(null, tmf.getTrustManagers(), null);
        sslsf = new SSLConnectionSocketFactory(context, new String[] { "TLSv1" }, null, null);
    } catch (KeyStoreException e) {
        Log.e(HttpClient.class.getSimpleName(), e.getMessage());
    } catch (CertificateException e) {
        Log.e(HttpClient.class.getSimpleName(), e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        Log.e(HttpClient.class.getSimpleName(), e.getMessage());
    } catch (KeyManagementException e) {
        Log.e(HttpClient.class.getSimpleName(), e.getMessage());
    } catch (IOException e) {
        Log.e(HttpClient.class.getSimpleName(), e.getMessage());
    }
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
Example 81
Project: airavata-master  File: TrustStoreManager.java View source code
public SSLContext initializeTrustStoreManager(String trustStorePath, String trustStorePassword) throws AiravataSecurityException {
    try {
        // load and initialize the trust store
        InputStream trustStream = new FileInputStream(new File(trustStorePath));
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        char[] trustPassword = trustStorePassword.toCharArray();
        trustStore.load(trustStream, trustPassword);
        // initialize a trust manager factory
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        // get the trust managers from the factory
        TrustManager[] trustManagers = trustFactory.getTrustManagers();
        // initialize an ssl context to use these managers and set as default
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustManagers, null);
        SSLContext.setDefault(sslContext);
        return sslContext;
    } catch (CertificateException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    } catch (FileNotFoundException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new AiravataSecurityException("Error in initializing the trust store.");
    }
}
Example 82
Project: android-15-master  File: TrustManagerImplTest.java View source code
private X509TrustManager trustManager(X509Certificate ca) throws Exception {
    KeyStore keyStore = TestKeyStore.createKeyStore();
    keyStore.setCertificateEntry("alias", ca);
    String algorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init(keyStore);
    return (X509TrustManager) tmf.getTrustManagers()[0];
}
Example 83
Project: android-libcore64-master  File: TrustManagerFactorySpiTest.java View source code
/**
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
     */
public void test_engineInit_01() throws NoSuchAlgorithmException, KeyStoreException {
    factory.reset();
    Provider provider = new MyProvider();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", provider);
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        tmf.init(ks);
    } catch (Exception e) {
        fail("Unexpected exception " + e.toString());
    }
    assertTrue(factory.isEngineInitCalled());
    assertEquals(ks, factory.getKs());
    factory.reset();
    tmf.init((KeyStore) null);
    assertTrue(factory.isEngineInitCalled());
    assertNull(factory.getKs());
}
Example 84
Project: android-socket.io-demo-master  File: SSLConnectionTest.java View source code
SSLContext createSSLContext() throws GeneralSecurityException, IOException {
    KeyStore ks = KeyStore.getInstance("JKS");
    File file = new File("src/test/resources/keystore.jks");
    ks.load(new FileInputStream(file), "password".toCharArray());
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, "password".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    return sslContext;
}
Example 85
Project: Android-ZBLibrary-master  File: SSLUtil.java View source code
/**
     * ��认�
     * @param keyManagers KeyManager[]
     * @param certificates �书的输入�
     * @return SSLSocketFactory
     */
public static SSLSocketFactory getSSLSocketFactory(KeyManager[] keyManagers, InputStream... certificates) {
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), new SecureRandom());
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();
        return socketFactory;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 86
Project: AndroidSource-master  File: SsX509TrustManager.java View source code
private javax.net.ssl.X509TrustManager fetchTrustManager(InputStream keyStore, String keyStorePassword) throws GeneralSecurityException {
    javax.net.ssl.X509TrustManager ret = null;
    TrustManagerFactory tmf = prepareTrustManagerFactory(keyStore, keyStorePassword);
    TrustManager tms[] = tmf.getTrustManagers();
    for (int i = 0; i < tms.length; i++) {
        if (tms[i] instanceof javax.net.ssl.X509TrustManager) {
            ret = (javax.net.ssl.X509TrustManager) tms[i];
        //              break;
        }
    }
    return ret;
}
Example 87
Project: AndroidStudyDemo-master  File: HttpsUtil.java View source code
private static TrustManager[] prepareTrustManager(InputStream... certificates) {
    if (certificates == null || certificates.length <= 0)
        return null;
    try {
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null);
        int index = 0;
        for (InputStream certificate : certificates) {
            String certificateAlias = Integer.toString(index++);
            keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));
            try {
                if (certificate != null)
                    certificate.close();
            } catch (IOException e) {
            }
        }
        TrustManagerFactory trustManagerFactory = null;
        trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(keyStore);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        return trustManagers;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Example 88
Project: android_platform_libcore-master  File: TrustManagerFactorySpiTest.java View source code
/**
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
     */
public void test_engineInit_01() throws NoSuchAlgorithmException, KeyStoreException {
    factory.reset();
    Provider provider = new MyProvider();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", provider);
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        tmf.init(ks);
    } catch (Exception e) {
        fail("Unexpected exception " + e.toString());
    }
    assertTrue(factory.isEngineInitCalled());
    assertEquals(ks, factory.getKs());
    factory.reset();
    tmf.init((KeyStore) null);
    assertTrue(factory.isEngineInitCalled());
    assertNull(factory.getKs());
}
Example 89
Project: android_volley_examples-master  File: SsX509TrustManager.java View source code
private javax.net.ssl.X509TrustManager fetchTrustManager(InputStream keyStore, String keyStorePassword) throws GeneralSecurityException {
    javax.net.ssl.X509TrustManager ret = null;
    TrustManagerFactory tmf = prepareTrustManagerFactory(keyStore, keyStorePassword);
    TrustManager tms[] = tmf.getTrustManagers();
    for (int i = 0; i < tms.length; i++) {
        if (tms[i] instanceof javax.net.ssl.X509TrustManager) {
            ret = (javax.net.ssl.X509TrustManager) tms[i];
        //              break;
        }
    }
    return ret;
}
Example 90
Project: ApkTrack-master  File: SSLHelper.java View source code
// --------------------------------------------------------------------------------------------
/**
     * Creates an SSLSocketFactory to be used with <code>HttpsUrlConnection</code>. The object is
     * preloaded with ApkTrack's bundled SSL certificates, which allows the app to perform strict
     * server authentication and prevent man in the middle attacks.
     * @param context The context of the application.
     * @return An SSLSocketFactory to use for SSL connections to ApkTracks known servers, or
     * <code>null</code> if it could not be created.
     */
public static SSLSocketFactory get_ssl_socket_factory(Context context) {
    if (_ssl_context != null) {
        return _ssl_context.getSocketFactory();
    }
    KeyStore keystore = get_keystore(context);
    if (keystore == null) {
        return null;
    }
    try {
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
        tmf.init(keystore);
        _ssl_context = SSLContext.getInstance("TLS");
        _ssl_context.init(null, tmf.getTrustManagers(), null);
        return _ssl_context.getSocketFactory();
    } catch (GeneralSecurityException e) {
        Log.e(MainActivity.TAG, "[SSLHelper.get_ssl_socket_factory] Could not create " + "the SSLContext.", e);
    }
    _ssl_context = null;
    return null;
}
Example 91
Project: ARTPart-master  File: TrustManagerFactorySpiTest.java View source code
/**
     * @throws NoSuchAlgorithmException
     * @throws KeyStoreException
     * javax.net.ssl.TrustManagerFactorySpi#engineInit(KeyStore ks)
     */
public void test_engineInit_01() throws NoSuchAlgorithmException, KeyStoreException {
    factory.reset();
    Provider provider = new MyProvider();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("MyTMF", provider);
    KeyStore ks = null;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(null, null);
        tmf.init(ks);
    } catch (Exception e) {
        fail("Unexpected exception " + e.toString());
    }
    assertTrue(factory.isEngineInitCalled());
    assertEquals(ks, factory.getKs());
    factory.reset();
    tmf.init((KeyStore) null);
    assertTrue(factory.isEngineInitCalled());
    assertNull(factory.getKs());
}
Example 92
Project: batchee-master  File: ClientSslConfiguration.java View source code
public SSLContext getSslContext() {
    final SSLContext context;
    try {
        context = SSLContext.getInstance(sslContextType);
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(keyManagerType);
        final KeyManager[] km;
        if (keyManagerPath != null) {
            final InputStream fin = findInputStream(keyManagerPath);
            final KeyStore ks = KeyStore.getInstance(keystoreType);
            ks.load(fin, keystorePassword.toCharArray());
            km = kmf.getKeyManagers();
        } else {
            km = null;
        }
        final TrustManager[] tm;
        if (trustManagerAlgorithm != null) {
            if (trustManagerProvider != null) {
                tm = TrustManagerFactory.getInstance(trustManagerAlgorithm, trustManagerProvider).getTrustManagers();
            } else {
                tm = TrustManagerFactory.getInstance(trustManagerAlgorithm).getTrustManagers();
            }
        } else {
            tm = null;
        }
        context.init(km, tm, null);
    } catch (final Exception e) {
        throw new IllegalArgumentException(e);
    }
    return context;
}
Example 93
Project: bergamot-master  File: BergamotTrustManager.java View source code
/*
     * Load the Mozilla trust store that we bundle
     */
private static final X509ExtendedTrustManager loadMozillaTrustStore() {
    try {
        InputStream trustStoreStream = BergamotTrustManager.class.getResourceAsStream("trust_store.jks");
        // Create our trust key store
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(trustStoreStream, "bergamot".toCharArray());
        // Create the trust manager
        TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustFactory.init(trustStore);
        // fecking obscured types are not helpful
        TrustManager[] managers = trustFactory.getTrustManagers();
        return (X509ExtendedTrustManager) managers[0];
    } catch (Exception e) {
        throw new RuntimeException("Failed to load bundled Mozilla trust store!");
    }
}
Example 94
Project: bgpcep-master  File: SslContextFactory.java View source code
public SSLContext getServerContext() {
    try {
        final KeyStore ks = KeyStore.getInstance(this.tlsConfig.getKeystoreType().name());
        ks.load(SslKeyStore.asInputStream(this.tlsConfig.getKeystore(), this.tlsConfig.getKeystorePathType()), this.tlsConfig.getKeystorePassword().toCharArray());
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, this.tlsConfig.getCertificatePassword().toCharArray());
        final KeyStore ts = KeyStore.getInstance(this.tlsConfig.getTruststoreType().name());
        ts.load(SslKeyStore.asInputStream(this.tlsConfig.getTruststore(), this.tlsConfig.getTruststorePathType()), this.tlsConfig.getTruststorePassword().toCharArray());
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
        final SSLContext serverContext = SSLContext.getInstance(PROTOCOL);
        serverContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return serverContext;
    } catch (final IOException e) {
        LOG.warn("IOException - Failed to load keystore / truststore. Failed to initialize the server-side SSLContext", e);
    } catch (final NoSuchAlgorithmException e) {
        LOG.warn("NoSuchAlgorithmException - Unsupported algorithm. Failed to initialize the server-side SSLContext", e);
    } catch (final CertificateException e) {
        LOG.warn("CertificateException - Unable to access certificate (check password). Failed to initialize the server-side SSLContext", e);
    } catch (final Exception e) {
        LOG.warn("Exception - Failed to initialize the server-side SSLContext", e);
    }
    //TODO try to use default SSLContext instance?
    return null;
}
Example 95
Project: cagrid2-master  File: AbstractTrustManager.java View source code
public void reload(List<TrustedCAEntry> trustedCAList) {
    this.trustManager = null;
    if ((trustedCAList != null) && (trustedCAList.size() > 0)) {
        List<X509Certificate> certs = new ArrayList<X509Certificate>();
        Set<CRL> crls = new HashSet<CRL>();
        for (TrustedCAEntry ca : trustedCAList) {
            certs.add(ca.getCertificate());
            if (ca.getCRL() != null) {
                crls.add(ca.getCRL());
            }
        }
        try {
            // load keystore from specified cert store (or default)
            KeyStore ts = KeyStore.getInstance("jks");
            ts.load(null);
            // add all temporary certs to KeyStore (ts)
            for (Certificate cert : certs) {
                ts.setCertificateEntry(UUID.randomUUID().toString(), cert);
            }
            PKIXBuilderParameters pbParams = new PKIXBuilderParameters(ts, new X509CertSelector());
            pbParams.setSigProvider("BC");
            // Set maximum certification path length
            pbParams.setMaxPathLength(-1);
            // Make sure revocation checking is enabled
            pbParams.setRevocationEnabled(isRevocationEnabled());
            if (crls != null && !crls.isEmpty()) {
                pbParams.addCertStore(CertStore.getInstance("Collection", new CollectionCertStoreParameters(crls)));
            }
            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(SslContextFactory.DEFAULT_TRUSTMANAGERFACTORY_ALGORITHM);
            trustManagerFactory.init(new CertPathTrustManagerParameters(pbParams));
            // acquire X509 trust manager from factory
            TrustManager tms[] = trustManagerFactory.getTrustManagers();
            for (int i = 0; i < tms.length; i++) {
                if (tms[i] instanceof X509TrustManager) {
                    trustManager = (X509TrustManager) tms[i];
                    if (log.isDebugEnabled()) {
                        StringBuffer msg = new StringBuffer("Successfully loaded the trust manager with the following certificates:\n");
                        int count = 1;
                        for (X509Certificate cert : certs) {
                            msg.append("    (" + count + ") " + cert.getSubjectDN().getName() + "\n");
                            count = count + 1;
                        }
                        log.debug(msg.toString());
                    }
                    return;
                }
            }
            throw new NoSuchAlgorithmException("No X509TrustManager in TrustManagerFactory");
        } catch (Exception e) {
            log.error("An unexpected error occurred reloading the trust manager:", e);
        }
    }
}
Example 96
Project: Cassandra-KVPM-master  File: SSLFactory.java View source code
private static SSLContext createSSLContext(EncryptionOptions options) throws IOException {
    SSLContext ctx;
    try {
        ctx = SSLContext.getInstance(PROTOCOL);
        TrustManagerFactory tmf = null;
        KeyManagerFactory kmf = null;
        tmf = TrustManagerFactory.getInstance(ALGORITHM);
        KeyStore ts = KeyStore.getInstance(STORE_TYPE);
        ts.load(new FileInputStream(options.truststore), options.truststore_password.toCharArray());
        tmf.init(ts);
        kmf = KeyManagerFactory.getInstance(ALGORITHM);
        KeyStore ks = KeyStore.getInstance(STORE_TYPE);
        ks.load(new FileInputStream(options.keystore), options.keystore_password.toCharArray());
        kmf.init(ks, options.keystore_password.toCharArray());
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } catch (Exception e) {
        throw new IOException("Error creating the initializing the SSL Context", e);
    }
    return ctx;
}
Example 97
Project: chatty-master  File: SSLUtil.java View source code
public static SSLContext getSSLContextWithLE() throws Exception {
    // Load existing certs
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    Path ksPath = Paths.get(System.getProperty("java.home"), "lib", "security", "cacerts");
    keyStore.load(Files.newInputStream(ksPath), "changeit".toCharArray());
    addCert(keyStore, "DSTRootCAX3.crt");
    addCert(keyStore, "isrgrootx1.crt");
    //        if (false) { // enable to see
    //            System.out.println("Truststore now trusting: ");
    //            PKIXParameters params = new PKIXParameters(keyStore);
    //            params.getTrustAnchors().stream()
    //                    .map(TrustAnchor::getTrustedCert)
    //                    .map(X509Certificate::getSubjectDN)
    //                    .forEach(System.out::println);
    //            System.out.println();
    //        }
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(keyStore);
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, tmf.getTrustManagers(), null);
    return sslContext;
}
Example 98
Project: components-ness-tinyhttp-master  File: HttpsTrustManagerFactory.java View source code
@Nonnull
private static X509TrustManager trustManagerFromKeystore(final KeyStore keystore) throws GeneralSecurityException {
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX", "SunJSSE");
    trustManagerFactory.init(keystore);
    final TrustManager[] tms = trustManagerFactory.getTrustManagers();
    for (final TrustManager tm : tms) {
        if (tm instanceof X509TrustManager) {
            final X509TrustManager manager = X509TrustManager.class.cast(tm);
            final X509Certificate[] acceptedIssuers = manager.getAcceptedIssuers();
            LOG.debug("Found TrustManager with %d authorities.", acceptedIssuers.length);
            for (int i = 0; i < acceptedIssuers.length; i++) {
                X509Certificate issuer = acceptedIssuers[i];
                LOG.trace("Issuer #%d, subject DN=<%s>, serial=<%s>", i, issuer.getSubjectDN(), issuer.getSerialNumber());
            }
            return manager;
        }
    }
    throw new IllegalStateException("Could not locate X509TrustManager!");
}
Example 99
Project: CorfuDB-master  File: TlsUtils.java View source code
public static SslContext enableTls(SslContextType desiredType, String keyStore, Consumer<Exception> keyStoreException, String ksPasswordFile, Consumer<Exception> ksPasswordFileException, String trustStore, Consumer<Exception> trustStoreException, String tsPasswordFile, Consumer<Exception> tsPasswordFileException) {
    // Get the key store password
    String ksp = "";
    if (ksPasswordFile != null) {
        try {
            ksp = (new String(Files.readAllBytes(Paths.get(ksPasswordFile)))).trim();
        } catch (Exception e) {
            keyStoreException.accept(e);
            return null;
        }
    }
    // Get the key store
    KeyStore ks = null;
    if (keyStore != null) {
        try (FileInputStream fis = new FileInputStream(keyStore)) {
            ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(fis, ksp.toCharArray());
        } catch (Exception e) {
            ksPasswordFileException.accept(e);
            return null;
        }
    }
    // Get the trust store password
    String tsp = "";
    if (tsPasswordFile != null) {
        try {
            tsp = (new String(Files.readAllBytes(Paths.get(tsPasswordFile)))).trim();
        } catch (Exception e) {
            trustStoreException.accept(e);
            return null;
        }
    }
    // Get the trust store
    KeyStore ts = null;
    if (trustStore != null) {
        try (FileInputStream fis = new FileInputStream(trustStore)) {
            ts = KeyStore.getInstance(KeyStore.getDefaultType());
            ts.load(fis, tsp.toCharArray());
        } catch (Exception e) {
            tsPasswordFileException.accept(e);
            return null;
        }
    }
    try {
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, ksp.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
        switch(desiredType) {
            case CLIENT_CONTEXT:
                return SslContextBuilder.forClient().keyManager(kmf).trustManager(tmf).build();
            case SERVER_CONTEXT:
                return SslContextBuilder.forServer(kmf).trustManager(tmf).build();
            default:
                throw new RuntimeException("Bad SSL context type: " + desiredType);
        }
    } catch (Exception e) {
        throw new RuntimeException("Could not build SslContext type " + desiredType.toString() + ": " + e.getClass().getSimpleName(), e);
    }
}
Example 100
Project: countly-sdk-android-master  File: CertificateTrustManager.java View source code
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (chain == null) {
        throw new IllegalArgumentException("PublicKeyManager: X509Certificate array is null");
    }
    if (!(chain.length > 0)) {
        throw new IllegalArgumentException("PublicKeyManager: X509Certificate is empty");
    }
    if (!(null != authType && authType.contains("RSA"))) {
        throw new CertificateException("PublicKeyManager: AuthType is not RSA");
    }
    // Perform customary SSL/TLS checks
    TrustManagerFactory tmf;
    try {
        tmf = TrustManagerFactory.getInstance("X509");
        tmf.init((KeyStore) null);
        for (TrustManager trustManager : tmf.getTrustManagers()) {
            ((X509TrustManager) trustManager).checkServerTrusted(chain, authType);
        }
    } catch (Exception e) {
        throw new CertificateException(e);
    }
    byte serverPublicKey[] = chain[0].getPublicKey().getEncoded();
    byte serverCertificate[] = chain[0].getEncoded();
    for (byte[] key : keys) {
        if (Arrays.equals(key, serverPublicKey)) {
            return;
        }
    }
    for (byte[] key : certificates) {
        if (Arrays.equals(key, serverCertificate)) {
            return;
        }
    }
    throw new CertificateException("Public keys didn't pass checks");
}
Example 101
Project: cxf-fediz-master  File: Utils.java View source code
public static TrustManager[] getTrustManagers(KeyStore keyStore) throws GeneralSecurityException, IOException {
    // For tests, we just use the default algorithm
    String alg = TrustManagerFactory.getDefaultAlgorithm();
    // For tests, we just use the default provider.
    TrustManagerFactory fac = TrustManagerFactory.getInstance(alg);
    fac.init(keyStore);
    return fac.getTrustManagers();
}