Exemplo n.º 1
0
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

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

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
Exemplo n.º 2
0
  public static void main(String args[]) {

    int port = 6502;
    try {
      // tell the system who we trust
      System.setProperty("javax.net.ssl.trustStore", "myCool.truststore");
      // get an SSLSocketFactory
      SocketFactory sf = SSLSocketFactory.getDefault();

      // an SSLSocket "is a" Socket
      Socket s = sf.createSocket("localhost", 6505);

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      Scanner scanner = new Scanner(System.in);

      String answer = in.readLine();
      System.out.println(answer);
      String username = scanner.nextLine();
      out.write(username + "\n");
      out.flush();
      answer = in.readLine();
      System.out.println(answer);
      String password = scanner.nextLine();
      out.write(password + "\n");
      out.flush();
      answer = in.readLine();
      System.out.println(answer);

      out.close();
      in.close();
      // while(true);
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }