Getting javax.net.ssl.SSLHandshakeException: Connection closed by peer - java

I'm getting javax.net.ssl.SSLHandshakeException: Connection closed by peer when i try to make https request from android app using HttpsURLConnection
Above the code for to make request and return a Bitmap.
protected Bitmap doInBackground(String... params) {
try {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
HttpsURLConnection connection = (HttpsURLConnection)
new URL("www.example.com.br").openConnection();
connection.setHostnameVerifier(getHostnameVerifier("www.example.com.br");
connection.setRequestMethod("GET");
connection.setConnectTimeout(3000);
connection.setUseCaches(false);
connection.setAllowUserInteraction(false);
connection.connect();
setCookieActivity(connection.getHeaderField("Set-Cookie"));
return BitmapFactory.decodeStream(connection.getInputStream());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private HostnameVerifier getHostnameVerifier(final String url) {
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
HostnameVerifier hv =
HttpsURLConnection.getDefaultHostnameVerifier();
return hv.verify(url, session);
}
};
return hostnameVerifier;
}
I already tried many thing, but i get the same exception
This link works for many, but not for me.
telling java to accept self-signed ssl certificate

Related

How to indicate to HttpsUrlConnection the cert (previously imported to cacert file) that it should use

I'm trying to consume a web service, in which we import a certificate to the JDK's cacert file. But I can't understand how to "set" the HttpsURLConnection object the cert that it must use to be able to execute the web service.
I read that once the certificate was installed in the cacert file, it was no longer necessary to indicate anything when connecting to the web service.
I am currently skipping the KeyStore and TrustStore validation to invoke the web service.
This is my code:
public void tokenFotoCteNOCHOProd(String url) throws IOException {
HttpsURLConnection conn = null;
String params = "";
String res = "";
try {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
#Override
public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
/**/
}
#Override
public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
/**/
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
}
};
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLContext sc = SSLContext.getInstance("TLSv1.2");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
params = "someParams";
URL url = new URL(url);
conn = (HttpsURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setConnectTimeout(3000);
try (OutputStream os = conn.getOutputStream()) {
os.write(params.getBytes(StandardCharsets.UTF_8));
os.flush();
res = getRespWS(conn);//get resp..
}
} catch (KeyManagementException | NoSuchAlgorithmException | ClassCastException | JsonParseException e) {
LOGGER.info("error", e);
}
}

How to disable SSL for given url or for restTemplateBuilder?

I need to disable the SSL for a given url or for the restTemplate right know i can disable all the SSL's with the code bellow. How can i make this code for given URL only. Or how to disable it for the restTemplate.
public class SSLTool {
public static void disableCertificateValidation() {
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hv);
} catch (Exception e) {/* intentionally left blank */}
}
}
I solved this with the following code down below. here is the link to the source https://stackoverflow.com/a/42689331/16529288
TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
Returning RestTemplate with SSL disabled can be achieved via below(You can add other properties as your requirements.) :
CloseableHttpClient client = HttpClients.custom().setSSLHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).setSSLHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).build();
HttpComponentsClientHttpRequestFactory req = new HttpComponentsClientHttpRequestFactory(client);
RestTemplate template = new RestTemplate(req);

Am not able to connect to socket with HTTPS

TrustManager[] trustManager = new TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certificate, String str) {
}
public void checkServerTrusted(X509Certificate[] certificate, String str) {
}
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(null, trustManager, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HostnameVerifier myHostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient.Builder().hostnameVerifier(myHostnameVerifier)
.sslSocketFactory(sslSocketFactory,X509TrustManager trustManager).build();
am getting an error near sslSocketFactory(sslSocketFactory,X509TrustManager trustManager).build();
TrustManager[] trustManager = new X509TrustManager[]{
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certificate,
String str) {
}
public void checkServerTrusted(X509Certificate[] certificate,
String str) {
}
}
};
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS");
try {
sslContext.init(null, trustManager, null);
} catch (KeyManagementException e) {
e.printStackTrace();
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
HostnameVerifier myHostnameVerifier = new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient.Builder().hostnameVerifier(myHostnameVerifier).sslSocketFactory(sslSocketFactory).build();

wss web socket creation issue

I got - closed connection -1 , draft org.java_websocket.drafts.Draft_17#75599672 refuses handshake , false - then changed the code as below:
Socket creation coode
webClient = new APICWebClient(new URI(getWebSocketUrl(currentApic.IPAddress, port)), new Draft_17());
webClient.connect();
Constructor:
public APICWebClient(URI serverURI, Draft draft) {
super(serverURI, draft);
SSLContext sslContext = null;
try {
sslContext = SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setWebSocketFactory(new DefaultSSLWebSocketClientFactory(sslContext));
logger.info("Socket object created");
}
Draft_17. I get : closed connection -1 , , true. Any help here. This happens during socket creation.
Need to create sslcontext like below. it skips the certificate. I was successfully able make a connection without certificate
SSLContext sslContext = SSLContext.getInstance("SSL");
// set up a TrustManager that trusts everything
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
return null;
}
public void checkClientTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkClientTrusted =============");
}
public void checkServerTrusted(X509Certificate[] certs,
String authType) {
System.out.println("checkServerTrusted =============");
}
} }, new SecureRandom());

Getting Java to accept all certs over HTTPS

I'm trying to get Java to accept all certs over HTTPS. This is for testing purposes. Before I was getting a cert not found error. However, after adding the following code before my code I get a HTTPS hostname wrong: should be <sub.domain.com> error. The problem is my url IS that url. How do I get around this issue? The below is the code I've added to attempt to fix the problem..
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = 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) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
You need to set the a HostNameVarifier also
Ex:
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;
public class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
Then
httpsConnection.setHostnameVerifier(new TrustAllHostNameVerifier ());

Categories