Java Tutorial/Security/HTTPS

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

Certification for HTTPS

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", 9999);
    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);
  }
}





Disabling Certificate Validation in an HTTPS Connection

import java.net.URL;
import java.security.cert.X509Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class Main {
  public static void main(String[] argv) throws Exception {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      public void checkClientTrusted(X509Certificate[] certs, String authType) {
      }
      public void checkServerTrusted(X509Certificate[] certs, String authType) {
      }
    } };
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    URL url = new URL("https://hostname/index.html");
  }
}





HTTPS Client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
public class MainClass {
  public static void main(String[] args) throws Exception {
    System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
    URL url = new URL("https://www.verisign.ru/");
    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    in.close();
  }
}





HTTPS Server

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class MainClass {
  public static void main(String[] args) throws IOException {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(8080);
    while (true) {
      try {
        Socket s = ss.accept();
        OutputStream out = s.getOutputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while (((line = in.readLine()) != null) && (!("".equals(line)))) {
          System.out.println(line);
        }
        StringBuffer buffer = new StringBuffer();
        buffer.append("<HTML><HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
        buffer.append("<BODY>\n<H1>Success!</H1></BODY></HTML>\n");
        String string = buffer.toString();
        byte[] data = string.getBytes();
        out.write("HTTP/1.0 200 OK\n".getBytes());
        out.write(new String("Content-Length: " + data.length + "\n").getBytes());
        out.write("Content-Type: text/html\n\n".getBytes());
        out.write(data);
        out.flush();
        out.close();
        in.close();
        s.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}





HTTPS Server Authentication

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import javax.net.ssl.SSLServerSocket;
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 {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(443);
    ss.setNeedClientAuth(true);
    while (true) {
      Socket s = ss.accept();
      SSLSession session = ((SSLSocket) s).getSession();
      Certificate[] cchain = session.getPeerCertificates();
      for (int j = 0; j < cchain.length; j++) {
        System.out.println(((X509Certificate) cchain[j]).getSubjectDN());
      }
      PrintStream out = new PrintStream(s.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String info = null;
      while ((info = in.readLine()) != null) {
        System.out.println("now got " + info);
        if (info.equals(""))
          break;
      }
      out.println("HTTP/1.0 200 OK\nMIME_version:1.0");
      out.println("Content_Type:text/html");
      String c = "<html> <head></head><body> <h1> Hi,</h1></Body></html>";
      out.println("Content_Length:" + c.length());
      out.println("");
      out.println(c);
      out.close();
      s.close();
      in.close();
    }
  }
}





HTTPS Server Proxy

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
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(443);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String info = null;
      String request = null;
      String refer = null;
      while ((info = in.readLine()) != null) {
        if (info.startsWith("GET")) {
          request = info;
        }
        if (info.startsWith("Referer:")) {
          refer = info;
        }
        if (info.equals(""))
          break;
      }
      if (request != null) {
        out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
        int sp1 = request.indexOf(" ");
        int sp2 = request.indexOf(" ", sp1 + 1);
        String filename = request.substring(sp1 + 2, sp2);
        if (refer != null) {
          sp1 = refer.indexOf(" ");
          refer = refer.substring(sp1 + 1, refer.length());
          if (!refer.endsWith("/")) {
            refer = refer + "/";
          }
          filename = refer + filename;
        }
        URL con = new URL(filename);
        InputStream gotoin = con.openStream();
        int n = gotoin.available();
        byte buf[] = new byte[1024];
        out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
        out.println("Content_Length:" + n + "\n");
        while ((n = gotoin.read(buf)) >= 0) {
          out.write(buf, 0, n);
        }
        out.close();
        s.close();
        in.close();
      }
    }
  }
}





HTTPS Server using the JSSE

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class MainClass {
  public static void main(String[] args) throws IOException {
    SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket ss = (SSLServerSocket) ssf.createServerSocket(8080);
    ss.setNeedClientAuth(true);
    while (true) {
      try {
        Socket s = ss.accept();
        OutputStream out = s.getOutputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        String line = null;
        while (((line = in.readLine()) != null) && (!("".equals(line)))) {
          System.out.println(line);
        }
        System.out.println("");
        StringBuffer buffer = new StringBuffer();
        buffer.append("<HTML>\n");
        buffer.append("<HEAD><TITLE>HTTPS Server</TITLE></HEAD>\n");
        buffer.append("<BODY>\n");
        buffer.append("<H1>Success!</H1>\n");
        buffer.append("</BODY>\n");
        buffer.append("</HTML>\n");
        String string = buffer.toString();
        byte[] data = string.getBytes();
        out.write("HTTP/1.0 200 OK\n".getBytes());
        out.write(new String("Content-Length: " + data.length + "\n").getBytes());
        out.write("Content-Type: text/html\n\n".getBytes());
        out.write(data);
        out.flush();
        out.close();
        in.close();
        s.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}





Https Socket Client

import java.io.BufferedReader;
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 {
    System.setProperty("javax.net.ssl.trustStore", "clienttrust");
    SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    Socket s = ssf.createSocket("127.0.0.1", 8888);
    OutputStream outs = s.getOutputStream();
    PrintStream out = new PrintStream(outs);
    InputStream ins = s.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(ins));
    out.println("Hi,How are u!");
    out.println("");
    String line = null;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    in.close();
    out.close();
  }
}





Use HTTPS Server to transfer File

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
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(443);
    while (true) {
      Socket s = ss.accept();
      PrintStream out = new PrintStream(s.getOutputStream());
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String info = null;
      String request = null;
      while ((info = in.readLine()) != null) {
        if (info.indexOf("GET") != -1) {
          request = info;
        }
        if (info.equals(""))
          break;
      }
      if (request != null) {
        out.println("HTTP/1.0 200 OK\nMIME_version:1.0\nContent_Type:text/html");
        int sp1 = request.indexOf(" ");
        int sp2 = request.indexOf(" ", sp1 + 1);
        String filename = request.substring(sp1 + 2, sp2);
        if (filename.equals("") || filename.endsWith("/")) {
          filename += "index.html";
        }
        File fi = new File(filename);
        InputStream fs = new FileInputStream(fi);
        int n = fs.available();
        byte buf[] = new byte[1024];
        out.println("Content_Length:" + n);
        out.println("");
        while ((n = fs.read(buf)) >= 0) {
          out.write(buf, 0, n);
        }
        out.close();
        s.close();
        in.close();
      }
    }
  }
}