Java setProperty "https.protocols", "TLSv1.2" for one REST Call

10,295

I believe you can set the TLS protocol on your HttpsURLConnection directly and this way it will be only applied locally to this one connection.

First initialize your TLSv1.2 SSLContext

SSLContext sc = SSLContext.getInstance("TLSv1.2");
// Init the SSLContext with a TrustManager[] and SecureRandom()
sc.init(null, trustCerts, new java.security.SecureRandom()); 

Documentation about the init() parameters:

"Either of the first two parameters may be null in which case the installed security providers will be searched for the highest priority implementation of the appropriate factory. Likewise, the secure random parameter may be null in which case the default implementation will be used."

Afterwards just set this SSLContext on the HttpsURLConnection:

httpsCon.setSSLSocketFactory(sc.getSocketFactory());

If for debugging purposes you need an all-trusting, albeit unsafe implementation of the trustCert, then you can initialize it like this and use it as the second parameter in the init().
(This implementation completely disables SSL checking and should not be used outside of a debug/development situation)

// Create a trust manager that does not validate certificate chains
TrustManager[] trustCerts = new TrustManager[]{
    new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        public void checkClientTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
        public void checkServerTrusted(
            java.security.cert.X509Certificate[] certs, String authType) {
        }
    }
};
Share:
10,295
Kamui
Author by

Kamui

Updated on June 04, 2022

Comments

  • Kamui
    Kamui almost 2 years

    currently I have to use Java 7 (can't change it atm) and the default TLS Version is 1.0(?), so below 1.2. And now i have to use an REST Api which doesnt accept any TLS below TLSv1.2.

    So my Solution for this was:

    Before the REST Call:

    System.setProperty("https.protocols", "TLSv1.2"); // Adding this System property only for this one function call. Has to be executed every time before
    

    And Afterwards the GET Call itself:

    ...
    URL url = new URL("https://test.com");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    ...
    

    Now my question is: Is there an alternative way to set the "https.protocols" property, so i dont have to set it in System?

    Else im doubtful if this System property affects REST Calls from other classes, which has been executed at the same time.

  • Robert
    Robert about 5 years
    Kamui never mentioned a certificate problem, therefore the accept-all-trustmanager is unnecessary. Proposing insecure code in a case where it is not necessary should be avoided. I would recommend to remove this part of your answer.