java中的SSLSocketFactory [英] SSLSocketFactory in java

查看:309
本文介绍了java中的SSLSocketFactory的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 HttpsURLConnection 时,java播放中 SSLSocketFactory 类的作用是什么? java文档没有多大帮助。

What role does SSLSocketFactory class in java play when using HttpsURLConnection? The java docs is not of much help.

有没有办法将密钥库和信任库绑定到sslsocketfactory对象,使其指向密钥库和信任库?

Are there any ways to bind the keystore and the truststore to with the sslsocketfactory object, to make it point to the keystore and the truststore?

否则连接将如何知道密钥库和信任库的位置(我不想使用java 系统属性)?

Otherwise how will the connection know the location of the keystore and the truststore(I don't want to use java System Properties)?

推荐答案

这是通过SSLContext完成的。你初始化一个,然后使用它的套接字工厂来创建HttpsConnection实例。

It is done through SSLContext. You init one and then use it's socket factory to create HttpsConnection instances.

这是我在我的应用程序中如何管理它的粗略示例:

Here is rough example of how I manage this in my application:

SSLContext sc = SSLContext.getInstance("SSL");
sc.init(myKeyManagerFactory.getKeyManagers(), myTrustManagerArray, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

之后你的openConnection()调用https网站将使用你在这里初始化的sslsocketfactory。

after that your openConnection() calls for https sites will use the sslsocketfactory you initialized here.

此处TrustManager在您的ssl上下文中使用的代码将信任所有证书:

Here code for TrustManager to use in your ssl context wich will trust all certificates:

TrustManager[] myTrustManagerArray = new TrustManager[]{new TrustEveryoneManager()};

class TrustEveryoneManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] arg0, String arg1){}
    public void checkServerTrusted(X509Certificate[] arg0, String arg1){}
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

布鲁诺的更新:当心,信任任何证书,但是方便的是,使连接易受MITM攻击

Upd from Bruno: beware, trusting any certificate, however convenient it is, makes the connection vulnerable to MITM attacks

这篇关于java中的SSLSocketFactory的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆