I have to connect to a server via SSL dual authentication. I have added my own private key plus certificate to a keystore.jks and the self signed certificate of the server to a truststore.jks, both files are copied to /usr/share/tomcat7. The socket factory used by my code is delivered by the following provider:
#Singleton
public static class SecureSSLSocketFactoryProvider implements Provider<SSLSocketFactory> {
private SSLSocketFactory sslSocketFactory;
public SecureSSLSocketFactoryProvider() throws RuntimeException {
try {
final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
final InputStream trustStoreFile = new FileInputStream("/usr/share/tomcat7/truststore.jks");
trustStore.load(trustStoreFile, "changeit".toCharArray());
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
final InputStream keyStoreFile = new FileInputStream("/usr/share/tomcat7/keystore.jks");
keyStore.load(keyStoreFile, "changeit".toCharArray());
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "changeit".toCharArray());
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
this.sslSocketFactory = sslContext.getSocketFactory();
} catch (final KeyStoreException e) {
Log.error("Key store exception: {}", e.getMessage(), e);
} catch (final CertificateException e) {
Log.error("Certificate exception: {}", e.getMessage(), e);
} catch (final UnrecoverableKeyException e) {
Log.error("Unrecoverable key exception: {}", e.getMessage(), e);
} catch (final NoSuchAlgorithmException e) {
Log.error("No such algorithm exception: {}", e.getMessage(), e);
} catch (final KeyManagementException e) {
Log.error("Key management exception: {}", e.getMessage(), e);
} catch (final IOException e) {
Log.error("IO exception: {}", e.getMessage(), e);
}
}
#Override
public SSLSocketFactory get() {
return sslSocketFactory;
}
}
When I try to connect to an endpoint on the server I get the following exception though:
javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) ~[na:1.7.0_45]
at sun.security.ssl.Alerts.getSSLException(Alerts.java:154) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1959) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1077) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339) ~[na:1.7.0_45]
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323) ~[na:1.7.0_45]
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:563) ~[na:1.7.0_45]
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) ~[na:1.7.0_45]
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153) ~[na:1.7.0_45]
Any idea what I have missed here?
If you get an alert unknown_ca back from the server, then the server did not like the certificate you've send as the client certificate, because it is not signed by a CA which is trusted by the server for client certificates.
Related
I'm creating in Java HttpsURLConnection. I downloaded certificates from website and created file truststore.jks with this certs. My application is getting certs from truststore.jks and connecting to website. And it works... on my PC. But after deploy application on server I got this ugly exception:
Cause: 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
Stack trace:
[sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.fatal(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.Handshaker.fatalSE(Unknown Source)
sun.security.ssl.ClientHandshaker.serverCertificate(Unknown Source)
sun.security.ssl.ClientHandshaker.processMessage(Unknown Source)
sun.security.ssl.Handshaker.processLoop(Unknown Source)
sun.security.ssl.Handshaker.process_record(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.net.www.protocol.https.HttpsClient.afterConnect(Unknown Source)
sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream0(Unknown Source)
sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
I'm creating HttpsURLConnection in ConnectionFactory class, and running connection.getInputStream() method.
ConnectionFactory.java:
public final class ConnectionFactory {
public HttpsURLConnection getHttpsURLConnection(URL url, String trustStorePath, String trustStorePassword)
throws FileTransferWorkerException {
KeyStore keyStore = loadKeyStore(trustStorePath, trustStorePassword);
TrustManagerFactory trustManagerFactory = initTrustManagerFactory(keyStore);
SSLSocketFactory sslSocketFactory = buildSSLSocketFactory(trustManagerFactory);
return buildConnection(url, sslSocketFactory);
}
private KeyStore loadKeyStore(String path, String password) throws FileTransferWorkerException {
KeyStore keystore;
try {
keystore = KeyStore.getInstance("JKS");
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
try (FileInputStream fileInputStream = new FileInputStream(path)) {
keystore.load(fileInputStream, password.toCharArray());
} catch (IOException | CertificateException | NoSuchAlgorithmException e) {
throw new FileTransferWorkerException("Can not load keyStore from " + path, e);
}
return keystore;
}
private TrustManagerFactory initTrustManagerFactory(KeyStore keyStore) throws FileTransferWorkerException {
TrustManagerFactory trustManagerFactory;
try {
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
trustManagerFactory.init(keyStore);
} catch (KeyStoreException e) {
throw new FileTransferWorkerException(e);
}
return trustManagerFactory;
}
private SSLSocketFactory buildSSLSocketFactory(TrustManagerFactory trustManagerFactory) throws FileTransferWorkerException {
SSLContext sslContext;
try {
sslContext = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new FileTransferWorkerException(e);
}
try {
sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
} catch (KeyManagementException e) {
throw new FileTransferWorkerException(e);
}
return sslContext.getSocketFactory();
}
private HttpsURLConnection buildConnection(URL url, SSLSocketFactory sslSocketFactory) throws FileTransferWorkerException {
HttpsURLConnection connection;
try {
connection = (HttpsURLConnection) url.openConnection();
} catch (IOException e) {
throw new FileTransferWorkerException("Can not connect to " + url.getPath(), e);
}
connection.setSSLSocketFactory(sslSocketFactory);
return connection;
}
}
and invoke method:
private void download(URL url, String trustStorePath, String trustStorePassword, File file)
throws IOException, FileTransferWorkerException {
HttpsURLConnection connection = new ConnectionFactory().getHttpsURLConnection(url, trustStorePath, trustStorePassword);
try (ReadableByteChannel reader = Channels.newChannel(connection.getInputStream()){
...
} finally {
connection.disconnect();
}
}
I need to use my truststor.jks file, not cacerts. Do you have any ideas where I made a mistake? Help.
I figured it. Locally I'm connected to my company's network and I have their certificates (because of proxy). But server isn't using proxy and should have real certificates from endpoint server.
i have added all the certs to cacerts. using these cacerts and jks got from MQ team i have created a SSLConnectionFactory. and passed it to the Mqconnectionfactory. I have added VM args:
-Dcom.ibm.mq.cfg.useIBMCipherMappings=false
-Djavax.net.debug=all
-Dcom.ibm.mq.cfg.preferTLS=true
and we have unlimited JCE policy, JDK 1.8 , IBM MQ all client 9.0.4.0
Sample Code
private SSLSocketFactory getSocketFactory() {
KeyStore ks;
SSLSocketFactory sslSocketFactory = null;
String keystoreFile = environment.getProperty("ibmmq.keystoreFile");
String truststoreFile = environment.getProperty("ibmmq.truststoreFile");
String keystorePassword = environment.getProperty("ibmmq.keystorePassword");
String trustStorePassword = environment.getProperty("ibmmq.trustStorePassword");
try {
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(keystoreFile), keystorePassword.toCharArray());
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(truststoreFile), trustStorePassword.toCharArray());
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
keyManagerFactory.init(ks, keystorePassword.toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
sslSocketFactory = sslContext.getSocketFactory();
logger.info("Initialized ssl socket factory... " + sslSocketFactory.toString());
} catch (KeyStoreException e) {
logger.error("KeyStoreException on getSocketFactory due to {}", e);
} catch (NoSuchAlgorithmException e) {
logger.error("NoSuchAlgorithmException on getSocketFactory due to {}", e);
} catch (CertificateException e) {
logger.error("CertificateException on getSocketFactory due to {}", e);
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException on getSocketFactory due to {}", e);
} catch (IOException e) {
logger.error("IOException on getSocketFactory due to {}", e);
} catch (UnrecoverableKeyException e) {
logger.error("UnrecoverableKeyException on getSocketFactory due to {}", e);
} catch (KeyManagementException e) {
logger.error("KeyManagementException on getSocketFactory due to {}", e);
}
return sslSocketFactory;
}
private MQQueueConnectionFactory mqQueueConnectionFactoryBill() {
MQQueueConnectionFactory mqQueueConnectionFactory = new MQQueueConnectionFactory();
try {
mqQueueConnectionFactory.setHostName(environment.getProperty("ibmmq.host"));
mqQueueConnectionFactory.setPort(environment.getProperty("ibmmq.port", Integer.class));
mqQueueConnectionFactory.setTransportType(WMQConstants.WMQ_CM_CLIENT);
mqQueueConnectionFactory.setCCSID(WMQConstants.CCSID_UTF8);
mqQueueConnectionFactory.setChannel(environment.getProperty("ibmmq.channel"));
mqQueueConnectionFactory.setQueueManager(environment.getProperty("ibmmq.queue-manager"));
mqQueueConnectionFactory.setSSLCipherSuite(environment.getProperty("ibmmq.cipher.suite"));
mqQueueConnectionFactory.setSSLSocketFactory(getSocketFactory());
mqQueueConnectionFactory.setSSLFipsRequired(false);
System.out.println("mqQueueConnectionFactory initialized..!!! ==> " + mqQueueConnectionFactory.toString());
//System.out.println("mqQueueConnectionFactory connection ..!!! ==> " + mqQueueConnectionFactory.createConnection());
//System.out.println("mqQueueConnectionFactory ..!!! ==> " + mqQueueConnectionFactory.getClientReconnectOptions());
} catch (Exception e) {
e.printStackTrace();
}
return mqQueueConnectionFactory;
}
#Bean
public CachingConnectionFactory cachingConnectionFactory() {
CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory();
cachingConnectionFactory.setTargetConnectionFactory(userCredentialsConnectionFactoryAdapterBill());
cachingConnectionFactory.setSessionCacheSize(500);
cachingConnectionFactory.setCacheProducers(true);
cachingConnectionFactory.setReconnectOnException(true);
return cachingConnectionFactory;
}
private UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapterBill() {
UserCredentialsConnectionFactoryAdapter userCredentialsConnectionFactoryAdapter = new UserCredentialsConnectionFactoryAdapter();
userCredentialsConnectionFactoryAdapter.setUsername(environment.getProperty("ibmmq.username"));
userCredentialsConnectionFactoryAdapter.setPassword(environment.getProperty("ibmmq.password"));
userCredentialsConnectionFactoryAdapter.setTargetConnectionFactory(mqQueueConnectionFactoryBill());
return userCredentialsConnectionFactoryAdapter;
}
#Bean
public SimpleMessageListenerContainer sampleQueueContainer(#Autowired MessageListener listener) {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(cachingConnectionFactory());
container.setDestinationName(environment.getProperty("ibmmq.mq.name"));
container.setMessageListener(listener);
container.afterPropertiesSet();
container.start();
return container;
}
Error As Follows
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2009;AMQ9213: A communications error for 'TCP' occurred. [1=java.net.SocketException[Connection reset],4=TCP,5=sockInStream.read]
at com.ibm.mq.jmqi.remote.impl.RemoteTCPConnection.receive(RemoteTCPConnection.java:1717) ~[com.ibm.mq.allclient-9.0.4.0.jar:9.0.4.0 - p904-L171030.1]
at com.ibm.mq.jmqi.remote.impl.RemoteConnection.receiveTSH(RemoteConnection.java:3110) ~[com.ibm.mq.allclient-9.0.4.0.jar:9.0.4.0 - p904-L171030.1]
at org.springframework.jms.listener.AbstractJmsListeningContainer.start(AbstractJmsListeningContainer.java:270) ~[spring-jms-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at com.sample.sampleMQConfig.sampleQueueContainer(sampleMQConfig.java:84) ~[classes/:?]
at com.sample.sampleMQConfig$$EnhancerBySpringCGLIB$$701bd166.CGLIB$sampleQueueContainer$3(<generated>) ~[classes/:?]
at com.sample.sampleMQConfig$$EnhancerBySpringCGLIB$$701bd166$$FastClassBySpringCGLIB$$8ac69a00.invoke(<generated>) ~[classes/:?]
at com.sample.sampleMQConfig$$EnhancerBySpringCGLIB$$701bd166.sampleQueueContainer(<generated>) ~[classes/:?]
Caused by: java.net.SocketException: Connection reset
at com.ibm.mq.ese.jmqi.ESEJMQI.jmqiConnect(ESEJMQI.java:562) ~[com.ibm.mq.allclient-9.0.4.0.jar:9.0.4.0 - p904-L171030.1]
at com.ibm.msg.client.wmq.internal.WMQConnection.<init>(WMQConnection.java:357) ~[com.ibm.mq.allclient-9.0.4.0.jar:9.0.4.0 - p904-L171030.1]
at org.springframework.jms.listener.AbstractJmsListeningContainer.start(AbstractJmsListeningContainer.java:270) ~[spring-jms-4.3.14.RELEASE.jar:4.3.14.RELEASE]
at com.sample.sampleMQConfig.sampleQueueContainer(sampleMQConfig.java:84) ~[classes/:?]
I didn't find any way to implement an SSLContext with DownloadManager. Is there a way to add a Client certificate (keystore)?
For now, it is a self signed certificate (both client&server). I'm able to connect to this server with okhttp (managing SSLContext) but with DownloadManager i get an error 'SSL Handshake'.
Here is my code,
#Nullable
private static SSLContext initTrustManager(Context context) {
try {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream is = context.getAssets().open("s_cert.cer");
Certificate ca;
try {
ca = certificateFactory.generateCertificate(is);
Log.i("TrustManager", "ca=" + ((X509Certificate) ca).getSubjectDN());
} finally {
is.close();
}
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
return sslContext;
} catch (CertificateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
And here is how I implement it:
builder.sslSocketFactory(initTrustManager(context).getSocketFactory());
This is working code, so if you still get exceptions, pay attention to SSL certificate itself or make some changes inside api of server. Hope it helps))
I'm trying to connect to my API server using a self-signed certificate. The certificate was successfully installed on the server. I've tested it via OpenSSL and also in Firefox.
I followed the Andrey Makarov's answer to configure OkHttp. But it doesn't work. When I try to execute my request I get javax.net.ssl.SSLHandshakeException with java.security.cert.CertPathValidatorException: Trust anchor for certification path not found message.
Here is my code:
public HttpClient() {
/* ... */
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLSv1.2");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
KeyStore keyStore = readKeyStore();
TrustManagerFactory trustManagerFactory = null;
try {
trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, "password".toCharArray());
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
}
catch (final Exception e) {
Log.e(TAG, e.toString());
}
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
X509TrustManager trustManager = (X509TrustManager) trustManagers[0];
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslContext.getSocketFactory(), trustManager)
.build();
mRetrofit = new Retrofit.Builder()
.client(client)
.baseUrl(mBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
private KeyStore readKeyStore() {
KeyStore ks = null;
try {
ks = KeyStore.getInstance("BKS");
}
catch (final Exception e) {
Log.e(TAG, e.toString());
}
char[] password = "password".toCharArray();
final Context context = App.app;
InputStream is = context.getResources().openRawResource(R.raw.key_sorage);
try {
ks.load(is, password);
}
catch (final Exception e) {
Log.e(TAG, e.toString());
}
finally {
if (is != null) {
try {
is.close();
}
catch (final Exception e2) {
Log.e(TAG, e2.toString());
}
}
}
return ks;
}
Retrofit version is 2.3.0.
Am trying to establish an ssl connection.I have a Server and I have a client. I have both of them running on the same machine. am trying to establish an SSL connection between the client and the server. i have generated certificates for both the server and the client with the following keytool command.
For Client
keytool -keystore clientstore -genkey -alias client -validity 3650
Then i export the root certificate of the client to a cer file callled client.cer
For Server
keytool -keystore serverstore -genkey -alias server -validity 3650 Then i export the root certificate of the server to a cer file callled server.cer
I now import the client certificate "client.cer" into the serverstore keystore with the following command
keytool -import -keystore serverstore -file client.cer -alias client
And also import the servers certificate "server.cer" into the clientstore keystore with the following command
keytool -import -keystore clientstore -file server.cer -alias server
After doing this, i imported both the server.cer and client.cer into the cacerts Keystore. But when i try to establish an ssl connection, i get this error on the server javax.net.ssl.SSLHandshakeException: null cert chain and this error on the client javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate.
My Servers Code.
package serverapplicationssl;
import java.io.*;
import java.security.KeyStore;
import java.security.Security;
import java.security.PrivilegedActionException;
import javax.net.ssl.*;
import com.sun.net.ssl.internal.ssl.Provider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
import java.io.*;
public class ServerApplicationSSL {
public static void main(String[] args) {
boolean debug = true;
System.out.println("Waiting For Connection");
int intSSLport = 4447;
{
Security.addProvider(new Provider());
}
if (debug) {
System.setProperty("javax.net.debug", "all");
}
FileWriter file = null;
try {
file = new FileWriter("C:\\SSLCERT\\Javalog.txt");
} catch (Exception ee) {
//message = ee.getMessage();
}
try {
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("C:\\SSLCERT\\OntechServerKS"), "server".toCharArray());
file.write("Incoming Connection\r\n");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keystore, "server".toCharArray());
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketfactory = (SSLServerSocketFactory) context.getServerSocketFactory();
SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketfactory.createServerSocket(intSSLport);
sslServerSocket.setEnabledCipherSuites(sslServerSocket.getSupportedCipherSuites());
sslServerSocket.setNeedClientAuth(true);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
//SSLServerSocket server_socket = (SSLServerSocket) sslServerSocket;
sslSocket.startHandshake();
// Start the session
System.out.println("Connection Accepted");
file.write("Connection Accepted\r\n");
while (true) {
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
String inputLine;
//while ((inputLine = in.readLine()) != null) {
out.println("Hello Client....Welcome");
System.out.println("Hello Client....Welcome");
//}
out.close();
//in.close();
sslSocket.close();
sslServerSocket.close();
file.flush();
file.close();
}
} catch (Exception exp) {
try {
System.out.println(exp.getMessage() + "\r\n");
exp.printStackTrace();
file.write(exp.getMessage() + "\r\n");
file.flush();
file.close();
} catch (Exception eee) {
//message = eee.getMessage();
}
}
}
}
Here's My Clients Code
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.Enumeration;
import javax.net.ssl.*;
public class SSLConnect {
public String MakeSSlCall(String meternum) {
String message = "";
FileWriter file = null;
try {
file = new FileWriter("C:\\SSLCERT\\ClientJavalog.txt");
} catch (Exception ee) {
message = ee.getMessage();
}
//writer = new BufferedWriter(file );
try {
file.write("KeyStore Generated\r\n");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("C:\\SSLCERT\\SkyeClientKS"), "client".toCharArray());
file.write("KeyStore Generated\r\n");
Enumeration enumeration = keystore.aliases();
while (enumeration.hasMoreElements()) {
String alias = (String) enumeration.nextElement();
file.write("alias name: " + alias + "\r\n");
keystore.getCertificate(alias);
file.write(keystore.getCertificate(alias).toString() + "\r\n");
}
TrustManagerFactory tmf =TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
file.write("KeyStore Stored\r\n");
SSLContext context = SSLContext.getInstance("SSL");
TrustManager[] trustManagers = tmf.getTrustManagers();
context.init(null, trustManagers, null);
SSLSocketFactory f = context.getSocketFactory();
file.write("About to Connect to Ontech\r\n");
SSLSocket c = (SSLSocket) f.createSocket("192.168.1.16", 4447);
file.write("Connection Established to 196.14.30.33 Port: 8462\r\n");
file.write("About to Start Handshake\r\n");
c.startHandshake();
file.write("Handshake Established\r\n");
file.flush();
file.close();
return "Connection Established";
} catch (Exception e) {
try {
file.write("An Error Occured\r\n");
file.write(e.getMessage() + "\r\n");
StackTraceElement[] arrmessage = e.getStackTrace();
for (int i = 0; i < arrmessage.length; i++) {
file.write(arrmessage[i] + "\r\n");
}
file.flush();
file.close();
} catch (Exception eee) {
message = eee.getMessage();
}
return "Connection Failed";
}
}
}
Stack Trace Execption on my Server
javax.net.ssl.SSLHandshakeException: null cert chain
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1937)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:302)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:292)
at sun.security.ssl.ServerHandshaker.clientCertificate(ServerHandshaker.java:1804)
at sun.security.ssl.ServerHandshaker.processMessage(ServerHandshaker.java:222)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:957)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:892)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1050)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1363)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1391)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1375)
at serverapplicationssl.ServerApplicationSSL.main(ServerApplicationSSL.java:69)
Stack Trace Execption on my client
Received fatal alert: bad_certificate
sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.Alerts.getSSLException(Unknown Source)
sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source)
sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
SSLConnect.MakeSSlCall(SSLConnect.java:96)
BankCollectSSLCon.main(BankCollectSSLCon.java:13)
What could be causing this error?, could it be because i am running both the server and the client on the same machine?...Been on this for quite a while now. i need help
Please try to include this code snippet so that all the certificates will be trusted.
public static void trustSelfSignedSSL() {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
X509TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] xcs, String string)
throws CertificateException {}
public void checkServerTrusted(X509Certificate[] xcs, String string)
throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
ctx.init(null, new TrustManager[] { tm }, null);
SSLContext.setDefault(ctx);
} catch (Exception ex) {
// LOGGER.error("Exception : ", ex.getStackTrace());
System.out.println(ex.getStackTrace());
}