Mega Code Archive

 
Categories / Java Tutorial / Security
 

Sun SSL Socket Client

import java.io.*; import java.net.*; import java.security.*; import javax.net.ssl.SSLSocketFactory; import com.sun.net.ssl.SSLContext; import com.sun.net.ssl.TrustManagerFactory; import com.sun.net.ssl.TrustManager; public class MainClass {   private static final String HOST = "localhost";   private static final int PORT = 8080;   public static void main(String[] args) throws Exception {     char[] passphrase = "sasquatch".toCharArray();     KeyStore keystore = KeyStore.getInstance("JKS");     keystore.load(new FileInputStream(".keystore"), passphrase);     TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");     tmf.init(keystore);     SSLContext context = SSLContext.getInstance("TLS");     TrustManager[] trustManagers = tmf.getTrustManagers();     context.init(null, trustManagers, null);     SSLSocketFactory sf = context.getSocketFactory();     Socket s = sf.createSocket(HOST, PORT);     OutputStream out = s.getOutputStream();     out.write("\nConnection established.\n\n".getBytes());     int theCharacter = 0;     theCharacter = System.in.read();     while (theCharacter != '~') // The '~' is an escape character to exit     {       out.write(theCharacter);       out.flush();       theCharacter = System.in.read();     }     out.close();     s.close();   } }