Friday 11 October 2013

Socket Server with SSL

Socket Server with SSL
import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;

public class SocketServerTest{
  public static void main(String args[]) throws Exception {
   
    
    char[] storepass = "testpass".toCharArray();
    char[] keypass = "testpass".toCharArray();
    String storename = "ServerKeystore";

    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    FileInputStream fin = new FileInputStream(storename);
    KeyStore  ks = KeyStore.getInstance("JKS");
    ks.load(fin, storepass);
    kmf.init(ks, keypass);
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory ssf = context.getServerSocketFactory();

    ServerSocket ss = ssf.createServerSocket(9999);
    while (true) 
   {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      out.print("Server Data Pushed to Client");
      out.flush();
      out.close();
      s.close();
    }

  }
}
Ref:
http://docs.oracle.com/javase/6/docs/technotes/guides/security/jsse/JSSERefGuide.html#WhySSL

No comments:

Post a Comment

Please comment here