Friday, January 20, 2017

Linux: java SSL socket connections sample code

1. The SSL server

public class SSLServer {
    public static void main(String args[]) {
        //set which keystore to use
        System.setProperty("javax.net.ssl.keyStore", "<path>/<keystore file name>");
        System.setProperty("javax.net.ssl.keyStorePassword", "<keystore password>");

        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                  public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                  public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
                  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                  }
             }};

             //Load the keystore
             KeyStore ks = KeyStore.getInstance("JKS");
             InputStream readCert = new FileInputStream("<path>/<keystore file name>");
             try {
                  ks.load(readCert, "<keystore password>".toCharArray());
              } finally {
                  readCert.close();
              }

              //Initialize the KeyManagerFactory
              KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
              kmf.init(ks, "<keystore password>".toCharArray());

              //Initialize the SSLContext
              SSLContext sc = SSLContext.getInstance("TLSv1.2");
              sc.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

              //Create the SSLServerSocket
              SSLServerSocket serverSocket = (SSLServerSocket) sc.getServerSocketFactory().createServerSocket(csServerPort);
              serverSocket.setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2", "SSLv3"});

            while (true) {
                //accept connections from client
                Socket s = ss.accept();

                //the reader
                BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //the wirter
                PrintStream out = new PrintStream(s.getOutputStream());
                String message;
                while (!(message = in.readLine()).equals("end")) {
                      if (message.equals("Got it?")){
                            out.println("Yes, received.");
                      } else if (message.equals("Hello")) {
                            out.println("Hi");
                      } else if (message.equals("Thanks")){
                            out.println("end");
                      }
                }
                out.close();
                s.close();
            }
        } catch (IOException e) {
            e.printStackTrace(System.out);
        }
    }
}

2. The SSL Client

public class SSLClient {
    public static void main(String args[]) throws Exception {
          System.setProperty("javax.net.ssl.trustStore", "<path>/<truststore file name>");
          System.setProperty("javax.net.ssl.keyStorePassword", "<truststore password>");

          // Create a trust manager that does not validate certificate chains
          TrustManager[] trustManagers = new TrustManager[]{new X509TrustManager() {
                  public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) { }
                  public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {}
                  public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                         return null;
                  }
             }};

             //Load the keystore
             KeyStore ks = KeyStore.getInstance("JKS");
             FileInputStream readCert = new FileInputStream("<path>/<truststore file name>");
             try {
                  ks.load(readCert, "<truststore password>".toCharArray());
              } finally {
                  readCert.close();
              }

              //Initialize the KeyManagerFactory
              KeyManagerFactory kmf = KeyManagerFactory.getInstance(
                    KeyManagerFactory.getDefaultAlgorithm());
              kmf.init(ks, "<truststore password>".toCharArray());

              //Initialize the SSLContext
              SSLContext sc = SSLContext.getInstance("TLSv1.2");
              sc.init(kmf.getKeyManagers(), trustManagers, new SecureRandom());

              SSLSocketFactory socketFactory = sc.getSocketFactory(); 
              SSLSocket socket = (SSLSocket)socketFactory.createSocket("<server IP>", <port>);               
              socket.setEnabledCipherSuites(socket.getSupportedCipherSuites());

              // SSLSession session = socket.getSession();
              // Certificate[] cchain = session.getPeerCertificates();
              //System.out.println("The Certificates used by peer");
              //for (int i = 0; i < cchain.length; i++) {
                   //  System.out.println(((X509Certificate) cchain[i]).getSubjectDN());
              // }
              // System.out.println("Peer host is " + session.getPeerHost());
              // System.out.println("Cipher is " + session.getCipherSuite());
              // System.out.println("Protocol is " + session.getProtocol());
              // System.out.println("ID is " + new BigInteger(session.getId()));
              //System.out.println("Session created in " + session.getCreationTime());
              // System.out.println("Session accessed in " + session.getLastAccessedTime());

              PrintStream out = new PrintStream(s.getOutputStream());
              out.println("Hello");
             BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
             String x;
             while(!(x = in.readLine()).equals("end")){
                   System.out.println(x);
                   if (x.equals("Hi")){
                        out.println("Got it?");
                   } else if (x.equals("Yes, received.")){
                       out.println("Thanks");
                   }
             }
             out.println("end");
             in.close();
             out.close();
            s.close();
      }
}

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.



No comments:

Post a Comment