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();
Related
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);
I'm trying to replace the following deprecated (e.g. Apache DefaultHttpClient, SSLSocketFactory are deprecated) code:
public class HttpUtil {
public static DefaultHttpClient getDefaultHttpClient(IClientConfiguration configuration,
ExternalAPILogger logger) {
DefaultHttpClient client = new DefaultHttpClient();
if(configuration.isIgnoreSSLCertificate()) {
try {
SSLContext context = SSLContext.getInstance("TLS");
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
context.init(null, new TrustManager[]{trustManager}, null);
SSLSocketFactory sslSocketFactory = new SSLSocketFactory(context);
sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
ClientConnectionManager connectionManager = client.getConnectionManager();
SchemeRegistry schemeRegistry = connectionManager.getSchemeRegistry();
schemeRegistry.register(new Scheme("https", sslSocketFactory, 443));
client = new DefaultHttpClient(connectionManager, client.getParams());
} catch (NoSuchAlgorithmException e) {
logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
} catch(KeyManagementException e) {
logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
}
}
if(configuration.isUseProxy()) {
HttpHost proxy = new HttpHost(configuration.getProxyHost(),
configuration.getProxyPort());
ConnRouteParams.setDefaultProxy(client.getParams(), proxy);
}
client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 60 * 1000);
client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60 * 1000);
return client;
}
}
by this new code:
public static HttpClient getHttpClient(IClientConfiguration configuration,
ExternalAPILogger logger) {
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
// clientBuilder.useSystemProperties();
if (configuration.isIgnoreSSLCertificate()) {
try {
SSLContext context = SSLContext.getInstance("TLS");
X509TrustManager trustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
context.init(null, new TrustManager[] { trustManager }, null);
// clientBuilder.setSSLContext(context);
// clientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
SSLConnectionSocketFactory sslSocketFactory =
new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
clientBuilder.setSSLSocketFactory(sslSocketFactory);
Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("https", sslSocketFactory).build();
HttpClientConnectionManager httpClientConnectionManager =
new BasicHttpClientConnectionManager(schemeRegistry);
clientBuilder.setConnectionManager(httpClientConnectionManager);
} catch (NoSuchAlgorithmException e) {
logger.log(HttpUtil.class.getName(), "TLS not available", e, ExternalAPILogger.DEBUG);
} catch (KeyManagementException e) {
logger.log(HttpUtil.class, "ssl context init failed", e, ExternalAPILogger.DEBUG);
}
}
RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
if (configuration.isUseProxy()) {
HttpHost proxy = new HttpHost(
configuration.getProxyHost(),
configuration.getProxyPort());
// clientBuilder
// .setRoutePlanner(new DefaultProxyRoutePlanner(proxy))
// .setProxy(proxy)
// .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
requestConfigBuilder.setProxy(proxy);
}
requestConfigBuilder
.setConnectTimeout(60 * 1000)
.setSocketTimeout(60 * 1000);
clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());
// SocketConfig.Builder socketConfig = SocketConfig.custom();
// socketConfig.setSoTimeout(60 * 1000);
// clientBuilder.setDefaultSocketConfig(socketConfig.build());
return clientBuilder.build();
}
but I have problems to get the code running using a http proxy. I get the following error message.:
Caused by: org.apache.http.conn.UnsupportedSchemeException: http protocol is not supported
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());
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
The question is very simple.
How to re-enable SSL certificate validation once the following code is executed ?
// 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) {
}
Try this:
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, null, null);
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
If a parameter of the init method is null, the default implementation is used.