javax.net.ssl.SSLHandshakeException: null cert chain - java

Can anybody tell me what exactly is the cause of the error?. Am trying to establish an SSL connection to a server. But connection is always failing. After requesting for logs from the server guys, i can see javax.net.ssl.SSLHandshakeException: null cert chain on their error logs. i have been trying to research what this error is and what could cause it but to no avail. i would appreciate it if someone could give me a detailed explanation on what this error is and what could cause it.
Between here is my client code i am using to connect to the server
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\\newclientkeystore"), "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");
file.flush();
file.close();
} catch (Exception eee) {
message = eee.getMessage();
}
return "Connection Failed";
}
}
}
My Keytool commands for generating a Truststore and importing the servers certificate and my own certificate
Keytool commands for creating my truststore
keytool -import -alias client -file client.cer -keystore MyKeystore -storepass mystore
keytool -import -alias server -file server.cer -keystore MyKeystore -storepass mystore

Related

Java HTTPS Server "Unsupported Protocol Error" in Chrome

I'm making a custom HTTP/1.1 server implementation in Java. It's working fine in HTTP mode, but I also want to support HTTPS. I haven't generated a certificate for the server yet, but it should at least be trying to connect. I set the protocol and cipher suite to the same settings as google.com (TLS 1.2, ECDHE_RSA, AES_128_GCM), so I know Chrome supports them.
But when I try to connect to https://localhost in Chrome, it gives ERR_SSL_VERSION_OR_CIPHER_MISMATCH (localhost uses an unsupported protocol) error. On the Java side, I get "no cipher suites in common" error.
Java Code:
public class Server {
private final String dir;
private final ServerSocket server;
private final SSLServerSocket sslServer;
public static String jarDir() {
String uri = ClassLoader.getSystemClassLoader().getResource(".").getPath();
try { return new File(URLDecoder.decode(uri,"UTF-8")).getPath()+File.separator; }
catch (Exception e) { return null; }
}
private static SSLContext createSSLContext(String cert, char[] pass) throws Exception {
/*//Load KeyStore in JKS format:
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(new FileInputStream(cert), pass);
//Create key manager:
KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("SunX509");
kmFactory.init(keyStore, pass); KeyManager[] km = kmFactory.getKeyManagers();
//Create trust manager:
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance("SunX509");
tmFactory.init(keyStore); TrustManager[] tm = tmFactory.getTrustManagers();
//Create SSLContext with protocol:
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(km, tm, null); return ctx;*/
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(null, null, null); return ctx;
}
Server(String localPath, int port) throws Exception {
this(localPath, port, 0);
}
//Server is being initialized with:
//new Server("root", 80, 443);
Server(String localPath, int port, int httpsPort) throws Exception {
dir = localPath; File fdir = new File(jarDir(), dir);
if(!fdir.isDirectory()) throw new Exception("No such directory '"+fdir.getAbsolutePath()+"'!");
//Init Server:
server = new ServerSocket(port);
if(httpsPort > 0) {
SSLContext ctx = createSSLContext("cert.jks", "pass".toCharArray());
sslServer = (SSLServerSocket)ctx.getServerSocketFactory().createServerSocket(httpsPort);
//TLS_DH_anon_WITH_AES_128_GCM_SHA256
sslServer.setEnabledCipherSuites(new String[]{"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"});
sslServer.setEnabledProtocols(new String[]{"TLSv1.2"});
//Also does not work, same error:
//sslServer.setEnabledCipherSuites(sslServer.getSupportedCipherSuites());
//sslServer.setEnabledProtocols(sslServer.getSupportedProtocols());
} else sslServer = null;
/*new Thread(() -> { while(true) try {
new HTTPSocket(server.accept(), this);
} catch(Exception e) { Main.err("HTTP Server Error",e); }}).start();*/
if(httpsPort > 0) new Thread(() -> { while(true) try {
new HTTPSocket(sslServer.accept(), this);
} catch(Exception e) { Main.err("HTTPS Server Error",e); }}).start();
}
/* ... Other Stuff ... */
}
EDIT: I generated a certificate using keytool -genkey -keyalg RSA -alias selfsigned -keystore cert.jks -storepass password -validity 360 -keysize 2048, but now Java throws Keystore was tampered with, or password was incorrect error.
Like I said in the comments, using "password" in keyStore.load solved the issue.
private static SSLContext createSSLContext(String cert, char[] pass) throws Exception {
//Load KeyStore in JKS format:
KeyStore keyStore = KeyStore.getInstance("jks");
keyStore.load(new FileInputStream(cert), "password".toCharArray());
//Create key manager:
KeyManagerFactory kmFactory = KeyManagerFactory.getInstance("SunX509");
kmFactory.init(keyStore, pass); KeyManager[] km = kmFactory.getKeyManagers();
//Create trust manager:
TrustManagerFactory tmFactory = TrustManagerFactory.getInstance("SunX509");
tmFactory.init(keyStore); TrustManager[] tm = tmFactory.getTrustManagers();
//Create SSLContext with protocol:
SSLContext ctx = SSLContext.getInstance("TLSv1.2");
ctx.init(km, tm, null); return ctx;
}

javax.net.ssl.SSLHandshakeException: null cert chain null cert chain

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
#WiteCastle Yes I did, and trust me i had a real unpleasant experience finding out what the issue was. Before i paste my snippet of code, let me start by explaining the SSL Communication.SSL Connection between client and Server.
Client Says Hello
Server says Hello.
Server Presents. Certificate for Validation.
Client checks if certificate is in its TrustStore.
Server request for client certificate.
Client presents certificate for server to validate.
If the clients certificate passes validation communication can now
occur.
So the javax.net.ssl.SSLHandshakeException: null cert chain error happens when the client certificate failed validation on the server and javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate happens when server cannot find the certificate the client presented in its truststore.
So what i did was
For The Client
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");
}
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keystore, KeystorePassword.toCharArray());
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(kmf.getKeyManagers(), 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";
}
}
}
For Server
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());
TrustManagerFactory tmf =TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
file.write("KeyStore Stored\r\n");
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), trustManagers, 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();
}
}
}
}

Received fatal alert, bad_certificate

I am trying to make an SSL conection to a server. I have created a Truststore and imported the server's certificate as well as mine as trusted entries into the Keystore. The server guys also have imported my certificate into their keystore. But when i try to connect, i get this error:
Received fatal alert: bad_certificate
On the server, they are getting this error:
javax.net.ssl.SSLHandshakeException: null cert chain
What could i be possibly be doing wrong?, How do i fix this error? I have been battling this issue for a very long time now.
My Client 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\\newclientkeystore"), "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");
file.flush();
file.close();
} catch (Exception eee) {
message = eee.getMessage();
}
return "Connection Failed";
}
}
}
Keytool commands for creating my truststore
keytool -import -alias client -file client.cer -keystore MyKeystore -storepass mystore
keytool -import -alias server -file server.cer -keystore MyKeystore -storepass mystore
And i have also added the two certificates to my cacerts keystore
It's been a while, but I had to face similar issue. Here is my working code:
Properties systemProps = System.getProperties();
systemProps.put("javax.net.debug","ssl");
systemProps.put("javax.net.ssl.trustStore","<path to trustore>");
systemProps.put("javax.net.ssl.trustStorePassword","password");
System.setProperties(systemProps);
SSLContext sslcontext;
KeyStore keyStore;
final char[] JKS_PASSWORD = "password".toCharArray();
final char[] KEY_PASSWORD = "password".toCharArray();
try {
final InputStream is = new FileInputStream("<path_to_keystore.pkcs12>");
keyStore = KeyStore.getInstance("pkcs12");
keyStore.load(is, JKS_PASSWORD);
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keyStore, KEY_PASSWORD);
sslcontext=SSLContext.getInstance("TLS");
sslcontext.init(kmf.getKeyManagers(), null, new java.security.SecureRandom());
} catch (Exception ex) {
throw new IllegalStateException("Failure initializing default SSL context", ex);
}
SSLSocketFactory sslsocketfactory = sslcontext.getSocketFactory();
DataOutputStream os = null;
try {
SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket();
sslsocket.connect(new InetSocketAddress(host, port), connectTimeout);
sslsocket.startHandshake();
os = new DataOutputStream(sslsocket.getOutputStream());
// log.info("Sending echo packet");
String toSend = "{\"echo\":\"echo\"}";
os.writeBytes(toSend);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Java Web Sockets with SSL - SSLHandshakeException - no cipher suites in common

I am trying to create web socket server in Java which can accept connections from web clients (using Https). When open URL "https://localhost:8887" in chrome, Java application throws error: javax.net.ssl.SSLHandshakeException: no cipher suites in common. Below are the steps I have followed.
1) First I have created a keystore using following command (as mentioned # https://github.com/TooTallNate/Java-WebSocket/issues/160):
keytool -genkey -validity 3650 -keystore "keystore.jks" -storepass "storepassword" -keypass "keypassword" -alias "default" -dname "CN=127.0.0.1, OU=MyOrgUnit, O=MyOrg, L=MyCity, S=MyRegion, C=MyCountry"
2) Below is my Java web socket server creation code:
public class SocketServer extends WebSocketServer {
/** The web socket port number */
private static int PORT = 8887;
private static volatile SocketServer socketServer = null;
/**
* private constructor Creates a new WebSocketServer with the wildcard IP
* accepting all connections.
*/
private SocketServer() {
super(new InetSocketAddress(PORT));
}
/**
* Get singleton instance of Socket Server class
*/
public static SocketServer getInstance() {
if (socketServer == null) {
synchronized (SocketServer.class) {
// Double check
if (socketServer == null) {
WebSocketImpl.DEBUG = true;
socketServer = new SocketServer();
// load up the key store
String STORETYPE = "JKS";
String KEYSTORE = "keystore.jks";
String STOREPASSWORD = "storepassword";
String KEYPASSWORD = "keypassword";
try {
KeyStore ks = KeyStore.getInstance( STORETYPE );
File kf = new File( KEYSTORE );
ks.load( new FileInputStream( kf ), STOREPASSWORD.toCharArray() );
KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
kmf.init( ks, KEYPASSWORD.toCharArray() );
TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
tmf.init( ks );
SSLContext sslContext = null;
sslContext = SSLContext.getInstance( "TLS" );
sslContext.init( kmf.getKeyManagers(), tmf.getTrustManagers(), null );
socketServer.setWebSocketFactory( new DefaultSSLWebSocketServerFactory( sslContext ) );
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
socketServer.start();
}
}
}
return socketServer;
}
Please suggest what could be the issue?
Thanks in advance!

RMI with SSL: Failed handshake

I'm writing a Client Server application with RMI and I want to secure the traffic between Client and Server. I want to use the SslRMIClientSocketFactory and SslRMIServerSocketFactory for this.
I've created a keypair for the Client and for the Server (client.private and server.private) and also a certificate for the Client and for the Server (client.public and server.public).
I think I'm correctly adding the keypair to the keystore and the certificate to the truststore. I only use the custom Socket Factory's when exporting my objects, not when I'm creating the RMI Registry. Here's my code:
Server:
public class Server implements ServerProtocol {
public Server() {
super();
SecureRandom sr = new SecureRandom();
sr.nextInt();
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
FileInputStream client = new FileInputStream("src/client.public");
String passphrase = //
clientKeyStore.load(client, passphrase.toCharArray());
client.close();
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
FileInputStream server = new FileInputStream("src/server.private");
String password = //
serverKeyStore.load(server, password.toCharArray());
server.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(clientKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(serverKeyStore, password.toCharArray());
SSLContext SSLC = SSLContext.getInstance("TLS");
SSLC.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(null, null, true);
LocateRegistry.createRegistry(2020).rebind("server", this);
UnicastRemoteObject.exportObject(this, 2020, csf, ssf);
}
public void sayHello() {
System.out.println("Hello");
}
}
Client:
public class Client implements ClientProtocol {
public Client() {
SecureRandom sr = new SecureRandom();
sr.nextInt();
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
FileInputStream server = new FileInputStream("src/server.public");
String passphrase = //
serverKeyStore.load(server, passphrase.toCharArray());
server.close();
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
FileInputStream client = new FileInputStream("src/client.private");
String password = //
clientKeyStore.load(client, password.toCharArray());
client.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(clientKeyStore, password.toCharArray());
SSLContext SSLC = SSLContext.getInstance("TLS");
SSLC.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
SslRMIClientSocketFactory csf = new SslRMIClientSocketFactory();
SslRMIServerSocketFactory ssf = new SslRMIServerSocketFactory(null, null, true);
Registry reg = LocateRegistry.getRegistry("localhost", 2020);
serverStub = (ServerService) reg.lookup("server");
stub = (ClientService) UnicastRemoteObject.exportObject(this, 2020, csf, ssf);
serverStub.sayHello();
}
}
When I run this, I get the following error message:
javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:136)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1822)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1004)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1188)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.writeRecord(SSLSocketImpl.java:654)
at com.sun.net.ssl.internal.ssl.AppOutputStream.write(AppOutputStream.java:100)
at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:65)
at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:123)
at java.io.DataOutputStream.flush(DataOutputStream.java:106)
at sun.rmi.transport.tcp.TCPChannel.createConnection(TCPChannel.java:211)
at sun.rmi.transport.tcp.TCPChannel.newConnection(TCPChannel.java:184)
at sun.rmi.server.UnicastRef.invoke(UnicastRef.java:110)
at java.rmi.server.RemoteObjectInvocationHandler.invokeRemoteMethod(RemoteObjectInvocationHandler.java:178)
at java.rmi.server.RemoteObjectInvocationHandler.invoke(RemoteObjectInvocationHandler.java:132)
at com.sun.proxy.$Proxy0.sayHello(Unknown Source)
at project.Client.<init>(Client.java:100)
at project.Client.main(Client.java:785)
I used the following commands to create the keys, export and import them:
keytool -genkey -alias clientprivate -keystore client.private -storetype JKS -keyalg rsa -storepass * -keypass * -validity 360
keytool -genkey -alias serverprivate -keystore server.private -storetype JKS -keyalg rsa -storepass * -keypass * -validity 360
keytool -export -alias clientprivate -keystore client.private -file temp.key -storepass *
keytool -import -noprompt -alias clientpublic -keystore client.public -file temp.key -storepass *
keytool -export -alias serverprivate -keystore server.private -file temp.key -storepass *
keytool -import -noprompt -alias serverpublic -keystore server.public -file temp.key -storepass *
Do I need to configure something else to make this work? Something in Eclipse?
You're creating the Registry with SSL socket factories but you're not supplying a socket factory to getRegistry().
I was able to solve this by avoiding the build-in Java classes SslRMIClientSocketFactory and SslRMIServerSocketFactory and creating my own classes which implement the RMIClientSocketFactory and RMIServerSocketFactory interfaces.
RMIClientSocketFactory
public class MyClientSocketFactory implements RMIClientSocketFactory, Serializable {
public MyClientSocketFactory() {}
public Socket createSocket(String host, int port) {
SecureRandom sr = new SecureRandom();
sr.nextInt();
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
FileInputStream server = new FileInputStream("src/server.public");
String passphrase = //
serverKeyStore.load(server, passphrase.toCharArray());
server.close();
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
FileInputStream client = new FileInputStream("src/client.private");
String password = //
clientKeyStore.load(client, password.toCharArray());
client.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(clientKeyStore, password.toCharArray());
SSLContext SSLC = SSLContext.getInstance("TLS");
SSLC.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
SSLSocketFactory sf = SSLC.getSocketFactory();
SSLSocket socket = (SSLSocket) sf.createSocket(host, port);
return socket;
}
public int hashCode() {
return getClass().hashCode();
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || getClass() != obj.getClass()) {
return false;
}
return true;
}
}
RMIServerSocketFactory
public class MyServerSocketFactory implements RMIClientSocketFactory, Serializable {
public MyServerSocketFactory() {}
public Socket createSocket(String host, int port) {
SecureRandom sr = new SecureRandom();
sr.nextInt();
KeyStore clientKeyStore = KeyStore.getInstance("JKS");
FileInputStream client = new FileInputStream("src/client.public");
String passphrase = //
clientKeyStore.load(client, passphrase.toCharArray());
client.close();
KeyStore serverKeyStore = KeyStore.getInstance("JKS");
FileInputStream server = new FileInputStream("src/server.private");
String password = //
serverKeyStore.load(server, password.toCharArray());
server.close();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(serverKeyStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(clientKeyStore, password.toCharArray());
SSLContext SSLC = SSLContext.getInstance("TLS");
SSLC.init(kmf.getKeyManagers(), tmf.getTrustManagers(), sr);
SSLServerSocketFactory sf = SSLC.getServerSocketFactory();
SSLServerSocket socket = (SSLServerSocket) sf.createServerSocket(host, port);
return socket;
}
public int hashCode() {
return getClass().hashCode();
}
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj == null || getClass() != obj.getClass()) {
return false;
}
return true;
}
}

Categories