Java Tutorial/Security/SSL Socket

Материал из Java эксперт
Перейти к: навигация, поиск

Get peer certificate from SSL session

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.security.cert.CertPath;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket("127.0.0.1", 8888);
    socket.startHandshake();
    SSLSession session = socket.getSession();
    java.security.cert.Certificate[] servercerts = session.getPeerCertificates();
    List mylist = new ArrayList();
    for (int i = 0; i < servercerts.length; i++) {
      mylist.add(servercerts[i]);
    }
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    CertPath cp = cf.generateCertPath(mylist);
    FileOutputStream f = new FileOutputStream("CertPath.dat");
    ObjectOutputStream b = new ObjectOutputStream(f);
    b.writeObject(cp);
  }
}





Retrieving the Certification Path of an SSL Server

import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class Main {
  public static void main(String[] argv) throws Exception {
    int port = 443;
    String hostname = "hostname";
    SSLSocketFactory factory = HttpsURLConnection.getDefaultSSLSocketFactory();
    SSLSocket socket = (SSLSocket) factory.createSocket(hostname, port);
    socket.startHandshake();
    // Retrieve the server"s certificate chain
    Certificate[] serverCerts = socket.getSession().getPeerCertificates();
    socket.close();
  }
}





Send html(gif) file through SSLSocket

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    FileOutputStream fouts = null;
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    OutputStream outs = s.getOutputStream();
    PrintStream out = new PrintStream(outs);
    InputStream ins = s.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(ins));
    out.println(args[0]);
    fouts = new FileOutputStream("result.html");
//  fouts = new FileOutputStream("result.gif");
    int kk;
    while ((kk = ins.read()) != -1) {
      fouts.write(kk);
    }
    in.close();
    fouts.close();
  }
}





SSL Client Demo

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();
  }
}





SSL Client Session

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    SSLSession session = ((SSLSocket) s).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());
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();
  }
}





SSL Client Verifier

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.security.cert.X509Certificate;
import sun.security.x509.X500Name;
public class MainClass {
  public static void main(String[] args) throws Exception {
    SocketFactory sf = SSLSocketFactory.getDefault();
    SSLSocket s = (SSLSocket) sf.createSocket(args[0], Integer.parseInt(args[1]));
    SSLSession sess = s.getSession();
    String host = sess.getPeerHost();
    X509Certificate[] certs = sess.getPeerCertificateChain();
    String dn = certs[0].getSubjectDN().getName();
    X500Name name = new X500Name(dn);
    if (!host.equals(name.getCommonName()))
      System.out.println("Warning: Expected " + host + " and got " + name.getCommonName());
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    pw.println("hi");
    pw.flush();
    System.out.println(br.readLine());
    s.close();
  }
}





SSL Client with javax.net.ssl.trustStore setting

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 5432);
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String x = in.readLine();
    System.out.println(x);
    in.close();
  }
}





SSLContext and Key manager

import java.io.FileInputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    SSLContext context;
    KeyManagerFactory kmf;
    KeyStore ks;
    char[] storepass = "newpass".toCharArray();
    char[] keypass = "wshr.ut".toCharArray();
    String storename = "newstore";
    context = SSLContext.getInstance("TLS");
    kmf = KeyManagerFactory.getInstance("SunX509");
    FileInputStream fin = new FileInputStream(storename);
    ks = KeyStore.getInstance("JKS");
    ks.load(fin, storepass);
    kmf.init(ks, keypass);
    context.init(kmf.getKeyManagers(), null, null);
    SSLServerSocketFactory ssf = context.getServerSocketFactory();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      out.println("Hi");
      out.close();
      s.close();
    }
  }
}





SSL Server Session

import java.io.PrintStream;
import java.math.BigInteger;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
public class MainClass {
  public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "lfkeystore2");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
      Socket s = ss.accept();
      SSLSession session = ((SSLSocket) s).getSession();
      Certificate[] cchain2 = session.getLocalCertificates();
      for (int i = 0; i < cchain2.length; i++) {
        System.out.println(((X509Certificate) cchain2[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("Hi");
      out.close();
      s.close();
    }
  }
}





SSL Server with KeyStore and Key Store Password setting

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    System.setProperty("javax.net.ssl.keyStore", "mykeystore");
    System.setProperty("javax.net.ssl.keyStorePassword", "wshr.ut");
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      out.println("Hi");
      out.close();
      s.close();
    }
  }
}





SSL Simple Client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
public class MainClass {
  public static void main(String[] args) throws Exception {
    SocketFactory sf = SSLSocketFactory.getDefault();
    Socket s = sf.createSocket(args[0], Integer.parseInt(args[1]));
    BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
    PrintWriter pw = new PrintWriter(s.getOutputStream());
    System.out.println("Who is Sylvia?");
    pw.println("Who is Sylvia?");
    pw.flush();
    System.out.println(br.readLine());
    s.close();
  }
}





SSL Simple Server

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ServerSocketFactory;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass extends Thread {
  public static void main(String[] args) throws Exception {
    ServerSocketFactory ssf = SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(9096);
    while (true) {
      new SSLSimpleServer(ss.accept()).start();
    }
  }
  private Socket sock;
  public SSLSimpleServer(Socket s) {
    sock = s;
  }
  public void run() {
    try {
      BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
      PrintWriter pw = new PrintWriter(sock.getOutputStream());
      String data = br.readLine();
      pw.println("What is she?");
      pw.close();
      sock.close();
    } catch (IOException ioe) {
      // Client disconnected
    }
  }
}





SSL Socket Client

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class MainClass {
  private static final String HOST = "localhost";
  private static final int PORT = 8080;
  public static void main(String[] args) throws Exception {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = sf.createSocket(HOST, PORT);
    OutputStream out = s.getOutputStream();
    out.write("\nConnection established.\n\n".getBytes());
    out.flush();
    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();
  }
}





SSL Socket Server

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class MainClass {
  private static final int PORT = 8080;
  public static void main(String[] args) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(PORT);
    Socket s = ss.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line = null;
    while (((line = in.readLine()) != null)) {
      System.out.println(line);
    }
    in.close();
    s.close();
  }
}





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();
  }
}





Sun SSL Socket Server

import java.io.*;
import java.net.*;
import java.security.*;
import javax.net.ssl.*;
import com.sun.net.ssl.*;
public class MainClass {
  private static final int PORT = 8080;
  public static void main(String[] args) throws Exception {
    char[] passphrase = "password".toCharArray();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream(".keystore"), passphrase);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(keystore, passphrase);
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManager[] keyManagers = kmf.getKeyManagers();
    context.init(keyManagers, null, null);
    SSLServerSocketFactory ssf = context.getServerSocketFactory();
    ServerSocket ss = ssf.createServerSocket(PORT);
    Socket s = ss.accept();
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String line = null;
    while (((line = in.readLine()) != null)) {
      System.out.println(line);
    }
    in.close();
    s.close();
  }
}





Use SSLServerSocketFactory to create a SSL Server

import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
  public static void main(String args[]) throws Exception {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(5432);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      out.println("Hi");
      out.close();
      s.close();
    }
  }
}