Java SSLSocket ignore keys and trust all certificate

Description

Java SSLSocket ignore keys and trust all certificate

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class Main {
   public static void main(String[] args) {
      try {/* w w  w .  j a v  a  2  s  .c  o  m*/
         TrustManager[] trustAllCerts = { new X509TrustManager() {
            public 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 SecureRandom());
         SSLSocketFactory factory = (SSLSocketFactory) sc.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