Java Code Examples for javax.net.ssl.TrustManagerFactory

The following are top voted examples for showing how to use javax.net.ssl.TrustManagerFactory. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: push-network-proxies   File: SSLHelper.java   View source code 9 votes vote down vote up
public static SSLContext newSSLContext(final KeyStore ks, final String password,
    final String ksAlgorithm) throws InvalidSSLConfig {
    try {
        // Get a KeyManager and initialize it
        final KeyManagerFactory kmf = KeyManagerFactory.getInstance(ksAlgorithm);
        kmf.init(ks, password.toCharArray());

        // Get a TrustManagerFactory with the DEFAULT KEYSTORE, so we have all the certificates in cacerts trusted
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance(ksAlgorithm);
        tmf.init((KeyStore) null);

        // Get the SSLContext to help create SSLSocketFactory
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslContext;
    } catch (final GeneralSecurityException e) {
        throw new InvalidSSLConfig(e);
    }
}
 
Example 2
Project: automat   File: HTTPSCoder.java   View source code 7 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 3
Project: message-broker   File: SslHandlerFactory.java   View source code 7 votes vote down vote up
public SslHandlerFactory(AmqpServerConfiguration configuration) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = getKeyStore(configuration.getSsl().getKeyStore().getType(),
                                    configuration.getSsl().getKeyStore().getLocation(),
                                    configuration.getSsl().getKeyStore().getPassword());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(configuration.getSsl()
                                                                                     .getKeyStore()
                                                                                     .getCertType());
    keyManagerFactory.init(keyStore, configuration.getSsl().getKeyStore().getPassword().toCharArray());

    KeyStore trustStore = getKeyStore(configuration.getSsl().getTrustStore().getType(),
                                      configuration.getSsl().getTrustStore().getLocation(),
                                      configuration.getSsl().getTrustStore().getPassword());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(configuration.getSsl()
                                                                           .getTrustStore()
                                                                           .getCertType());
    trustManagerFactory.init(trustStore);

    sslContext = SSLContext.getInstance(configuration.getSsl().getProtocol());
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
 
Example 4
Project: habpanelviewer   File: LocalTrustManager.java   View source code 7 votes vote down vote up
LocalTrustManager(KeyStore localKeyStore) {
    try {
        TrustManagerFactory tmf = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init((KeyStore) null);

        defaultTrustManager = findX509TrustManager(tmf);
        if (defaultTrustManager == null) {
            throw new IllegalStateException("Couldn't find X509TrustManager");
        }

        localTrustManager = new LocalStoreX509TrustManager(localKeyStore);

        List<X509Certificate> allIssuers = new ArrayList<>();
        allIssuers.addAll(Arrays.asList(defaultTrustManager.getAcceptedIssuers()));
        allIssuers.addAll(Arrays.asList(localTrustManager.getAcceptedIssuers()));
        acceptedIssuers = allIssuers.toArray(new X509Certificate[allIssuers.size()]);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }


}
 
Example 5
Project: lazycat   File: JSSESocketFactory.java   View source code 6 votes vote down vote up
@Override
public TrustManager[] getTrustManagers() throws Exception {
	String truststoreType = endpoint.getTruststoreType();
	if (truststoreType == null) {
		truststoreType = System.getProperty("javax.net.ssl.trustStoreType");
	}
	if (truststoreType == null) {
		truststoreType = endpoint.getKeystoreType();
	}
	if (truststoreType == null) {
		truststoreType = defaultKeystoreType;
	}

	String algorithm = endpoint.getTruststoreAlgorithm();
	if (algorithm == null) {
		algorithm = TrustManagerFactory.getDefaultAlgorithm();
	}

	return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(), algorithm);
}
 
Example 6
Project: quorrabot   File: EventWebSocketSecureServer.java   View source code 6 votes vote down vote up
public EventWebSocketSecureServer(int port, String keystorepath, String keystorepassword, InetAddress ip) {
    super(port, ip);

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        char ksPassword[] = keystorepassword.toCharArray();
        if (!keystorepath.equals("")) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(new File(keystorepath)), ksPassword);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ksPassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } else {
            sslContext.init(null, null, null);
        }
        this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
    } catch (Exception e) {
        com.gmt2001.Console.out.println("Secure EventSocketServer failed: " + e);
        e.printStackTrace();
    }
}
 
Example 7
Project: export-distro   File: EdgeXSecurityManager.java   View source code 6 votes vote down vote up
public EdgeXSecurityManager() throws IllegalStateException {
	super();
	
	try {
		keystore = KeyStore.getInstance("JKS");
		InputStream jksInputStream = EdgeXSecurityManager.class.getClassLoader().getResourceAsStream("/mqttkeystore.jks"); 
		keystore.load(jksInputStream, "storepassword".toCharArray()); 

		keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyManagerFactory.init(keystore, "keypassword".toCharArray()); 

		trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); 
           trustManagerFactory.init(this.keystore);

	} catch (Exception e) {
		failedInitializationCause = e;
		keystore = null;
		keyManagerFactory = null;
		trustManagerFactory = null;
		throw new IllegalStateException("SecurityManager failed to initialize.", failedInitializationCause);
	}
}
 
Example 8
Project: zabbkit-android   File: SSLManager.java   View source code 6 votes vote down vote up
public void dumpTrustedCerts() {
	try {
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
				.getDefaultAlgorithm());
		tmf.init((KeyStore) null);
		X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
		StringBuffer buff = new StringBuffer();
		for (X509Certificate cert : xtm.getAcceptedIssuers()) {
			String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
					+ cert.getIssuerDN().getName();
			Log.d(TAG, certStr);
			buff.append(certStr + "\n\n");
		}
	} catch (GeneralSecurityException e) {
		throw new RuntimeException(e);
	}
}
 
Example 9
Project: kafka-0.11.0.0-src-with-comment   File: SslFactory.java   View source code 6 votes vote down vote up
private SSLContext createSSLContext() throws GeneralSecurityException, IOException  {
    SSLContext sslContext;
    if (provider != null)
        sslContext = SSLContext.getInstance(protocol, provider);
    else
        sslContext = SSLContext.getInstance(protocol);

    KeyManager[] keyManagers = null;
    if (keystore != null) {
        String kmfAlgorithm = this.kmfAlgorithm != null ? this.kmfAlgorithm : KeyManagerFactory.getDefaultAlgorithm();
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
        KeyStore ks = keystore.load();
        Password keyPassword = this.keyPassword != null ? this.keyPassword : keystore.password;
        kmf.init(ks, keyPassword.value().toCharArray());
        keyManagers = kmf.getKeyManagers();
    }

    String tmfAlgorithm = this.tmfAlgorithm != null ? this.tmfAlgorithm : TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    KeyStore ts = truststore == null ? null : truststore.load();
    tmf.init(ts);

    sslContext.init(keyManagers, tmf.getTrustManagers(), this.secureRandomImplementation);
    return sslContext;
}
 
Example 10
Project: thingsboard-gateway   File: CertPemClientCredentials.java   View source code 6 votes vote down vote up
private SSLSocketFactory getSocketFactory() {
    try {
        Security.addProvider(new BouncyCastleProvider());

        TrustManagerFactory trustManagerFactory = createAndInitTrustManagerFactory();
        KeyManagerFactory keyManagerFactory = createAndInitKeyManagerFactory();

        SSLContext context = SSLContext.getInstance(TLS_VERSION);
        context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

        return context.getSocketFactory();
    } catch (Exception e) {
        log.error("[{}:{}:{}:{}] Creating TLS factory failed!", caCert, cert, privateKey, password, e);
        throw new RuntimeException("Creating TLS factory failed!", e);
    }
}
 
Example 11
Project: thingsboard-gateway   File: CertPemClientCredentials.java   View source code 6 votes vote down vote up
private TrustManagerFactory createAndInitTrustManagerFactory() throws Exception {
    X509Certificate caCertHolder;
    if (caCertFileName != null) {
        caCertHolder = readCertFile(caCert);
    } else {
        caCertHolder = certificateConverter.getCertificate((X509CertificateHolder) readPEMFile(caCert));
    }

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);
    caKeyStore.setCertificateEntry("caCert-cert", caCertHolder);

    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);
    return trustManagerFactory;
}
 
Example 12
Project: openjdk-jdk10   File: EmptyCertificateAuthorities.java   View source code 6 votes vote down vote up
private void initialize() throws CertificateException {
    String passwd =
        System.getProperty("javax.net.ssl.trustStorePassword");
    char [] password = passwd.toCharArray();
    String trustFilename =
        System.getProperty("javax.net.ssl.trustStore");

    try {
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(trustFilename), password);

        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("PKIX");
        tmf.init(ks);
        tm = (X509TrustManager)tmf.getTrustManagers()[0];
    } catch (Exception e) {
        throw new CertificateException("Unable to initialize TM");
    }

}
 
Example 13
Project: bouncr   File: BouncrSSLSocketFactory.java   View source code 6 votes vote down vote up
public BouncrSSLSocketFactory() {
    try {
        SSLContext ctx = SSLContext.getInstance("TLSv1.2");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance("JKS");

        try (InputStream in = new FileInputStream(keyStoreInfo.get().getTruststorePath())) {
            trustStore.load(in, keyStoreInfo.get().getTruststorePassword().toCharArray());
        }
        tmf.init(trustStore);
        ctx.init(null, tmf.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
        delegate = ctx.getSocketFactory();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example 14
Project: iBase4J-Common   File: HTTPSPKCSCoder.java   View source code 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 15
Project: iBase4J-Common   File: HTTPSCoder.java   View source code 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 16
Project: drift   File: ApacheThriftMethodInvokerFactory.java   View source code 6 votes vote down vote up
private static SSLContext createSslContext(ApacheThriftClientConfig config)
{
    try {
        KeyStore trustStore = loadTrustStore(config.getTrustCertificate());
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        KeyManager[] keyManagers = null;
        if (config.getKey() != null) {
            Optional<String> keyPassword = Optional.ofNullable(config.getKeyPassword());
            KeyStore keyStore = loadKeyStore(config.getTrustCertificate(), config.getKey(), keyPassword);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, new char[0]);
            keyManagers = keyManagerFactory.getKeyManagers();
        }

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        return sslContext;
    }
    catch (IOException | GeneralSecurityException e) {
        throw new IllegalArgumentException("Unable to load SSL keys", e);
    }
}
 
Example 17
Project: RoughWorld   File: WebInterfaceSSL.java   View source code 6 votes vote down vote up
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers)
{
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } 
    catch (Exception e) 
    {
    	System.out.println(e.toString());
        //throw new IOException(e.getMessage());
    }
    return res;
}
 
Example 18
Project: alfresco-repository   File: AlfrescoSSLSocketFactory.java   View source code 6 votes vote down vote up
/**
 * Initialize the factory with custom trustStore
 * @param trustStore KeyStore
 */
public static synchronized void initTrustedSSLSocketFactory(final KeyStore trustStore)
{
    try
    {
        final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(trustStore);
        context = SSLContext.getInstance("SSL");
        context.init(null, trustManagerFactory.getTrustManagers(), SecureRandom.getInstance("SHA1PRNG"));
    }
    catch (NoSuchAlgorithmException nsae)
    {
        throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", nsae);
    }
    catch (KeyStoreException kse)
    {
        throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", kse);
    }
    catch (KeyManagementException kme)
    {
        throw new AlfrescoRuntimeException("The SSL socket factory cannot be initialized.", kme);
    }
}
 
Example 19
Project: quorrabot   File: MusicWebSocketSecureServer.java   View source code 6 votes vote down vote up
public MusicWebSocketSecureServer(int port, String keystorepath, String keystorepassword, InetAddress ip) {
    super(port, ip);

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        char ksPassword[] = keystorepassword.toCharArray();
        if (!keystorepath.equals("")) {
            KeyStore ks = KeyStore.getInstance("JKS");
            ks.load(new FileInputStream(new File(keystorepath)), ksPassword);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
            kmf.init(ks, ksPassword);
            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
            tmf.init(ks);

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        } else {
            sslContext.init(null, null, null);
        }
        this.setWebSocketFactory(new DefaultSSLWebSocketServerFactory(sslContext));
    } catch (Exception e) {
        com.gmt2001.Console.out.println("Secure EventSocketServer failed: " + e);
        e.printStackTrace();
    }
}
 
Example 20
Project: spur   File: SpurOptions.java   View source code 6 votes vote down vote up
private static SSLContext createSSLContext(final KeyStore keyStore, final KeyStore trustStore, String password) throws Exception {
    KeyManager[] keyManagers;
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password.toCharArray());
    keyManagers = keyManagerFactory.getKeyManagers();

    TrustManager[] trustManagers;
    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 21
Project: dropwizard-dsegraph   File: DseGraphFactory.java   View source code 6 votes vote down vote up
private DseCluster.Builder withSSL(DseCluster.Builder builder) throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException, KeyManagementException, UnrecoverableKeyException {

        // JKS Truststore
        KeyStore truststore = KeyStore.getInstance("JKS");
        truststore.load(new FileInputStream(sslTruststoreFile), sslTruststorePassword.toCharArray());
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(truststore);

        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");

        // Keystore details means supporting client authentication
        if (null != sslKeystoreFile && sslKeystoreFile.length() > 0 && null != sslKeystorePassword && sslKeystorePassword.length() > 0) {
            KeyStore keystore = KeyStore.getInstance("JKS");
            keystore.load(new FileInputStream(sslKeystoreFile), sslKeystorePassword.toCharArray());
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, sslKeystorePassword.toCharArray());

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new java.security.SecureRandom());
        } else {
            sslContext.init(null, tmf.getTrustManagers(), new java.security.SecureRandom());
        }

        return builder.withSSL(RemoteEndpointAwareJdkSSLOptions.builder().withSSLContext(sslContext).build());
    }
 
Example 22
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 6 votes vote down vote up
private static TrustManagerFactory createTrustManagerFactory(
	final String caCertificateFileName) 
	throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException 
{
	// Creates a trust manager factory
	// Load CA certificate
	final X509Certificate caCertificate = (X509Certificate) createX509CertificateFromFile(caCertificateFileName);
	// CA certificate is used to authenticate server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
	keyStore.load(null, null);
	keyStore.setCertificateEntry("ca-certificate", caCertificate);
	final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	trustManagerFactory.init(keyStore);

	return trustManagerFactory;
}
 
Example 23
Project: BTNotifierAndroid   File: SslUtils.java   View source code 6 votes vote down vote up
private void reloadTrustManager() throws Exception {
    KeyStore ts = getKeyStore();

    Enumeration<String> aliases = ts.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        Log.i(TAG, "Trusted certificate " + alias + ": " + ts.getCertificate(alias));
    }

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

    TrustManager tms[] = tmf.getTrustManagers();
    for (int i = 0; i < tms.length; i++) {
        if (tms[i] instanceof X509TrustManager) {
            trustManager = (X509TrustManager) tms[i];
            return;
        }
    }

    throw new NoSuchAlgorithmException("No X509TrustManager in TrustManagerFactory");
}
 
Example 24
Project: spring-credhub   File: ClientHttpRequestFactoryFactory.java   View source code 6 votes vote down vote up
private static X509TrustManager getTrustManager() {
	try {
		TrustManagerFactory trustManagerFactory =
				TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init((KeyStore) null);

		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
		
		for (TrustManager trustManager : trustManagers) {
			if (trustManager instanceof X509TrustManager) {
				return (X509TrustManager) trustManager;
			}
		}

		throw new IllegalStateException("Unable to setup SSL with OkHttp3; no X509TrustManager found in: " +
				Arrays.toString(trustManagers));
	} catch (GeneralSecurityException e) {
		throw new IllegalStateException("Unable to setup SSL with OkHttp3; error getting a X509TrustManager: " +
				e.getMessage(), e);
	}
}
 
Example 25
Project: flume-release-1.7.0   File: ThriftRpcClient.java   View source code 6 votes vote down vote up
/**
 * Lifted from ACCUMULO-3318 - Lifted from TSSLTransportFactory in Thrift-0.9.1.
 * The method to create a client socket with an SSLContextFactory object is not visible to us.
 * Have to use * SslConnectionParams instead of TSSLTransportParameters because no getters exist
 * on TSSLTransportParameters.
 */
private static SSLContext createSSLContext(String truststore,
                                           String truststorePassword,
                                           String truststoreType) throws FlumeException {
  SSLContext ctx;
  try {
    ctx = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf;
    tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    KeyStore ts = null;
    if (truststore != null && truststoreType != null) {
      ts = KeyStore.getInstance(truststoreType);
      ts.load(new FileInputStream(truststore), truststorePassword.toCharArray());
      tmf.init(ts);
    }

    tmf.init(ts);
    ctx.init(null, tmf.getTrustManagers(), null);

  } catch (Exception e) {
    throw new FlumeException("Error creating the transport", e);
  }
  return ctx;
}
 
Example 26
Project: athena   File: Controller.java   View source code 6 votes vote down vote up
private void initSsl() throws Exception {

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore ts = KeyStore.getInstance("JKS");
        ts.load(new FileInputStream(tsLocation), tsPwd);
        tmFactory.init(ts);

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        KeyStore ks = KeyStore.getInstance("JKS");
        ks.load(new FileInputStream(ksLocation), ksPwd);
        kmf.init(ks, ksPwd);

        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(kmf.getKeyManagers(), tmFactory.getTrustManagers(), null);


    }
 
Example 27
Project: cyberduck   File: DefaultX509TrustManager.java   View source code 6 votes vote down vote up
public DefaultX509TrustManager init() throws IOException {
    try {
        final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(KeyStore.getInstance(KeyStore.getDefaultType()));
        final TrustManager[] trustmanagers = factory.getTrustManagers();
        if(trustmanagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        system = (javax.net.ssl.X509TrustManager) trustmanagers[0];
    }
    catch(NoSuchAlgorithmException | KeyStoreException e) {
        log.error(String.format("Initialization of trust store failed. %s", e.getMessage()));
        throw new IOException(e);
    }
    return this;
}
 
Example 28
Project: iBase4J   File: HTTPSCoder.java   View source code 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 29
Project: okhttpUtil   File: CustomTrustParams.java   View source code 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 30
Project: TrackMeIfYouCanChat   File: Client.java   View source code 5 votes vote down vote up
public static SSLContext createSSLContext()
{
    try
    {
        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(new FileInputStream("A2KeyStore.jks"), "1234567890".toCharArray());

        // Create key manager
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(keyStore, "1234567890".toCharArray());
        KeyManager[] km = keyManagerFactory.getKeyManagers();

        // Create trust manager
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509");
        trustManagerFactory.init(keyStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();

        // Initialize SSLContext
        SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
        sslContext.init(km, tm, null);

        return sslContext;
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

    return null;
}
 
Example 31
Project: firebase-admin-java   File: NettyWebSocketClient.java   View source code 5 votes vote down vote up
@Override
public void connect() {
  checkState(channel == null, "channel already initialized");
  try {
    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustFactory.init((KeyStore) null);
    final SslContext sslContext = SslContextBuilder.forClient()
        .trustManager(trustFactory).build();
    Bootstrap bootstrap = new Bootstrap();
    final int port = uri.getPort() != -1 ? uri.getPort() : DEFAULT_WSS_PORT;
    bootstrap.group(group)
        .channel(NioSocketChannel.class)
        .handler(new ChannelInitializer<SocketChannel>() {
          @Override
          protected void initChannel(SocketChannel ch) {
            ChannelPipeline p = ch.pipeline();
            p.addLast(sslContext.newHandler(ch.alloc(), uri.getHost(), port));
            p.addLast(
                new HttpClientCodec(),
                // Set the max size for the HTTP responses. This only applies to the WebSocket
                // handshake response from the server.
                new HttpObjectAggregator(32 * 1024),
                channelHandler);
          }
        });

    ChannelFuture channelFuture = bootstrap.connect(uri.getHost(), port);
    this.channel = channelFuture.channel();
    channelFuture.addListener(
        new ChannelFutureListener() {
          @Override
          public void operationComplete(ChannelFuture future) throws Exception {
            if (!future.isSuccess()) {
              eventHandler.onError(future.cause());
            }
          }
        }
    );
  } catch (Exception e) {
    eventHandler.onError(e);
  }
}
 
Example 32
Project: Virtual-IoT-Server   File: SSLClientSocket.java   View source code 5 votes vote down vote up
private CertificateTrustManager getCertificateTrustManager(KeyStore keyStore) {
 CertificateTrustManager certificateTrustManager = null;
 try {
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  tmf.init(keyStore);
        X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
        certificateTrustManager = new CertificateTrustManager(defaultTrustManager);
 } catch (Exception e) {
  e.printStackTrace();
 }
 return certificateTrustManager;
}
 
Example 33
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
/** Returns a trust manager that trusts the VM's default certificate authorities. */
private X509TrustManager defaultTrustManager() throws GeneralSecurityException {
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init((KeyStore) null);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 34
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
/**
 * Returns a trust manager that trusts {@code certificates} and none other. HTTPS services whose
 * certificates have not been signed by these certificates will fail with a {@code
 * SSLHandshakeException}.
 *
 * <p>This can be used to replace the host platform's built-in trusted certificates with a custom
 * set. This is useful in development where certificate authority-trusted certificates aren't
 * available. Or in production, to avoid reliance on third-party certificate authorities.
 *
 * <p>See also {@link CertificatePinner}, which can limit trusted certificates while still using
 * the host platform's built-in trust store.
 *
 * <h3>Warning: Customizing Trusted Certificates is Dangerous!</h3>
 *
 * <p>Relying on your own trusted certificates limits your server team's ability to update their
 * TLS certificates. By installing a specific set of trusted certificates, you take on additional
 * operational complexity and limit your ability to migrate between certificate authorities. Do
 * not use custom trusted certificates in production without the blessing of your server's TLS
 * administrator.
 */
private X509TrustManager trustManagerForCertificates(InputStream in)
    throws GeneralSecurityException {
  CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
  Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
  if (certificates.isEmpty()) {
    throw new IllegalArgumentException("expected non-empty set of trusted certificates");
  }

  // Put the certificates a key store.
  char[] password = "password".toCharArray(); // Any password will work.
  KeyStore keyStore = newEmptyKeyStore(password);
  int index = 0;
  for (Certificate certificate : certificates) {
    String certificateAlias = Integer.toString(index++);
    keyStore.setCertificateEntry(certificateAlias, certificate);
  }

  // Use it to build an X509 trust manager.
  KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
      KeyManagerFactory.getDefaultAlgorithm());
  keyManagerFactory.init(keyStore, password);
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init(keyStore);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 35
Project: GitHub   File: SslClient.java   View source code 5 votes vote down vote up
public SslClient build() {
  try {
    // Put the certificate in a key store.
    char[] password = "password".toCharArray();
    KeyStore keyStore = newEmptyKeyStore(password);

    if (keyPair != null) {
      Certificate[] certificates = chainCertificates.toArray(
          new Certificate[chainCertificates.size()]);
      keyStore.setKeyEntry("private", keyPair.getPrivate(), password, certificates);
    }

    for (int i = 0; i < certificates.size(); i++) {
      keyStore.setCertificateEntry("cert_" + i, certificates.get(i));
    }

    // Wrap it up in an SSL context.
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(
        KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, password);
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();

    if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
      throw new IllegalStateException("Unexpected default trust managers:"
          + Arrays.toString(trustManagers));
    }

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagers, new SecureRandom());

    return new SslClient(sslContext, (X509TrustManager) trustManagers[0]);
  } catch (GeneralSecurityException gse) {
    throw new AssertionError(gse);
  }
}
 
Example 36
Project: openjdk-jdk10   File: SSLEngineTestCase.java   View source code 5 votes vote down vote up
/**
 * Returns SSLContext with TESTED_SECURITY_PROTOCOL protocol and
 * sets up keys.
 *
 * @return - SSLContext with a protocol specified by
 *           TESTED_SECURITY_PROTOCOL.
 */
public static SSLContext getContext() {
    try {
        java.security.Security.setProperty(
                "jdk.tls.disabledAlgorithms", "");
        java.security.Security.setProperty(
                "jdk.certpath.disabledAlgorithms", "");
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        char[] passphrase = PASSWD.toCharArray();
        try (FileInputStream keyFileStream =
                new FileInputStream(KEY_FILE_NAME)) {
            ks.load(keyFileStream, passphrase);
        }
        try (FileInputStream trustFileStream =
                new FileInputStream(TRUST_FILE_NAME)) {
            ts.load(trustFileStream, passphrase);
        }
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(ks, passphrase);
        TrustManagerFactory tmf =
                TrustManagerFactory.getInstance("SunX509");
        tmf.init(ts);
        SSLContext sslCtx =
                SSLContext.getInstance(TESTED_SECURITY_PROTOCOL);
        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        return sslCtx;
    } catch (KeyStoreException | IOException | NoSuchAlgorithmException |
            CertificateException | UnrecoverableKeyException |
            KeyManagementException ex) {
        throw new Error("Unexpected exception", ex);
    }
}
 
Example 37
Project: GitHub   File: CustomCipherSuites.java   View source code 5 votes vote down vote up
/** Returns a trust manager that trusts the VM's default certificate authorities. */
private X509TrustManager defaultTrustManager() throws GeneralSecurityException {
  TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
      TrustManagerFactory.getDefaultAlgorithm());
  trustManagerFactory.init((KeyStore) null);
  TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
  if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
    throw new IllegalStateException("Unexpected default trust managers:"
        + Arrays.toString(trustManagers));
  }
  return (X509TrustManager) trustManagers[0];
}
 
Example 38
Project: react-native-android-library-humaniq-api   File: SelfSigningClientBuilder.java   View source code 5 votes vote down vote up
public static OkHttpClient createClient(Context context) {

        OkHttpClient client = null;

        CertificateFactory cf = null;
        InputStream cert = null;
        Certificate ca = null;
        SSLContext sslContext = null;
        try {
            cf = CertificateFactory.getInstance("X.509");
            cert = context.getResources().openRawResource(R.raw.public_key); // Place your 'my_cert.crt' file in `res/raw`

            ca = cf.generateCertificate(cert);
            cert.close();
            
            String keyStoreType = KeyStore.getDefaultType();
            KeyStore keyStore = KeyStore.getInstance(keyStoreType);
            keyStore.load(null, null);
            keyStore.setCertificateEntry("ca", ca);

            String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            tmf.init(keyStore);

            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, tmf.getTrustManagers(), null);

            client = new OkHttpClient.Builder()
                    .sslSocketFactory(sslContext.getSocketFactory())
                .addInterceptor(new JwtTokenInterceptor())
                    .build();

        } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException | KeyManagementException e) {
            e.printStackTrace();
        }


        return client;
    }
 
Example 39
Project: okhttpUtil   File: HttpsUtil.java   View source code 5 votes vote down vote up
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
 
Example 40
Project: VBrowser-Android   File: NanoHTTPD.java   View source code 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and an
 * array of loaded KeyManagers. These objects must properly
 * loaded/initialized by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
    SSLServerSocketFactory res = null;
    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(loadedKeyStore);
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
        res = ctx.getServerSocketFactory();
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    return res;
}