import java.io.FileInputStream; import java.net.ServerSocket; import java.net.Socket; import java.security.KeyStore; import javax.net.ServerSocketFactory; import javax.net.SocketFactory; import javax.net.ssl.SSLSocket; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; /* * Created on 28 oct. 2004 */ public class CommonSocketFactory { public static final boolean USE_SSL = false; public static final int PORT = 5555; public static final String KEYSTORE_SERVER_FILE = "server_keystore"; public static final String KEYSTORE_CLIENT_FILE = "client_keystore"; public static final String ALGORITHM = "sunx509"; public static final String PASSWORD = "master1"; public ServerSocket createServerSocket( boolean ssl){ ServerSocket s = null; try{ if (ssl){ //creation d'une socket serveur cryptee System.out.println("creation d'une socket serveur cryptee"); SSLContext sslc = getSSLContext(KEYSTORE_SERVER_FILE); ServerSocketFactory ssf = sslc.getServerSocketFactory(); return ssf.createServerSocket( PORT); } System.out.println("creation d'une socket serveur non cryptee"); s = new ServerSocket(PORT); } catch (Exception e){ System.out.println(e); } return s; } public Socket createClientSocket( String host, boolean ssl){ Socket s = null; try{ if (ssl){ //creation d'une socket serveur cryptee System.out.println("creation d'une socket client cryptee"); SSLContext sslc=getSSLContext(KEYSTORE_CLIENT_FILE); SocketFactory sf = sslc.getSocketFactory(); return (SSLSocket) sf.createSocket( host, PORT); } System.out.println("creation d'une socket client non cryptee"); s=new Socket(host, PORT); } catch (Exception e){System.out.println(e);} return s; } public SSLContext getSSLContext( String keystore_file ){ SSLContext sslc = null; try{ KeyManagerFactory kmf = KeyManagerFactory.getInstance( ALGORITHM ); KeyStore ks = KeyStore.getInstance("JKS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(ALGORITHM); sslc = SSLContext.getInstance("TLS"); ks.load(new FileInputStream( keystore_file), PASSWORD.toCharArray()); kmf.init(ks, PASSWORD.toCharArray()); tmf.init(ks); KeyManager[] km = kmf.getKeyManagers() ; TrustManager[] tm = tmf.getTrustManagers() ; sslc.init(km, tm,null); } catch (Exception e){System.out.println(e);} return sslc; } }