Java SSLServerSocket create from key store file

Description

Java SSLServerSocket create from key store file

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManagerFactory;

public class Main {
   public static void main(String[] args) {
      try {//from w w  w.j av a2 s  . c om
         char[] password = "123456".toCharArray();
         KeyStore ks = KeyStore.getInstance("JKS");
         ks.load(new FileInputStream("server.ks"), password);

         KeyStore ts = KeyStore.getInstance("JKS");
         ts.load(new FileInputStream("server.ts"), password);

         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
         kmf.init(ks, password);

         TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
         tmf.init(ts);

         SSLContext sslContext = SSLContext.getInstance("TLS");
         sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

         SSLServerSocketFactory factory = (SSLServerSocketFactory) sslContext.getServerSocketFactory();

         SSLServerSocketFactory.getDefault();
         SSLServerSocket sss = (SSLServerSocket) factory.createServerSocket(6789);
         SSLSocket ss = (SSLSocket) sss.accept();

         ss.setNeedClientAuth(true);
         BufferedReader in = new BufferedReader(new InputStreamReader(ss.getInputStream()));
         PrintWriter out = new PrintWriter(ss.getOutputStream(), true);

         String line = null;
         while ((line = in.readLine()) != null) {
            System.out.println("received<-- " + line);
            out.println(line);
            System.out.println("sent    --> " + line);
         }
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}



PreviousNext

Related