org.apache.http.conn.ssl.SSLSocketFactory类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.9k)|赞(0)|评价(0)|浏览(396)

本文整理了Java中org.apache.http.conn.ssl.SSLSocketFactory类的一些代码示例,展示了SSLSocketFactory类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。SSLSocketFactory类的具体详情如下:
包路径:org.apache.http.conn.ssl.SSLSocketFactory
类名称:SSLSocketFactory

SSLSocketFactory介绍

[英]Layered socket factory for TLS/SSL connections, based on JSSE. .

SSLSocketFactory can be used to validate the identity of the HTTPS server against a list of trusted certificates and to authenticate to the HTTPS server using a private key.

SSLSocketFactory will enable server authentication when supplied with a KeyStore file containg one or several trusted certificates. The client secure socket will reject the connection during the SSL session handshake if the target HTTPS server attempts to authenticate itself with a non-trusted certificate.

Use JDK keytool utility to import a trusted certificate and generate a truststore file:

keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

SSLSocketFactory will enable client authentication when supplied with a KeyStore file containg a private key/public certificate pair. The client secure socket will use the private key to authenticate itself to the target HTTPS server during the SSL session handshake if requested to do so by the server. The target HTTPS server will in its turn verify the certificate presented by the client in order to establish client's authenticity

Use the following sequence of actions to generate a keystore file

  • Use JDK keytool utility to generate a new key
keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore

For simplicity use the same password for the key as that of the keystore

  • Issue a certificate signing request (CSR)
keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore
  • Send the certificate request to the trusted Certificate Authority for signature. One may choose to act as her own CA and sign the certificate request using a PKI tool, such as OpenSSL.
  • Import the trusted CA root certificate
keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore
  • Import the PKCS#7 file containg the complete certificate chain
keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore
  • Verify the content the resultant keystore file
keytool -list -v -keystore my.keystore

[中]基于JSSE的TLS/SSL连接分层套接字工厂。
SSLSocketFactory可用于根据可信证书列表验证HTTPS服务器的身份,并使用私钥对HTTPS服务器进行身份验证。
当提供包含一个或多个受信任证书的密钥库文件时,SSLSocketFactory将启用服务器身份验证。如果目标HTTPS服务器尝试使用不受信任的证书进行身份验证,则客户端安全套接字将在SSL会话握手期间拒绝连接。
使用JDK keytool实用程序导入受信任的证书并生成信任库文件:

keytool -import -alias "my server cert" -file server.crt -keystore my.truststore

当提供包含私钥/公钥证书对的密钥库文件时,SSLSocketFactory将启用客户端身份验证。如果服务器请求,客户端安全套接字将在SSL会话握手期间使用私钥向目标HTTPS服务器进行身份验证。目标HTTPS服务器将依次验证客户端提供的证书,以确定客户端的真实性
使用以下操作序列生成密钥库文件
*使用JDK keytool实用程序生成新密钥

keytool -genkey -v -alias "my client key" -validity 365 -keystore my.keystore

为简单起见,请使用与密钥库相同的密钥密码
*发出证书签名请求(CSR)

keytool -certreq -alias "my client key" -file mycertreq.csr -keystore my.keystore

*将证书请求发送到受信任的证书颁发机构进行签名。用户可以选择充当自己的CA,并使用PKI工具(如OpenSSL)对证书请求进行签名。
*导入受信任的CA根证书

keytool -import -alias "my trusted ca" -file caroot.crt -keystore my.keystore

*导入包含完整证书链的PKCS#7文件

keytool -import -alias "my client key" -file mycert.p7 -keystore my.keystore

*验证生成的密钥库文件中的内容

keytool -list -v -keystore my.keystore

代码示例

代码示例来源:origin: apache/kylin

public KylinClient(KylinConnectionInfo connInfo) {
  this.connInfo = connInfo;
  this.connProps = connInfo.getConnectionProperties();
  this.httpClient = new DefaultHttpClient();
  this.jsonMapper = new ObjectMapper();
  // trust all certificates
  if (isSSL()) {
    try {
      SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() {
        public boolean isTrusted(final X509Certificate[] chain, String authType)
            throws CertificateException {
          // Oh, I am easy...
          return true;
        }
      });
      httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, sslsf));
    } catch (Exception e) {
      throw new RuntimeException("Initialize HTTPS client failed", e);
    }
  }
}

代码示例来源:origin: androidquery/androidquery

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", ssf == null ? SSLSocketFactory.getSocketFactory() : ssf, 443));
client = new DefaultHttpClient(cm, httpParams);

代码示例来源:origin: k9mail/k-9

public WebDavSocketFactory(TrustManagerFactory trustManagerFactory, String host, int port) throws NoSuchAlgorithmException, KeyManagementException {
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, new TrustManager[] {
      trustManagerFactory.getTrustManagerForDomain(host, port)
  }, null);
  mSocketFactory = sslContext.getSocketFactory();
  mSchemeSocketFactory = org.apache.http.conn.ssl.SSLSocketFactory.getSocketFactory();
  mSchemeSocketFactory.setHostnameVerifier(
      org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
}

代码示例来源:origin: robovm/robovm

private static class NoPreloadHolder {
  /**
   * The factory using the default JVM settings for secure connections.
   */
  private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory();
}

代码示例来源:origin: Netflix/eureka

/**
 * Since Jersey 1.19 depends on legacy apache http-client API, we have to as well.
 */
private ThreadSafeClientConnManager createConnectionManager() {
  try {
    ThreadSafeClientConnManager connectionManager;
    if (sslContext != null) {
      SchemeSocketFactory socketFactory = new SSLSocketFactory(sslContext, new AllowAllHostnameVerifier());
      SchemeRegistry sslSchemeRegistry = new SchemeRegistry();
      sslSchemeRegistry.register(new Scheme("https", 443, socketFactory));
      connectionManager = new ThreadSafeClientConnManager(sslSchemeRegistry);
    } else {
      connectionManager = new ThreadSafeClientConnManager();
    }
    return connectionManager;
  } catch (Exception e) {
    throw new IllegalStateException("Cannot initialize Apache connection manager", e);
  }
}

代码示例来源:origin: fluxtream/fluxtream-app

public static DefaultHttpClient httpClientTrustingAllSSLCerts() throws NoSuchAlgorithmException, KeyManagementException {
  DefaultHttpClient httpclient = new DefaultHttpClient();
  SSLContext sc = SSLContext.getInstance("SSL");
  sc.init(null, getTrustingManager(), new java.security.SecureRandom());
  SSLSocketFactory socketFactory = new SSLSocketFactory(sc);
  Scheme sch = new Scheme("https", socketFactory, 443);
  httpclient.getConnectionManager().getSchemeRegistry().register(sch);
  return httpclient;
}

代码示例来源:origin: rest-assured/rest-assured

SSLContext sslContext;
try {
  sslContext = SSLContext.getInstance(protocol);
} catch (NoSuchAlgorithmException e) {
  return SafeExceptionRethrower.safeRethrow(e);
  sslContext.init(null, new TrustManager[]{new X509TrustManager() {
    public X509Certificate[] getAcceptedIssuers() {
      return null;
SSLSocketFactory sf = new SSLSocketFactory(sslContext, ALLOW_ALL_HOSTNAME_VERIFIER);
return sslSocketFactory(sf);

代码示例来源:origin: onyxbits/Raccoon

public static Scheme getMockedScheme() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { new DummyX509TrustManager() }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
Scheme https = new Scheme("https", 443, sf);
return https;
}

代码示例来源:origin: alien4cloud/alien4cloud-cloudify-events-model

/**
 * Returns a HTTP client configured to use SSL.
 *
 * @param url
 *
 * @return HTTP client configured to use SSL
 * @throws org.cloudifysource.restclient.exceptions.RestClientException
 *             Reporting different failures while creating the HTTP client
 */
private static DefaultHttpClient createSSLHttpClient(final URL url) throws NoSuchAlgorithmException, KeyManagementException {
  final X509TrustManager trustManager = createTrustManager();
  final SSLContext ctx = SSLContext.getInstance("TLS");
  ctx.init(null, new TrustManager[] { trustManager }, null);
  final SSLSocketFactory ssf = new SSLSocketFactory(ctx, createHostnameVerifier());
  SyncBasicHttpParams params = new SyncBasicHttpParams();
  DefaultHttpClient.setDefaultHttpParams(params);
  DefaultHttpClient httpClient = createSimpleHttpClient(params);
  httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme(HTTPS, url.getPort(), ssf));
  return httpClient;
}

代码示例来源:origin: io.brooklyn.networking/brooklyn-networking-cloudstack

public static HttpClient createHttpClient(URI uri, Optional<Credentials> credentials) {
  final DefaultHttpClient httpClient = new DefaultHttpClient();
  // TODO if supplier returns null, we may wish to defer initialization until url available?
  if (uri != null && "https".equalsIgnoreCase(uri.getScheme())) {
    try {
      int port = (uri.getPort() >= 0) ? uri.getPort() : 443;
      SSLSocketFactory socketFactory = new SSLSocketFactory(
          new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      Scheme sch = new Scheme("https", port, socketFactory);
      httpClient.getConnectionManager().getSchemeRegistry().register(sch);
    } catch (Exception e) {
      LOG.warn("Error in HTTP Feed of {}, setting trust for uri {}", uri);
      throw Exceptions.propagate(e);
    }
  }
  // Set credentials
  if (uri != null && credentials.isPresent()) {
    String hostname = uri.getHost();
    int port = uri.getPort();
    httpClient.getCredentialsProvider().setCredentials(new AuthScope(hostname, port), credentials.get());
  }
  return httpClient;
}

代码示例来源:origin: Odoo-mobile/framework

private static void createThreadSafeClient(boolean forceSecure) {
  httpClient = new DefaultHttpClient();
  ClientConnectionManager mgr = httpClient.getConnectionManager();
  HttpParams params = httpClient.getParams();
  SchemeRegistry schemeRegistry = mgr.getSchemeRegistry();
  if (forceSecure) {
    schemeRegistry.register(new Scheme("https",
        getSecureConnectionSetting(), 443));
  } else {
    HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
    SSLSocketFactory socketFactory = SSLSocketFactory
        .getSocketFactory();
    socketFactory
        .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    schemeRegistry.register(new Scheme("https", socketFactory, 443));
  }
  httpClient = new DefaultHttpClient(new ThreadSafeClientConnManager(params,
      schemeRegistry), params);
}

代码示例来源:origin: rnewson/couchdb-lucene

ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRouteBean(1000));
final SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry
    .register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 5984));
schemeRegistry
    .register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
final ClientConnectionManager cm = new ShieldedClientConnManager(
    new ThreadSafeClientConnManager(params, schemeRegistry));
instance = new DefaultHttpClient(cm, params);
  instance.setCredentialsProvider(credsProvider);
  instance.addRequestInterceptor(new PreemptiveAuthenticationRequestInterceptor(), 0);

代码示例来源:origin: stackoverflow.com

SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
Scheme sch = new Scheme("https", socketFactory, 443);
httpclient.getConnectionManager().getSchemeRegistry().register(sch);

代码示例来源:origin: aws-amplify/aws-sdk-android

/**
 * Constructor.
 * @param config the client configuration.
 */
public ApacheHttpClient(ClientConfiguration config) {
  HttpClientFactory httpClientFactory = new HttpClientFactory();
  httpClient = httpClientFactory.createHttpClient(config);
  // disable retry
  ((AbstractHttpClient) httpClient)
      .setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
  SchemeRegistry schemeRegistry = httpClient.getConnectionManager().getSchemeRegistry();
  Scheme https = schemeRegistry.getScheme("https");
  ((SSLSocketFactory) https.getSocketFactory())
      .setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
}

代码示例来源:origin: com.hynnet/solr-solrj

public static void setHostNameVerifier(DefaultHttpClient httpClient,
  X509HostnameVerifier hostNameVerifier) {
 Scheme httpsScheme = httpClient.getConnectionManager().getSchemeRegistry().get("https");
 if (httpsScheme != null) {
  SSLSocketFactory sslSocketFactory = (SSLSocketFactory) httpsScheme.getSchemeSocketFactory();
  sslSocketFactory.setHostnameVerifier(hostNameVerifier);
 }
}

代码示例来源:origin: sealtalk/sealtalk-android

public static SSLSocketFactory getFixedSocketFactory() {
  SSLSocketFactory socketFactory;
  try {
    socketFactory = new MySSLSocketFactory(getKeystore());
    socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  } catch (Throwable t) {
    t.printStackTrace();
    socketFactory = SSLSocketFactory.getSocketFactory();
  }
  return socketFactory;
}

代码示例来源:origin: com.hynnet/httpclient

Args.notNull(host, "HTTP host");
Args.notNull(remoteAddress, "Remote address");
final Socket sock = socket != null ? socket : createSocket(context);
if (localAddress != null) {
  sock.bind(localAddress);
  final SSLSocket sslsock = (SSLSocket) sock;
  sslsock.startHandshake();
  verifyHostname(sslsock, host.getHostName());
  return sock;
} else {
  return createLayeredSocket(sock, host.getHostName(), remoteAddress.getPort(), context);

代码示例来源:origin: robovm/robovm

((sock != null) ? sock : createSocket());

代码示例来源:origin: MobiVM/robovm

private static class NoPreloadHolder {
  /**
   * The factory using the default JVM settings for secure connections.
   */
  private static final SSLSocketFactory DEFAULT_FACTORY = new SSLSocketFactory();
}

代码示例来源:origin: stackoverflow.com

SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory
  .getSocketFactory(), 80));
if (_resources != null) {
  registry.register(new Scheme("https", newSslSocketFactory(), 443));
} else {
  registry.register(new Scheme("https", SSLSocketFactory
    in.close();
  return new SSLSocketFactory(trusted);
} catch (Exception e) {
  throw new AssertionError(e);

相关文章