Getting SSLException using Retrofit 2

I create an authorization application where I use Retrofit 2. When I make a call, it goes onFailure and gets an exception

"javax.net.ssl.SSLException: Connection closed by peer"

But the problem is that it did a great job yesterday. Today he gives an exception. I found several SSLException on the Internet - a connection closed by a peer in versions of Android 4.x , or this How to add TLS v 1.0 and TLS v.1.1 using "Retrofit" , but this did not help me. Any ideas how to fix this. In the backend, TLS1.2 is enabled.

public class RegistrationFragment extends BaseFragment {
View mainView;

ApiClient apiClient = ApiClient.getInstance();

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    mainView = inflater.inflate
            (R.layout.registration_fragment, container, false);

            //Calling the authorization method
            registerCall();
        }
    });

    return mainView;
}

//User authorization method

public void registerCall() {

    Call<ResponseBody> call = apiClient.registration(supportopObj);
    call.enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            if (response.isSuccessful()) {

                //Calling the clientCall method for getting the user clientID and clientSecret
                Toast.makeText(getActivity(), "Registration Successful ",
                        Toast.LENGTH_SHORT).show();;

            } else {
                //if the response not successful
                Toast.makeText(getActivity(), "Could not register the user maybe already registered ",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Toast.makeText(getActivity(), "An error occurred", Toast.LENGTH_SHORT).show();
        }
    });
}
}
+4
source share
2 answers

I used something like this in my OkHttp initialization class, but is it safe to use here?

Tls12SocketFactory.class

.

public class Tls12SocketFactory extends SSLSocketFactory {
private static final String[] TLS_V12_ONLY = {"TLSv1.2"};

final SSLSocketFactory delegate;

public Tls12SocketFactory(SSLSocketFactory base) {
    this.delegate = base;
}

@Override
public String[] getDefaultCipherSuites() {
    return delegate.getDefaultCipherSuites();
}

@Override
public String[] getSupportedCipherSuites() {
    return delegate.getSupportedCipherSuites();
}

@Override
public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
    return patch(delegate.createSocket(s, host, port, autoClose));
}

@Override
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException {
    return patch(delegate.createSocket(host, port, localHost, localPort));
}

@Override
public Socket createSocket(InetAddress host, int port) throws IOException {
    return patch(delegate.createSocket(host, port));
}

@Override
public Socket createSocket(InetAddress address, int port, InetAddress localAddress, int localPort) throws IOException {
    return patch(delegate.createSocket(address, port, localAddress, localPort));
}

private Socket patch(Socket s) {
    if (s instanceof SSLSocket) {
        ((SSLSocket) s).setEnabledProtocols(TLS_V12_ONLY);
    }
    return s;
}
}

- OkHttp.

X509TrustManager trustManager = null;

    try {
        TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init((KeyStore) null);
        TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
        if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
            throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
        }
         trustManager = (X509TrustManager) trustManagers[0];
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }

    OkHttpClient.Builder client = new OkHttpClient.Builder()
            .readTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS);

    try {
        SSLContext sc = SSLContext.getInstance("TLSv1.2");
        sc.init(null, new TrustManager[] { trustManager }, null);
        client.sslSocketFactory(new Tls12SocketFactory(sc.getSocketFactory()), trustManager);
        ConnectionSpec cs = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                .tlsVersions(TlsVersion.TLS_1_2)
                .build();
        client.connectionSpecs(Collections.singletonList(cs));
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }

 name = new Retrofit.Builder()
            .baseUrl(endpoint)
            .client(client.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Android. - ? . , - .

0

- , - okhttp. okhttp version 3.x, . okhttp version 2.x. , , , Android 16-20

0

Source: https://habr.com/ru/post/1695043/


All Articles