Search code examples
javasslhttpsurlconnection

Which security technique is used in HttpsURLConnection?


I've got the following lines of code to set up an SSL connection:

HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();

I use the given connection to send a message and retrieve a response. Now I've gotten the question: Which security technique is used in this connection? I'd like to know if the connection is, for example, TLS1.2. How can I retrieve this using Java?


Solution

  • HttpsURLConnection will use whatever scheme is negotiated between the client and the server. It is possible to get some information about the cipher suites used, and the client and server certificates, but the protocol / version are not directly exposed by the public APIs.

    Retrieving the protocol that was actually used is tricky.

    • If you have enabled SSL debug, then the debug output will include the protocol version, and copious other information. However, since the format of the debug output is not specified / subject to change, it would not be a good idea to try to extract this programatically.

      But if eyeballing debug output is acceptable, this is the answer.

    • If you read the Java SSL codebase, you will find a class called SSLEngineImpl, which has a private field called protocolVersion that gives the protocol and version that the connection is using. Unfortunately, the "engine" instance is deeply buried and it would be difficult to get to it at runtime.

    • If you implement your own SSLSocketFactory, you can get the protocol used from the SSLSession object after the session has been established; see Get SSL Version used in HttpsURLConnection - Java.

    • Finally, it is possible to figure out which protocol is used by decoding the initial messages sent over the TCP/IP connection. The messages are the "client hello" and "server hello" messages. The connection is not encrypted at this stage.

    Oracle References: