title: How to simply generate SSL certificate and ServerSocket form Java code
body: <p>Is there simply way to dinamic generate untrusted ssl certificate without domain and applay it to server socket - all from code, no commandline or additional files?</p>
  
  <p>Purpose is secure connection between two hosts witch know only IP and port to communicate each other - certificates generated randomly at server start and used as "untrusted", no domain so no verification (if I'm not wrong). I think this can be usefull in secureing data transfer between datacenters in third party apps.</p>
  
  <p>This is working code for not encrypted simply client-server test.</p>
  
  <pre><code>package study.benchmark.utils;
  
  import java.io.IOException;
  import java.io.InputStream;
  import java.io.OutputStream;
  import java.net.ServerSocket;
  import java.net.Socket;
  import javax.net.ServerSocketFactory;
  import javax.net.SocketFactory;
  import org.junit.Test;
  
  public class DynamicSSLTest {
  
      @Test
      public void sslServerSocketTest() throws Exception {
  
          System.out.println("ssl server test");
  
          final int port = 8750;
  
          // server
  
          Thread th = new Thread() {
  
              @Override
              public void run() {
  
                  try {
                      //ServerSocketFactory factory = SSLServerSocketFactory.getDefault();
                      ServerSocketFactory factory = ServerSocketFactory.getDefault();
  
                      ServerSocket server = factory.createServerSocket(port);
                      Socket socket = server.accept();
  
                      OutputStream out = socket.getOutputStream();
                      out.write("some data".getBytes());
  
                      socket.close();
  
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          };
  
          th.start();
  
          //client
  
          //SocketFactory factory =  SSLSocketFactory.getDefault();
          SocketFactory factory = SocketFactory.getDefault();
  
          Socket socket = factory.createSocket("localhost", port);
          InputStream is = socket.getInputStream();
  
          StringBuffer sb = new StringBuffer();
  
          int data;
          while ((data = is.read()) &gt;= 0) {
              System.out.print((char) data);
          }
  
          System.out.println();
  
          socket.close();
  
          th.join();
      }
  
  }
  </code></pre>