Java 类javax.net.ssl.TrustManager 实例源码

项目:framework    文件:HttpClientUtil.java   
@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());
}
项目:revolution-irc    文件:UserOverrideTrustManager.java   
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");
    }
}
项目:RoughWorld    文件:WebClient.java   
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) {}
}
项目:Android_Code_Arbiter    文件:KeyStoresTrustManager.java   
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()]);
}
项目:boohee_v5.6    文件:HttpsTrustManager.java   
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());
}
项目:incubator-servicecomb-java-chassis    文件:TrustManagerExtTest.java   
@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);
}
项目:nifi-android-s2s    文件:SiteToSiteRemoteCluster.java   
/**
 * 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;
    }
}
项目:lazycat    文件:JSSESocketFactory.java   
@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);
}
项目:logistimo-web-service    文件:SSLUtilities.java   
/**
 * 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());
}
项目:SmartChart    文件:HttpsUtils.java   
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);
    }
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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);
    }       
}
项目:server-utility    文件:HttpsUtil.java   
/**
 * 创建一个默认的,空的信任管理工厂
 *
 * @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;
}
项目:flume-release-1.7.0    文件:TestAvroSource.java   
@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);
  }
}
项目:dpdirect    文件:SSL.java   
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;
}
项目:dracoon-dropzone    文件:RestClient.java   
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;
    }
}
项目:rxjava2_retrofit2    文件:HttpsUtils.java   
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);
    }
}
项目:encdroidMC    文件:FileProvider7.java   
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;
    }
}
项目:lib-commons-httpclient    文件:AuthSSLProtocolSocketFactory.java   
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; 
}
项目:alfresco-core    文件:AuthSSLProtocolSocketFactory.java   
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);
    }
}
项目:tomcat7    文件:JSSESocketFactory.java   
@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);
}
项目:bubichain-sdk-java    文件:HttpKit.java   
/**
 * 鍙戦�丟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();
}
项目:ats-framework    文件:SslUtils.java   
/**
 * @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);
    }
}
项目:openjdk-jdk10    文件:CipherTestUtils.java   
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;
    }

}
项目:aliyun-cloudphotos-android-demo    文件:SSLUtil.java   
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());
}
项目:java-android-websocket-client    文件:SSLContextBuilder.java   
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);
}
项目:Android_Code_Arbiter    文件:SslDisablerUsage.java   
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());
}
项目:golos4j    文件:Util.java   
/**
 * Получить экземпляр протокол безопасного сокета
 * 
 * @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);
    }
}
项目:lorne_core    文件:EasyX509TrustManager.java   
/**
 * 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];
}
项目:GitHub    文件:Main.java   
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);
  }
}
项目:GitHub    文件:OkHttpClient.java   
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.
  }
}
项目:GitHub    文件:OkHttpClient.java   
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.
  }
}
项目:apache-tomcat-7.0.73-with-comment    文件:JSSESocketFactory.java   
@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);
}
项目:Okhttp-demo    文件:HttpsUtils.java   
private static X509TrustManager chooseTrustManager(TrustManager[] trustManagers) {
    for (TrustManager trustManager : trustManagers) {
        if (trustManager instanceof X509TrustManager) {
            return (X509TrustManager) trustManager;
        }
    }
    return null;
}
项目:lorne_core    文件:EasySSLConnectionSocketFactory.java   
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());
    }
}
项目:GitHub    文件:CustomTrust.java   
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();
}
项目:GitHub    文件:CustomTrust.java   
/**
 * 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];
}
项目:GitHub    文件:SslClient.java   
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);
  }
}
项目:raven    文件:NativeHttpClient.java   
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);
    }
}
项目:oryx2    文件:SecureAPIConfigIT.java   
@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")));
  }
}
项目:GitHub    文件:OkHttpClient.java   
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.
  }
}