Java org.apache.http.conn.ssl.StrictHostnameVerifier 代码实例

・36 分钟阅读

以下是展示如何使用org.apache.http.conn.ssl.StrictHostnameVerifier的最佳示例。 我们使用了代码质量辨别算法从开源项目中提取出了最佳的优秀示例。

实例 1


private HttpURLConnection getConnection(String urlFragment, String method, String body)
    throws PushNetworkException
{
  try {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, trustManagers, null);
    URL url = new URL(String.format("%s%s", serviceUrl, urlFragment));
    Log.w(TAG, "Push service URL: " + serviceUrl);
    Log.w(TAG, "Opening URL: " + url);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    if (ENFORCE_SSL) {
      ((HttpsURLConnection) connection).setSSLSocketFactory(context.getSocketFactory());
      ((HttpsURLConnection) connection).setHostnameVerifier(new StrictHostnameVerifier());
    }
    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/json");
    if (credentialsProvider.getPassword() != null) {
      connection.setRequestProperty("Authorization", getAuthorizationHeader());
    }
    if (userAgent != null) {
      connection.setRequestProperty("X-Signal-Agent", userAgent);
    }
    if (body != null) {
      connection.setDoOutput(true);
    }
    connection.connect();
    if (body != null) {
      Log.w(TAG, method + "  --  " + body);
      OutputStream out = connection.getOutputStream();
      out.write(body.getBytes());
      out.close();
    }
    return connection;
  } catch (IOException e) {
    throw new PushNetworkException(e);
  } catch (NoSuchAlgorithmException | KeyManagementException e) {
    throw new AssertionError(e);
  }
}
 

实例 2


@Override
public List<Exception> initialize() {
        SmackConfiguration.setDefaultHostnameVerifier(new StrictHostnameVerifier());
        Base64.setEncoder(AndroidBase64Encoder.getInstance());
        Base64UrlSafeEncoder.setEncoder(AndroidBase64UrlSafeEncoder.getInstance());
        return null;
}
 

实例 3


private X509HostnameVerifier initHostnameVerifier() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null) {
        verifier = new VerifierWrapper(this.verifier);
    } else {
        switch (policy)
        {
            case ANY:
                verifier = new AllowAllHostnameVerifier();
                break;
            case WILDCARD:
                verifier = new BrowserCompatHostnameVerifier();
                break;
            case STRICT:
                verifier = new StrictHostnameVerifier();
                break;
        }
    }
    return verifier;
}
 

实例 4


synchronized HostnameVerifier getHostnameVerifier() {
  String verifierStr = MagnetDefaultSettings.getInstance(mContext).getSslHostnameVerifier();
  Log.d(TAG, "getHostnameVerifier(): Value from settings: " + verifierStr);
  try {
    HostnameVerifierEnum verifier = HostnameVerifierEnum.valueOf(verifierStr);
    if (mHostnameVerifier == null || verifier != mCurrentVerifier) {
      switch (verifier) {
      case ALLOW_ALL:
        mHostnameVerifier = new AllowAllHostnameVerifier();
        break;
      case BROWSER_COMPAT:
        mHostnameVerifier = new BrowserCompatHostnameVerifier();
        break;
      case STRICT:
      default:
        mHostnameVerifier = new StrictHostnameVerifier();
      }
      mCurrentVerifier = verifier;
    }
  } catch (Exception ex) {
    Log.w(TAG, "getHostnameVerifier(): caught exception.  Will default to STRICT.", ex);
    if (mCurrentVerifier != HostnameVerifierEnum.STRICT) {
      mHostnameVerifier = new StrictHostnameVerifier();
      mCurrentVerifier = HostnameVerifierEnum.STRICT;
    }
  }
  return mHostnameVerifier;
}
 

实例 5


public void checkServerTrusted(X509Certificate[] chain, String authType)
        throws CertificateException {
    String message = null;
    X509Certificate certificate = chain[0];
    Throwable cause = null;
    try {
        defaultTrustManager.checkServerTrusted(chain, authType);
        new StrictHostnameVerifier().verify(mHost, certificate);
        return;
    } catch (CertificateException e) {
        // cert. chain can't be validated
        message = e.getMessage();
        cause = e;
    } catch (SSLException e) {
        // host name doesn't match certificate
        message = e.getMessage();
        cause = e;
    }
    // Check the local key store if we couldn't verify the certificate using the global
    // key store or if the host name doesn't match the certificate name
    if (!keyStore.isValidCertificate(certificate, mHost, mPort)) {
        throw new CertificateChainException(message, chain, cause);
    }
}
 

实例 6


public void setupTrustManager(final HttpsURLConnection connection, final boolean interactive) {
        final X509TrustManager trustManager;
        final HostnameVerifier hostnameVerifier;
        if (interactive) {
                trustManager = mXmppConnectionService.getMemorizingTrustManager();
                hostnameVerifier = mXmppConnectionService
                                .getMemorizingTrustManager().wrapHostnameVerifier(
                                                new StrictHostnameVerifier());
        } else {
                trustManager = mXmppConnectionService.getMemorizingTrustManager()
                                .getNonInteractive();
                hostnameVerifier = mXmppConnectionService
                                .getMemorizingTrustManager()
                                .wrapHostnameVerifierNonInteractive(
                                                new StrictHostnameVerifier());
        }
        try {
                final SSLContext sc = SSLContext.getInstance("TLS");
                sc.init(null, new X509TrustManager[]{trustManager},
                                mXmppConnectionService.getRNG());
                final SSLSocketFactory sf = sc.getSocketFactory();
                final String[] cipherSuites = CryptoHelper.getOrderedCipherSuites(
                                sf.getSupportedCipherSuites());
                if (cipherSuites.length > 0) {
                        sc.getDefaultSSLParameters().setCipherSuites(cipherSuites);
                }
                connection.setSSLSocketFactory(sf);
                connection.setHostnameVerifier(hostnameVerifier);
        } catch (final KeyManagementException | NoSuchAlgorithmException ignored) {
        }
}
 

实例 7


public HttpResponse post(String url,
                List<NameValuePair> headerNameValuePairs,
                List<NameValuePair> entryNameValuePairs) {
        try {
                UrlEncodedFormEntity ent = new UrlEncodedFormEntity(
                                entryNameValuePairs);
                URL request = new URL(url);
                HttpsURLConnection urlConnection = (HttpsURLConnection) request
                                .openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setChunkedStreamingMode(0);
                urlConnection.setHostnameVerifier(new StrictHostnameVerifier());
                urlConnection.setSSLSocketFactory(sslcontext.getSocketFactory());
                urlConnection.setConnectTimeout(15000);
                OutputStream os = urlConnection.getOutputStream();
                ent.writeTo(os);
                InputStream in = urlConnection.getInputStream();
                BasicHttpEntity res = new BasicHttpEntity();
                res.setContent(in);
                HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,
                                urlConnection.getResponseCode(), "");
                response.setEntity(res);
                if (Util.DEBUGGABLE) {
                        printResponseHeader(response);
                }
                return response;
        } catch (Exception e) {
                if (Util.DEBUGGABLE) {
                        Log.e(TAG, "POST Error (" + e.getMessage() + ") URL: " + url);
                }
                Util.startErrorIntent((Activity) context,
                                C.badServerResponseMessage, true);
        }
        return null;
}
 

实例 8


private CouchPotato( String scheme, String hostname, int port, String path, String api, String username, String password, boolean trustAll, String trustMe )
{
        this.scheme = scheme;
        this.hostName = hostname;
        this.port = port;
        this.path = path;
        this.api = api;
        this.username = username;
        this.password = password;
        this.trustAll = trustAll;
        if ( this.username == null )
                this.username = "";
        if ( this.password == null )
                this.password = "";
        // Configure SSL behavior based on user preferences
        Authenticator.setDefault(new CouchAuthenticator(username, password, hostname));
        HostnameVerifier verifier;
        try {
                SSLContext ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager(trustAll, trustMe)}, new SecureRandom());
                if( trustAll ) {
                        verifier = new AllowAllHostnameVerifier();
                } else {
                        verifier = new StrictHostnameVerifier();
                }
                HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
                HttpsURLConnection.setDefaultHostnameVerifier(verifier);
        } catch (NoSuchAlgorithmException e) {
        } catch (KeyManagementException e) {
        } catch (KeyStoreException e) {
        }
}
 

实例 9


static PoolingHttpClientConnectionManager createConnectionManager(ClientConfiguration clientConfiguration, SslConfigurator sslConfig) {
    SSLContext sslContext = sslConfig.createSSLContext();
    X509HostnameVerifier hostnameVerifier;
    if (clientConfiguration.isIgnoreSSLErrors()) {
        ignoreSslCertificateErrorInit(sslContext);
        hostnameVerifier = new AllowAllHostnameVerifier();
    } else {
        hostnameVerifier = new StrictHostnameVerifier();
    }
    LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(
            sslContext,
            hostnameVerifier);
    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory)
            .build();
    return new PoolingHttpClientConnectionManager(registry);
}
 

实例 10


private void handleResult(SSLEngineResult res) {
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
        final Runnable task = engine.getDelegatedTask();
        task.run();
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
        write(ByteBuffer.allocate(0));
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
        mEmitter.onDataAvailable();
    }
    try {
        if (!finishedHandshake && (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING || engine.getHandshakeStatus() == HandshakeStatus.FINISHED)) {
            TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            tmf.init((KeyStore) null);
            boolean trusted = false;
            for (TrustManager tm : tmf.getTrustManagers()) {
                try {
                    X509TrustManager xtm = (X509TrustManager) tm;
                    peerCertificates = (X509Certificate[]) engine.getSession().getPeerCertificates();
                    xtm.checkServerTrusted(peerCertificates, "SSL");
                    if (mHost != null) {
                        StrictHostnameVerifier verifier = new StrictHostnameVerifier();
                        verifier.verify(mHost, StrictHostnameVerifier.getCNs(peerCertificates[0]), StrictHostnameVerifier.getDNSSubjectAlts(peerCertificates[0]));
                    }
                    trusted = true;
                    break;
                }
                catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            finishedHandshake = true;
            if (!trusted) {
                AsyncSSLException e = new AsyncSSLException();
                report(e);
                if (!e.getIgnore())
                    throw e;
            }
            Assert.assertNotNull(mWriteableCallback);
            mWriteableCallback.onWriteable();
            mEmitter.onDataAvailable();
        }
    }
    catch (Exception ex) {
        report(ex);
    }
}
 

实例 11


private void handleResult(SSLEngineResult res) {
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
        final Runnable task = engine.getDelegatedTask();
        task.run();
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
        write(ByteBufferList.EMPTY_BYTEBUFFER);
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
        mEmitter.onDataAvailable();
    }
    try {
        if (!finishedHandshake && (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING || engine.getHandshakeStatus() == HandshakeStatus.FINISHED)) {
            if (clientMode) {
                TrustManager[] trustManagers = this.trustManagers;
                if (trustManagers == null) {
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init((KeyStore) null);
                    trustManagers = tmf.getTrustManagers();
                }
                boolean trusted = false;
                for (TrustManager tm : trustManagers) {
                    try {
                        X509TrustManager xtm = (X509TrustManager) tm;
                        peerCertificates = (X509Certificate[]) engine.getSession().getPeerCertificates();
                        xtm.checkServerTrusted(peerCertificates, "SSL");
                        if (mHost != null) {
                            if (hostnameVerifier == null) {
                                StrictHostnameVerifier verifier = new StrictHostnameVerifier();
                                verifier.verify(mHost, StrictHostnameVerifier.getCNs(peerCertificates[0]), StrictHostnameVerifier.getDNSSubjectAlts(peerCertificates[0]));
                            }
                            else {
                                hostnameVerifier.verify(mHost, engine.getSession());
                            }
                        }
                        trusted = true;
                        break;
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                finishedHandshake = true;
                if (!trusted) {
                    AsyncSSLException e = new AsyncSSLException();
                    report(e);
                    if (!e.getIgnore())
                        throw e;
                }
            }
            if (mWriteableCallback != null)
                mWriteableCallback.onWriteable();
            mEmitter.onDataAvailable();
        }
    }
    catch (Exception ex) {
        report(ex);
    }
}
 

实例 12


private void handleHandshakeStatus(HandshakeStatus status) {
    if (status == HandshakeStatus.NEED_TASK) {
        final Runnable task = engine.getDelegatedTask();
        task.run();
    }
    if (status == HandshakeStatus.NEED_WRAP) {
        write(writeList);
    }
    if (status == HandshakeStatus.NEED_UNWRAP) {
        dataCallback.onDataAvailable(this, new ByteBufferList());
    }
    try {
        if (!finishedHandshake && (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING || engine.getHandshakeStatus() == HandshakeStatus.FINISHED)) {
            if (clientMode) {
                TrustManager[] trustManagers = this.trustManagers;
                if (trustManagers == null) {
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init((KeyStore) null);
                    trustManagers = tmf.getTrustManagers();
                }
                boolean trusted = false;
                Exception peerUnverifiedCause = null;
                for (TrustManager tm : trustManagers) {
                    try {
                        X509TrustManager xtm = (X509TrustManager) tm;
                        peerCertificates = (X509Certificate[]) engine.getSession().getPeerCertificates();
                        xtm.checkServerTrusted(peerCertificates, "SSL");
                        if (mHost != null) {
                            if (hostnameVerifier == null) {
                                StrictHostnameVerifier verifier = new StrictHostnameVerifier();
                                verifier.verify(mHost, StrictHostnameVerifier.getCNs(peerCertificates[0]), StrictHostnameVerifier.getDNSSubjectAlts(peerCertificates[0]));
                            }
                            else {
                                hostnameVerifier.verify(mHost, engine.getSession());
                            }
                        }
                        trusted = true;
                        break;
                    }
                    catch (GeneralSecurityException ex) {
                        peerUnverifiedCause = ex;
                    }
                    catch (SSLException ex) {
                        peerUnverifiedCause = ex;
                    }
                }
                finishedHandshake = true;
                if (!trusted) {
                    AsyncSSLException e = new AsyncSSLException(peerUnverifiedCause);
                    report(e);
                    if (!e.getIgnore())
                        throw e;
                }
            }
            else {
                finishedHandshake = true;
            }
            handshakeCallback.onHandshakeCompleted(null, this);
            handshakeCallback = null;
            mSocket.setClosedCallback(null);
            // handshake can complete during a wrap, so make sure that the call
            // stack and wrap flag is cleared before invoking writable
            getServer().post(new Runnable() {
                @Override
                public void run() {
                    if (mWriteableCallback != null)
                        mWriteableCallback.onWriteable();
                }
            });
            onDataAvailable();
        }
    }
    catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
    catch (GeneralSecurityException ex) {
        report(ex);
    }
    catch (AsyncSSLException ex) {
        report(ex);
    }
}
 

实例 13


protected ClientHttpEngine initDefaultEngine()
{
   DefaultHttpClient httpClient = null;
   X509HostnameVerifier verifier = null;
   if (this.verifier != null) verifier = new VerifierWrapper(this.verifier);
   else
   {
      switch (policy)
      {
         case ANY:
            verifier = new AllowAllHostnameVerifier();
            break;
         case WILDCARD:
            verifier = new BrowserCompatHostnameVerifier();
            break;
         case STRICT:
            verifier = new StrictHostnameVerifier();
            break;
      }
   }
   try
   {
      SSLSocketFactory sslsf = null;
      SSLContext theContext = sslContext;
      if (disableTrustManager)
      {
         theContext = SSLContext.getInstance("SSL");
         theContext.init(null, new TrustManager[]{new PassthroughTrustManager()},
                 new SecureRandom());
         verifier =  new AllowAllHostnameVerifier();
         sslsf = new SSLSocketFactory(theContext, verifier);
      }
      else if (theContext != null)
      {
         sslsf = new SSLSocketFactory(theContext, verifier);
      }
      else if (clientKeyStore != null || truststore != null)
      {
         sslsf = new SSLSocketFactory(SSLSocketFactory.TLS, clientKeyStore, clientPrivateKeyPassword, truststore, null, verifier);
      }
      else
      {
         //sslsf = new SSLSocketFactory(SSLContext.getInstance(SSLSocketFactory.TLS), verifier);
         final SSLContext tlsContext = SSLContext.getInstance(SSLSocketFactory.TLS);
         tlsContext.init(null, null, null);
         sslsf = new SSLSocketFactory(tlsContext, verifier);
      }
      SchemeRegistry registry = new SchemeRegistry();
      registry.register(
              new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
      Scheme httpsScheme = new Scheme("https", 443, sslsf);
      registry.register(httpsScheme);
      ClientConnectionManager cm = null;
      if (connectionPoolSize > 0)
      {
         PoolingClientConnectionManager tcm = new PoolingClientConnectionManager(registry, connectionTTL, connectionTTLUnit);
         tcm.setMaxTotal(connectionPoolSize);
         if (maxPooledPerRoute == 0) maxPooledPerRoute = connectionPoolSize;
         tcm.setDefaultMaxPerRoute(maxPooledPerRoute);
         cm = tcm;
      }
      else
      {
         cm = new BasicClientConnectionManager(registry);
      }
      BasicHttpParams params = new BasicHttpParams();
      if (socketTimeout > -1)
      {
         HttpConnectionParams.setSoTimeout(params, (int) socketTimeoutUnits.toMillis(socketTimeout));
      }
      if (establishConnectionTimeout > -1)
      {
         HttpConnectionParams.setConnectionTimeout(params, (int)establishConnectionTimeoutUnits.toMillis(establishConnectionTimeout));
      }
      httpClient = new DefaultHttpClient(cm, params);
      ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(httpClient, true);
      engine.setResponseBufferSize(responseBufferSize);
      engine.setHostnameVerifier(verifier);
      // this may be null.  We can't really support this with Apache Client.
      engine.setSslContext(theContext);
      engine.setDefaultProxy(defaultProxy);
      return engine;
   }
   catch (Exception e)
   {
      throw new RuntimeException(e);
   }
}
 

实例 14


/**
 * Build the definition of the HTTPClientBuilder which contains all our configuration.
 * 
 * @param element the HTTPMetadataProvider parser.
 * @param parserContext 
 * @param haveTLSTrustEngine whether have a TLS TrustEngine configured
 * @return the bean definition with the parameters.
 */
// Checkstyle: CyclomaticComplexity OFF
// Checkstyle: MethodLength OFF
private BeanDefinition buildHttpClient(Element element, ParserContext parserContext, boolean haveTLSTrustEngine) {
    String caching = DEFAULT_CACHING;
    if (element.hasAttributeNS(null, "httpCaching")) {
        caching = element.getAttributeNS(null, "httpCaching");
    }
    BeanDefinitionBuilder clientBuilder = null;
    switch (caching) {
        case "none":
            clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(HttpClientFactoryBean.class);
            break;
        case "file":
            clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(FileCachingHttpClientFactoryBean.class);
            if (element.hasAttributeNS(null, "httpCacheDirectory")) {
                clientBuilder.addPropertyValue("cacheDirectory", 
                        element.getAttributeNS(null, "httpCacheDirectory"));
            }
            if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
                clientBuilder.addPropertyValue("maxCacheEntries", 
                        element.getAttributeNS(null, "httpMaxCacheEntries"));
            }
            if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
                clientBuilder.addPropertyValue("maxCacheEntrySize", 
                        element.getAttributeNS(null, "httpMaxCacheEntrySize"));
            }
            break;
        case "memory":
            clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(InMemoryCachingHttpClientFactoryBean.class);
            if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
                clientBuilder.addPropertyValue("maxCacheEntries", 
                        element.getAttributeNS(null, "httpMaxCacheEntries"));
            }
            if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
                clientBuilder.addPropertyValue("maxCacheEntrySize", 
                        element.getAttributeNS(null, "httpMaxCacheEntrySize"));
            }
            break;
        default:
            throw new BeanDefinitionParsingException(new Problem(
                    String.format("Caching value '%s' is unsupported", caching),
                    new Location( parserContext.getReaderContext().getResource())));
    }
    clientBuilder.setLazyInit(true);
    if (element.hasAttributeNS(null, "requestTimeout")) {
        clientBuilder.addPropertyValue("connectionTimeout", element.getAttributeNS(null, "requestTimeout"));
    }
    if (haveTLSTrustEngine) {
        clientBuilder.addPropertyValue("tLSSocketFactory", 
                new TrustEngineTLSSocketFactory(HttpClientSupport.buildNoTrustSSLConnectionSocketFactory(), 
                        new StrictHostnameVerifier()));
    }
    if (element.hasAttributeNS(null, "disregardTLSCertificate")) {
        clientBuilder.addPropertyValue("connectionDisregardTLSCertificate",
                element.getAttributeNS(null, "disregardTLSCertificate"));
    } else if (element.hasAttributeNS(null, "disregardSslCertificate")) {
        log.warn("disregardSslCertificate is deprecated, please switch to disregardTLSCertificate");
        clientBuilder.addPropertyValue("connectionDisregardTLSCertificate",
                element.getAttributeNS(null, "disregardSslCertificate"));
    }
    if (element.hasAttributeNS(null, "proxyHost")) {
        clientBuilder.addPropertyValue("connectionProxyHost", element.getAttributeNS(null, "proxyHost"));
    }
    if (element.hasAttributeNS(null, "proxyPort")) {
        clientBuilder.addPropertyValue("connectionProxyPort", element.getAttributeNS(null, "proxyPort"));
    }
    if (element.hasAttributeNS(null, "proxyUser")) {
        clientBuilder.addPropertyValue("connectionProxyUsername", element.getAttributeNS(null, "proxyUser"));
    }
    if (element.hasAttributeNS(null, "proxyPassword")) {
        clientBuilder.addPropertyValue("connectionProxyPassword", element.getAttributeNS(null, "proxyPassword"));
    }
    return clientBuilder.getBeanDefinition();
}
 

实例 15


private void handleResult(SSLEngineResult res) {
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
        final Runnable task = engine.getDelegatedTask();
        task.run();
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_WRAP) {
        write(ByteBufferList.EMPTY_BYTEBUFFER);
    }
    if (res.getHandshakeStatus() == HandshakeStatus.NEED_UNWRAP) {
        mEmitter.onDataAvailable();
    }
    try {
        if (!finishedHandshake && (engine.getHandshakeStatus() == HandshakeStatus.NOT_HANDSHAKING || engine.getHandshakeStatus() == HandshakeStatus.FINISHED)) {
            if (clientMode) {
                TrustManager[] trustManagers = this.trustManagers;
                if (trustManagers == null) {
                    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
                    tmf.init((KeyStore) null);
                    trustManagers = tmf.getTrustManagers();
                }
                boolean trusted = false;
                for (TrustManager tm : trustManagers) {
                    try {
                        X509TrustManager xtm = (X509TrustManager) tm;
                        peerCertificates = (X509Certificate[]) engine.getSession().getPeerCertificates();
                        xtm.checkServerTrusted(peerCertificates, "SSL");
                        if (mHost != null) {
                            if (hostnameVerifier == null) {
                                StrictHostnameVerifier verifier = new StrictHostnameVerifier();
                                verifier.verify(mHost, StrictHostnameVerifier.getCNs(peerCertificates[0]), StrictHostnameVerifier.getDNSSubjectAlts(peerCertificates[0]));
                            }
                            else {
                                hostnameVerifier.verify(mHost, engine.getSession());
                            }
                        }
                        trusted = true;
                        break;
                    }
                    catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                finishedHandshake = true;
                if (!trusted) {
                    AsyncSSLException e = new AsyncSSLException();
                    report(e);
                    if (!e.getIgnore())
                        throw e;
                }
            }
            if (mWriteableCallback != null)
                mWriteableCallback.onWriteable();
            mEmitter.onDataAvailable();
        }
    }
    catch (Exception ex) {
        report(ex);
    }
}
 
讨论
淘淘あ西西 profile image