I'm trying to establish a SSL Connection between an IPhone App and an Java SSLServerSocket.
My Java Server looks like that:
SSLServerSocketFactory ssf = null;
try {
// set up key manager to do server authentication
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = "passphrase".toCharArray();
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("fsKeystore"), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getServerSocketFactory();
System.out.println("Waiting for Connection");
SSLServerSocket sslsocketServer = (SSLServerSocket) ssf.createServerSocket(9999);
SSLSocket sslsocket = (SSLSocket) sslsocketServer.accept();
sslsocket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
#Override
public void handshakeCompleted(HandshakeCompletedEvent arg0) {
System.out.println("Handshake finished");
}
});
InputStream inputstream = sslsocket.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader;
bufferedreader = new BufferedReader(inputstreamreader);
String string = "";
while ((string = bufferedreader.readLine()) != null) {
string = bufferedreader.readLine();
System.out.println(System.currentTimeMillis());
System.out.println(string);
System.out.flush();
}
} catch (Exception e) {
e.printStackTrace();
}
In Objective-c I have implemented this solution:
-(id) initWithUrl: (NSString*) host onPort: (NSInteger) port withDelegate:(id<TCPDelegate>) delegate{
self = [super init];
if(self){
//initTimer
sendBuffer=[[NSMutableArray alloc]init];
NSTimer *timer =[NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:#selector(timerTick:) userInfo:nil repeats:YES];
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
[runloop addTimer:timer forMode:NSDefaultRunLoopMode];
del=delegate;
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL,(__bridge CFStringRef)host, port,&readStream,&writeStream);
iStream = (__bridge_transfer NSInputStream *)readStream;
oStream = (__bridge_transfer NSOutputStream *)writeStream;
[iStream setDelegate:self];
[oStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
[oStream open];
[iStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
[oStream setProperty:NSStreamSocketSecurityLevelNegotiatedSSL
forKey:NSStreamSocketSecurityLevelKey];
line = #"";
}
return self;
}
in the Iphone App I get
CFNetwork SSLHandshake failed (-9807)
Any Idea what the problem might be?
You may want to investigate using NSURLConnection. It has a delegate that you can use for authentication challenges.
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/URLLoadingSystem/Articles/AuthenticationChallenges.html#//apple_ref/doc/uid/TP40009507-SW3
Related
Hello i'm trying to run a SSL server and client program. I'm first creating a certificate with the cmd command "keytool -genkey -keystore mySrvKeyStore -keyalg RSA". 123456 is the password after i fill in the info. I put the certificate in the same folder as the server and client, i run the server and I get this error:
"java.lang.IllegalStateException: SSLContext is not initialized"
The server:
public class SSLServer {
private static int port = 4000;
private static SSLServerSocketFactory sf;
private static SSLServerSocket ss;
public static void StabilireConexiune(int nrPort) {
try {
sf = (SSLServerSocketFactory) SSLServer.getServerSocketFactory();
ss = (SSLServerSocket) sf.createServerSocket(nrPort);
System.out.println("Server connected ready to accept new connections at the address " + ss.getLocalPort());
String[] enable = {"TLS_DH_anon_WITH_AES_128_CBC_SHA"};
ss.setEnabledCipherSuites(enable);
String[] cipherSuites = ss.getEnabledCipherSuites();
System.out.println("CipherSuites: ");
for (int i = 0; i < cipherSuites.length; i++) {
System.out.println(cipherSuites[i]);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static SSLSocket clientSocket;
public static void ConectareClient(){
try{
clientSocket = (SSLSocket) ss.accept();
System.out.println("Client connected succesfully");
InputStream input = clientSocket.getInputStream();
InputStreamReader inputreader = new InputStreamReader(input);
BufferedReader br = new BufferedReader(inputreader);
String string = null;
while( (string = br.readLine()) != null){
System.out.println(string);
System.out.flush();
}
}catch(Exception ex){
ex.printStackTrace();
}
finally{
try{
clientSocket.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
private static ServerSocketFactory getServerSocketFactory() throws NoSuchAlgorithmException{
SSLServerSocketFactory ssf = null;
try{
KeyManagerFactory kmf;
KeyStore ks;
SSLContext ctx;
char[] passphrase = "123456".toCharArray();
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("mySrvKeystore"), passphrase);
kmf.init(ks, passphrase);
ctx.getServerSocketFactory();
return ssf;
}catch(Exception ex){
ex.printStackTrace();
}
return null;
}
public static void main(String args[]){
if(args.length != 0){
port = Integer.parseInt(args[0]);
}
StabilireConexiune(port);
while(true){
ConectareClient();
}
}}
The client:
public class SSLClient {
public static void main(String args[]) {
conectare("127.0.0.1", 4000);
}
private static SSLSocket socket;
public static void conectare(String host, int port) {
try {
SSLSocketFactory factory = (SSLSocketFactory) SSLClient.getSocketFactory();
socket = (SSLSocket) factory.createSocket(host, port);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] enable = {"TLS_DH_anon_WITH_AES_128_CBC_SHA"};
socket.setEnabledCipherSuites(enable);
String[] cipherSuites = socket.getEnabledCipherSuites();
for (int i = 0; i < cipherSuites.length; i++) {
System.out.println(cipherSuites[i]);
}
socket.addHandshakeCompletedListener(new HandshakeCompletedListener() {
public void handshakeCompleted(HandshakeCompletedEvent event) {
System.out.println("handshake done");
}
});
socket.startHandshake();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.println("Give a message to the server...");
String string = br.readLine();
out.println("Message to the server..." + string);
out.println();
out.flush();
}catch(IOException ex){
ex.printStackTrace();
}
finally{
try{
socket.close();
}catch(IOException ex){
ex.printStackTrace();
}
}
}
private static SocketFactory getSocketFactory(){
SSLSocketFactory ssf = null;
try{
SSLContext ctx;
KeyManagerFactory kmf;
KeyStore ks;
char[] passphrase = "123456".toCharArray();
ctx = SSLContext.getInstance("TLS");
kmf = KeyManagerFactory.getInstance("SunX509");
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream("mySrvKeystore"), passphrase);
kmf.init(ks, passphrase);
ctx.init(kmf.getKeyManagers(), null, null);
ssf = ctx.getSocketFactory();
return ssf;
}catch(Exception e){
e.printStackTrace();
}
return null;
}}
Please help me, what is the problem?
The error is in these two lines:
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.getServerSocketFactory();
Why does it throw this Exception? Method getServerSocketFactory() states:
Throws:
IllegalStateException - if the SSLContextImpl requires initialization and the init() has not been called
In the client, you do indeed call ctx.init(kmf.getKeyManagers(), null, null); before you call ctx.getServerSocketFactory();
But in the server you do not call this - you only initialise the KeyManagerFactory.
I am trying to send data from my client to my server. Therefore I am using TSL.
I created the certificates and these are loaded without any troubles.
The connection is established, but the handshake between the client and the server is never called, and the handshakeCompleted is never called.
Client:
char[] password = "Password".toCharArray();
KeyStore trustStore = KeyStore.getInstance("BKS");
trustStore.load(activity.getResources().openRawResource(R.raw.truststore), password);
Log.i("Update", "Loaded trust certificate");
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(trustStore);
Log.i("Update", "Loaded trustManagerFactory");
KeyStore keyStore = KeyStore.getInstance("BKS");
keyStore.load(activity.getResources().openRawResource(R.raw.keystore), password);
Log.i("Update", "Loaded key certificate");
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
Log.i("Update", "Loaded keyManagerFactory");
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
Log.i("Update", "Loaded SSLContext");
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(InetAddress.getByName(host), port);
Log.i("Update", "Loaded SSL
socket.addHandshakeCompletedListener(new HandshakeCompletedListener(){
#Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent){
try{
Log.i("Update", "Did handshake");
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
Log.i("Update", "Writer");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("Update", "Reader");
while(isRunning){
try{
writer.println("Test");
writer.flush();
Log.i("DATA", "DATA SENT");
}catch(Exception e){
e.printStackTrace();
}
}
writer.close();
reader.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
socket.startHandshake();
Server:
char[] password = "Password".toCharArray();
KeyStore keyStore = KeyStore.getInstance("JKS");
keyStore.load(getClass().getResourceAsStream("/security/keystore.jks"), password);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(7826);
System.out.println("Accepting connections now...");
while(true){
SSLSocket socket = (SSLSocket) serverSocket.accept();
socket.setUseClientMode(false);
socket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while(running){
if(!socket.isConnected() || socket.isClosed()){
disconnect();
return;
}
for(Iterator<String> pendingIterator = pendingMessages.iterator(); pendingIterator.hasNext();){
String message = pendingIterator.next();
pendingIterator.remove();
writer.println(message); writer.flush();
}
//Auto decrypt when message arrives, but no thread blocking
if(reader.ready()){
String line = reader.readLine();
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
});
socket.startHandshake();
}
As you can see I am waiting on both sides for the handshakeComplete, using it only on the client or only on the server side doesn't work either
Am trying to establish an SSL Connection between a client and a server. But anytime time i try to connect from my client, i get a javax.net.ssl.SSLHandshakeException: no cipher suites in common no cipher suites in common error on my server. I have generated a keystore with signed certificates and i am referencing the keystore on both my client and server. I have gotten fed up after numerous research on this issue and related post on this site hasn't been helpful.
Here is my Server code
public class ServerApplicationSSL {
public static void main(String[] args) {
boolean debug = true;
System.out.println("Waiting For Connection");
int intSSLport = 4444;
{
Security.addProvider(new Provider());
//Security.addProvider(new BouncyCastleProvider());
//System.setProperty("javax.net.ssl.keyStore","C:\\SSLCERT\\NEWAEDCKSSKYE");
//System.setProperty("javax.net.ssl.keyStorePassword", "skyebank");
}
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\\NEWAEDCKSSKYE"), "skyebank".toCharArray());
file.write("Incoming Connection\r\n");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
.getDefaultAlgorithm());
kmf.init(keystore, "skyebank".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
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);
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
SSLServerSocket server_socket = (SSLServerSocket) sslServerSocket;
server_socket.setNeedClientAuth(true);
sslSocket.startHandshake();
System.out.println("Connection Accepted");
file.write("Connection Accepted\r\n");
while (true) {
PrintWriter out = new PrintWriter(sslSocket.getOutputStream(), true);
//BufferedReader in = new BufferedReader(new InputStreamReader(sslSocket.getInputStream()));
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");
System.out.println(exp.getStackTrace() + "\r\n");
file.write(exp.getMessage() + "\r\n");
file.flush();
file.close();
} catch (Exception eee) {
//message = eee.getMessage();
}
}
}
}
Here is my clients code
public String MakeSSlCall(String meternum) {
String message = "";
FileWriter file = null;
try {
file = new FileWriter("C:\\SSLCERT\\ClientJavalog.txt");
} catch (Exception ee) {
message = ee.getMessage();
}
try {
file.write("KeyStore Generated\r\n");
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("C:\\SSLCERT\\NEWAEDCKSSKYE"), "skyebank".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, "skyebank".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(keystore);
file.write("KeyStore Stored\r\n");
SSLContext context = SSLContext.getInstance("SSL");
TrustManager[] trustManagers = tmf.getTrustManagers();
KeyManager[] AllKeysMan = kmf.getKeyManagers();
file.write("Key Manager Length is " + AllKeysMan.length + "\r\n");
for (int i = 0; i < AllKeysMan.length; i++) {
file.write("Key Manager At This Point is " + AllKeysMan[i] + "\r\n");
}
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", 4444);
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";
}
}
}
can someone please tell me what am doing wrong?
You will have to use SSLContext for this purpose. Check out the sample code which I implemented in one of my applications below. Client context means you become the client and call some back end. Server context means you accept the client requests.
public class SSLUtil {
private static String KEY_STORE_TYPE = "JKS";
private static String TRUST_STORE_TYPE = "JKS";
private static String KEY_MANAGER_TYPE = "SunX509";
private static String TRUST_MANAGER_TYPE = "SunX509";
private static String PROTOCOL = "TLS";
private static SSLContext serverSSLCtx = null;
private static SSLContext clientSSLCtx = null;
public static SSLContext createServerSSLContext(final String keyStoreLocation,
final String keyStorePwd)
throws KeyStoreException,
NoSuchAlgorithmException,
CertificateException,
FileNotFoundException,
IOException,
UnrecoverableKeyException,
KeyManagementException {
if (serverSSLCtx == null) {
KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE);
keyStore.load(new FileInputStream(keyStoreLocation), keyStorePwd.toCharArray());
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KEY_MANAGER_TYPE);
keyManagerFactory.init(keyStore, keyStorePwd.toCharArray());
serverSSLCtx = SSLContext.getInstance(PROTOCOL);
serverSSLCtx.init(keyManagerFactory.getKeyManagers(), null, null);
}
return serverSSLCtx;
}
public static SSLContext createClientSSLContext(final String trustStoreLocation,
final String trustStorePwd)
throws KeyStoreException,
NoSuchAlgorithmException,
CertificateException,
FileNotFoundException,
IOException,
KeyManagementException {
if (clientSSLCtx == null) {
KeyStore trustStore = KeyStore.getInstance(TRUST_STORE_TYPE);
trustStore.load(new FileInputStream(trustStoreLocation), trustStorePwd.toCharArray());
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TRUST_MANAGER_TYPE);
trustManagerFactory.init(trustStore);
clientSSLCtx = SSLContext.getInstance(PROTOCOL);
clientSSLCtx.init(null, trustManagerFactory.getTrustManagers(), null);
}
return clientSSLCtx;
}
}
Finally make sure you import the trusted server certificate to the client key store. Literally server and client should have different key stores. The key store used in the client side is referred to as client trust store since we are trusting the server certificate here. This article may help.
I want to create an app use SSLSocket: client send a String to server and server will uppercase that String and send back to client for display.
SSLServer
public class SSLServer {
public static void main(String args[]) throws Exception
{
try{
//Creaet a SSLServersocket
SSLServerSocketFactory factory=(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslserversocket=(SSLServerSocket) factory.createServerSocket(1234);
//Tạo 1 đối tượng Socket từ serversocket để lắng nghe và chấp nhận kết nối từ client
SSLSocket sslsocket=(SSLSocket) sslserversocket.accept();
//Tao cac luong de nhan va gui du lieu cua client
DataInputStream is=new DataInputStream(sslsocket.getInputStream());
PrintStream os=new PrintStream(sslsocket.getOutputStream());
while(true) //khi dang ket noi voi client
{
//Doc du lieu den
String input=is.readUTF();
String ketqua=input.toUpperCase();
//Du lieu tra ve
os.println(ketqua);
}
}
catch(IOException e)
{
System.out.print(e);
}
}
}
SSLClient
public class SSLClient {
public static void main(String args[])
{
try
{
//Mo 1 client socket den server voi so cong va dia chi xac dinh
SSLSocketFactory factory=(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslsocket=(SSLSocket) factory.createSocket("127.0.0.1",1234);
//Tao luong nhan va gui du lieu len server
DataOutputStream os=new DataOutputStream(sslsocket.getOutputStream());
DataInputStream is=new DataInputStream(sslsocket.getInputStream());
//Gui du lieu len server
String str="helloworld";
os.writeBytes(str);
//Nhan du lieu da qua xu li tu server ve
String responseStr;
if((responseStr=is.readUTF())!=null)
{
System.out.println(responseStr);
}
os.close();
is.close();
sslsocket.close();
}
catch(UnknownHostException e)
{
System.out.println(e.getMessage());
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
When run SSLServer. It displays this error:
javax.net.ssl.SSLException: No available certificate or key corresponds
to the SSL cipher suites which are enabled
I have search and do some ways but.. Can you help me.
This will generate certificate:
keytool -genkey -keystore yourKEYSTORE -keyalg RSA
Enter yourPASSWORD and than start your server with ssl debug information(put yourKEYSTORE into directory with SSLServer.class):
java -Djavax.net.ssl.keyStore=yourKEYSTORE -Djavax.net.ssl.keyStorePassword=yourPASSWORD -Djava.protocol.handler.pkgs=com.sun.net.ssl.internal.www.protocol -Djavax.net.debug=ssl SSLServer
Than start your client(put yourKEYSTORE into directory with SSLClient.class):
java -Djavax.net.ssl.trustStore=yourKEYSTORE -Djavax.net.ssl.trustStorePassword=yourPASSWORD SSLClient
#corVaroxid's answer is right. But if you want to set configurations programmatically to avoid global settings (like me), you can go like below (Kotlin):
val password = "yourPassword".toCharArray()
val keyStore = KeyStore.getInstance(File("yourKeystorePath.jks"), password)
val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)
val keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509")
keyManagerFactory.init(keyStore, password)
val context = SSLContext.getInstance("TLS") //"SSL" "TLS"
context.init(keyManagerFactory.keyManagers, trustManagerFactory.trustManagers, null)
val factory = context.serverSocketFactory
(factory.createServerSocket(LISTENING_PORT) as SSLServerSocket).use { serverSocket ->
logger.trace("Listening on port: $LISTENING_PORT")
// ...
}
Or in Java:
final char[] password = "yourPassword".toCharArray();
final KeyStore keyStore = KeyStore.getInstance(new File("yourKeystorePath.jks"), password);
final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
final KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("NewSunX509");
keyManagerFactory.init(keyStore, password);
final SSLContext context = SSLContext.getInstance("TLS");//"SSL" "TLS"
context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
final SSLServerSocketFactory factory = context.getServerSocketFactory();
try (SSLServerSocket serverSocket = ((SSLServerSocket) factory.createServerSocket(LISTENING_PORT))) {
logger.trace("Listening on port: " + LISTENING_PORT);
// ...
}
Check the certificates that you have installed. Make sure they are supporting the cipher suites that you are negotiating.
I am using the p12 file to connect to APN server using java code but am getting error:javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure
Code:
private String token="c585ca35 21468c52 e7285b15 5441fcd3 77b50594 c05000c1 165aa025a87a1660";
private String host = "gateway.sandbox.push.apple.com";
private int port = 2195;
private String payload = "{\"aps\":{\"alert\":\"Message from Java o_O\"}}";
try {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(getClass().getResourceAsStream("E://workspace//Product//javatest//lib//Certificates_key.p12"), "ducont".toCharArray());
// keyStore.load(getClass().getResourceAsStream("Certificates_key.p12"), "ducont".toCharArray());
KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance("SunX509");
keyMgrFactory.init(keyStore, "ducont".toCharArray());
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyMgrFactory.getKeyManagers(), null, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
String[] cipherSuites = sslSocket.getSupportedCipherSuites();
sslSocket.setEnabledCipherSuites(cipherSuites);
sslSocket.startHandshake();
char[] t = token.toCharArray();
byte[] b = Hex.decodeHex(t);
OutputStream outputstream = sslSocket.getOutputStream();
outputstream.write(0);
outputstream.write(0);
outputstream.write(32);
outputstream.write(b);
outputstream.write(0);
outputstream.write(payload.length());
outputstream.write(payload.getBytes());
outputstream.flush();
outputstream.close();
} catch (Exception exception) {
exception.printStackTrace();
}