Java SSLSocket create from key store

Description

Java SSLSocket create from key store


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.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManagerFactory;

public class Main {
   public static void main(String[] args) {
      try {//from   w  ww .  j a v a  2  s  . c  o  m
         char[] password = "123456".toCharArray();
         KeyStore ks = KeyStore.getInstance("JKS");
         ks.load(new FileInputStream("client.ks"), password);

         KeyStore ts = KeyStore.getInstance("JKS");
         ts.load(new FileInputStream("client.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);

         SSLSocketFactory factory = (SSLSocketFactory) sslContext.getSocketFactory();

         // SSLSocketFactory factory = (SSLSocketFactory)
         SSLSocketFactory.getDefault();
         SSLSocket ss = (SSLSocket) factory.createSocket(args[0], 6789);

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

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



PreviousNext

Related