Romowski Romowski - 1 month ago 12
Java Question

Web Service client SSL authorization in JAVA

Trying to authorize on https url via SSL and certificate. I am not really understand how this mechanism works... So need help extremely ))

Developing on Mac, targeting to Windows.

First of all I have imported .p12 file into KeyChain -> My Certificates.
After that I managed to authorize to web service from Safari.

Ok. Everything is well, but I can not authorize with this .p12 from JAVA code:

Here was my last attempt to authorize:

URL url = new URL("https://ws.service");

KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore keyStore = KeyStore.getInstance("PKCS12");

InputStream keyInput = new FileInputStream("path_to_p12_file");
keyStore.load(keyInput, p12password.toCharArray());
keyInput.close();

keyManagerFactory.init(keyStore, p12password.toCharArray());

SSLContext context = SSLContext.getInstance("SSL");
context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());

HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setSSLSocketFactory(context.getSocketFactory());
con.connect();


Here is the error:

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


I have also tried to import my p12 into JKS file and set system params:

System.setProperty("javax.net.ssl.trustStore", path_to_jks);
System.setProperty("javax.net.ssl.trustStorePassword", jks_pass);
System.setProperty("javax.net.ssl.trustStoreType", "JKS");


Added SSL debug messages:

%% Invalidated: [Session-1, SSL_RSA_WITH_RC4_128_MD5]
JavaFX Application Thread, SEND SSLv3 ALERT: fatal, description = certificate_unknown
JavaFX Application Thread, WRITE: SSLv3 Alert, length = 2
JavaFX Application Thread, called closeSocket()

Answer