Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to...












187















I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate. Is it possible to ignore the client-server authentication? If so, how?



package com.da;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;

public class RSDDownloadFile {
static FileOutputStream fos;

public void DownloadFile(String URI, String Request) throws Exception
{
java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
"Lang=EN&AuthToken=package", null);
System.out.println("URI Query: " + uri.toString());

HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
Future<Boolean> future = httpclient.execute(
new HttpAsyncGet(uri),
new ResponseCallback(), null);

Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("nRequest successfully executed");
} else {
System.out.println("Request failed");
}
}
catch(Exception e){
System.out.println("[DownloadFile] Exception: " + e.getMessage());
}
finally {
System.out.println("Shutting down");
httpclient.shutdown();
}
System.out.println("Done");

}

static class ResponseCallback extends AsyncCharConsumer<Boolean> {

@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println("Response: " + response.getStatusLine());
System.out.println("Header: " + response.toString());
try {
//if(response.getStatusLine().getStatusCode()==200)
fos = new FileOutputStream( "Response.html" );
}catch(Exception e){
System.out.println("[onResponseReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try
{
while (buf.hasRemaining())
{
//System.out.print(buf.get());
fos.write(buf.get());
}
}catch(Exception e)
{
System.out.println("[onCharReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCleanup() {
try
{
if(fos!=null)
fos.close();
}catch(Exception e){
System.out.println("[onCleanup] Exception: " + e.getMessage());
}
System.out.println("onCleanup()");
}

@Override
protected Boolean buildResult() {
return Boolean.TRUE;
}

}
}


Errors:



URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
at javax.net.ssl.SSLEngine.wrap(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
... 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 21 more
onCleanup()

[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done









share|improve this question

























  • One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

    – kayleeFrye_onDeck
    Jul 18 '16 at 23:19
















187















I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate. Is it possible to ignore the client-server authentication? If so, how?



package com.da;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;

public class RSDDownloadFile {
static FileOutputStream fos;

public void DownloadFile(String URI, String Request) throws Exception
{
java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
"Lang=EN&AuthToken=package", null);
System.out.println("URI Query: " + uri.toString());

HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
Future<Boolean> future = httpclient.execute(
new HttpAsyncGet(uri),
new ResponseCallback(), null);

Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("nRequest successfully executed");
} else {
System.out.println("Request failed");
}
}
catch(Exception e){
System.out.println("[DownloadFile] Exception: " + e.getMessage());
}
finally {
System.out.println("Shutting down");
httpclient.shutdown();
}
System.out.println("Done");

}

static class ResponseCallback extends AsyncCharConsumer<Boolean> {

@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println("Response: " + response.getStatusLine());
System.out.println("Header: " + response.toString());
try {
//if(response.getStatusLine().getStatusCode()==200)
fos = new FileOutputStream( "Response.html" );
}catch(Exception e){
System.out.println("[onResponseReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try
{
while (buf.hasRemaining())
{
//System.out.print(buf.get());
fos.write(buf.get());
}
}catch(Exception e)
{
System.out.println("[onCharReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCleanup() {
try
{
if(fos!=null)
fos.close();
}catch(Exception e){
System.out.println("[onCleanup] Exception: " + e.getMessage());
}
System.out.println("onCleanup()");
}

@Override
protected Boolean buildResult() {
return Boolean.TRUE;
}

}
}


Errors:



URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
at javax.net.ssl.SSLEngine.wrap(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
... 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 21 more
onCleanup()

[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done









share|improve this question

























  • One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

    – kayleeFrye_onDeck
    Jul 18 '16 at 23:19














187












187








187


88






I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate. Is it possible to ignore the client-server authentication? If so, how?



package com.da;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;

public class RSDDownloadFile {
static FileOutputStream fos;

public void DownloadFile(String URI, String Request) throws Exception
{
java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
"Lang=EN&AuthToken=package", null);
System.out.println("URI Query: " + uri.toString());

HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
Future<Boolean> future = httpclient.execute(
new HttpAsyncGet(uri),
new ResponseCallback(), null);

Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("nRequest successfully executed");
} else {
System.out.println("Request failed");
}
}
catch(Exception e){
System.out.println("[DownloadFile] Exception: " + e.getMessage());
}
finally {
System.out.println("Shutting down");
httpclient.shutdown();
}
System.out.println("Done");

}

static class ResponseCallback extends AsyncCharConsumer<Boolean> {

@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println("Response: " + response.getStatusLine());
System.out.println("Header: " + response.toString());
try {
//if(response.getStatusLine().getStatusCode()==200)
fos = new FileOutputStream( "Response.html" );
}catch(Exception e){
System.out.println("[onResponseReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try
{
while (buf.hasRemaining())
{
//System.out.print(buf.get());
fos.write(buf.get());
}
}catch(Exception e)
{
System.out.println("[onCharReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCleanup() {
try
{
if(fos!=null)
fos.close();
}catch(Exception e){
System.out.println("[onCleanup] Exception: " + e.getMessage());
}
System.out.println("onCleanup()");
}

@Override
protected Boolean buildResult() {
return Boolean.TRUE;
}

}
}


Errors:



URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
at javax.net.ssl.SSLEngine.wrap(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
... 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 21 more
onCleanup()

[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done









share|improve this question
















I have a class that will download a file from a https server. When I run it, it returns a lot of errors. It seems that I have a problem with my certificate. Is it possible to ignore the client-server authentication? If so, how?



package com.da;

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;

import org.apache.http.HttpResponse;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.nio.client.DefaultHttpAsyncClient;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.HttpAsyncClient;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncGet;
import org.apache.http.nio.client.methods.HttpAsyncPost;

public class RSDDownloadFile {
static FileOutputStream fos;

public void DownloadFile(String URI, String Request) throws Exception
{
java.net.URI uri = URIUtils.createURI("https", "176.66.3.69:6443", -1, "download.aspx",
"Lang=EN&AuthToken=package", null);
System.out.println("URI Query: " + uri.toString());

HttpAsyncClient httpclient = new DefaultHttpAsyncClient();
httpclient.start();
try {
Future<Boolean> future = httpclient.execute(
new HttpAsyncGet(uri),
new ResponseCallback(), null);

Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("nRequest successfully executed");
} else {
System.out.println("Request failed");
}
}
catch(Exception e){
System.out.println("[DownloadFile] Exception: " + e.getMessage());
}
finally {
System.out.println("Shutting down");
httpclient.shutdown();
}
System.out.println("Done");

}

static class ResponseCallback extends AsyncCharConsumer<Boolean> {

@Override
protected void onResponseReceived(final HttpResponse response) {
System.out.println("Response: " + response.getStatusLine());
System.out.println("Header: " + response.toString());
try {
//if(response.getStatusLine().getStatusCode()==200)
fos = new FileOutputStream( "Response.html" );
}catch(Exception e){
System.out.println("[onResponseReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
try
{
while (buf.hasRemaining())
{
//System.out.print(buf.get());
fos.write(buf.get());
}
}catch(Exception e)
{
System.out.println("[onCharReceived] Exception: " + e.getMessage());
}
}

@Override
protected void onCleanup() {
try
{
if(fos!=null)
fos.close();
}catch(Exception e){
System.out.println("[onCleanup] Exception: " + e.getMessage());
}
System.out.println("onCleanup()");
}

@Override
protected Boolean buildResult() {
return Boolean.TRUE;
}

}
}


Errors:



URI Query: https://176.66.3.69:6443/download.aspx?Lang=EN&AuthToken=package
Aug 2, 2011 3:47:57 PM org.apache.http.impl.nio.client.NHttpClientProtocolHandler exception
SEVERE: I/O error: General SSLEngine problem
javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Handshaker.checkThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.checkTaskThrown(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.writeAppRecord(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.wrap(Unknown Source)
at javax.net.ssl.SSLEngine.wrap(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:154)
at org.apache.http.impl.nio.reactor.SSLIOSession.isAppInputReady(SSLIOSession.java:276)
at org.apache.http.impl.nio.client.InternalClientEventDispatch.inputReady(InternalClientEventDispatch.java:79)
at org.apache.http.impl.nio.reactor.BaseIOReactor.readable(BaseIOReactor.java:161)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvent(AbstractIOReactor.java:335)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.processEvents(AbstractIOReactor.java:315)
at org.apache.http.impl.nio.reactor.AbstractIOReactor.execute(AbstractIOReactor.java:275)
at org.apache.http.impl.nio.reactor.BaseIOReactor.execute(BaseIOReactor.java:104)
at org.apache.http.impl.nio.reactor.AbstractMultiworkerIOReactor$Worker.run(AbstractMultiworkerIOReactor.java:542)
at java.lang.Thread.run(Unknown Source)
Caused by: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Unknown Source)
at com.sun.net.ssl.internal.ssl.SSLEngineImpl.fatal(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.fatalSE(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverCertificate(Unknown Source)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Unknown Source)
at com.sun.net.ssl.internal.ssl.Handshaker$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.net.ssl.internal.ssl.Handshaker$DelegatedTask.run(Unknown Source)
at org.apache.http.impl.nio.reactor.SSLIOSession.doHandshake(SSLIOSession.java:180)
... 9 more
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.validator.PKIXValidator.doBuild(Unknown Source)
at sun.security.validator.PKIXValidator.engineValidate(Unknown Source)
at sun.security.validator.Validator.validate(Unknown Source)
at com.sun.net.ssl.internal.ssl.X509TrustManagerImpl.checkServerTrusted(Unknown Source)
at com.sun.net.ssl.internal.ssl.JsseX509TrustManager.checkServerTrusted(Unknown Source)
... 16 more
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(Unknown Source)
at java.security.cert.CertPathBuilder.build(Unknown Source)
... 21 more
onCleanup()

[DownloadFile] Exception: javax.net.ssl.SSLHandshakeException: General SSLEngine problem
Shutting down
Done






java ssl https ssl-certificate






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 4 '16 at 14:42









ROMANIA_engineer

33.6k19149141




33.6k19149141










asked Aug 2 '11 at 8:04









neztrehneztreh

1,04621216




1,04621216













  • One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

    – kayleeFrye_onDeck
    Jul 18 '16 at 23:19



















  • One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

    – kayleeFrye_onDeck
    Jul 18 '16 at 23:19

















One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

– kayleeFrye_onDeck
Jul 18 '16 at 23:19





One time I got this error and contacted our security team, and it turned out I had to patch the JAR we were using, as our team was using an outdated one provided by the company. Just an FYI for anyone else who may be in a similar situation.

– kayleeFrye_onDeck
Jul 18 '16 at 23:19












20 Answers
20






active

oldest

votes


















172














The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.



In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.



See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.






share|improve this answer





















  • 2





    this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

    – Cheruvim
    May 20 '15 at 18:13











  • The problem also appears with a certificate signed by someone else that isn't trusted.

    – user207421
    Oct 26 '16 at 9:16













  • Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

    – Dima Fomin
    Dec 21 '18 at 17:02











  • In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

    – java-addict301
    Jan 23 at 17:47



















122














Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.



openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit





share|improve this answer





















  • 3





    Works for me why? You need to provide an explanation.

    – user207421
    Oct 26 '16 at 9:16











  • openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

    – Vishnu Ranganathan
    Nov 26 '16 at 4:54








  • 2





    .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

    – Gabe Martin-Dempesy
    Mar 14 '17 at 19:15











  • Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

    – Zotov
    Jun 13 '17 at 20:13






  • 1





    This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

    – Patrik Beck
    Jul 13 '17 at 12:16



















37














I had the same issue with a valid signed wildcard certificate from symantec.



First try running your java application with -Djavax.net.debug=SSL to see what is really going on.



I ended up importing the intermediate certificate which was causing the cert chain to break.



I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).



And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:



keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer





share|improve this answer
























  • This was the case:

    – kisna
    Jan 4 '17 at 3:17











  • To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

    – kisna
    Jan 4 '17 at 3:26













  • And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

    – kisna
    Jan 4 '17 at 3:51











  • I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

    – Pigritia
    May 18 '17 at 22:07



















29















  1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt

  2. Go to your JRE_HOME/bin or JDK/JRE/bin

  3. Type the command

  4. keytool -keystore ..libsecuritycacerts -import -alias your.ssl.server.name -file .relative-path-to-cert-fileyour.ssl.server.name.crt

  5. Restart your Java process






share|improve this answer


























  • I see following error, please help

    – user5268786
    Oct 26 '15 at 20:30






  • 9





    If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

    – Fr4nz
    Jul 28 '16 at 14:26













  • You are the BEST!!!

    – Mehraj Malik
    May 28 '18 at 12:19





















17














Quoting from No more 'unable to find valid certification path to requested target'




when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.



Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.



Basically, you want to add the server's certificate to the KeyStore with your trusted certificates




Try the code provided there. It might help.






share|improve this answer



















  • 5





    The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

    – AgilePro
    Oct 13 '13 at 4:16











  • @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

    – user207421
    Oct 26 '16 at 9:20













  • @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

    – AgilePro
    Oct 26 '16 at 16:20











  • @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

    – user207421
    Jun 27 '18 at 3:34



















17














@Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.



Install a certificate from host:



> sudo ./java-cert-importer.sh example.com


Remove the certificate that installed already.



> sudo ./java-cert-importer.sh example.com --delete


java-cert-importer.sh



#!/usr/bin/env bash

# Exit on error
set -e

# Ensure script is running as root
if [ "$EUID" -ne 0 ]
then echo "WARN: Please run as root (sudo)"
exit 1
fi

# Check required commands
command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }

# Get command line args
host=$1; port=${2:-443}; deleteCmd=${3:-${2}}

# Check host argument
if [ ! ${host} ]; then
cat << EOF
Please enter required parameter(s)

usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]

EOF
exit 1
fi;

if [ "$JAVA_HOME" ]; then
javahome=${JAVA_HOME}
elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
javahome=$(readlink -f $(which java) | sed "s:bin/java::")
elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
javahome="$(/usr/libexec/java_home)/jre"
fi

if [ ! "$javahome" ]; then
echo "WARN: Java home cannot be found."
exit 1
elif [ ! -d "$javahome" ]; then
echo "WARN: Detected Java home does not exists: $javahome"
exit 1
fi

echo "Detected Java Home: $javahome"

# Set cacerts file path
cacertspath=${javahome}/lib/security/cacerts
cacertsbackup="${cacertspath}.$$.backup"

if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
echo "Certificate is deleted for ${host}"
exit 0
fi

# Get host info from user
#read -p "Enter server host (E.g. example.com) : " host
#read -p "Enter server port (Default 443) : " port

# create temp file
tmpfile="/tmp/${host}.$$.crt"

# Create java cacerts backup file
cp ${cacertspath} ${cacertsbackup}

echo "Java CaCerts Backup: ${cacertsbackup}"

# Get certificate from speficied host
openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}

# Import certificate into java cacerts file
sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit

# Remove temp certificate file
rm ${tmpfile}

# Check certificate alias name (same with host) that imported successfully
result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")

# Show results to user
if [ "$result" ]; then
echo "Success: Certificate is imported to java cacerts for ${host}";
else
echo "Error: Something went wrong";
fi;





share|improve this answer
























  • Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

    – lepe
    Apr 24 '17 at 7:30






  • 1





    Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

    – xyz
    Oct 10 '17 at 14:24











  • Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

    – Wolfgang Fahl
    Jan 31 at 15:53



















5














I was able to get it working with code only, i.e. no need to use keytool:



import com.netflix.config.DynamicBooleanProperty;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.apache.http.nio.conn.NoopIOSessionStrategy;
import org.apache.http.nio.conn.SchemeIOSessionStrategy;
import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class Test
{
private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

public static void main(String args) throws Exception
{

SSLContext sslcontext = SSLContexts.custom()
.useTLS()
.loadTrustMaterial(null, new TrustStrategy()
{
@Override
public boolean isTrusted(X509Certificate chain, String authType) throws CertificateException
{
return true;
}
})
.build();
SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
.register("http", NoopIOSessionStrategy.INSTANCE)
.register("https", sslSessionStrategy)
.build();

DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(SOCKET_TIMEOUT.get())
.setConnectTimeout(CONNECT_TIMEOUT.get())
.setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
.setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
.build();

CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
.setSSLStrategy(sslSessionStrategy)
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.build();

httpClient.start();

// use httpClient...
}

private static class AllowAll implements X509HostnameVerifier
{
@Override
public void verify(String s, SSLSocket sslSocket) throws IOException
{}

@Override
public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

@Override
public void verify(String s, String strings, String strings2) throws SSLException
{}

@Override
public boolean verify(String s, SSLSession sslSession)
{
return true;
}
}
}





share|improve this answer





















  • 1





    Btw, I'm using httpasyncclient:4.0.1

    – Jonas Bergström
    Aug 4 '14 at 11:49











  • I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

    – EnterSB
    Oct 17 '14 at 12:13






  • 8





    Note that this solution is insecure.

    – user207421
    May 22 '15 at 23:15











  • Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

    – twcai
    Nov 12 '15 at 2:54



















4














For those who like Debian and prepackaged Java:



sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
sudo update-ca-certificates --fresh --verbose


Don't forget to check /etc/default/cacerts for:



# enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
cacerts_updates=yes


To remove cert:



sudo rm /usr/share/ca-certificates/test/test.loc.crt
sudo rm /etc/ssl/certs/java/cacerts
sudo update-ca-certificates --fresh --verbose





share|improve this answer































    4














    The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:



    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
    ... 22 more


    In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.






    share|improve this answer


























    • ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

      – kisna
      Dec 26 '16 at 4:52



















    4














    For Windows only, follow these steps:




    1. In Chrome go to settings.

    2. In Settings click show advance settings.

    3. Under HTTPS/SSL Click on Manage Certificates.

    4. Export Your Certificate.

    5. In Windows searchs (Pressing windows key on keyboard) type java.

    6. Select (Configure Java) Option Which will open Java Control Panel

    7. Select Security tab in Java Control Panel

    8. Select Manage Certificates

    9. Click Import

    10. Under (User) tab selected and certificate type as (Trusted Certificates)

    11. Click import button and browse to downloaded certificate and import it.






    share|improve this answer

































      2














      This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.



      Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.



      More info on the issue can be found here, as well as how to resolve it on your server if you need to now.






      share|improve this answer































        2














        UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:



        Import the self-signed certificate:



        keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks


        Add the official root certificates:



        keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks


        Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.



        ORIGINAL POSTING:



        Nobody will believe this, I know. Still, if all else fails, give it a try:
        After a reboot of my Mac the problem was gone. Grrr.



        Background:
        ./gradlew jar kept giving me "unable to find valid certification path to requested target"



        I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:



        org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit


        As mentioned, this only worked after a reboot.






        share|improve this answer

































          2














          AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.



          Solution: enter in AVG section called "Web and email" and disable the "email protection".
          AVG block the certificate if the site isn't secure.






          share|improve this answer

































            1














            I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job



               <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.6</version>
            </dependency>





            share|improve this answer































              1














              You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:



              jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory





              share|improve this answer































                0














                This solved my issue,



                We need to import the cert onto the local java. If not we could get the below exception.




                javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
                at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)


                SSLPOKE is a tool where you can test the https connectivity from your local machine.



                Command to test the connectivity:



                "%JAVA_HOME%/bin/java" SSLPoke <hostname> 443



                sun.security.validator.ValidatorException: PKIX path building failed:
                sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
                at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
                at sun.security.validator.Validator.validate(Validator.java:260)
                at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
                at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
                at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
                at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
                at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
                at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
                at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
                at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
                at SSLPoke.main(SSLPoke.java:31)
                Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
                requested target
                at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
                ... 15 more


                keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>


                this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.



                Verfication:



                C:tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
                Successfully connected





                share|improve this answer































                  0














                  In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).



                  Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.



                  bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
                  bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit





                  share|improve this answer































                    0














                    first Download the ssl certificate then you can go to your java bin path execute the below command in the console.



                    C:javaJDK1.8.0_66-X64bin>keytool -printcert -file C:Userslovaopenapi.cer -keystore openapistore





                    share|improve this answer































                      0














                      Make sure that the https://176.66.3.69:6443/ have a valid certificate.
                      you can check it via browser firstly https not secure if it works in browser it will work in java.



                      that is working for me






                      share|improve this answer































                        -3














                        When I have this problem, I just extract the android studio zip to the same old folder, that solved my problem






                        share|improve this answer























                          Your Answer






                          StackExchange.ifUsing("editor", function () {
                          StackExchange.using("externalEditor", function () {
                          StackExchange.using("snippets", function () {
                          StackExchange.snippets.init();
                          });
                          });
                          }, "code-snippets");

                          StackExchange.ready(function() {
                          var channelOptions = {
                          tags: "".split(" "),
                          id: "1"
                          };
                          initTagRenderer("".split(" "), "".split(" "), channelOptions);

                          StackExchange.using("externalEditor", function() {
                          // Have to fire editor after snippets, if snippets enabled
                          if (StackExchange.settings.snippets.snippetsEnabled) {
                          StackExchange.using("snippets", function() {
                          createEditor();
                          });
                          }
                          else {
                          createEditor();
                          }
                          });

                          function createEditor() {
                          StackExchange.prepareEditor({
                          heartbeatType: 'answer',
                          autoActivateHeartbeat: false,
                          convertImagesToLinks: true,
                          noModals: true,
                          showLowRepImageUploadWarning: true,
                          reputationToPostImages: 10,
                          bindNavPrevention: true,
                          postfix: "",
                          imageUploader: {
                          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                          allowUrls: true
                          },
                          onDemand: true,
                          discardSelector: ".discard-answer"
                          ,immediatelyShowMarkdownHelp:true
                          });


                          }
                          });














                          draft saved

                          draft discarded


















                          StackExchange.ready(
                          function () {
                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6908948%2fjava-sun-security-provider-certpath-suncertpathbuilderexception-unable-to-find%23new-answer', 'question_page');
                          }
                          );

                          Post as a guest















                          Required, but never shown

























                          20 Answers
                          20






                          active

                          oldest

                          votes








                          20 Answers
                          20






                          active

                          oldest

                          votes









                          active

                          oldest

                          votes






                          active

                          oldest

                          votes









                          172














                          The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.



                          In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.



                          See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.






                          share|improve this answer





















                          • 2





                            this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                            – Cheruvim
                            May 20 '15 at 18:13











                          • The problem also appears with a certificate signed by someone else that isn't trusted.

                            – user207421
                            Oct 26 '16 at 9:16













                          • Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                            – Dima Fomin
                            Dec 21 '18 at 17:02











                          • In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                            – java-addict301
                            Jan 23 at 17:47
















                          172














                          The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.



                          In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.



                          See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.






                          share|improve this answer





















                          • 2





                            this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                            – Cheruvim
                            May 20 '15 at 18:13











                          • The problem also appears with a certificate signed by someone else that isn't trusted.

                            – user207421
                            Oct 26 '16 at 9:16













                          • Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                            – Dima Fomin
                            Dec 21 '18 at 17:02











                          • In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                            – java-addict301
                            Jan 23 at 17:47














                          172












                          172








                          172







                          The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.



                          In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.



                          See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.






                          share|improve this answer















                          The problem appears when your server has self signed certificate. To workaround it you can add this certificate to the list of trusted certificates of your JVM.



                          In this article author describes how to fetch the certificate from your browser and add it to cacerts file of your JVM. You can either edit JAVA_HOME/jre/lib/security/cacerts file or run you application with -Djavax.net.ssl.trustStore parameter. Verify which JDK/JRE you are using too as this is often a source of confusion.



                          See also: How are SSL certificate server names resolved/Can I add alternative names using keytool? If you run into java.security.cert.CertificateException: No name matching localhost found exception.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited May 23 '17 at 12:26









                          Community

                          11




                          11










                          answered Aug 27 '12 at 17:42









                          Maxim MazinMaxim Mazin

                          2,49611615




                          2,49611615








                          • 2





                            this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                            – Cheruvim
                            May 20 '15 at 18:13











                          • The problem also appears with a certificate signed by someone else that isn't trusted.

                            – user207421
                            Oct 26 '16 at 9:16













                          • Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                            – Dima Fomin
                            Dec 21 '18 at 17:02











                          • In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                            – java-addict301
                            Jan 23 at 17:47














                          • 2





                            this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                            – Cheruvim
                            May 20 '15 at 18:13











                          • The problem also appears with a certificate signed by someone else that isn't trusted.

                            – user207421
                            Oct 26 '16 at 9:16













                          • Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                            – Dima Fomin
                            Dec 21 '18 at 17:02











                          • In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                            – java-addict301
                            Jan 23 at 17:47








                          2




                          2





                          this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                          – Cheruvim
                          May 20 '15 at 18:13





                          this hasn't worked for me. I have the root and the chain cert installed, but Tomcat-7 still reports validatorException caused by "unable to find valid certification path to requested target" any way to debug this?

                          – Cheruvim
                          May 20 '15 at 18:13













                          The problem also appears with a certificate signed by someone else that isn't trusted.

                          – user207421
                          Oct 26 '16 at 9:16







                          The problem also appears with a certificate signed by someone else that isn't trusted.

                          – user207421
                          Oct 26 '16 at 9:16















                          Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                          – Dima Fomin
                          Dec 21 '18 at 17:02





                          Great! It works! Just don't forget that you could have both jre and jdk, and both their cacerts must be updated

                          – Dima Fomin
                          Dec 21 '18 at 17:02













                          In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                          – java-addict301
                          Jan 23 at 17:47





                          In my case, the root CA was there but not the next CA down. Adding the next CA down did the trick - thanks.

                          – java-addict301
                          Jan 23 at 17:47













                          122














                          Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.



                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
                          sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit





                          share|improve this answer





















                          • 3





                            Works for me why? You need to provide an explanation.

                            – user207421
                            Oct 26 '16 at 9:16











                          • openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                            – Vishnu Ranganathan
                            Nov 26 '16 at 4:54








                          • 2





                            .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                            – Gabe Martin-Dempesy
                            Mar 14 '17 at 19:15











                          • Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                            – Zotov
                            Jun 13 '17 at 20:13






                          • 1





                            This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                            – Patrik Beck
                            Jul 13 '17 at 12:16
















                          122














                          Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.



                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
                          sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit





                          share|improve this answer





















                          • 3





                            Works for me why? You need to provide an explanation.

                            – user207421
                            Oct 26 '16 at 9:16











                          • openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                            – Vishnu Ranganathan
                            Nov 26 '16 at 4:54








                          • 2





                            .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                            – Gabe Martin-Dempesy
                            Mar 14 '17 at 19:15











                          • Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                            – Zotov
                            Jun 13 '17 at 20:13






                          • 1





                            This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                            – Patrik Beck
                            Jul 13 '17 at 12:16














                          122












                          122








                          122







                          Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.



                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
                          sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit





                          share|improve this answer















                          Here's what reliably works for me on macOS. Make sure to replace example.com and 443 with the actual hostname and port you're trying to connect to, and give a custom alias. The first command downloads the provided certificate from the remote server and saves it locally in x509 format. The second command loads the saved certificate into Java's SSL trust store.



                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt
                          sudo keytool -importcert -file ~/example.crt -alias example -keystore $(/usr/libexec/java_home)/jre/lib/security/cacerts -storepass changeit






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 14 '17 at 19:14

























                          answered Oct 24 '13 at 21:48









                          Gabe Martin-DempesyGabe Martin-Dempesy

                          5,94242824




                          5,94242824








                          • 3





                            Works for me why? You need to provide an explanation.

                            – user207421
                            Oct 26 '16 at 9:16











                          • openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                            – Vishnu Ranganathan
                            Nov 26 '16 at 4:54








                          • 2





                            .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                            – Gabe Martin-Dempesy
                            Mar 14 '17 at 19:15











                          • Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                            – Zotov
                            Jun 13 '17 at 20:13






                          • 1





                            This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                            – Patrik Beck
                            Jul 13 '17 at 12:16














                          • 3





                            Works for me why? You need to provide an explanation.

                            – user207421
                            Oct 26 '16 at 9:16











                          • openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                            – Vishnu Ranganathan
                            Nov 26 '16 at 4:54








                          • 2





                            .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                            – Gabe Martin-Dempesy
                            Mar 14 '17 at 19:15











                          • Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                            – Zotov
                            Jun 13 '17 at 20:13






                          • 1





                            This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                            – Patrik Beck
                            Jul 13 '17 at 12:16








                          3




                          3





                          Works for me why? You need to provide an explanation.

                          – user207421
                          Oct 26 '16 at 9:16





                          Works for me why? You need to provide an explanation.

                          – user207421
                          Oct 26 '16 at 9:16













                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                          – Vishnu Ranganathan
                          Nov 26 '16 at 4:54







                          openssl x509 -in <(openssl s_client -connect example.com:443 -prexit 2>/dev/null) -out ~/example.crt - what is example.crt in the command i have a .pem certificate i need to give that here ??

                          – Vishnu Ranganathan
                          Nov 26 '16 at 4:54






                          2




                          2





                          .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                          – Gabe Martin-Dempesy
                          Mar 14 '17 at 19:15





                          .crt and .pem are commonly used file extensions for the same file format. If you already have the file, just run the second command and pass it into the -file argument.

                          – Gabe Martin-Dempesy
                          Mar 14 '17 at 19:15













                          Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                          – Zotov
                          Jun 13 '17 at 20:13





                          Great stuff. Only thing is: I had to use latest openssl 1.0.Xx for some reason, old 9.X.Xx wasn't working.

                          – Zotov
                          Jun 13 '17 at 20:13




                          1




                          1





                          This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                          – Patrik Beck
                          Jul 13 '17 at 12:16





                          This doesn't work with SNI endpoint. For that case you need to add: -servername example.com when fetching the cert

                          – Patrik Beck
                          Jul 13 '17 at 12:16











                          37














                          I had the same issue with a valid signed wildcard certificate from symantec.



                          First try running your java application with -Djavax.net.debug=SSL to see what is really going on.



                          I ended up importing the intermediate certificate which was causing the cert chain to break.



                          I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).



                          And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:



                          keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer





                          share|improve this answer
























                          • This was the case:

                            – kisna
                            Jan 4 '17 at 3:17











                          • To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                            – kisna
                            Jan 4 '17 at 3:26













                          • And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                            – kisna
                            Jan 4 '17 at 3:51











                          • I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                            – Pigritia
                            May 18 '17 at 22:07
















                          37














                          I had the same issue with a valid signed wildcard certificate from symantec.



                          First try running your java application with -Djavax.net.debug=SSL to see what is really going on.



                          I ended up importing the intermediate certificate which was causing the cert chain to break.



                          I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).



                          And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:



                          keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer





                          share|improve this answer
























                          • This was the case:

                            – kisna
                            Jan 4 '17 at 3:17











                          • To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                            – kisna
                            Jan 4 '17 at 3:26













                          • And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                            – kisna
                            Jan 4 '17 at 3:51











                          • I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                            – Pigritia
                            May 18 '17 at 22:07














                          37












                          37








                          37







                          I had the same issue with a valid signed wildcard certificate from symantec.



                          First try running your java application with -Djavax.net.debug=SSL to see what is really going on.



                          I ended up importing the intermediate certificate which was causing the cert chain to break.



                          I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).



                          And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:



                          keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer





                          share|improve this answer













                          I had the same issue with a valid signed wildcard certificate from symantec.



                          First try running your java application with -Djavax.net.debug=SSL to see what is really going on.



                          I ended up importing the intermediate certificate which was causing the cert chain to break.



                          I downloaded the missing intermediate cert from symantec (you can see the download link to the missing cert in the ssl handshake log: http://svrintl-g3-aia.verisign.com/SVRIntlG3.cer in my case).



                          And I imported the cert in the java keystore. After importing the intermediate certificate my wildcard ssl cert finally started working:



                          keytool -import -keystore ../jre/lib/security/cacerts -trustcacerts -alias "VeriSign Class 3 International Server CA - G3" -file /pathto/SVRIntlG3.cer






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Mar 14 '14 at 13:51









                          Stephan OudmaijerStephan Oudmaijer

                          60354




                          60354













                          • This was the case:

                            – kisna
                            Jan 4 '17 at 3:17











                          • To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                            – kisna
                            Jan 4 '17 at 3:26













                          • And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                            – kisna
                            Jan 4 '17 at 3:51











                          • I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                            – Pigritia
                            May 18 '17 at 22:07



















                          • This was the case:

                            – kisna
                            Jan 4 '17 at 3:17











                          • To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                            – kisna
                            Jan 4 '17 at 3:26













                          • And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                            – kisna
                            Jan 4 '17 at 3:51











                          • I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                            – Pigritia
                            May 18 '17 at 22:07

















                          This was the case:

                          – kisna
                          Jan 4 '17 at 3:17





                          This was the case:

                          – kisna
                          Jan 4 '17 at 3:17













                          To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                          – kisna
                          Jan 4 '17 at 3:26







                          To avoid confusion, run java (or jcurl) with debug parameters to see remote "Certificate chain" in logs, then grep the "CN" in truststore explicitly passed (instead of default) as follows, if not present, you need to add. ssllabs.com/ssltest/analyze.html will show if server side certs has incomplete chain, and includes intermediate certification path certificates that need to be added. -Djavax.net.debug=ssl,handshake -Djavax.net.ssl.keyStoreType=PKCS12 -Djavax.net.ssl.keyStore=our-client-certs -Djavax.net.ssl.trustStoreType=jks -Djavax.net.ssl.trustStore=their-server-certs

                          – kisna
                          Jan 4 '17 at 3:26















                          And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                          – kisna
                          Jan 4 '17 at 3:51





                          And, of course, the official article to debug SSL issues: docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/… blogs.oracle.com/java-platform-group/entry/…

                          – kisna
                          Jan 4 '17 at 3:51













                          I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                          – Pigritia
                          May 18 '17 at 22:07





                          I had the same issue, this is very useful, but in my case you only had to add the server certificate to cacerts file of the JDK version

                          – Pigritia
                          May 18 '17 at 22:07











                          29















                          1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt

                          2. Go to your JRE_HOME/bin or JDK/JRE/bin

                          3. Type the command

                          4. keytool -keystore ..libsecuritycacerts -import -alias your.ssl.server.name -file .relative-path-to-cert-fileyour.ssl.server.name.crt

                          5. Restart your Java process






                          share|improve this answer


























                          • I see following error, please help

                            – user5268786
                            Oct 26 '15 at 20:30






                          • 9





                            If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                            – Fr4nz
                            Jul 28 '16 at 14:26













                          • You are the BEST!!!

                            – Mehraj Malik
                            May 28 '18 at 12:19


















                          29















                          1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt

                          2. Go to your JRE_HOME/bin or JDK/JRE/bin

                          3. Type the command

                          4. keytool -keystore ..libsecuritycacerts -import -alias your.ssl.server.name -file .relative-path-to-cert-fileyour.ssl.server.name.crt

                          5. Restart your Java process






                          share|improve this answer


























                          • I see following error, please help

                            – user5268786
                            Oct 26 '15 at 20:30






                          • 9





                            If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                            – Fr4nz
                            Jul 28 '16 at 14:26













                          • You are the BEST!!!

                            – Mehraj Malik
                            May 28 '18 at 12:19
















                          29












                          29








                          29








                          1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt

                          2. Go to your JRE_HOME/bin or JDK/JRE/bin

                          3. Type the command

                          4. keytool -keystore ..libsecuritycacerts -import -alias your.ssl.server.name -file .relative-path-to-cert-fileyour.ssl.server.name.crt

                          5. Restart your Java process






                          share|improve this answer
















                          1. Export the SSL certificate using Firefox. You can export it by hitting the URL in the browser and then select the option to export the certificate. Let's assume the cert file name is your.ssl.server.name.crt

                          2. Go to your JRE_HOME/bin or JDK/JRE/bin

                          3. Type the command

                          4. keytool -keystore ..libsecuritycacerts -import -alias your.ssl.server.name -file .relative-path-to-cert-fileyour.ssl.server.name.crt

                          5. Restart your Java process







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Sep 29 '15 at 15:45









                          Nayuki

                          14.2k53765




                          14.2k53765










                          answered Dec 22 '14 at 20:22









                          RobinRobin

                          2,17952830




                          2,17952830













                          • I see following error, please help

                            – user5268786
                            Oct 26 '15 at 20:30






                          • 9





                            If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                            – Fr4nz
                            Jul 28 '16 at 14:26













                          • You are the BEST!!!

                            – Mehraj Malik
                            May 28 '18 at 12:19





















                          • I see following error, please help

                            – user5268786
                            Oct 26 '15 at 20:30






                          • 9





                            If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                            – Fr4nz
                            Jul 28 '16 at 14:26













                          • You are the BEST!!!

                            – Mehraj Malik
                            May 28 '18 at 12:19



















                          I see following error, please help

                          – user5268786
                          Oct 26 '15 at 20:30





                          I see following error, please help

                          – user5268786
                          Oct 26 '15 at 20:30




                          9




                          9





                          If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                          – Fr4nz
                          Jul 28 '16 at 14:26







                          If asked for a password, use the default cacerts keystore password changeit (stackoverflow.com/a/22782035/1304830). Also be sure to run cmd as administrator.

                          – Fr4nz
                          Jul 28 '16 at 14:26















                          You are the BEST!!!

                          – Mehraj Malik
                          May 28 '18 at 12:19







                          You are the BEST!!!

                          – Mehraj Malik
                          May 28 '18 at 12:19













                          17














                          Quoting from No more 'unable to find valid certification path to requested target'




                          when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.



                          Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.



                          Basically, you want to add the server's certificate to the KeyStore with your trusted certificates




                          Try the code provided there. It might help.






                          share|improve this answer



















                          • 5





                            The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                            – AgilePro
                            Oct 13 '13 at 4:16











                          • @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                            – user207421
                            Oct 26 '16 at 9:20













                          • @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                            – AgilePro
                            Oct 26 '16 at 16:20











                          • @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                            – user207421
                            Jun 27 '18 at 3:34
















                          17














                          Quoting from No more 'unable to find valid certification path to requested target'




                          when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.



                          Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.



                          Basically, you want to add the server's certificate to the KeyStore with your trusted certificates




                          Try the code provided there. It might help.






                          share|improve this answer



















                          • 5





                            The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                            – AgilePro
                            Oct 13 '13 at 4:16











                          • @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                            – user207421
                            Oct 26 '16 at 9:20













                          • @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                            – AgilePro
                            Oct 26 '16 at 16:20











                          • @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                            – user207421
                            Jun 27 '18 at 3:34














                          17












                          17








                          17







                          Quoting from No more 'unable to find valid certification path to requested target'




                          when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.



                          Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.



                          Basically, you want to add the server's certificate to the KeyStore with your trusted certificates




                          Try the code provided there. It might help.






                          share|improve this answer













                          Quoting from No more 'unable to find valid certification path to requested target'




                          when trying to open an SSL connection to a host using JSSE. What this usually means is that the server is using a test certificate (possibly generated using keytool) rather than a certificate from a well known commercial Certification Authority such as Verisign or GoDaddy. Web browsers display warning dialogs in this case, but since JSSE cannot assume an interactive user is present it just throws an exception by default.



                          Certificate validation is a very important part of SSL security, but I am not writing this entry to explain the details. If you are interested, you can start by reading the Wikipedia blurb. I am writing this entry to show a simple way to talk to that host with the test certificate, if you really want to.



                          Basically, you want to add the server's certificate to the KeyStore with your trusted certificates




                          Try the code provided there. It might help.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Aug 2 '11 at 8:09









                          NishantNishant

                          41.2k989105




                          41.2k989105








                          • 5





                            The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                            – AgilePro
                            Oct 13 '13 at 4:16











                          • @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                            – user207421
                            Oct 26 '16 at 9:20













                          • @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                            – AgilePro
                            Oct 26 '16 at 16:20











                          • @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                            – user207421
                            Jun 27 '18 at 3:34














                          • 5





                            The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                            – AgilePro
                            Oct 13 '13 at 4:16











                          • @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                            – user207421
                            Oct 26 '16 at 9:20













                          • @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                            – AgilePro
                            Oct 26 '16 at 16:20











                          • @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                            – user207421
                            Jun 27 '18 at 3:34








                          5




                          5





                          The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                          – AgilePro
                          Oct 13 '13 at 4:16





                          The part about "Certificate validation is a very important part of SSL security" is not necessarily true. SSL gives you two assurances: (1) that your communication is private, and (2) that you are talking to a server which is known to the NSA.(:-) Sometimes you only care about privacy of the conversation, and then a self-signed certification is fine. See social-biz.org/2011/10/16/the-anti-ssl-conspiracy

                          – AgilePro
                          Oct 13 '13 at 4:16













                          @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                          – user207421
                          Oct 26 '16 at 9:20







                          @AgilePro SSL gives you four assurances: authentication, privacy, integrity, and the possibilty of authorization. It does not give you any assurance that you are talking to a server known to the NSA. Caring only about privacy without authentication is a contradiction in terms.

                          – user207421
                          Oct 26 '16 at 9:20















                          @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                          – AgilePro
                          Oct 26 '16 at 16:20





                          @EJP Agree that if you use a client certificate you can get authentication and I suppose the possibility of authorization ... but most uses are not with a client certificate. What would you call the difference between a "self-signed" certificate, and a certificate from a signing authority? Does signing authority give "integrity". My Joke about NSA is that all signing authorities can not positively guarantee independence from everything. Not that paranoid really, but the point is your certificate is ONLY as secret as the signing authority can make it. Self-signed can be more secret.

                          – AgilePro
                          Oct 26 '16 at 16:20













                          @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                          – user207421
                          Jun 27 '18 at 3:34





                          @AgilePro Using a server certificate authenticates the server, and is required to make SSL secure, as noted in RFC 2246. Certificates are not secret at all: therefore remainder of your comment makes no sense.

                          – user207421
                          Jun 27 '18 at 3:34











                          17














                          @Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.



                          Install a certificate from host:



                          > sudo ./java-cert-importer.sh example.com


                          Remove the certificate that installed already.



                          > sudo ./java-cert-importer.sh example.com --delete


                          java-cert-importer.sh



                          #!/usr/bin/env bash

                          # Exit on error
                          set -e

                          # Ensure script is running as root
                          if [ "$EUID" -ne 0 ]
                          then echo "WARN: Please run as root (sudo)"
                          exit 1
                          fi

                          # Check required commands
                          command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
                          command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }

                          # Get command line args
                          host=$1; port=${2:-443}; deleteCmd=${3:-${2}}

                          # Check host argument
                          if [ ! ${host} ]; then
                          cat << EOF
                          Please enter required parameter(s)

                          usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]

                          EOF
                          exit 1
                          fi;

                          if [ "$JAVA_HOME" ]; then
                          javahome=${JAVA_HOME}
                          elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
                          javahome=$(readlink -f $(which java) | sed "s:bin/java::")
                          elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
                          javahome="$(/usr/libexec/java_home)/jre"
                          fi

                          if [ ! "$javahome" ]; then
                          echo "WARN: Java home cannot be found."
                          exit 1
                          elif [ ! -d "$javahome" ]; then
                          echo "WARN: Detected Java home does not exists: $javahome"
                          exit 1
                          fi

                          echo "Detected Java Home: $javahome"

                          # Set cacerts file path
                          cacertspath=${javahome}/lib/security/cacerts
                          cacertsbackup="${cacertspath}.$$.backup"

                          if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
                          sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
                          echo "Certificate is deleted for ${host}"
                          exit 0
                          fi

                          # Get host info from user
                          #read -p "Enter server host (E.g. example.com) : " host
                          #read -p "Enter server port (Default 443) : " port

                          # create temp file
                          tmpfile="/tmp/${host}.$$.crt"

                          # Create java cacerts backup file
                          cp ${cacertspath} ${cacertsbackup}

                          echo "Java CaCerts Backup: ${cacertsbackup}"

                          # Get certificate from speficied host
                          openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}

                          # Import certificate into java cacerts file
                          sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit

                          # Remove temp certificate file
                          rm ${tmpfile}

                          # Check certificate alias name (same with host) that imported successfully
                          result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")

                          # Show results to user
                          if [ "$result" ]; then
                          echo "Success: Certificate is imported to java cacerts for ${host}";
                          else
                          echo "Error: Something went wrong";
                          fi;





                          share|improve this answer
























                          • Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                            – lepe
                            Apr 24 '17 at 7:30






                          • 1





                            Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                            – xyz
                            Oct 10 '17 at 14:24











                          • Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                            – Wolfgang Fahl
                            Jan 31 at 15:53
















                          17














                          @Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.



                          Install a certificate from host:



                          > sudo ./java-cert-importer.sh example.com


                          Remove the certificate that installed already.



                          > sudo ./java-cert-importer.sh example.com --delete


                          java-cert-importer.sh



                          #!/usr/bin/env bash

                          # Exit on error
                          set -e

                          # Ensure script is running as root
                          if [ "$EUID" -ne 0 ]
                          then echo "WARN: Please run as root (sudo)"
                          exit 1
                          fi

                          # Check required commands
                          command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
                          command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }

                          # Get command line args
                          host=$1; port=${2:-443}; deleteCmd=${3:-${2}}

                          # Check host argument
                          if [ ! ${host} ]; then
                          cat << EOF
                          Please enter required parameter(s)

                          usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]

                          EOF
                          exit 1
                          fi;

                          if [ "$JAVA_HOME" ]; then
                          javahome=${JAVA_HOME}
                          elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
                          javahome=$(readlink -f $(which java) | sed "s:bin/java::")
                          elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
                          javahome="$(/usr/libexec/java_home)/jre"
                          fi

                          if [ ! "$javahome" ]; then
                          echo "WARN: Java home cannot be found."
                          exit 1
                          elif [ ! -d "$javahome" ]; then
                          echo "WARN: Detected Java home does not exists: $javahome"
                          exit 1
                          fi

                          echo "Detected Java Home: $javahome"

                          # Set cacerts file path
                          cacertspath=${javahome}/lib/security/cacerts
                          cacertsbackup="${cacertspath}.$$.backup"

                          if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
                          sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
                          echo "Certificate is deleted for ${host}"
                          exit 0
                          fi

                          # Get host info from user
                          #read -p "Enter server host (E.g. example.com) : " host
                          #read -p "Enter server port (Default 443) : " port

                          # create temp file
                          tmpfile="/tmp/${host}.$$.crt"

                          # Create java cacerts backup file
                          cp ${cacertspath} ${cacertsbackup}

                          echo "Java CaCerts Backup: ${cacertsbackup}"

                          # Get certificate from speficied host
                          openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}

                          # Import certificate into java cacerts file
                          sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit

                          # Remove temp certificate file
                          rm ${tmpfile}

                          # Check certificate alias name (same with host) that imported successfully
                          result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")

                          # Show results to user
                          if [ "$result" ]; then
                          echo "Success: Certificate is imported to java cacerts for ${host}";
                          else
                          echo "Error: Something went wrong";
                          fi;





                          share|improve this answer
























                          • Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                            – lepe
                            Apr 24 '17 at 7:30






                          • 1





                            Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                            – xyz
                            Oct 10 '17 at 14:24











                          • Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                            – Wolfgang Fahl
                            Jan 31 at 15:53














                          17












                          17








                          17







                          @Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.



                          Install a certificate from host:



                          > sudo ./java-cert-importer.sh example.com


                          Remove the certificate that installed already.



                          > sudo ./java-cert-importer.sh example.com --delete


                          java-cert-importer.sh



                          #!/usr/bin/env bash

                          # Exit on error
                          set -e

                          # Ensure script is running as root
                          if [ "$EUID" -ne 0 ]
                          then echo "WARN: Please run as root (sudo)"
                          exit 1
                          fi

                          # Check required commands
                          command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
                          command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }

                          # Get command line args
                          host=$1; port=${2:-443}; deleteCmd=${3:-${2}}

                          # Check host argument
                          if [ ! ${host} ]; then
                          cat << EOF
                          Please enter required parameter(s)

                          usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]

                          EOF
                          exit 1
                          fi;

                          if [ "$JAVA_HOME" ]; then
                          javahome=${JAVA_HOME}
                          elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
                          javahome=$(readlink -f $(which java) | sed "s:bin/java::")
                          elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
                          javahome="$(/usr/libexec/java_home)/jre"
                          fi

                          if [ ! "$javahome" ]; then
                          echo "WARN: Java home cannot be found."
                          exit 1
                          elif [ ! -d "$javahome" ]; then
                          echo "WARN: Detected Java home does not exists: $javahome"
                          exit 1
                          fi

                          echo "Detected Java Home: $javahome"

                          # Set cacerts file path
                          cacertspath=${javahome}/lib/security/cacerts
                          cacertsbackup="${cacertspath}.$$.backup"

                          if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
                          sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
                          echo "Certificate is deleted for ${host}"
                          exit 0
                          fi

                          # Get host info from user
                          #read -p "Enter server host (E.g. example.com) : " host
                          #read -p "Enter server port (Default 443) : " port

                          # create temp file
                          tmpfile="/tmp/${host}.$$.crt"

                          # Create java cacerts backup file
                          cp ${cacertspath} ${cacertsbackup}

                          echo "Java CaCerts Backup: ${cacertsbackup}"

                          # Get certificate from speficied host
                          openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}

                          # Import certificate into java cacerts file
                          sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit

                          # Remove temp certificate file
                          rm ${tmpfile}

                          # Check certificate alias name (same with host) that imported successfully
                          result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")

                          # Show results to user
                          if [ "$result" ]; then
                          echo "Success: Certificate is imported to java cacerts for ${host}";
                          else
                          echo "Error: Something went wrong";
                          fi;





                          share|improve this answer













                          @Gabe Martin-Dempesy's answer is helped to me. And I wrote a small script related to it. The usage is very simple.



                          Install a certificate from host:



                          > sudo ./java-cert-importer.sh example.com


                          Remove the certificate that installed already.



                          > sudo ./java-cert-importer.sh example.com --delete


                          java-cert-importer.sh



                          #!/usr/bin/env bash

                          # Exit on error
                          set -e

                          # Ensure script is running as root
                          if [ "$EUID" -ne 0 ]
                          then echo "WARN: Please run as root (sudo)"
                          exit 1
                          fi

                          # Check required commands
                          command -v openssl >/dev/null 2>&1 || { echo "Required command 'openssl' not installed. Aborting." >&2; exit 1; }
                          command -v keytool >/dev/null 2>&1 || { echo "Required command 'keytool' not installed. Aborting." >&2; exit 1; }

                          # Get command line args
                          host=$1; port=${2:-443}; deleteCmd=${3:-${2}}

                          # Check host argument
                          if [ ! ${host} ]; then
                          cat << EOF
                          Please enter required parameter(s)

                          usage: ./java-cert-importer.sh <host> [ <port> | default=443 ] [ -d | --delete ]

                          EOF
                          exit 1
                          fi;

                          if [ "$JAVA_HOME" ]; then
                          javahome=${JAVA_HOME}
                          elif [[ "$OSTYPE" == "linux-gnu" ]]; then # Linux
                          javahome=$(readlink -f $(which java) | sed "s:bin/java::")
                          elif [[ "$OSTYPE" == "darwin"* ]]; then # Mac OS X
                          javahome="$(/usr/libexec/java_home)/jre"
                          fi

                          if [ ! "$javahome" ]; then
                          echo "WARN: Java home cannot be found."
                          exit 1
                          elif [ ! -d "$javahome" ]; then
                          echo "WARN: Detected Java home does not exists: $javahome"
                          exit 1
                          fi

                          echo "Detected Java Home: $javahome"

                          # Set cacerts file path
                          cacertspath=${javahome}/lib/security/cacerts
                          cacertsbackup="${cacertspath}.$$.backup"

                          if ( [ "$deleteCmd" == "-d" ] || [ "$deleteCmd" == "--delete" ] ); then
                          sudo keytool -delete -alias ${host} -keystore ${cacertspath} -storepass changeit
                          echo "Certificate is deleted for ${host}"
                          exit 0
                          fi

                          # Get host info from user
                          #read -p "Enter server host (E.g. example.com) : " host
                          #read -p "Enter server port (Default 443) : " port

                          # create temp file
                          tmpfile="/tmp/${host}.$$.crt"

                          # Create java cacerts backup file
                          cp ${cacertspath} ${cacertsbackup}

                          echo "Java CaCerts Backup: ${cacertsbackup}"

                          # Get certificate from speficied host
                          openssl x509 -in <(openssl s_client -connect ${host}:${port} -prexit 2>/dev/null) -out ${tmpfile}

                          # Import certificate into java cacerts file
                          sudo keytool -importcert -file ${tmpfile} -alias ${host} -keystore ${cacertspath} -storepass changeit

                          # Remove temp certificate file
                          rm ${tmpfile}

                          # Check certificate alias name (same with host) that imported successfully
                          result=$(keytool -list -v -keystore ${cacertspath} -storepass changeit | grep "Alias name: ${host}")

                          # Show results to user
                          if [ "$result" ]; then
                          echo "Success: Certificate is imported to java cacerts for ${host}";
                          else
                          echo "Error: Something went wrong";
                          fi;






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Jun 30 '15 at 8:25









                          bhdrkbhdrk

                          1,9471615




                          1,9471615













                          • Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                            – lepe
                            Apr 24 '17 at 7:30






                          • 1





                            Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                            – xyz
                            Oct 10 '17 at 14:24











                          • Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                            – Wolfgang Fahl
                            Jan 31 at 15:53



















                          • Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                            – lepe
                            Apr 24 '17 at 7:30






                          • 1





                            Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                            – xyz
                            Oct 10 '17 at 14:24











                          • Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                            – Wolfgang Fahl
                            Jan 31 at 15:53

















                          Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                          – lepe
                          Apr 24 '17 at 7:30





                          Works flawlessly. Great job! . This is how it works: start your SSL service (if its not running), and execute the command as explained (e.g. ./java-cert-importer.sh example.com 1234). That's it.

                          – lepe
                          Apr 24 '17 at 7:30




                          1




                          1





                          Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                          – xyz
                          Oct 10 '17 at 14:24





                          Works great. I was getting the error on a Jenkins server connecting to an external API which changes his certificate and fails my builts. This solves my issue

                          – xyz
                          Oct 10 '17 at 14:24













                          Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                          – Wolfgang Fahl
                          Jan 31 at 15:53





                          Oracle should have provided something like this in the first place or never every created their own horrible SSL solution. SSL certificate handling should be an operating system's job.

                          – Wolfgang Fahl
                          Jan 31 at 15:53











                          5














                          I was able to get it working with code only, i.e. no need to use keytool:



                          import com.netflix.config.DynamicBooleanProperty;
                          import com.netflix.config.DynamicIntProperty;
                          import com.netflix.config.DynamicPropertyFactory;
                          import org.apache.http.client.config.RequestConfig;
                          import org.apache.http.config.Registry;
                          import org.apache.http.config.RegistryBuilder;
                          import org.apache.http.conn.ssl.SSLContexts;
                          import org.apache.http.conn.ssl.TrustStrategy;
                          import org.apache.http.conn.ssl.X509HostnameVerifier;
                          import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
                          import org.apache.http.impl.nio.client.HttpAsyncClients;
                          import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
                          import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
                          import org.apache.http.impl.nio.reactor.IOReactorConfig;
                          import org.apache.http.nio.conn.NoopIOSessionStrategy;
                          import org.apache.http.nio.conn.SchemeIOSessionStrategy;
                          import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

                          import javax.net.ssl.SSLContext;
                          import javax.net.ssl.SSLException;
                          import javax.net.ssl.SSLSession;
                          import javax.net.ssl.SSLSocket;
                          import java.io.IOException;
                          import java.security.cert.CertificateException;
                          import java.security.cert.X509Certificate;

                          public class Test
                          {
                          private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
                          private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
                          private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
                          private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

                          public static void main(String args) throws Exception
                          {

                          SSLContext sslcontext = SSLContexts.custom()
                          .useTLS()
                          .loadTrustMaterial(null, new TrustStrategy()
                          {
                          @Override
                          public boolean isTrusted(X509Certificate chain, String authType) throws CertificateException
                          {
                          return true;
                          }
                          })
                          .build();
                          SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

                          Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                          .register("http", NoopIOSessionStrategy.INSTANCE)
                          .register("https", sslSessionStrategy)
                          .build();

                          DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
                          PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
                          connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
                          connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

                          RequestConfig requestConfig = RequestConfig.custom()
                          .setSocketTimeout(SOCKET_TIMEOUT.get())
                          .setConnectTimeout(CONNECT_TIMEOUT.get())
                          .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
                          .setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
                          .build();

                          CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                          .setSSLStrategy(sslSessionStrategy)
                          .setConnectionManager(connectionManager)
                          .setDefaultRequestConfig(requestConfig)
                          .build();

                          httpClient.start();

                          // use httpClient...
                          }

                          private static class AllowAll implements X509HostnameVerifier
                          {
                          @Override
                          public void verify(String s, SSLSocket sslSocket) throws IOException
                          {}

                          @Override
                          public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

                          @Override
                          public void verify(String s, String strings, String strings2) throws SSLException
                          {}

                          @Override
                          public boolean verify(String s, SSLSession sslSession)
                          {
                          return true;
                          }
                          }
                          }





                          share|improve this answer





















                          • 1





                            Btw, I'm using httpasyncclient:4.0.1

                            – Jonas Bergström
                            Aug 4 '14 at 11:49











                          • I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                            – EnterSB
                            Oct 17 '14 at 12:13






                          • 8





                            Note that this solution is insecure.

                            – user207421
                            May 22 '15 at 23:15











                          • Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                            – twcai
                            Nov 12 '15 at 2:54
















                          5














                          I was able to get it working with code only, i.e. no need to use keytool:



                          import com.netflix.config.DynamicBooleanProperty;
                          import com.netflix.config.DynamicIntProperty;
                          import com.netflix.config.DynamicPropertyFactory;
                          import org.apache.http.client.config.RequestConfig;
                          import org.apache.http.config.Registry;
                          import org.apache.http.config.RegistryBuilder;
                          import org.apache.http.conn.ssl.SSLContexts;
                          import org.apache.http.conn.ssl.TrustStrategy;
                          import org.apache.http.conn.ssl.X509HostnameVerifier;
                          import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
                          import org.apache.http.impl.nio.client.HttpAsyncClients;
                          import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
                          import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
                          import org.apache.http.impl.nio.reactor.IOReactorConfig;
                          import org.apache.http.nio.conn.NoopIOSessionStrategy;
                          import org.apache.http.nio.conn.SchemeIOSessionStrategy;
                          import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

                          import javax.net.ssl.SSLContext;
                          import javax.net.ssl.SSLException;
                          import javax.net.ssl.SSLSession;
                          import javax.net.ssl.SSLSocket;
                          import java.io.IOException;
                          import java.security.cert.CertificateException;
                          import java.security.cert.X509Certificate;

                          public class Test
                          {
                          private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
                          private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
                          private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
                          private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

                          public static void main(String args) throws Exception
                          {

                          SSLContext sslcontext = SSLContexts.custom()
                          .useTLS()
                          .loadTrustMaterial(null, new TrustStrategy()
                          {
                          @Override
                          public boolean isTrusted(X509Certificate chain, String authType) throws CertificateException
                          {
                          return true;
                          }
                          })
                          .build();
                          SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

                          Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                          .register("http", NoopIOSessionStrategy.INSTANCE)
                          .register("https", sslSessionStrategy)
                          .build();

                          DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
                          PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
                          connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
                          connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

                          RequestConfig requestConfig = RequestConfig.custom()
                          .setSocketTimeout(SOCKET_TIMEOUT.get())
                          .setConnectTimeout(CONNECT_TIMEOUT.get())
                          .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
                          .setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
                          .build();

                          CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                          .setSSLStrategy(sslSessionStrategy)
                          .setConnectionManager(connectionManager)
                          .setDefaultRequestConfig(requestConfig)
                          .build();

                          httpClient.start();

                          // use httpClient...
                          }

                          private static class AllowAll implements X509HostnameVerifier
                          {
                          @Override
                          public void verify(String s, SSLSocket sslSocket) throws IOException
                          {}

                          @Override
                          public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

                          @Override
                          public void verify(String s, String strings, String strings2) throws SSLException
                          {}

                          @Override
                          public boolean verify(String s, SSLSession sslSession)
                          {
                          return true;
                          }
                          }
                          }





                          share|improve this answer





















                          • 1





                            Btw, I'm using httpasyncclient:4.0.1

                            – Jonas Bergström
                            Aug 4 '14 at 11:49











                          • I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                            – EnterSB
                            Oct 17 '14 at 12:13






                          • 8





                            Note that this solution is insecure.

                            – user207421
                            May 22 '15 at 23:15











                          • Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                            – twcai
                            Nov 12 '15 at 2:54














                          5












                          5








                          5







                          I was able to get it working with code only, i.e. no need to use keytool:



                          import com.netflix.config.DynamicBooleanProperty;
                          import com.netflix.config.DynamicIntProperty;
                          import com.netflix.config.DynamicPropertyFactory;
                          import org.apache.http.client.config.RequestConfig;
                          import org.apache.http.config.Registry;
                          import org.apache.http.config.RegistryBuilder;
                          import org.apache.http.conn.ssl.SSLContexts;
                          import org.apache.http.conn.ssl.TrustStrategy;
                          import org.apache.http.conn.ssl.X509HostnameVerifier;
                          import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
                          import org.apache.http.impl.nio.client.HttpAsyncClients;
                          import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
                          import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
                          import org.apache.http.impl.nio.reactor.IOReactorConfig;
                          import org.apache.http.nio.conn.NoopIOSessionStrategy;
                          import org.apache.http.nio.conn.SchemeIOSessionStrategy;
                          import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

                          import javax.net.ssl.SSLContext;
                          import javax.net.ssl.SSLException;
                          import javax.net.ssl.SSLSession;
                          import javax.net.ssl.SSLSocket;
                          import java.io.IOException;
                          import java.security.cert.CertificateException;
                          import java.security.cert.X509Certificate;

                          public class Test
                          {
                          private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
                          private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
                          private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
                          private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

                          public static void main(String args) throws Exception
                          {

                          SSLContext sslcontext = SSLContexts.custom()
                          .useTLS()
                          .loadTrustMaterial(null, new TrustStrategy()
                          {
                          @Override
                          public boolean isTrusted(X509Certificate chain, String authType) throws CertificateException
                          {
                          return true;
                          }
                          })
                          .build();
                          SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

                          Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                          .register("http", NoopIOSessionStrategy.INSTANCE)
                          .register("https", sslSessionStrategy)
                          .build();

                          DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
                          PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
                          connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
                          connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

                          RequestConfig requestConfig = RequestConfig.custom()
                          .setSocketTimeout(SOCKET_TIMEOUT.get())
                          .setConnectTimeout(CONNECT_TIMEOUT.get())
                          .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
                          .setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
                          .build();

                          CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                          .setSSLStrategy(sslSessionStrategy)
                          .setConnectionManager(connectionManager)
                          .setDefaultRequestConfig(requestConfig)
                          .build();

                          httpClient.start();

                          // use httpClient...
                          }

                          private static class AllowAll implements X509HostnameVerifier
                          {
                          @Override
                          public void verify(String s, SSLSocket sslSocket) throws IOException
                          {}

                          @Override
                          public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

                          @Override
                          public void verify(String s, String strings, String strings2) throws SSLException
                          {}

                          @Override
                          public boolean verify(String s, SSLSession sslSession)
                          {
                          return true;
                          }
                          }
                          }





                          share|improve this answer















                          I was able to get it working with code only, i.e. no need to use keytool:



                          import com.netflix.config.DynamicBooleanProperty;
                          import com.netflix.config.DynamicIntProperty;
                          import com.netflix.config.DynamicPropertyFactory;
                          import org.apache.http.client.config.RequestConfig;
                          import org.apache.http.config.Registry;
                          import org.apache.http.config.RegistryBuilder;
                          import org.apache.http.conn.ssl.SSLContexts;
                          import org.apache.http.conn.ssl.TrustStrategy;
                          import org.apache.http.conn.ssl.X509HostnameVerifier;
                          import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
                          import org.apache.http.impl.nio.client.HttpAsyncClients;
                          import org.apache.http.impl.nio.conn.PoolingNHttpClientConnectionManager;
                          import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
                          import org.apache.http.impl.nio.reactor.IOReactorConfig;
                          import org.apache.http.nio.conn.NoopIOSessionStrategy;
                          import org.apache.http.nio.conn.SchemeIOSessionStrategy;
                          import org.apache.http.nio.conn.ssl.SSLIOSessionStrategy;

                          import javax.net.ssl.SSLContext;
                          import javax.net.ssl.SSLException;
                          import javax.net.ssl.SSLSession;
                          import javax.net.ssl.SSLSocket;
                          import java.io.IOException;
                          import java.security.cert.CertificateException;
                          import java.security.cert.X509Certificate;

                          public class Test
                          {
                          private static final DynamicIntProperty MAX_TOTAL_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty ROUTE_CONNECTIONS = DynamicPropertyFactory.getInstance().getIntProperty("X.total.connections", 40);
                          private static final DynamicIntProperty CONNECT_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connect.timeout", 60000);
                          private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.socket.timeout", -1);
                          private static final DynamicIntProperty CONNECTION_REQUEST_TIMEOUT = DynamicPropertyFactory.getInstance().getIntProperty("X.connectionrequest.timeout", 60000);
                          private static final DynamicBooleanProperty STALE_CONNECTION_CHECK = DynamicPropertyFactory.getInstance().getBooleanProperty("X.checkconnection", true);

                          public static void main(String args) throws Exception
                          {

                          SSLContext sslcontext = SSLContexts.custom()
                          .useTLS()
                          .loadTrustMaterial(null, new TrustStrategy()
                          {
                          @Override
                          public boolean isTrusted(X509Certificate chain, String authType) throws CertificateException
                          {
                          return true;
                          }
                          })
                          .build();
                          SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new AllowAll());

                          Registry<SchemeIOSessionStrategy> sessionStrategyRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
                          .register("http", NoopIOSessionStrategy.INSTANCE)
                          .register("https", sslSessionStrategy)
                          .build();

                          DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT);
                          PoolingNHttpClientConnectionManager connectionManager = new PoolingNHttpClientConnectionManager(ioReactor, sessionStrategyRegistry);
                          connectionManager.setMaxTotal(MAX_TOTAL_CONNECTIONS.get());
                          connectionManager.setDefaultMaxPerRoute(ROUTE_CONNECTIONS.get());

                          RequestConfig requestConfig = RequestConfig.custom()
                          .setSocketTimeout(SOCKET_TIMEOUT.get())
                          .setConnectTimeout(CONNECT_TIMEOUT.get())
                          .setConnectionRequestTimeout(CONNECTION_REQUEST_TIMEOUT.get())
                          .setStaleConnectionCheckEnabled(STALE_CONNECTION_CHECK.get())
                          .build();

                          CloseableHttpAsyncClient httpClient = HttpAsyncClients.custom()
                          .setSSLStrategy(sslSessionStrategy)
                          .setConnectionManager(connectionManager)
                          .setDefaultRequestConfig(requestConfig)
                          .build();

                          httpClient.start();

                          // use httpClient...
                          }

                          private static class AllowAll implements X509HostnameVerifier
                          {
                          @Override
                          public void verify(String s, SSLSocket sslSocket) throws IOException
                          {}

                          @Override
                          public void verify(String s, X509Certificate x509Certificate) throws SSLException {}

                          @Override
                          public void verify(String s, String strings, String strings2) throws SSLException
                          {}

                          @Override
                          public boolean verify(String s, SSLSession sslSession)
                          {
                          return true;
                          }
                          }
                          }






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Aug 4 '14 at 11:45

























                          answered Jun 26 '14 at 13:08









                          Jonas BergströmJonas Bergström

                          509412




                          509412








                          • 1





                            Btw, I'm using httpasyncclient:4.0.1

                            – Jonas Bergström
                            Aug 4 '14 at 11:49











                          • I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                            – EnterSB
                            Oct 17 '14 at 12:13






                          • 8





                            Note that this solution is insecure.

                            – user207421
                            May 22 '15 at 23:15











                          • Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                            – twcai
                            Nov 12 '15 at 2:54














                          • 1





                            Btw, I'm using httpasyncclient:4.0.1

                            – Jonas Bergström
                            Aug 4 '14 at 11:49











                          • I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                            – EnterSB
                            Oct 17 '14 at 12:13






                          • 8





                            Note that this solution is insecure.

                            – user207421
                            May 22 '15 at 23:15











                          • Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                            – twcai
                            Nov 12 '15 at 2:54








                          1




                          1





                          Btw, I'm using httpasyncclient:4.0.1

                          – Jonas Bergström
                          Aug 4 '14 at 11:49





                          Btw, I'm using httpasyncclient:4.0.1

                          – Jonas Bergström
                          Aug 4 '14 at 11:49













                          I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                          – EnterSB
                          Oct 17 '14 at 12:13





                          I needed something similar, @JonasBergström, your solution with SSLContext help a lot.

                          – EnterSB
                          Oct 17 '14 at 12:13




                          8




                          8





                          Note that this solution is insecure.

                          – user207421
                          May 22 '15 at 23:15





                          Note that this solution is insecure.

                          – user207421
                          May 22 '15 at 23:15













                          Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                          – twcai
                          Nov 12 '15 at 2:54





                          Thank you Jonas, your solution does solved the problem. But I found it costs a very long time (3 - 5s) to create the first connection, after that every connection only need 300-400 ms.

                          – twcai
                          Nov 12 '15 at 2:54











                          4














                          For those who like Debian and prepackaged Java:



                          sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
                          sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
                          sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
                          sudo update-ca-certificates --fresh --verbose


                          Don't forget to check /etc/default/cacerts for:



                          # enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
                          cacerts_updates=yes


                          To remove cert:



                          sudo rm /usr/share/ca-certificates/test/test.loc.crt
                          sudo rm /etc/ssl/certs/java/cacerts
                          sudo update-ca-certificates --fresh --verbose





                          share|improve this answer




























                            4














                            For those who like Debian and prepackaged Java:



                            sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
                            sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
                            sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
                            sudo update-ca-certificates --fresh --verbose


                            Don't forget to check /etc/default/cacerts for:



                            # enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
                            cacerts_updates=yes


                            To remove cert:



                            sudo rm /usr/share/ca-certificates/test/test.loc.crt
                            sudo rm /etc/ssl/certs/java/cacerts
                            sudo update-ca-certificates --fresh --verbose





                            share|improve this answer


























                              4












                              4








                              4







                              For those who like Debian and prepackaged Java:



                              sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
                              sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
                              sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
                              sudo update-ca-certificates --fresh --verbose


                              Don't forget to check /etc/default/cacerts for:



                              # enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
                              cacerts_updates=yes


                              To remove cert:



                              sudo rm /usr/share/ca-certificates/test/test.loc.crt
                              sudo rm /etc/ssl/certs/java/cacerts
                              sudo update-ca-certificates --fresh --verbose





                              share|improve this answer













                              For those who like Debian and prepackaged Java:



                              sudo mkdir /usr/share/ca-certificates/test/  # don't mess with other certs
                              sudo cp ~/tmp/test.loc.crt /usr/share/ca-certificates/test/
                              sudo dpkg-reconfigure --force ca-certificates # check your cert in curses GUI!
                              sudo update-ca-certificates --fresh --verbose


                              Don't forget to check /etc/default/cacerts for:



                              # enable/disable updates of the keystore /etc/ssl/certs/java/cacerts
                              cacerts_updates=yes


                              To remove cert:



                              sudo rm /usr/share/ca-certificates/test/test.loc.crt
                              sudo rm /etc/ssl/certs/java/cacerts
                              sudo update-ca-certificates --fresh --verbose






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Jul 18 '14 at 7:29









                              gavenkoagavenkoa

                              22.9k10143185




                              22.9k10143185























                                  4














                                  The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:



                                  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
                                  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
                                  ... 22 more


                                  In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.






                                  share|improve this answer


























                                  • ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                    – kisna
                                    Dec 26 '16 at 4:52
















                                  4














                                  The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:



                                  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
                                  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
                                  ... 22 more


                                  In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.






                                  share|improve this answer


























                                  • ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                    – kisna
                                    Dec 26 '16 at 4:52














                                  4












                                  4








                                  4







                                  The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:



                                  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
                                  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
                                  ... 22 more


                                  In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.






                                  share|improve this answer















                                  The source of this error on my Apache 2.4 instance (using a Comodo wildcard certificate) was an incomplete path to the SHA-1 signed root certificate. There were multiple chains in the issued certificate, and the chain leading to a SHA-1 root certificate was missing an intermediate certificate. Modern browsers know how to handle this, but Java 7 doesn't handle it by default (although there are some convoluted ways to accomplish this in code). The result is error messages that look identical to the case of self-signed certificates:



                                  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:196)
                                  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:268)
                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:380)
                                  ... 22 more


                                  In this case, the "unable to find valid certification path to requested target" message is being produced due to the missing intermediate certificate. You can check which certificate is missing using SSL Labs test against the server. Once you find the appropriate certificate, download it and (if the server is under your control) add it to the certificate bundle. Alternatively, you can import the missing certificate locally. Accommodating this issue on the server is a more general solution to the problem.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Jun 15 '15 at 23:07

























                                  answered Jun 12 '15 at 15:39









                                  vallismortisvallismortis

                                  3,510104064




                                  3,510104064













                                  • ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                    – kisna
                                    Dec 26 '16 at 4:52



















                                  • ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                    – kisna
                                    Dec 26 '16 at 4:52

















                                  ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                  – kisna
                                  Dec 26 '16 at 4:52





                                  ssllabs.com/ssltest is a savior, just have to compare it with a working cert validation.

                                  – kisna
                                  Dec 26 '16 at 4:52











                                  4














                                  For Windows only, follow these steps:




                                  1. In Chrome go to settings.

                                  2. In Settings click show advance settings.

                                  3. Under HTTPS/SSL Click on Manage Certificates.

                                  4. Export Your Certificate.

                                  5. In Windows searchs (Pressing windows key on keyboard) type java.

                                  6. Select (Configure Java) Option Which will open Java Control Panel

                                  7. Select Security tab in Java Control Panel

                                  8. Select Manage Certificates

                                  9. Click Import

                                  10. Under (User) tab selected and certificate type as (Trusted Certificates)

                                  11. Click import button and browse to downloaded certificate and import it.






                                  share|improve this answer






























                                    4














                                    For Windows only, follow these steps:




                                    1. In Chrome go to settings.

                                    2. In Settings click show advance settings.

                                    3. Under HTTPS/SSL Click on Manage Certificates.

                                    4. Export Your Certificate.

                                    5. In Windows searchs (Pressing windows key on keyboard) type java.

                                    6. Select (Configure Java) Option Which will open Java Control Panel

                                    7. Select Security tab in Java Control Panel

                                    8. Select Manage Certificates

                                    9. Click Import

                                    10. Under (User) tab selected and certificate type as (Trusted Certificates)

                                    11. Click import button and browse to downloaded certificate and import it.






                                    share|improve this answer




























                                      4












                                      4








                                      4







                                      For Windows only, follow these steps:




                                      1. In Chrome go to settings.

                                      2. In Settings click show advance settings.

                                      3. Under HTTPS/SSL Click on Manage Certificates.

                                      4. Export Your Certificate.

                                      5. In Windows searchs (Pressing windows key on keyboard) type java.

                                      6. Select (Configure Java) Option Which will open Java Control Panel

                                      7. Select Security tab in Java Control Panel

                                      8. Select Manage Certificates

                                      9. Click Import

                                      10. Under (User) tab selected and certificate type as (Trusted Certificates)

                                      11. Click import button and browse to downloaded certificate and import it.






                                      share|improve this answer















                                      For Windows only, follow these steps:




                                      1. In Chrome go to settings.

                                      2. In Settings click show advance settings.

                                      3. Under HTTPS/SSL Click on Manage Certificates.

                                      4. Export Your Certificate.

                                      5. In Windows searchs (Pressing windows key on keyboard) type java.

                                      6. Select (Configure Java) Option Which will open Java Control Panel

                                      7. Select Security tab in Java Control Panel

                                      8. Select Manage Certificates

                                      9. Click Import

                                      10. Under (User) tab selected and certificate type as (Trusted Certificates)

                                      11. Click import button and browse to downloaded certificate and import it.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Jan 7 '18 at 14:07









                                      vallismortis

                                      3,510104064




                                      3,510104064










                                      answered Nov 18 '16 at 11:07









                                      PraveenPraveen

                                      24425




                                      24425























                                          2














                                          This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.



                                          Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.



                                          More info on the issue can be found here, as well as how to resolve it on your server if you need to now.






                                          share|improve this answer




























                                            2














                                            This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.



                                            Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.



                                            More info on the issue can be found here, as well as how to resolve it on your server if you need to now.






                                            share|improve this answer


























                                              2












                                              2








                                              2







                                              This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.



                                              Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.



                                              More info on the issue can be found here, as well as how to resolve it on your server if you need to now.






                                              share|improve this answer













                                              This can also be caused by using GoDaddy certs with Java 7 that are signed using SHA2.



                                              Chrome and all other browsers are starting to deprecate SSL certs that are signed using SHA1, as it's not as secure.



                                              More info on the issue can be found here, as well as how to resolve it on your server if you need to now.







                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered Apr 16 '15 at 17:14









                                              Brad ParksBrad Parks

                                              29.3k36165225




                                              29.3k36165225























                                                  2














                                                  UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:



                                                  Import the self-signed certificate:



                                                  keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks


                                                  Add the official root certificates:



                                                  keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks


                                                  Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.



                                                  ORIGINAL POSTING:



                                                  Nobody will believe this, I know. Still, if all else fails, give it a try:
                                                  After a reboot of my Mac the problem was gone. Grrr.



                                                  Background:
                                                  ./gradlew jar kept giving me "unable to find valid certification path to requested target"



                                                  I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:



                                                  org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit


                                                  As mentioned, this only worked after a reboot.






                                                  share|improve this answer






























                                                    2














                                                    UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:



                                                    Import the self-signed certificate:



                                                    keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks


                                                    Add the official root certificates:



                                                    keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks


                                                    Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.



                                                    ORIGINAL POSTING:



                                                    Nobody will believe this, I know. Still, if all else fails, give it a try:
                                                    After a reboot of my Mac the problem was gone. Grrr.



                                                    Background:
                                                    ./gradlew jar kept giving me "unable to find valid certification path to requested target"



                                                    I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:



                                                    org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit


                                                    As mentioned, this only worked after a reboot.






                                                    share|improve this answer




























                                                      2












                                                      2








                                                      2







                                                      UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:



                                                      Import the self-signed certificate:



                                                      keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks


                                                      Add the official root certificates:



                                                      keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks


                                                      Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.



                                                      ORIGINAL POSTING:



                                                      Nobody will believe this, I know. Still, if all else fails, give it a try:
                                                      After a reboot of my Mac the problem was gone. Grrr.



                                                      Background:
                                                      ./gradlew jar kept giving me "unable to find valid certification path to requested target"



                                                      I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:



                                                      org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit


                                                      As mentioned, this only worked after a reboot.






                                                      share|improve this answer















                                                      UPDATE: That a reboot helped was coincidental (I hoped so, hooray!). The real cause of the problem was this: When Gradle is directed to use a specific keystore, that keystore must also contain all the official root certificates. Otherwise it cannot access libraries from regular repositories. What I had to do was this:



                                                      Import the self-signed certificate:



                                                      keytool -import -trustcacerts -alias myselfsignedcert -file /Users/me/Desktop/selfsignedcert.crt -keystore ./privateKeystore.jks


                                                      Add the official root certificates:



                                                      keytool -importkeystore -srckeystore <java-home>/lib/security/cacerts -destkeystore ./privateKeystore.jks


                                                      Maybe the Gradle daemon also got in the way. Might be worth killing all running daemons found with ./gradlew --status if things start looking bleak.



                                                      ORIGINAL POSTING:



                                                      Nobody will believe this, I know. Still, if all else fails, give it a try:
                                                      After a reboot of my Mac the problem was gone. Grrr.



                                                      Background:
                                                      ./gradlew jar kept giving me "unable to find valid certification path to requested target"



                                                      I am stuck with a self-signed certificate, saved from browser, imported in privateKeystore.jks. Then instructed Gradle to work with privateKeystore.jks:



                                                      org.gradle.jvmargs=-Djavax.net.debug=SSL -Djavax.net.ssl.trustStore="/Users/me/IntelliJ/myproject/privateKeystore.jks"  -Djavax.net.ssl.trustStorePassword=changeit


                                                      As mentioned, this only worked after a reboot.







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Feb 14 '17 at 15:51

























                                                      answered Feb 9 '17 at 13:32









                                                      StaticNoiseLogStaticNoiseLog

                                                      734920




                                                      734920























                                                          2














                                                          AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.



                                                          Solution: enter in AVG section called "Web and email" and disable the "email protection".
                                                          AVG block the certificate if the site isn't secure.






                                                          share|improve this answer






























                                                            2














                                                            AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.



                                                            Solution: enter in AVG section called "Web and email" and disable the "email protection".
                                                            AVG block the certificate if the site isn't secure.






                                                            share|improve this answer




























                                                              2












                                                              2








                                                              2







                                                              AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.



                                                              Solution: enter in AVG section called "Web and email" and disable the "email protection".
                                                              AVG block the certificate if the site isn't secure.






                                                              share|improve this answer















                                                              AVG version 18.1.3044 (with Windows 10) interfer with my local Spring application.



                                                              Solution: enter in AVG section called "Web and email" and disable the "email protection".
                                                              AVG block the certificate if the site isn't secure.







                                                              share|improve this answer














                                                              share|improve this answer



                                                              share|improve this answer








                                                              edited Feb 23 '18 at 7:24

























                                                              answered Feb 22 '18 at 16:06









                                                              InsoftInsoft

                                                              346316




                                                              346316























                                                                  1














                                                                  I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job



                                                                     <dependency>
                                                                  <groupId>org.apache.httpcomponents</groupId>
                                                                  <artifactId>httpclient</artifactId>
                                                                  <version>4.3.6</version>
                                                                  </dependency>





                                                                  share|improve this answer




























                                                                    1














                                                                    I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job



                                                                       <dependency>
                                                                    <groupId>org.apache.httpcomponents</groupId>
                                                                    <artifactId>httpclient</artifactId>
                                                                    <version>4.3.6</version>
                                                                    </dependency>





                                                                    share|improve this answer


























                                                                      1












                                                                      1








                                                                      1







                                                                      I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job



                                                                         <dependency>
                                                                      <groupId>org.apache.httpcomponents</groupId>
                                                                      <artifactId>httpclient</artifactId>
                                                                      <version>4.3.6</version>
                                                                      </dependency>





                                                                      share|improve this answer













                                                                      I had the same problem with the certificates error and was because of SNI, and http client that I used didn't had SNI implemented. So an version update did the job



                                                                         <dependency>
                                                                      <groupId>org.apache.httpcomponents</groupId>
                                                                      <artifactId>httpclient</artifactId>
                                                                      <version>4.3.6</version>
                                                                      </dependency>






                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Oct 26 '15 at 6:55









                                                                      Radu ToaderRadu Toader

                                                                      992813




                                                                      992813























                                                                          1














                                                                          You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:



                                                                          jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory





                                                                          share|improve this answer




























                                                                            1














                                                                            You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:



                                                                            jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory





                                                                            share|improve this answer


























                                                                              1












                                                                              1








                                                                              1







                                                                              You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:



                                                                              jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory





                                                                              share|improve this answer













                                                                              You have two options, import the self-signed cert into java's keystore for each jvm the software will run on or try the non-validating ssl factory:



                                                                              jdbc:postgresql://myserver.com:5432/mydatabasename?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory






                                                                              share|improve this answer












                                                                              share|improve this answer



                                                                              share|improve this answer










                                                                              answered Apr 21 '16 at 3:45









                                                                              Pradip DasPradip Das

                                                                              5581616




                                                                              5581616























                                                                                  0














                                                                                  This solved my issue,



                                                                                  We need to import the cert onto the local java. If not we could get the below exception.




                                                                                  javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                  at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                                                                                  at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
                                                                                  at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)


                                                                                  SSLPOKE is a tool where you can test the https connectivity from your local machine.



                                                                                  Command to test the connectivity:



                                                                                  "%JAVA_HOME%/bin/java" SSLPoke <hostname> 443



                                                                                  sun.security.validator.ValidatorException: PKIX path building failed:
                                                                                  sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
                                                                                  at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
                                                                                  at sun.security.validator.Validator.validate(Validator.java:260)
                                                                                  at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                                                                                  at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                                                                                  at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                                                                                  at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
                                                                                  at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                                                                                  at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
                                                                                  at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
                                                                                  at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
                                                                                  at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
                                                                                  at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
                                                                                  at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
                                                                                  at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
                                                                                  at SSLPoke.main(SSLPoke.java:31)
                                                                                  Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
                                                                                  requested target
                                                                                  at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                                                                                  at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                                                                                  at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                                                                                  at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
                                                                                  ... 15 more


                                                                                  keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>


                                                                                  this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.



                                                                                  Verfication:



                                                                                  C:tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
                                                                                  Successfully connected





                                                                                  share|improve this answer




























                                                                                    0














                                                                                    This solved my issue,



                                                                                    We need to import the cert onto the local java. If not we could get the below exception.




                                                                                    javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                    at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                                                                                    at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
                                                                                    at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)


                                                                                    SSLPOKE is a tool where you can test the https connectivity from your local machine.



                                                                                    Command to test the connectivity:



                                                                                    "%JAVA_HOME%/bin/java" SSLPoke <hostname> 443



                                                                                    sun.security.validator.ValidatorException: PKIX path building failed:
                                                                                    sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
                                                                                    at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
                                                                                    at sun.security.validator.Validator.validate(Validator.java:260)
                                                                                    at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                                                                                    at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                                                                                    at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                                                                                    at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
                                                                                    at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                                                                                    at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
                                                                                    at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
                                                                                    at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
                                                                                    at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
                                                                                    at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
                                                                                    at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
                                                                                    at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
                                                                                    at SSLPoke.main(SSLPoke.java:31)
                                                                                    Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
                                                                                    requested target
                                                                                    at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                                                                                    at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                                                                                    at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                                                                                    at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
                                                                                    ... 15 more


                                                                                    keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>


                                                                                    this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.



                                                                                    Verfication:



                                                                                    C:tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
                                                                                    Successfully connected





                                                                                    share|improve this answer


























                                                                                      0












                                                                                      0








                                                                                      0







                                                                                      This solved my issue,



                                                                                      We need to import the cert onto the local java. If not we could get the below exception.




                                                                                      javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                      at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                                                                                      at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
                                                                                      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)


                                                                                      SSLPOKE is a tool where you can test the https connectivity from your local machine.



                                                                                      Command to test the connectivity:



                                                                                      "%JAVA_HOME%/bin/java" SSLPoke <hostname> 443



                                                                                      sun.security.validator.ValidatorException: PKIX path building failed:
                                                                                      sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
                                                                                      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
                                                                                      at sun.security.validator.Validator.validate(Validator.java:260)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                                                                                      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
                                                                                      at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                                                                                      at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
                                                                                      at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
                                                                                      at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
                                                                                      at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
                                                                                      at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
                                                                                      at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
                                                                                      at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
                                                                                      at SSLPoke.main(SSLPoke.java:31)
                                                                                      Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
                                                                                      requested target
                                                                                      at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                                                                                      at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                                                                                      at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                                                                                      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
                                                                                      ... 15 more


                                                                                      keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>


                                                                                      this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.



                                                                                      Verfication:



                                                                                      C:tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
                                                                                      Successfully connected





                                                                                      share|improve this answer













                                                                                      This solved my issue,



                                                                                      We need to import the cert onto the local java. If not we could get the below exception.




                                                                                      javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                      at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
                                                                                      at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1949)
                                                                                      at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)


                                                                                      SSLPOKE is a tool where you can test the https connectivity from your local machine.



                                                                                      Command to test the connectivity:



                                                                                      "%JAVA_HOME%/bin/java" SSLPoke <hostname> 443



                                                                                      sun.security.validator.ValidatorException: PKIX path building failed:
                                                                                      sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                                                                      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:387)
                                                                                      at sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:292)
                                                                                      at sun.security.validator.Validator.validate(Validator.java:260)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.validate(X509TrustManagerImpl.java:324)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:229)
                                                                                      at sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:124)
                                                                                      at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1496)
                                                                                      at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:216)
                                                                                      at sun.security.ssl.Handshaker.processLoop(Handshaker.java:1026)
                                                                                      at sun.security.ssl.Handshaker.process_record(Handshaker.java:961)
                                                                                      at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
                                                                                      at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
                                                                                      at sun.security.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:747)
                                                                                      at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:123)
                                                                                      at sun.security.ssl.AppOutputStream.write(AppOutputStream.java:138)
                                                                                      at SSLPoke.main(SSLPoke.java:31)
                                                                                      Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to
                                                                                      requested target
                                                                                      at sun.security.provider.certpath.SunCertPathBuilder.build(SunCertPathBuilder.java:141)
                                                                                      at sun.security.provider.certpath.SunCertPathBuilder.engineBuild(SunCertPathBuilder.java:126)
                                                                                      at java.security.cert.CertPathBuilder.build(CertPathBuilder.java:280)
                                                                                      at sun.security.validator.PKIXValidator.doBuild(PKIXValidator.java:382)
                                                                                      ... 15 more


                                                                                      keytool -import -alias brinternal -keystore "%JAVA_HOME%/jre/lib/security/cacerts" -file <cert path>


                                                                                      this would first prompt to "Enter keystore password:" changeit is the default password. and finally a prompt "Trust this certificate? [no]:", provide "yes" to add the cert to keystore.



                                                                                      Verfication:



                                                                                      C:tools>"%JAVA_HOME%/bin/java" SSLPoke <hostname> 443
                                                                                      Successfully connected






                                                                                      share|improve this answer












                                                                                      share|improve this answer



                                                                                      share|improve this answer










                                                                                      answered Jul 9 '18 at 10:43









                                                                                      NaveenNaveen

                                                                                      445




                                                                                      445























                                                                                          0














                                                                                          In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).



                                                                                          Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.



                                                                                          bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
                                                                                          bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit





                                                                                          share|improve this answer




























                                                                                            0














                                                                                            In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).



                                                                                            Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.



                                                                                            bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
                                                                                            bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit





                                                                                            share|improve this answer


























                                                                                              0












                                                                                              0








                                                                                              0







                                                                                              In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).



                                                                                              Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.



                                                                                              bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
                                                                                              bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit





                                                                                              share|improve this answer













                                                                                              In my case I'm running MacOs High Sierra with Java 1.6. The cacert file is in a different location than referenced above in Gabe Martin-Dempesy's answer. The cacert file was also already linked to another location (/Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/security/cacerts).



                                                                                              Using FireFox, I exported the certificate from the web site in question to a local file called "exportedCertFile.crt". From there, I used keytool to move the certificate into the cacert file. This fixed the problem.



                                                                                              bash-3.2# cd /Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/lib/security/
                                                                                              bash-3.2# keytool -importcert -file ~/exportedCertFile.crt -alias example -keystore cacerts -storepass changeit






                                                                                              share|improve this answer












                                                                                              share|improve this answer



                                                                                              share|improve this answer










                                                                                              answered Jul 17 '18 at 20:26









                                                                                              Alan CurtisAlan Curtis

                                                                                              11




                                                                                              11























                                                                                                  0














                                                                                                  first Download the ssl certificate then you can go to your java bin path execute the below command in the console.



                                                                                                  C:javaJDK1.8.0_66-X64bin>keytool -printcert -file C:Userslovaopenapi.cer -keystore openapistore





                                                                                                  share|improve this answer




























                                                                                                    0














                                                                                                    first Download the ssl certificate then you can go to your java bin path execute the below command in the console.



                                                                                                    C:javaJDK1.8.0_66-X64bin>keytool -printcert -file C:Userslovaopenapi.cer -keystore openapistore





                                                                                                    share|improve this answer


























                                                                                                      0












                                                                                                      0








                                                                                                      0







                                                                                                      first Download the ssl certificate then you can go to your java bin path execute the below command in the console.



                                                                                                      C:javaJDK1.8.0_66-X64bin>keytool -printcert -file C:Userslovaopenapi.cer -keystore openapistore





                                                                                                      share|improve this answer













                                                                                                      first Download the ssl certificate then you can go to your java bin path execute the below command in the console.



                                                                                                      C:javaJDK1.8.0_66-X64bin>keytool -printcert -file C:Userslovaopenapi.cer -keystore openapistore






                                                                                                      share|improve this answer












                                                                                                      share|improve this answer



                                                                                                      share|improve this answer










                                                                                                      answered Aug 21 '18 at 10:28









                                                                                                      Lova ChittumuriLova Chittumuri

                                                                                                      7351013




                                                                                                      7351013























                                                                                                          0














                                                                                                          Make sure that the https://176.66.3.69:6443/ have a valid certificate.
                                                                                                          you can check it via browser firstly https not secure if it works in browser it will work in java.



                                                                                                          that is working for me






                                                                                                          share|improve this answer




























                                                                                                            0














                                                                                                            Make sure that the https://176.66.3.69:6443/ have a valid certificate.
                                                                                                            you can check it via browser firstly https not secure if it works in browser it will work in java.



                                                                                                            that is working for me






                                                                                                            share|improve this answer


























                                                                                                              0












                                                                                                              0








                                                                                                              0







                                                                                                              Make sure that the https://176.66.3.69:6443/ have a valid certificate.
                                                                                                              you can check it via browser firstly https not secure if it works in browser it will work in java.



                                                                                                              that is working for me






                                                                                                              share|improve this answer













                                                                                                              Make sure that the https://176.66.3.69:6443/ have a valid certificate.
                                                                                                              you can check it via browser firstly https not secure if it works in browser it will work in java.



                                                                                                              that is working for me







                                                                                                              share|improve this answer












                                                                                                              share|improve this answer



                                                                                                              share|improve this answer










                                                                                                              answered Sep 24 '18 at 9:58









                                                                                                              Amr IbrahimAmr Ibrahim

                                                                                                              567625




                                                                                                              567625























                                                                                                                  -3














                                                                                                                  When I have this problem, I just extract the android studio zip to the same old folder, that solved my problem






                                                                                                                  share|improve this answer




























                                                                                                                    -3














                                                                                                                    When I have this problem, I just extract the android studio zip to the same old folder, that solved my problem






                                                                                                                    share|improve this answer


























                                                                                                                      -3












                                                                                                                      -3








                                                                                                                      -3







                                                                                                                      When I have this problem, I just extract the android studio zip to the same old folder, that solved my problem






                                                                                                                      share|improve this answer













                                                                                                                      When I have this problem, I just extract the android studio zip to the same old folder, that solved my problem







                                                                                                                      share|improve this answer












                                                                                                                      share|improve this answer



                                                                                                                      share|improve this answer










                                                                                                                      answered Aug 22 '18 at 7:36









                                                                                                                      Jacob GeorgeJacob George

                                                                                                                      11




                                                                                                                      11






























                                                                                                                          draft saved

                                                                                                                          draft discarded




















































                                                                                                                          Thanks for contributing an answer to Stack Overflow!


                                                                                                                          • Please be sure to answer the question. Provide details and share your research!

                                                                                                                          But avoid



                                                                                                                          • Asking for help, clarification, or responding to other answers.

                                                                                                                          • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                          To learn more, see our tips on writing great answers.




                                                                                                                          draft saved


                                                                                                                          draft discarded














                                                                                                                          StackExchange.ready(
                                                                                                                          function () {
                                                                                                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f6908948%2fjava-sun-security-provider-certpath-suncertpathbuilderexception-unable-to-find%23new-answer', 'question_page');
                                                                                                                          }
                                                                                                                          );

                                                                                                                          Post as a guest















                                                                                                                          Required, but never shown





















































                                                                                                                          Required, but never shown














                                                                                                                          Required, but never shown












                                                                                                                          Required, but never shown







                                                                                                                          Required, but never shown

































                                                                                                                          Required, but never shown














                                                                                                                          Required, but never shown












                                                                                                                          Required, but never shown







                                                                                                                          Required, but never shown







                                                                                                                          Popular posts from this blog

                                                                                                                          Full-time equivalent

                                                                                                                          Bicuculline

                                                                                                                          さくらももこ