下面列出了javax.net.ssl.SSLContext#getSocketFactory ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* @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);
}
}
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);
}
}
/**
* Creates an SSLSocketFactory that supports only the specified protocols
* and ciphers.
*/
public static SSLSocketFactory getSSLSocketFactory(String protocol,
String[] sslEnabledProtocols,
String[] sslCipherSuites,
SecureRandom random,
TrustManager[] tms,
KeyManager[] kms)
throws NoSuchAlgorithmException, KeyManagementException
{
SSLContext sc = SSLContext.getInstance(protocol);
// System.out.println("Wanted protocol: " + protocol);
// System.out.println("Got protocol: " + sc.getProtocol());
sc.init(kms, tms, random);
SSLSocketFactory sf = sc.getSocketFactory();
if(null != sslEnabledProtocols
|| null != sslCipherSuites)
sf = new CustomSSLSocketFactory(sf,
sslEnabledProtocols,
sslCipherSuites);
return sf;
}
public static void main(String[] args) throws Exception {
System.out.println("Client: arguments=" + String.join("; ", args));
int port = Integer.valueOf(args[0]);
String[] trustNames = args[1].split(TLSRestrictions.DELIMITER);
String[] certNames = args[2].split(TLSRestrictions.DELIMITER);
String constraint = args[3];
TLSRestrictions.setConstraint("Client", constraint);
SSLContext context = TLSRestrictions.createSSLContext(
trustNames, certNames);
SSLSocketFactory socketFactory = context.getSocketFactory();
try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) {
socket.connect(new InetSocketAddress("localhost", port),
TLSRestrictions.TIMEOUT);
socket.setSoTimeout(TLSRestrictions.TIMEOUT);
System.out.println("Client: connected");
InputStream sslIS = socket.getInputStream();
OutputStream sslOS = socket.getOutputStream();
sslOS.write('C');
sslOS.flush();
sslIS.read();
System.out.println("Client: finished");
} catch (Exception e) {
throw new RuntimeException("Client: failed.", e);
}
}
public void enableTLSv12UsingSSLContext() throws NoSuchAlgorithmException, KeyManagementException, UnknownHostException, IOException {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
SSLSocket socket = (SSLSocket) socketFactory.createSocket(url, port);
handleCommunication(socket, "SSLContext");
}
/**
* This function will install a trust manager that will blindly trust all SSL
* certificates. The reason this code is being added is to enable developers
* to do development using self signed SSL certificates on their web server.
*
* The standard HttpsURLConnection class will throw an exception on self
* signed certificates if this code is not run.
*/
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
// Install the all-trusting trust manager
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
// Install our all trusting manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return oldFactory;
}
private static void setupClientSSLContext() throws Exception {
SecureRandom secureRandom = new SecureRandom();
secureRandom.nextInt();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStorePublic);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(clientKeyStorePrivate, "private".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), secureRandom);
sslSocketFactory = sslContext.getSocketFactory();
}
private SSLSocketFactory trustAllSSLFactory() {
SSLSocketFactory ssfFactory = null;
try {
SSLContext sc = SSLContext.getInstance("TLS");
MyTrustManager[] trustManager = {new MyTrustManager()};
sc.init(null, trustManager, new SecureRandom());
ssfFactory = sc.getSocketFactory();
} catch (Exception e) {
e.printStackTrace();
}
return ssfFactory;
}
public void testConnect() throws Exception {
String wsUrl = "wss://cn-n1-core-k8s-cell-12.leancloud.cn";
SSLContext sslContext = SSLContext.getDefault();
SSLSocketFactory sf = sslContext.getSocketFactory();
AVStandardWebSocketClient client = new AVStandardWebSocketClient(URI.create(wsUrl),
AVStandardWebSocketClient.SUB_PROTOCOL_2_3,
true, true, sf, 0, this.monitor);
boolean rst = client.connectBlocking();
assertTrue(rst);
final int requestId = 100;
final String installation = "d45304813cf37c6c1a2177f84aee0bb8";
LoginPacket lp = new LoginPacket();
lp.setAppId(Configure.TEST_APP_ID);
lp.setInstallationId(installation);
lp.setRequestId(requestId - 1);
client.send(lp);
Thread.sleep(3000);
SessionControlPacket scp = SessionControlPacket.genSessionCommand(
"fengjunwen", null,
SessionControlPacket.SessionControlOp.OPEN, null,
0, 0, requestId);
scp.setTag("mobile");
scp.setAppId(Configure.TEST_APP_ID);
scp.setInstallationId(installation);
scp.setReconnectionRequest(false);
client.send(scp);
Thread.sleep(3000);
client.close();
Thread.sleep(3000);
}
/**
* Upgrade the port to SSL. If it is already secured, this is a no-op.
* If the data port type doesn't support SSL it should throw an exception.
*/
public void upgradeToSecure() throws IOException {
Options options = this.connection.getOptions();
SSLContext context = options.getSslContext();
SSLSocketFactory factory = context.getSocketFactory();
Duration timeout = options.getConnectionTimeout();
this.sslSocket = (SSLSocket) factory.createSocket(socket, this.host, this.port, true);
this.sslSocket.setUseClientMode(true);
final CompletableFuture<Void> waitForHandshake = new CompletableFuture<>();
this.sslSocket.addHandshakeCompletedListener((evt) -> {
waitForHandshake.complete(null);
});
this.sslSocket.startHandshake();
try {
waitForHandshake.get(timeout.toNanos(), TimeUnit.NANOSECONDS);
} catch (Exception ex) {
this.connection.handleCommunicationIssue(ex);
return;
}
in = sslSocket.getInputStream();
out = sslSocket.getOutputStream();
}
/**
*
* @throws SecurityException if the {@link SSLSocketFactory} instantiation failed
*/
public BasicSslSocketFactory() {
try {
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[]{ new BasicTrustManager() }, null);
factory = sslcontext.getSocketFactory();
} catch (Exception e) {
throw new SecurityException("Failed to instantiate SSLSocketFactory", e);
}
}
private static SSLSocket sslSocket(String address, int port, int timeout) throws Exception {
SSLContext sc = TLSUtil.createTrustingContext();
SSLSocketFactory ssf = sc.getSocketFactory();
SSLSocket socket = (SSLSocket) ssf.createSocket(address, port);
socket.setSoTimeout(timeout);
socket.startHandshake();
return socket;
}
public static SSLSocketFactory getSslSocketFactory(InputStream cerIn, String storePass) {
SSLSocketFactory sslSocketFactory = null;
try {
TrustManager[] trustManagers = prepareTrustManager(cerIn, storePass);
X509TrustManager manager;
// 优先使用自定义的证书管理器
if (trustManagers != null) {
manager = chooseTrustManager(trustManagers);
LOG.debug("---https访问,使用自定义证书---");
} else {
// 否则使用无证书认证的证书管理器
manager = UnSafeTrustManager;
LOG.debug("---https访问,无证书---");
}
// 创建TLS类型的SSLContext对象
SSLContext sslContext = SSLContext.getInstance("TLS");
// 用上面得到的trustManagers初始化SSLContext,这样sslContext就会信任keyStore中的证书
// 第一个参数是授权的密钥管理器,用来授权验证,比如授权自签名的证书验证。第二个是被授权的证书管理器,用来验证服务器端的证书
sslContext.init(null, new TrustManager[] { manager }, null);
// 通过sslContext获取SSLSocketFactory对象
sslSocketFactory = sslContext.getSocketFactory();
return sslSocketFactory;
} catch (Exception e) {
//LOG.error("--证书加载出错-", e);
throw new RuntimeException("证书信息加载错误");
}
}
private static SSLSocketFactory createInsecureSslSocketFactory() {
try {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new TrustManager[]{new AcceptEverythingTrustManager()}, null);
return context.getSocketFactory();
} catch (Exception e) {
throw new AssertionError(e);
}
}
public static void main(String[] args) throws Exception {
System.out.println("Client: arguments=" + String.join("; ", args));
int port = Integer.valueOf(args[0]);
String[] trustNames = args[1].split(TLSRestrictions.DELIMITER);
String[] certNames = args[2].split(TLSRestrictions.DELIMITER);
String constraint = args[3];
TLSRestrictions.setConstraint("Client", constraint);
SSLContext context = TLSRestrictions.createSSLContext(
trustNames, certNames);
SSLSocketFactory socketFactory = context.getSocketFactory();
try (SSLSocket socket = (SSLSocket) socketFactory.createSocket()) {
socket.connect(new InetSocketAddress("localhost", port),
TLSRestrictions.TIMEOUT);
socket.setSoTimeout(TLSRestrictions.TIMEOUT);
System.out.println("Client: connected");
InputStream sslIS = socket.getInputStream();
OutputStream sslOS = socket.getOutputStream();
sslOS.write('C');
sslOS.flush();
sslIS.read();
System.out.println("Client: finished");
} catch (Exception e) {
throw new RuntimeException("Client: failed.", e);
}
}
/**
* Creates a new SSL socket factory that generates SSL sockets that trust all certificates unconditionally.
*
* @return A new SSL socket factory that generates SSL sockets that trust all certificates unconditionally.
*/
public SSLSocketFactory createSslSocketFactory() {
try {
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{this}, null);
return sslContext.getSocketFactory();
} catch (NoSuchAlgorithmException | KeyManagementException e) {
throw new AssertionError(e);
}
}
static SSLClient init(int port, String ciphersuite)
throws NoSuchAlgorithmException, IOException {
SSLContext context = SSLContext.getDefault();
SSLSocketFactory ssf = (SSLSocketFactory)
context.getSocketFactory();
SSLSocket socket = (SSLSocket) ssf.createSocket("localhost", port);
if (ciphersuite != null) {
System.out.println("Client: enable cipher suite: "
+ ciphersuite);
socket.setEnabledCipherSuites(new String[] { ciphersuite });
}
return new SSLClient(socket);
}
/**
* Build an {@link SSLSessionStrategy}.
*
* @param trustStore the trust store
* @param trustStorePassword the truststore password (if any)
* @param keyStore the keystore
* @param keyStorePassword the keystore password (if any)
* @param keyAliases the key aliases that are candidates for use (if any)
* @param keyPassword the key password (if any)
* @param allowedProtocols the allowed transport protocols.
* <strong><em>Avoid specifying insecure protocols</em></strong>
* @param allowedCiphers allowed crypto ciphersuites, <tt>null</tt> to use system defaults
* @param trustSelfSigned true if self signed certificates can be trusted.
* <strong><em>Use with caution</em></strong>
* @param allowAnyHostname true if any hostname can be connected to (i.e. does not need to match
* certificate hostname). <strong><em>Do not use in production</em></strong>
* @return the connection socket factory
* @throws NoSuchAlgorithmException if the selected algorithm is not available on the system
* @throws KeyStoreException if there was a problem with the keystore
* @throws CertificateException if there was a problem with the certificate
* @throws IOException if the truststore could not be found or was invalid
* @throws KeyManagementException if there is a problem with keys
* @throws UnrecoverableKeyException if the key cannot be recovered
*/
public static SSLSessionStrategy build(String trustStore,
String trustStorePassword,
String keyStore,
String keyStorePassword,
String[] keyAliases,
String keyPassword,
String[] allowedProtocols,
String[] allowedCiphers,
boolean allowAnyHostname,
boolean trustSelfSigned)
throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException,
KeyManagementException, UnrecoverableKeyException {
Args.notNull(allowedProtocols, "Allowed protocols"); //$NON-NLS-1$
Args.notNull(allowedCiphers, "Allowed ciphers"); //$NON-NLS-1$
TrustStrategy trustStrategy = trustSelfSigned ? SELF_SIGNED : null;
HostnameVerifier hostnameVerifier = allowAnyHostname ? ALLOW_ANY :
SSLConnectionSocketFactory.getDefaultHostnameVerifier();
PrivateKeyStrategy privateKeyStrategy = keyAliases == null ? null : new SelectByAlias(keyAliases);
boolean clientAuth = keyStore == null ? false : true;
SSLContextBuilder builder = SSLContexts.custom();
if (trustStore != null) {
loadTrustMaterial(builder,
new File(trustStore),
trustStorePassword.toCharArray(),
trustStrategy);
}
if (keyStore != null) {
char[] ksp = keyStorePassword == null ? null : keyStorePassword.toCharArray();
char[] kp = keyPassword == null ? null : keyPassword.toCharArray();
loadKeyMaterial(builder, new File(keyStore), ksp, kp, privateKeyStrategy);
}
SSLContext sslContext = builder.build();
return new SSLSessionStrategy(hostnameVerifier, new CipherSelectingSSLSocketFactory(
sslContext.getSocketFactory(), allowedCiphers, allowedProtocols, clientAuth));
}
private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, sTrustManagers, null);
return context.getSocketFactory();
}
/**
* 以https get方式通信
*
* @param url
* @param sslContext
* @throws IOException
*/
protected void httpsGetMethod(String url, SSLContext sslContext) throws IOException {
SSLSocketFactory sf = sslContext.getSocketFactory();
HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);
conn.setSSLSocketFactory(sf);
this.doGet(conn);
}