获取HttpsURLConnection中使用的SSL版本 - Java

时间:2014-11-22 08:56:24

标签: java ssl httpsurlconnection

我正在开发一个java代理来监控我的应用服务器中发生的http通信。我想知道传出Https连接中使用的SSL版本(SSLv3,TLS等)。有没有办法以任何方式获得SSL版本?

1 个答案:

答案 0 :(得分:7)

我使用了这个解决方案,也许它可以帮到你:

首先,您需要SSLSocketFactory的扩展类,以便将HandshakeCompletedListener附加到SSLSocketFactory创建的套接字: (受How to override the cipherlist sent to the server by Android when using HttpsURLConnection?启发)

public class SecureSSLSocketFactory extends SSLSocketFactory {
private final SSLSocketFactory delegate;
private HandshakeCompletedListener handshakeListener;

public SecureSSLSocketFactory(
        SSLSocketFactory delegate, HandshakeCompletedListener handshakeListener) {
    this.delegate = delegate;
    this.handshakeListener = handshakeListener;
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) 
    throws IOException {
    SSLSocket socket = (SSLSocket) this.delegate.createSocket(s, host, port, autoClose);

    if (null != this.handshakeListener) {
        socket.addHandshakeCompletedListener(this.handshakeListener);
    }

    return socket;
}
// and so on for all the other createSocket methods of SSLSocketFactory.

@Override
public String[] getDefaultCipherSuites() {
    // TODO: or your own preferences
    return this.delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    // TODO: or your own preferences
    return this.delegate.getSupportedCipherSuites();
}

然后您需要实现HandshakeCompletedListener接口。您必须实施handshakeCompleted方法:

public class MyHandshakeCompletedListener implements HandshakeCompletedListener {
@Override
public void handshakeCompleted(HandshakeCompletedEvent event) {
    SSLSession session = event.getSession();
    String protocol = session.getProtocol();
    String cipherSuite = session.getCipherSuite();
    String peerName = null;

    try {
        peerName = session.getPeerPrincipal().getName();
    } catch (SSLPeerUnverifiedException e) {
    }
}

handshakeCompleted中,您可以获得协议版本(可能是TLSv1.2),同样也可以获得密码套件等信息,也可以通过HttpsConnection访问。 您可以在连接之前通过conn.setSSLSocketFactory设置自定义SSL套接字工厂:

private void setupAndConnect() {
URL url = new URL("https://host.dom/xyz");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(/*keyManagers*/null, /*trustManagers*/null, /*new SecureRandom()*/null);    // simple here

conn.setSSLSocketFactory(new SecureSSLSocketFactory(sslContext.getSocketFactory(), new MyHandshakeCompletedListener()));

// conn.set... /* set other parameters */
conn.connect();