Java Code Examples for javax.net.ssl.TrustManager

The following are top voted examples for showing how to use javax.net.ssl.TrustManager. 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: framework   File: HttpClientUtil.java   View source code 10 votes vote down vote up
@PostConstruct
public void afterPropertiesSet() throws Exception {
	RegistryBuilder<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.create();

	schemeRegistry.register("http", PlainConnectionSocketFactory.getSocketFactory());

	SSLContext sslcontext = SSLContext.getInstance("TLS");
	sslcontext.init(new KeyManager[0], new TrustManager[]{new SimpleTrustManager()}, null);
	SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslcontext);
	schemeRegistry.register("https", sf);

	pool = new PoolingHttpClientConnectionManager(schemeRegistry.build());
	pool.setMaxTotal(maxConnection);
	pool.setDefaultMaxPerRoute(maxConnection);
	pool.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(sotimeout).build());
}
 
Example 2
Project: revolution-irc   File: UserOverrideTrustManager.java   View source code 9 votes vote down vote up
public SocketFactory createSocketFactory() {
    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { this }, null);
        return sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException("Failed to create a SSL socket factory");
    }
}
 
Example 3
Project: RoughWorld   File: WebClient.java   View source code 8 votes vote down vote up
public static void disableCertificateValidation() 
{
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] 
    { 
      new TrustAllManager() 
    };

    // Ignore differences between given hostname and certificate hostname
    HostnameVerifier hv = new TrustAllHostnameVerifier();
    
    // Install the all-trusting trust manager
    try 
    {
      SSLContext sc = SSLContext.getInstance("SSL");
      sc.init(null, trustAllCerts, new SecureRandom());
      HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
      HttpsURLConnection.setDefaultHostnameVerifier(hv);
    } catch (Exception e) {}
}
 
Example 4
Project: Android_Code_Arbiter   File: KeyStoresTrustManager.java   View source code 6 votes vote down vote up
public KeyStoresTrustManager(KeyStore... keyStores) throws NoSuchAlgorithmException, KeyStoreException {
    super();

    for (KeyStore keystore : keyStores) {
        TrustManagerFactory factory = TrustManagerFactory.getInstance("JKS");
        factory.init(keystore);
        TrustManager[] tms = factory.getTrustManagers();
        if (tms.length == 0) {
            throw new NoSuchAlgorithmException("Unable to load keystore");
        }
        trustManagers.add((X509TrustManager) tms[0]);
    }

    //Build accepted issuers list
    Set<X509Certificate> issuers = new HashSet<X509Certificate>();
    for (X509TrustManager tm : trustManagers) {
        for (X509Certificate issuer : tm.getAcceptedIssuers()) {
            issuers.add(issuer);
        }
    }
    acceptedIssuers = issuers.toArray(new X509Certificate[issuers.size()]);
}
 
Example 5
Project: boohee_v5.6   File: HttpsTrustManager.java   View source code 6 votes vote down vote up
public static void allowAllSSL() {
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String arg0, SSLSession arg1) {
            return true;
        }
    });
    SSLContext context = null;
    if (trustManagers == null) {
        trustManagers = new TrustManager[]{new HttpsTrustManager()};
    }
    try {
        context = SSLContext.getInstance("TLS");
        context.init(null, trustManagers, new SecureRandom());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e2) {
        e2.printStackTrace();
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
}
 
Example 6
Project: incubator-servicecomb-java-chassis   File: TrustManagerExtTest.java   View source code 6 votes vote down vote up
@SuppressWarnings("unused")
@Test
public void testConstructor() {
  String keyStoreName = custom.getFullPath(option.getKeyStore());
  char[] keyStoreValue = custom.decode(option.getKeyStoreValue().toCharArray());
  String trustStoreName = custom.getFullPath(option.getTrustStore());
  char[] trustStoreValue =
      custom.decode(option.getTrustStoreValue().toCharArray());
  KeyStore trustStore =
      KeyStoreUtil.createKeyStore(trustStoreName,
          option.getTrustStoreType(),
          trustStoreValue);
  TrustManager[] trustManager = KeyStoreUtil.createTrustManagers(trustStore);

  TrustManagerExt trustManagerExt = new TrustManagerExt((X509ExtendedTrustManager) trustManager[0],
      option, custom);
  Assert.assertEquals(3, trustManagerExt.getAcceptedIssuers()[0].getVersion());
  Assert.assertNotNull(trustManagerExt);
}
 
Example 7
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   View source code 6 votes vote down vote up
/**
 * Gets the ssl context for use making the connections
 *
 * @return the ssl context
 */
public SSLContext getSslContext() {
    KeyManager[] keyManagers = getKeyManagers();
    TrustManager[] trustManagers = getTrustManagers();
    if (keyManagers != null || trustManagers != null) {
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(getKeyManagers(), trustManagers, null);
            sslContext.getDefaultSSLParameters().setNeedClientAuth(true);
            return sslContext;
        } catch (Exception e) {
            throw new IllegalStateException("Created keystore and truststore but failed to initialize SSLContext", e);
        }
    } else {
        return null;
    }
}
 
Example 8
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 9
Project: logistimo-web-service   File: SSLUtilities.java   View source code 6 votes vote down vote up
/**
 * Set the default X509 Trust Manager to an instance of a fake class that
 * trust all certificates, even the self-signed ones. This method uses the
 * old deprecated API from the com.sun.ssl package.
 *
 * @deprecated see {@link #_trustAllHttpsCertificates()}.
 */
private static void __trustAllHttpsCertificates() {
  com.sun.net.ssl.SSLContext context;

  // Create a trust manager that does not validate certificate chains
  if (__trustManagers == null) {
    __trustManagers =
        new com.sun.net.ssl.TrustManager[]{new SSLUtilities._FakeX509TrustManager()};
  } // if
  // Install the all-trusting trust manager
  try {
    context = com.sun.net.ssl.SSLContext.getInstance("SSL");
    context.init(null, __trustManagers, new SecureRandom());
  } catch (GeneralSecurityException gse) {
    throw new IllegalStateException(gse.getMessage());
  } // catch
  com.sun.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context
      .getSocketFactory());
}
 
Example 10
Project: SmartChart   File: HttpsUtils.java   View source code 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 11
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 6 votes vote down vote up
public static SSLSocketFactory createSocketFactory(
	final String caCertificateFileName, 
	final String clientCertificateFileName, 
	final String clientKeyFileName) throws Exception
{
	// Creates a TLS socket factory with the given 
	// CA certificate file, client certificate, client key
	// In this case, we are working without a client key password
	final String clientKeyPassword = "";
	try
	{
		Security.addProvider(new BouncyCastleProvider());
		final KeyManager[] keyManagers = createKeyManagerFactory(clientCertificateFileName, clientKeyFileName, clientKeyPassword).getKeyManagers();
		final TrustManager[] trustManagers = createTrustManagerFactory(caCertificateFileName).getTrustManagers();
		
		// Create the TLS socket factory for the desired TLS version
		final SSLContext context = SSLContext.getInstance(TLS_VERSION);
		
		context.init(keyManagers, trustManagers, new SecureRandom());
		//context.init(keyManagers, trustManagers, null);

		return context.getSocketFactory();			
	}
	catch (Exception e)
	{
		throw new Exception("I cannot create the TLS socket factory.", e);
	}		
}
 
Example 12
Project: server-utility   File: HttpsUtil.java   View source code 6 votes vote down vote up
/**
 * 创建一个默认的,空的信任管理工厂
 *
 * @return 返回创建的信任管理工厂
 */
private static SSLSocketFactory createDefaultSSLSocketFactory() throws Exception {
    TrustManager[] tm = {new DefaultX509TrustManager()};
    SSLContext sslContext = null;
    SSLSocketFactory factory = null;
    try {
        sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new SecureRandom());

        factory = sslContext.getSocketFactory();
    } catch (NoSuchAlgorithmException | NoSuchProviderException | KeyManagementException e) {
        logger.error(e.getMessage());
    }

    if (null == factory) {
        throw new Exception("SSLSocketFactory is null");
    }

    return factory;
}
 
Example 13
Project: flume-release-1.7.0   File: TestAvroSource.java   View source code 6 votes vote down vote up
@Override
public SocketChannel newChannel(ChannelPipeline pipeline) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[]{new PermissiveTrustManager()},
                    null);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    sslEngine.setUseClientMode(true);
    // addFirst() will make SSL handling the first stage of decoding
    // and the last stage of encoding
    pipeline.addFirst("ssl", new SslHandler(sslEngine));
    return super.newChannel(pipeline);
  } catch (Exception ex) {
    throw new RuntimeException("Cannot create SSL channel", ex);
  }
}
 
Example 14
Project: dpdirect   File: SSL.java   View source code 6 votes vote down vote up
public static SSLSocketFactory initTrustAllSSLcontext(TrustManager[] trustAllCerts) throws NoSuchAlgorithmException,
                                                                                   KeyManagementException {
   // Install the all-trusting trust manager
   SSLSocketFactory sslSocketfactory = null;
   final SSLContext sc = SSLContext.getInstance("SSL");
   sc.init(null, trustAllCerts, new java.security.SecureRandom());
   HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
   sslSocketfactory = sc.getSocketFactory();
   return sslSocketfactory;
}
 
Example 15
Project: dracoon-dropzone   File: RestClient.java   View source code 6 votes vote down vote up
private X509TrustManager getX509TrustManager() {
	try {
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init((KeyStore) null);
		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
		if (trustManagers.length == 1 && (trustManagers[0] instanceof X509TrustManager)) {
			return (X509TrustManager) trustManagers[0];
		} else {
			LOG.error(String.format("Error while retrieving X509 trust manager! " + "(TrustMangers: %s)",
					Arrays.toString(trustManagers)));
			return null;
		}
	} catch (NoSuchAlgorithmException | KeyStoreException e) {
		LOG.error("Error while retrieving X509 trust manager!", e);
		return null;
	}
}
 
Example 16
Project: rxjava2_retrofit2   File: HttpsUtils.java   View source code 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 17
Project: encdroidMC   File: FileProvider7.java   View source code 6 votes vote down vote up
public static AbstractHttpClient wrapClient(HttpClient base) {
	try {
		SSLContext ctx = SSLContext.getInstance("TLS");
		X509TrustManager tm = new X509AlwaysTrust();

		ctx.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory ssf = new ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory(
				ctx);
		ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		ClientConnectionManager ccm = base.getConnectionManager();
		SchemeRegistry sr = ccm.getSchemeRegistry();
		sr.register(new Scheme("https", ssf, 443));
		return new DefaultHttpClient(ccm, base.getParams());
	} catch (Exception ex) {
		ex.printStackTrace();
		return null;
	}
}
 
Example 18
Project: lib-commons-httpclient   File: AuthSSLProtocolSocketFactory.java   View source code 6 votes vote down vote up
private static TrustManager[] createTrustManagers(final KeyStore keystore)
    throws KeyStoreException, NoSuchAlgorithmException
{ 
    if (keystore == null) {
        throw new IllegalArgumentException("Keystore may not be null");
    }
    LOG.debug("Initializing trust manager");
    TrustManagerFactory tmfactory = TrustManagerFactory.getInstance(
        TrustManagerFactory.getDefaultAlgorithm());
    tmfactory.init(keystore);
    TrustManager[] trustmanagers = tmfactory.getTrustManagers();
    for (int i = 0; i < trustmanagers.length; i++) {
        if (trustmanagers[i] instanceof X509TrustManager) {
            trustmanagers[i] = new AuthSSLX509TrustManager(
                (X509TrustManager)trustmanagers[i]); 
        }
    }
    return trustmanagers; 
}
 
Example 19
Project: alfresco-core   File: AuthSSLProtocolSocketFactory.java   View source code 6 votes vote down vote up
private SSLContext createSSLContext()
{
    KeyManager[] keymanagers = keyStore.createKeyManagers();;
    TrustManager[] trustmanagers = trustStore.createTrustManagers();

    try
    {
        SSLContext sslcontext = SSLContext.getInstance("TLS");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    }
    catch(Throwable e)
    {
        throw new AlfrescoRuntimeException("Unable to create SSL context", e);
    }
}
 
Example 20
Project: tomcat7   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 21
Project: bubichain-sdk-java   File: HttpKit.java   View source code 6 votes vote down vote up
/**
 * 鍙戦�丟et璇锋眰
 * @param url
 * @return
 * @throws NoSuchProviderException 
 * @throws NoSuchAlgorithmException 
 * @throws IOException 
 * @throws KeyManagementException 
 */
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
    StringBuffer bufferRes = null;
    TrustManager[] tm = { new MyX509TrustManager() };  
    SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  
    sslContext.init(null, tm, new java.security.SecureRandom());  
    // 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄  
    SSLSocketFactory ssf = sslContext.getSocketFactory();
    
    URL urlGet = new URL(url);
    HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
    // 杩炴帴瓒呮椂
    http.setConnectTimeout(25000);
    // 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
    http.setReadTimeout(25000);
    http.setRequestMethod("GET");
    http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
    http.setSSLSocketFactory(ssf);
    http.setHostnameVerifier(new Verifier());
    http.setDoOutput(true);
    http.setDoInput(true);
    http.connect();
    
    InputStream in = http.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null){
        bufferRes.append(valueString);
    }
    in.close();
    if (http != null) {
        // 鍏抽棴杩炴帴
        http.disconnect();
    }
    return bufferRes.toString();
}
 
Example 22
Project: ats-framework   File: SslUtils.java   View source code 6 votes vote down vote up
/**
 * @param host the host
 * @param port the port
 * 
 * @return array with all server-side certificates obtained from direct socket connection
 */
public static synchronized Certificate[] getCertificatesFromSocket( String host, String port ) {

    TrustManager[] trustAllCerts = new TrustManager[]{ new DefaultTrustManager() {} };

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, Integer.valueOf(port));
        sslSocket.startHandshake();
        return sslSocket.getSession().getPeerCertificates();
    } catch (Exception e) {
        throw new RuntimeException("Could not get certificate of secure socket to " + host + ":" + port + ".!", e);
    }
}
 
Example 23
Project: openjdk-jdk10   File: CipherTestUtils.java   View source code 5 votes vote down vote up
public AlwaysTrustManager(KeyStore keyStore)
        throws NoSuchAlgorithmException, KeyStoreException {

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

    TrustManager tms[] = tmf.getTrustManagers();
    for (TrustManager tm : tms) {
        trustManager = (X509TrustManager) tm;
        return;
    }

}
 
Example 24
Project: aliyun-cloudphotos-android-demo   File: SSLUtil.java   View source code 5 votes vote down vote up
private static void trustAllHttpsCertificates() throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[1];
    TrustManager tm = new miTM();
    trustAllCerts[0] = tm;
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}
 
Example 25
Project: java-android-websocket-client   File: SSLContextBuilder.java   View source code 5 votes vote down vote up
protected void initSSLContext(
        final SSLContext sslcontext,
        final Collection<KeyManager> keyManagers,
        final Collection<TrustManager> trustManagers,
        final SecureRandom secureRandom) throws KeyManagementException {
    sslcontext.init(
            !keyManagers.isEmpty() ? keyManagers.toArray(new KeyManager[keyManagers.size()]) : null,
            !trustManagers.isEmpty() ? trustManagers.toArray(new TrustManager[trustManagers.size()]) : null,
            secureRandom);
}
 
Example 26
Project: Android_Code_Arbiter   File: SslDisablerUsage.java   View source code 5 votes vote down vote up
public void useTrustAllManager() throws NoSuchAlgorithmException, KeyManagementException {
    final TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllManager() };
    final SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
 
Example 27
Project: golos4j   File: Util.java   View source code 5 votes vote down vote up
/**
 * Получить экземпляр протокол безопасного сокета
 * 
 * @return экземпляр протокола безопасного сокета
 * @throws SystemException
 *             системное исключение -
 */
public static SSLContext getSSLContext() throws SystemException {
	try {
		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(new KeyManager[0], new TrustManager[] { new AllowingAllTrustManager() },
				new SecureRandom());
		SSLContext.setDefault(sslContext);
		return sslContext;
	} catch (NoSuchAlgorithmException nsae) {
		throw new SystemException(" Unable get instance TLS: " + nsae.getMessage() + nsae);
	} catch (KeyManagementException kme) {
		throw new SystemException(" Unable init SSL context: " + kme.getMessage() + kme);
	}
}
 
Example 28
Project: lorne_core   File: EasyX509TrustManager.java   View source code 5 votes vote down vote up
/**
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore)
		throws NoSuchAlgorithmException, KeyStoreException {
	super();
	TrustManagerFactory factory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	factory.init(keystore);
	TrustManager[] trustmanagers = factory.getTrustManagers();
	if (trustmanagers.length == 0) {
		throw new NoSuchAlgorithmException("no trust manager found");
	}
	this.standardTrustManager = (X509TrustManager) trustmanagers[0];
}
 
Example 29
Project: GitHub   File: Main.java   View source code 5 votes vote down vote up
private static SSLSocketFactory createInsecureSslSocketFactory(TrustManager trustManager) {
  try {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] {trustManager}, null);
    return context.getSocketFactory();
  } catch (Exception e) {
    throw new AssertionError(e);
  }
}
 
Example 30
Project: GitHub   File: OkHttpClient.java   View source code 5 votes vote down vote up
private X509TrustManager systemDefaultTrustManager() {
  try {
    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];
  } catch (GeneralSecurityException e) {
    throw new AssertionError(); // The system has no TLS. Just give up.
  }
}
 
Example 31
Project: GitHub   File: OkHttpClient.java   View source code 5 votes vote down vote up
private SSLSocketFactory systemDefaultSslSocketFactory(X509TrustManager trustManager) {
  try {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    return sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw new AssertionError(); // The system has no TLS. Just give up.
  }
}
 
Example 32
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   View source code 5 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 33
Project: Okhttp-demo   File: HttpsUtils.java   View source code 5 votes vote down vote up
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
 
Example 34
Project: lorne_core   File: EasySSLConnectionSocketFactory.java   View source code 5 votes vote down vote up
private static SSLContext createEasySSLContext() throws IOException {
    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[]{new EasyX509TrustManager(
                null)}, null);
        return context;
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 35
Project: GitHub   File: CustomTrust.java   View source code 5 votes vote down vote up
public CustomTrust() {
  X509TrustManager trustManager;
  SSLSocketFactory sslSocketFactory;
  try {
    trustManager = trustManagerForCertificates(trustedCertificatesInputStream());
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { trustManager }, null);
    sslSocketFactory = sslContext.getSocketFactory();
  } catch (GeneralSecurityException e) {
    throw new RuntimeException(e);
  }

  client = new OkHttpClient.Builder()
      .sslSocketFactory(sslSocketFactory, trustManager)
      .build();
}
 
Example 36
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 37
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 38
Project: raven   File: NativeHttpClient.java   View source code 5 votes vote down vote up
protected void initSSL() {
       TrustManager[] tmCerts = new javax.net.ssl.TrustManager[1];
       tmCerts[0] = new SimpleTrustManager();
	try {
           SSLContext sslContext = SSLContext.getInstance("SSL");
		sslContext.init(null, tmCerts, null);
		HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
		
		HostnameVerifier hostnameVerifier = new SimpleHostnameVerifier();
		HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
	} catch (Exception e) {
		LOG.error("Init SSL error", e);
	}
}
 
Example 39
Project: oryx2   File: SecureAPIConfigIT.java   View source code 5 votes vote down vote up
@Test
public void testHTTPS() throws Exception {
  Config config = buildHTTPSConfig();
  startServer(config);

  // Turn off actual checking of the dummy SSL cert
  SSLContext sslContext = SSLContext.getInstance("SSL");
  sslContext.init(null, new TrustManager[] { ACCEPT_ALL_TM }, null);
  SSLSocketFactory originalFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
  HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

  try {
    String response = Resources.toString(
        new URL("https://localhost:" + getHTTPSPort() + "/helloWorld"),
        StandardCharsets.UTF_8);
    assertEquals("Hello, World", response);
  } finally {
    // Restore original SSL factory
    HttpsURLConnection.setDefaultSSLSocketFactory(originalFactory);
    Files.delete(Paths.get(config.getString("oryx.serving.api.keystore-file")));
  }
}
 
Example 40
Project: GitHub   File: OkHttpClient.java   View source code 5 votes vote down vote up
private X509TrustManager systemDefaultTrustManager() {
  try {
    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];
  } catch (GeneralSecurityException e) {
    throw assertionError("No System TLS", e); // The system has no TLS. Just give up.
  }
}