Java SSL context not initialised - java

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.

Related

SSL handshakeCompleted never called

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

javax.net.ssl.SSLHandshakeException: no cipher suites in common no cipher suites in common

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.

Java multi-client socket server - starvation

Consider the following Server:
public class TestServer {
public static void main(String[] args) {
String ksName = "/some/path/keystore-server.jks";
char ksPass[] = "password".toCharArray();
char ctPass[] = "pswd".toCharArray();
KeyStore ks;
try {
ks = KeyStore.getInstance("JKS");
ks.load(new FileInputStream(ksName), ksPass);
KeyManagerFactory kmf =
KeyManagerFactory.getInstance("SunX509");
kmf.init(ks, ctPass);
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(kmf.getKeyManagers(), null, null);
SSLServerSocketFactory ssf = sc.getServerSocketFactory();
SSLServerSocket s = (SSLServerSocket) ssf.createServerSocket(SERVER_PORT);
while(true){
SSLSocket sslsocket = (SSLSocket) s.accept();
System.out.println("New Client accepted");
TestThread t = new TestThread(sslsocket);
t.run();
}
} catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyManagementException ex) {
Logger.getLogger(TotalControlServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
The above is a simple server that accepts several clients: right after accepting a new connection, a dispatch a new thread (TestThread) in order to deal with the client incoming requests. Here's the code for TestThread:
public class TestThread implements Runnable {
SSLSocket sslsocket;
public TestThread(SSLSocket sslsocket) {
this.sslsocket = sslsocket;
}
#Override
public void run() {
ObjectInputStream is = null;
ObjectOutputStream os = null;
try {
is = new ObjectInputStream(sslsocket.getInputStream());
os = new ObjectOutputStream(sslsocket.getOutputStream());
while(true){
String p = (String) is.readObject();
System.out.println("We got: " + p);
os.writeObject(p.concat(p));
os.flush();
}//while
} catch (IOException ex) {
Logger.getLogger(CmdLineService.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CmdLineService.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
os.close();
this.sslsocket.close();
} catch (IOException ex) {
Logger.getLogger(CmdLineService.class.getName()).log(Level.SEVERE, null, ex);
}
}
}//run
}
Simple enough, it just loops indefinitely reading Strings and sending back its concatenation with itself.
The client is also rather simple:
public class TestClient {
public static void main(String[] args) {
System.setProperty("javax.net.ssl.trustStore" , "/path/keystore-client.jks") ;
ObjectOutputStream os = null;
ObjectInputStream is = null;
SSLSocket sslsocket = null;
try {
SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getDefault();
sslsocket = (SSLSocket) f.createSocket("localhost", SERVER_PORT);
sslsocket.startHandshake();
System.out.println("Authentication done");
os = new ObjectOutputStream(sslsocket.getOutputStream());
is = new ObjectInputStream(sslsocket.getInputStream());
BufferedReader b = new BufferedReader(new InputStreamReader(System.in));
boolean exit = false;
while(!exit){
System.out.print("> ");
String line = b.readLine();
os.writeObject(line);
os.flush();
String s = (String) is.readObject();
System.out.println(s);
}//while
} //main
catch (IOException ex) {
Logger.getLogger(TotalControlCmdClient.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
is.close();
sslsocket.close();
} catch (IOException ex) {
Logger.getLogger(TestClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Just loops indefinitely sending strings and reading a string.
This works fine for one client.. However, if I start another client, it does not connect! It seems that I'm facing some kind of thread starvation issue..
How can I fix that?
The reason is simple: You never start a second listener Thread:
while(true){
SSLSocket sslsocket = (SSLSocket) s.accept();
System.out.println("New Client accepted");
TestThread t = new TestThread(sslsocket);
t.run();
}
Calling run() does not start the Thread, that is done using start().
Therefore the main thread is processing the content of the run() method and as it is busy you can not connect using a second client.
Change t.run() to t.start and everything will be fine.

SSL Connection between IPhone App and Java ServerSocket

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

APN push notification from java server?

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();
}

Categories

Resources