public boolean verify(String hostName, SSLSession session) {
    System.out.println("Server: " + hostName + ":" + session.getPeerPort());
    try {
      X509Certificate[] chain = session.getPeerCertificateChain();
      for (X509Certificate cert : chain) {

        System.out.println("DN: " + cert.getSubjectDN());
      }
    } catch (SSLPeerUnverifiedException e) {
      e.printStackTrace();
    }
    System.out.println("-----");
    return true;
  }
Exemplo n.º 2
0
 static void accept(KeyStore keyStore, char[] keyPassword, KeyStore trustStore, int port)
     throws GeneralSecurityException, IOException {
   SSLContext sslContext = SSLContexts.create(keyStore, keyPassword, trustStore);
   SSLServerSocket serverSocket =
       (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
   try {
     serverSocket.setNeedClientAuth(true);
     SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
     javax.security.cert.X509Certificate peer =
         clientSocket.getSession().getPeerCertificateChain()[0];
     logger.info("peer: " + peer.getSubjectDN().getName());
     ServerThread.handle(clientSocket);
   } finally {
     serverSocket.close();
   }
 }
Exemplo n.º 3
0
 // Converts to javax.security
 public static javax.security.cert.X509Certificate convert(
     java.security.cert.X509Certificate cert) {
   try {
     byte[] encoded = cert.getEncoded();
     return javax.security.cert.X509Certificate.getInstance(encoded);
   } catch (java.security.cert.CertificateEncodingException e) {
   } catch (javax.security.cert.CertificateEncodingException e) {
   } catch (javax.security.cert.CertificateException e) {
   }
   return null;
 }
Exemplo n.º 4
0
 // Converts to java.security
 public static java.security.cert.X509Certificate convert(
     javax.security.cert.X509Certificate cert) {
   try {
     byte[] encoded = cert.getEncoded();
     ByteArrayInputStream bis = new ByteArrayInputStream(encoded);
     java.security.cert.CertificateFactory cf =
         java.security.cert.CertificateFactory.getInstance("X.509");
     return (java.security.cert.X509Certificate) cf.generateCertificate(bis);
   } catch (java.security.cert.CertificateEncodingException e) {
   } catch (javax.security.cert.CertificateEncodingException e) {
   } catch (java.security.cert.CertificateException e) {
   }
   return null;
 }
Exemplo n.º 5
0
  private static byte[] createEncryptedPreMaster(boolean fake) {
    if (fake) {
      // we do not have to do this calculation to force server to think
      int len = ((RSAPublicKey) cert.getPublicKey()).getModulus().bitLength() / 8;
      return new byte[len];
    }

    byte[] preMaster = new byte[48];
    preMaster[0] = (byte) 3;
    preMaster[1] = (byte) 1;
    SecretKey preMasterKey = new SecretKeySpec(preMaster, "RAW");
    Cipher rsa;
    try {
      rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
      rsa.init(Cipher.WRAP_MODE, cert.getPublicKey(), new SecureRandom());
      return rsa.wrap(preMasterKey);
    } catch (NoSuchAlgorithmException
        | NoSuchPaddingException
        | InvalidKeyException
        | IllegalBlockSizeException e) {
      e.printStackTrace();
      throw new RuntimeException("Problem", e);
    }
  }
Exemplo n.º 6
0
  public static void main(String[] args) throws Exception {
    String host = null;
    int port = -1;
    for (int i = 0; i < args.length; i++) {
      System.out.println("args[" + i + "] = " + args[i]);
    }
    if (args.length < 2) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }
    try {
        /* get input parameters */
      host = args[0];
      port = Integer.parseInt(args[1]);
    } catch (IllegalArgumentException e) {
      System.out.println("USAGE: java client host port");
      System.exit(-1);
    }

    try {
        /* set up a key manager for client authentication */
      SSLSocketFactory factory = null;
      try {
        KeyStore ks = KeyStore.getInstance("JKS");
        KeyStore ts = KeyStore.getInstance("JKS");
        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        SSLContext ctx = SSLContext.getInstance("TLS");
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        System.out.print("Enter keystore: ");
        String keystoreName = br.readLine();
        Console cons = System.console();

        if (cons != null) {
          password = cons.readPassword("%s", "Password: "******"Cannot find a console to read password from. Eclipse CANNOT fork a terminal child process.");
        }

        ks.load(new FileInputStream("keystores/" + keystoreName), password); // keystore
        // password
        // (storepass)
        char[] cliTrustPW = "password".toCharArray();
        ts.load(new FileInputStream("clienttruststore"), cliTrustPW); // truststore
        // password
        // (storepass);
        kmf.init(ks, password); // user password (keypass)
        tmf.init(ts); // keystore can be used as truststore here
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
        factory = ctx.getSocketFactory();
      } catch (Exception e) {
        e.printStackTrace();
        throw new IOException(e.getMessage());
      }

      SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
      System.out.println("Handshake socket: " + socket + "\n");

      /*
       * send http request
       *
       * See SSLSocketClient.java for more information about why there is
       * a forced handshake here when using PrintWriters.
       */
      socket.startHandshake();

      SSLSession session = socket.getSession();
      X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0];
      System.out.println("Server DN: " + cert.getSubjectDN().getName());
      System.out.println("Handshake socket: " + socket);
      System.out.println("Secure connection.");
      System.out.println("Issuer DN: " + cert.getIssuerDN().getName());
      System.out.println("Serial N: " + cert.getSerialNumber().toString());

      read = new BufferedReader(new InputStreamReader(System.in));
      serverMsg = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      out = new PrintWriter(socket.getOutputStream(), true);
      ois = new ObjectInputStream(socket.getInputStream());
      records = new ArrayList<Record>();

      boolean isLoggedIn = false;
      boolean isDone = false;

      isLoggedIn = waitForLoginData();

      if (!isLoggedIn) {
        System.out.println(
            "This certificate does not have a user. \n Press the RETURN key to exit.");
        System.console().readLine();

        out.close();
        read.close();
        socket.close();
        return;
      }

      boolean accessDenied = false;

      while (!isDone) {

        if (accessDenied) {
          System.out.println(
              "Access denied, or no such record exists! \n Type 'help' for commands.");
        }

        System.out.print(user.getUsername() + " commands>");
        msg = read.readLine();
        fetchRecords();
        splitMsg = msg.split("\\s+");

        try {
          if (msg.equalsIgnoreCase("quit")) {
            break;
          } else if (msg.equalsIgnoreCase("help")) {
            printHelp();
          } else if (splitMsg[0].equalsIgnoreCase("records")) {
            printRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("edit") && (accessDenied = hasPermissions(msg))) {
            editRecord(splitMsg[1]);
            fetchRecords();
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("read") && (accessDenied = hasPermissions(msg))) {
            printRecord(splitMsg[1]);
            accessDenied = false;
          } else if (splitMsg[0].equalsIgnoreCase("delete")
              && (accessDenied = hasPermissions(msg))) {
            for (Record r : records) {
              if (r.getId() == Long.parseLong(splitMsg[1])) {
                r.delete(user);
                accessDenied = false;
              }
            }
            fetchRecords();
          } else if (splitMsg[0].equalsIgnoreCase("create")
              && (accessDenied = hasPermissions(msg))) {
            createRecord();
            fetchRecords();
            accessDenied = false;
          } else {
            accessDenied = true;
          }
        } catch (Exception e) {
          accessDenied = true;
        }
      }

      ois.close();
      out.close();
      read.close();
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 7
0
  private HashMap<String, String> readCertificateInformation(byte[] buf) {

    HashMap<String, String> hashMap = new HashMap<String, String>();

    try {

      InputStream input = new ByteArrayInputStream(buf);
      Certificate certificate =
          CertificateFactory.getInstance("X.509", "BC").generateCertificate(input);

      X509Certificate X509certificates = X509Certificate.getInstance(certificate.getEncoded());

      String version = convertCertVersion(X509certificates.getVersion());

      String issuerDN = X509certificates.getIssuerDN().toString();

      String endDate =
          DateFormat.format("yyyy-MM-dd HH:mm:ss E", X509certificates.getNotAfter()).toString();
      String beginDate =
          DateFormat.format("yyyy-MM-dd HH:mm:ss E", X509certificates.getNotBefore()).toString();

      String serialNumber = X509certificates.getSerialNumber().toString(16);
      String sigAlgName = X509certificates.getSigAlgName();
      String sigAlgOID = X509certificates.getSigAlgOID();
      byte[] sigAlgParams = X509certificates.getSigAlgParams();
      String subjectDN = X509certificates.getSubjectDN().getName();

      hashMap.put("version", version); // 证书的版本号
      hashMap.put("issuerDN", issuerDN); // 特殊的编号
      hashMap.put("beginDate", beginDate); // 返回证书最后的有效期
      hashMap.put("endDate", endDate); // 返回证书的开始日期
      hashMap.put("serialNumber", serialNumber); // 返回证书的序列号
      hashMap.put("sigAlgName", sigAlgName); // 返回证书的签名
      hashMap.put("sigAlgOID", sigAlgOID); // 返回OID签名算法从证书

      if (sigAlgParams != null) {

        hashMap.put("sigAlgParams", ConverterUtil.getHexString(sigAlgParams, sigAlgParams.length));
      } else {
        hashMap.put("sigAlgParams", null);
      }

      hashMap.put("subjectDN", subjectDN);

      return hashMap;

    } catch (Exception e) {

      // recordLog(CustomUtil.LogMode.ERROR, "readCertificateInformation",
      // e.getMessage(), true);
      // new RuntimeException("证书异常,请稍后再试");

      if (e != null) e.printStackTrace();
    }

    return null;
  }
Exemplo n.º 8
0
  public void init(int port) throws IOException {
    String host = "localhost";
    String passwd = "";
    String userPath = "";
    boolean login = true;
    Scanner scan = new Scanner(System.in);
    FileInputStream keyfile = null;
    FileInputStream trustfile = null;
    URL tempLoc = server.class.getProtectionDomain().getCodeSource().getLocation();
    String loc = "" + tempLoc;
    loc = loc.substring(5, loc.length() - 5);
    SSLSocketFactory factory = null;
    Console console = System.console();
    boolean terminate = false;

    while (login) {
      System.out.println("Type \"quit\" to exit program");
      try {
        System.out.println("UserID: ");
        userPath = scan.nextLine();
        if (userPath.equalsIgnoreCase("quit")) {
          login = false;
          scan.close();
          System.out.println("Quit program");
          terminate = true;
          break;
        }
        clientID = userPath;
        /*Users keystore password is entered*/
        char[] pass = console.readPassword("Password: "******"/certificates/Users/" + userPath + "/" + userPath + "_keystore");
        trustfile =
            new FileInputStream(
                loc + "/certificates/Users/" + userPath + "/" + userPath + "_truststore");

        // SSLSocketFactory factory = null;
        try {

          KeyStore ks = KeyStore.getInstance("JKS");
          KeyStore ts = KeyStore.getInstance("JKS");

          KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
          TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

          SSLContext ctx = SSLContext.getInstance("TLS");

          /** Set and trim path to folders */
          URL tempLocation = server.class.getProtectionDomain().getCodeSource().getLocation();
          String location = "" + tempLocation;
          location = location.substring(5, location.length() - 5);

          ks.load(keyfile, pass); // keystore
          // password
          // (storepass)
          ts.load(trustfile, pass); // truststore
          // password
          // (storepass);
          kmf.init(ks, pass); // user password (keypass)
          tmf.init(ts); // keystore can be used as truststore here
          ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
          factory = ctx.getSocketFactory();
          login = false;
        } catch (Exception e) {
          System.out.println("Incorrect username or password");
        }
      } catch (FileNotFoundException e) {
        System.out.println("Incorrect username or password");
      }
    }
    if (!terminate) {
      try {
          /* set up a key manager for client authentication */
        SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
        socket.startHandshake();
        SSLSession session = socket.getSession();
        X509Certificate cert = (X509Certificate) session.getPeerCertificateChain()[0];
        serial = cert.getSerialNumber().toString();
        BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out =
            new PrintWriter(
                new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8), true);
        BufferedReader in =
            new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
        String msg;
        String allowed = in.readLine();
        if (allowed.equalsIgnoreCase("notAllowed")) {
          throw new LoginException("User already logged in");
        }
        System.out.println("Secure connection established\n\n");

        if (userPath.length() > 4) { // Patient
          String fromServer;
          msg = "logout";
          while ((fromServer = in.readLine()) != null) {
            if (fromServer.equals("listen")) {
              break;
            } else {
              System.out.println(fromServer);
            }
          }
        } else {
          System.out.println("Succesful login! Type a command in the prompt and press enter.");
          System.out.println("Help -h, Logout logout, Quit quit");
          for (; ; ) {
            System.out.print(">");
            msg = read.readLine();
            if (msg.equalsIgnoreCase("quit") || msg.equalsIgnoreCase("logout")) {
              break;
            }
            out.println(msg);
            out.flush();
            String fromServer;
            while ((fromServer = in.readLine()) != null) {
              if (fromServer.equals("listen")) {
                break;
              } else {
                System.out.println(fromServer);
              }
            }
          }
        }
        if (msg.equals("logout")) {
          System.out.println("\n\nLogged out\n");
          socket.close();
          in.close();
          out.close();
          init(port);
        } else {
          System.out.println("Exit client");
          socket.close();
          in.close();
          out.close();
          read.close();
        }
      } catch (LoginException e) {
        System.out.println(e.getMessage());
        init(port);
      }
    }
  }