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: boohee_v5.6   File: HttpUtils.java   Source Code and License 51 votes vote down vote up
public CustomSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    MyX509TrustManager myX509TrustManager;
    super(keyStore);
    try {
        myX509TrustManager = new MyX509TrustManager();
    } catch (Exception e) {
        myX509TrustManager = null;
    }
    this.a.init(null, new TrustManager[]{myX509TrustManager}, null);
}
 
Example 2
Project: okwallet   File: RequestWalletBalanceTask.java   Source Code and License 5 votes vote down vote up
private SSLSocketFactory sslTrustAllCertificates() {
    try {
        final SSLContext context = SSLContext.getInstance("SSL");
        context.init(null, new TrustManager[] { TRUST_ALL_CERTIFICATES }, null);
        final SSLSocketFactory socketFactory = context.getSocketFactory();
        return socketFactory;
    } catch (final Exception x) {
        throw new RuntimeException(x);
    }
}
 
Example 3
Project: nifi-android-s2s   File: SiteToSiteRemoteCluster.java   Source Code and License 5 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 4
Project: lazycat   File: JSSESocketFactory.java   Source Code and License 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 5
Project: logistimo-web-service   File: SSLUtilities.java   Source Code and License 5 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 6
Project: SmartChart   File: HttpsUtils.java   Source Code and License 5 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 7
Project: jdk8u-jdk   File: CipherTestUtils.java   Source Code and License 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 8
Project: cf-mta-deploy-service   File: SSLUtil.java   Source Code and License 5 votes vote down vote up
public static void disableSSLValidation() {
    try {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { NULL_TRUST_MANAGER }, null);
        SSLContext.setDefault(context);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}
 
Example 9
Project: revolution-irc   File: ServerCertificateManager.java   Source Code and License 5 votes vote down vote up
public static X509TrustManager createKeyStoreTrustManager(KeyStore keyStore) {
    try {
        TrustManagerFactory factory = TrustManagerFactory.getInstance(
                TrustManagerFactory.getDefaultAlgorithm());
        factory.init(keyStore);
        for (TrustManager manager : factory.getTrustManagers()) {
            if (manager instanceof X509TrustManager)
                return (X509TrustManager) manager;
        }
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        throw new RuntimeException(e);
    }
    return null;
}
 
Example 10
Project: lams   File: Undertow.java   Source Code and License 5 votes vote down vote up
private ListenerConfig(final ListenerType type, final int port, final String host, KeyManager[] keyManagers, TrustManager[] trustManagers) {
    this.type = type;
    this.port = port;
    this.host = host;
    this.keyManagers = keyManagers;
    this.trustManagers = trustManagers;
    this.sslContext = null;
}
 
Example 11
Project: af-pay   File: HttpsUtils.java   Source Code and License 5 votes vote down vote up
public static void initHttps(HttpsURLConnection connection, String protocol) {
    try {
        SSLContext context = SSLContext.getInstance(TextUtils.isEmpty(protocol) ? "TLS" : protocol);
        context.init(null, new TrustManager[]{new EmptyTrustManager()}, null);
        connection.setSSLSocketFactory(context.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 12
Project: EvolvingNetLib   File: HttpsUtil.java   Source Code and License 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 13
Project: private-WeChat   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new SaicX509TrustManager() };
//          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("connection timed out cause by " + ce.getMessage());
        } catch (Exception e) {
            logger.error("https request error : " + e.getMessage());
        }
        return jsonObject;
    }
 
Example 14
Project: private-WeChat   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new SaicX509TrustManager() };
//          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("connection timed out cause by " + ce.getMessage());
        } catch (Exception e) {
            logger.error("https request error : " + e.getMessage());
        }
        return jsonObject;
    }
 
Example 15
Project: private-WeChat   File: CommonUtil.java   Source Code and License 5 votes vote down vote up
/**
     * 发起https请求并获取结果
     * 
     * @param requestUrl
     *            请求地址
     * @param requestMethod
     *            请求方式(GET、POST)
     * @param outputStr
     *            提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpsRequest(String requestUrl,String requestMethod,String outputStr){
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new SaicX509TrustManager() };
//          SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            SSLContext sslContext = SSLContext.getInstance("TLS", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();

            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }

            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.fromObject(buffer.toString());
        } catch (ConnectException ce) {
            logger.error("connection timed out cause by " + ce.getMessage());
        } catch (Exception e) {
            logger.error("https request error : " + e.getMessage());
        }
        return jsonObject;
    }
 
Example 16
Project: server-utility   File: HttpsUtil.java   Source Code and License 5 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 17
Project: Book-Shelf   File: CustomTrust.java   Source Code and License 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 18
Project: flume-release-1.7.0   File: TestAvroSource.java   Source Code and License 5 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 19
Project: dpdirect   File: SSL.java   Source Code and License 5 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 20
Project: dracoon-dropzone   File: RestClient.java   Source Code and License 5 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 21
Project: MVVM-JueJin   File: HttpsUtil.java   Source Code and License 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 22
Project: BTNotifierAndroid   File: SslUtils.java   Source Code and License 5 votes vote down vote up
public static SSLContext getSSLContext(File myTrustStore) throws Exception {
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(
            new KeyManager[] { new MyX509KeyManager() },
            new TrustManager[] { new MyX509TrustManager(myTrustStore) },
            null
    );
    return sslContext;
}
 
Example 23
Project: cornerstone   File: SecurityUtil.java   Source Code and License 5 votes vote down vote up
public static SSLSocketFactory getSSLSocketFactory () throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {

        if(VISSLFACTORY == null) {
            TrustManager[] tm = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new SecureRandom());
            VISSLFACTORY = sslContext.getSocketFactory();
        }
        return VISSLFACTORY;
    }
 
Example 24
Project: TPlayer   File: HttpsUtils.java   Source Code and License 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 25
Project: TARA-Server   File: TaraConfiguration.java   Source Code and License 5 votes vote down vote up
@PostConstruct
protected void init() throws Exception {
    if (this.taraProperties.getApplication().isDevelopment()) {
        StringBuilder sb = new StringBuilder();
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{new InsecureTrustManager()}, new SecureRandom());
        SSLContext.setDefault(sslContext);
        sb.append(StringUtils.rightPad("<x> Using insecure trust manager configuration ", this.paddingSize, "-"));
        AsciiArtUtils.printAsciiArtWarning(this.log, "NB! DEVELOPMENT MODE ACTIVATED", sb.toString());
    }
}
 
Example 26
Project: openjdk-jdk10   File: JSSEServer.java   Source Code and License 5 votes vote down vote up
JSSEServer(CipherTest cipherTest) throws Exception {
    super(cipherTest);
    SSLContext serverContext = SSLContext.getInstance("TLS");
    serverContext.init(
            new KeyManager[] { CipherTest.keyManager },
            new TrustManager[] { CipherTest.trustManager },
            CipherTest.secureRandom);

    SSLServerSocketFactory factory = (SSLServerSocketFactory)serverContext.getServerSocketFactory();
    serverSocket = (SSLServerSocket)factory.createServerSocket(0);
    serverSocket.setSoTimeout(CipherTest.TIMEOUT);
    CipherTest.serverPort = serverSocket.getLocalPort();
    serverSocket.setEnabledCipherSuites(factory.getSupportedCipherSuites());
    serverSocket.setWantClientAuth(true);
}
 
Example 27
Project: awe-awesomesky   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	JSONObject jsonObject = null;
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new HttpsX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
		conn.setUseCaches(false);
		conn.setRequestProperty("Content-Type", "application/json;;charset=UTF-8");
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		jsonObject = JSONObject.parseObject(buffer.toString());
	} catch (ConnectException ce) {
		ce.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return jsonObject;
}
 
Example 28
Project: rxjava2_retrofit2   File: CustomHttpsTrust.java   Source Code and License 5 votes vote down vote up
private static TrustManager[] prepareTrustManager(InputStream[] inputStreams) {

        if (inputStreams == null || inputStreams.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 stream : inputStreams) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(stream));
                if (stream != null)
                    stream.close();

            }

            TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(
                    TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            return trustManagerFactory.getTrustManagers();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
 
Example 29
Project: rxjava2_retrofit2   File: HttpsUtils.java   Source Code and License 5 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 30
Project: rxjava2_retrofit2   File: HttpsUtils.java   Source Code and License 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 31
Project: encdroidMC   File: FileProvider7.java   Source Code and License 5 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 32
Project: lib-commons-httpclient   File: AuthSSLProtocolSocketFactory.java   Source Code and License 5 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 33
Project: alfresco-core   File: AuthSSLProtocolSocketFactory.java   Source Code and License 5 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 34
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the SSLContext of the TLSServer and TLSClient with the given keystore and truststore locations as
 * well as the password protecting the keystores/truststores.
 * 
 * @param keyStorePath The relative path and filename for the keystore
 * @param trustStorePath The relative path and filename for the truststore
 * @param keyStorePassword The password protecting the keystore
 */
public static void setSSLContext(
		String keyStorePath, 
		String trustStorePath,
		String keyStorePassword) {
    KeyStore keyStore = SecurityUtils.getKeyStore(keyStorePath, keyStorePassword);
    KeyStore trustStore = SecurityUtils.getKeyStore(trustStorePath, keyStorePassword);

	try {
		// Initialize a key manager factory with the keystore
	    KeyManagerFactory keyFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyFactory.init(keyStore, keyStorePassword.toCharArray());
	    KeyManager[] keyManagers = keyFactory.getKeyManagers();

	    // Initialize a trust manager factory with the truststore
	    TrustManagerFactory trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());    
	    trustFactory.init(trustStore);
	    TrustManager[] trustManagers = trustFactory.getTrustManagers();

	    // Initialize an SSL context to use these managers and set as default
	    SSLContext sslContext = SSLContext.getInstance("TLS");
	    sslContext.init(keyManagers, trustManagers, null);
	    SSLContext.setDefault(sslContext); 
	} catch (NoSuchAlgorithmException | UnrecoverableKeyException | KeyStoreException | 
			KeyManagementException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to initialize SSL context");
	}    
}
 
Example 35
Project: karate   File: HttpUtils.java   Source Code and License 5 votes vote down vote up
public static SSLContext getSslContext(String algorithm) {
    TrustManager[] certs = new TrustManager[]{new LenientTrustManager()};
    SSLContext ctx = null;
    if (algorithm == null) {
        algorithm = "TLS";
    }
    try {
        ctx = SSLContext.getInstance(algorithm);
        ctx.init(null, certs, new SecureRandom());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return ctx;
}
 
Example 36
Project: iothub   File: MqttSslHandlerProvider.java   Source Code and License 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 37
Project: letv   File: HttpUtils.java   Source Code and License 5 votes vote down vote up
public CustomSSLSocketFactory(KeyStore keyStore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    MyX509TrustManager myX509TrustManager;
    super(keyStore);
    try {
        myX509TrustManager = new MyX509TrustManager();
    } catch (Exception e) {
        myX509TrustManager = null;
    }
    this.a.init(null, new TrustManager[]{myX509TrustManager}, null);
}
 
Example 38
Project: tomcat7   File: JSSESocketFactory.java   Source Code and License 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 39
Project: bubichain-sdk-java   File: HttpKit.java   Source Code and License 5 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 40
Project: Fetax-AI   File: HttpUtil.java   Source Code and License 5 votes vote down vote up
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
	JSONObject jsonObject = null;
	try {
		// 创建SSLContext对象,并使用我们指定的信任管理器初始化
		TrustManager[] tm = { new HttpsX509TrustManager() };
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();
		URL url = new URL(requestUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setSSLSocketFactory(ssf);
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36");
		conn.setUseCaches(false);
		conn.setRequestProperty("Content-Type", "application/json;;charset=UTF-8");
		// 设置请求方式(GET/POST)
		conn.setRequestMethod(requestMethod);
		// 当outputStr不为null时向输出流写数据
		if (null != outputStr) {
			OutputStream outputStream = conn.getOutputStream();
			// 注意编码格式
			outputStream.write(outputStr.getBytes("UTF-8"));
			outputStream.close();
		}
		// 从输入流读取返回内容
		InputStream inputStream = conn.getInputStream();
		InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		String str = null;
		StringBuffer buffer = new StringBuffer();
		while ((str = bufferedReader.readLine()) != null) {
			buffer.append(str);
		}
		// 释放资源
		bufferedReader.close();
		inputStreamReader.close();
		inputStream.close();
		inputStream = null;
		conn.disconnect();
		jsonObject = JSONObject.parseObject(buffer.toString());
	} catch (ConnectException ce) {
		ce.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}
	return jsonObject;
}
 
Example 41
Project: okhttpUtil   File: HttpsUtil.java   Source Code and License 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 42
Project: AndroidBasicLibs   File: SSLUtil.java   Source Code and License 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 43
Project: ats-framework   File: SslUtils.java   Source Code and License 5 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 44
Project: iotplatform   File: MqttSslHandlerProvider.java   Source Code and License 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 45
Project: lighthouse   File: SSLContextBuilder.java   Source Code and License 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 46
Project: openjdk-jdk10   File: CipherTestUtils.java   Source Code and License 4 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 47
Project: aliyun-cloudphotos-android-demo   File: SSLUtil.java   Source Code and License 4 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 48
Project: java-android-websocket-client   File: SSLContextBuilder.java   Source Code and License 4 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 49
Project: Android_Code_Arbiter   File: SslDisablerUsage.java   Source Code and License 4 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 50
Project: lighthouse   File: SSLContextBuilder.java   Source Code and License 4 votes vote down vote up
public SSLContextBuilder() {
    super();
    this.keymanagers = new LinkedHashSet<KeyManager>();
    this.trustmanagers = new LinkedHashSet<TrustManager>();
}
 
Example 51
Project: golos4j   File: Util.java   Source Code and License 4 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 52
Project: lorne_core   File: EasyX509TrustManager.java   Source Code and License 4 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 53
Project: dswork   File: HttpCommon.java   Source Code and License 4 votes vote down vote up
public static TrustManager getTrustManager()
{
	return tm;
}
 
Example 54
Project: GitHub   File: Main.java   Source Code and License 4 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 55
Project: GitHub   File: OkHttpClient.java   Source Code and License 4 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 56
Project: GitHub   File: OkHttpClient.java   Source Code and License 4 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 57
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 4 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 58
Project: Okhttp-demo   File: HttpsUtils.java   Source Code and License 4 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 59
Project: lorne_core   File: EasySSLConnectionSocketFactory.java   Source Code and License 4 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 60
Project: GitHub   File: CustomTrust.java   Source Code and License 4 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();
}