Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- CLIENT:
- package client;
- import java.io.*;
- import java.net.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.nio.charset.StandardCharsets;
- import java.security.InvalidKeyException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.sql.DriverManager;
- import java.sql.PreparedStatement;
- import java.sql.ResultSet;
- import java.sql.Statement;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- import javax.crypto.Cipher;
- import javax.crypto.CipherInputStream;
- import javax.crypto.CipherOutputStream;
- import javax.crypto.IllegalBlockSizeException;
- import javax.crypto.KeyGenerator;
- import javax.crypto.NoSuchPaddingException;
- import javax.crypto.SealedObject;
- import javax.crypto.SecretKey;
- import javax.swing.*;
- import java.io.Serializable;
- //@SuppressWarnings("serial")
- public class Client extends JFrame implements Serializable {
- private JTextField userText;
- private JTextArea chatWindow;
- private ObjectOutputStream output;
- private ObjectInputStream input;
- private OutputStream tempOut;
- private Serializable object;
- private String msg = "";
- private String serverIP; //server IP
- //notice no Server object
- private Socket socketConnection;
- private String clientName;
- // public can't connect to the client's PC
- //constructor and GUI
- public Client(String host) {
- super("Client Chat");
- serverIP = host; // init serverIP to passed host, WE USE THE SAME COMPUTER FOR BOTH SERVER AND CLIENT
- //if not, input the actual server IP here
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //CENTER
- chatWindow = new JTextArea();
- add(new JScrollPane(chatWindow), BorderLayout.CENTER);
- //SOUTH
- userText = new JTextField();
- userText.setEditable(false); // disable typing until connected
- userText.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent event) {
- try {
- sendMessage(event.getActionCommand()); // get String and send
- } catch (NoSuchAlgorithmException ex) {
- Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
- } catch (InvalidKeyException ex) {
- Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
- } catch (UnknownHostException ex) {
- Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
- } catch (NoSuchPaddingException ex) {
- Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
- } catch (IllegalBlockSizeException ex) {
- Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
- }
- userText.setText(""); // reset to blank
- }
- }
- );
- add(userText, BorderLayout.SOUTH);
- setSize(500, 500);
- LoginView login = new LoginView(this);
- login.setVisible(true);
- //setVisible(true);
- }
- //connect to server
- public void startRunning() {
- try {
- //ON SERVER, we wait for connection,
- // but here the client has to connect to server
- connectToServer(); //CLIENT counterpart of waitForConnection
- setupStreams();
- whileChatting();
- } catch (EOFException eof) { // client doesn't want to talk anymore
- showMessage("\nClient Terminated connection");
- } catch (IOException ioe) { // something went horribly wrong
- ioe.printStackTrace();
- } finally { // maintenance - closing streams
- closeChat();
- }
- }
- //connect to server
- private void connectToServer() throws IOException {
- showMessage("Attempting connection... \n");
- //create a socket - IP and port number
- //connect to server IP and port - 6789
- socketConnection = new Socket(InetAddress.getByName(serverIP), 6789);
- //display connection info
- showMessage("Connected to: " + socketConnection.getInetAddress().getHostName()); //get server IP
- }
- //setup streams to send and receive messages
- private void setupStreams() throws IOException {
- output = new ObjectOutputStream(socketConnection.getOutputStream()); //get output stream - client to server
- output.flush(); //flush all the crap through the pipes
- input = new ObjectInputStream(socketConnection.getInputStream());
- showMessage("\n STREAMS ARE setup \n");
- }
- //while chatting with server
- private void whileChatting() throws IOException {
- ableToType(true);
- do {
- try {
- msg = (String) input.readObject();
- showMessage("\n" + msg);
- } catch (ClassNotFoundException cnfe) {
- showMessage("\n Unknown format");
- }
- } while (!msg.equals("SERVER - END"));
- }
- //close streams safely
- private void closeChat() {
- showMessage("\n Closing chat...");
- ableToType(false);
- try {
- output.close();
- input.close();
- socketConnection.close();
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- public String decryptMsg(InputStream input2) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
- Cipher cipher = Cipher.getInstance("RC4");
- KeyGenerator generator = KeyGenerator.getInstance("RC4");
- String pass = "haslo";
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
- generator.init(new SecureRandom(klucz));
- SecretKey key = generator.generateKey();
- cipher.init(Cipher.ENCRYPT_MODE, key);
- ByteArrayOutputStream output2 = new ByteArrayOutputStream();
- try (InputStream in = input) {
- try (OutputStream out = new CipherOutputStream(output2, cipher)) {
- byte[] buffer = new byte[256];
- while (true) {
- int count = in.read(buffer);
- if (count == -1) {
- break;
- }
- System.out.println(out);
- out.write(buffer, 0, count);
- }
- }
- }
- return output2.toString();
- }
- public void encryptMsg(String s) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnknownHostException, IOException, IllegalBlockSizeException {
- Cipher cipher = Cipher.getInstance("RC4");
- KeyGenerator generator = KeyGenerator.getInstance("RC4");
- String pass = "haslo";
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
- generator.init(new SecureRandom(klucz));
- SecretKey key = generator.generateKey();
- cipher.init(Cipher.ENCRYPT_MODE, key);
- InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
- //OutputStream out = null;
- byte[] tempArr = null;
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- try (InputStream in = new CipherInputStream(stream, cipher)) {
- byte[] buffer = new byte[256];
- while (true) {
- int count = in.read(buffer);
- if (count == -1) {
- break;
- }
- bos.write(buffer,0,count);
- //tempOut.write(buffer, 0, count);
- //ByteArrayOutputStream bis = new ByteArrayOutputStream(buffer);
- //tempArr = buffer;
- //output.write
- //new ObjectOutputStream(output).writeObject(obj);
- }
- }
- //ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutputStream tempOutput = new ObjectOutputStream(bos);
- //bos.write(klucz, ABORT, WIDTH);
- output.writeObject(tempOutput);
- output.flush();
- //OutputStream outstream = new ByteArrayOutputStream
- //output.writeObject()
- //output.
- //SealedObject sealedObject = new SealedObject(object, cipher);
- //CipherOutputStream cos = new CipherOutputStream(output, cipher);
- //ObjectOutputStream outputStream = new ObjectOutputStream(cos);
- //output.writeObject(sealedObject);
- //cObjectOutputStream outputStream = new ObjectOutputStream(cos);
- }
- //send message to server
- private void sendMessage(String s) throws NoSuchAlgorithmException, InvalidKeyException, UnknownHostException, NoSuchPaddingException, IllegalBlockSizeException {
- try {
- //output.writeObject("CLIENT - " + s);
- //object = (clientName + " - " + s);
- encryptMsg(s);
- //output.writeObject(clientName + " - " + s);
- //utput.flush();
- //showMessage("\nCLIENT - " + s);
- showMessage("\n" + clientName + " - " + s);
- } catch (IOException ioe) {
- chatWindow.append("\nMESSAGE NOT SENT");
- }
- }
- //show message - updates the chat window through a THREAD
- private void showMessage(final String msg) {
- SwingUtilities.invokeLater(
- new Runnable() { // create thread
- public void run() {
- chatWindow.append(msg); //add this string to the end
- }
- }
- );
- }
- //ableToType - enables/disable text field for user
- private void ableToType(final boolean tof) {
- SwingUtilities.invokeLater(
- new Runnable() { // create thread
- public void run() {
- userText.setEditable(tof);
- }
- }
- );
- }
- public void setClientName(String s) {
- clientName = s;
- }
- public String getClientName() {
- return clientName;
- }
- @SuppressWarnings("serial")
- public class LoginView extends JFrame {
- //static String servIP = "localhost";
- String servIP = "127.0.0.1:3306";
- private JTextField userText;
- private JPasswordField passwordText;
- private String username;
- public LoginView(Client c) {
- super("Login to Server-Messenger");
- setSize(300, 150);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- JPanel panel = new JPanel();
- panel.setLayout(null);
- JLabel userLabel = new JLabel("User");
- userLabel.setBounds(10, 10, 80, 25);
- panel.add(userLabel);
- userText = new JTextField(20);
- userText.setBounds(100, 10, 160, 25);
- panel.add(userText);
- JLabel passwordLabel = new JLabel("Password");
- passwordLabel.setBounds(10, 40, 80, 25);
- panel.add(passwordLabel);
- passwordText = new JPasswordField(20);
- passwordText.setBounds(100, 40, 160, 25);
- panel.add(passwordText);
- JButton loginButton = new JButton("login");
- loginButton.setBounds(10, 80, 80, 25);
- loginButton.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- //check credentials through DB connection
- if (verify()) {
- c.setClientName(username);
- c.setVisible(true);
- close();
- }
- }
- });
- panel.add(loginButton);
- JButton exitButton = new JButton("exit");
- exitButton.setBounds(180, 80, 80, 25);
- panel.add(exitButton);
- add(panel);
- }
- public boolean verify() {
- try {
- Class.forName("org.sqlite.JDBC");
- java.sql.Connection con = DriverManager.getConnection("jdbc:sqlite:src/test.db");
- // PreparedStatement statement = null;
- // String sql = "INSERT INTO users (username, password) VALUES (?,?)";
- // statement = con.prepareStatement(sql);
- //
- // statement.setString(1,"admin2");
- // statement.setString(2,"test1234");
- // statement.execute();
- //
- Statement st = con.createStatement();
- //SQL query
- String query = "SELECT * FROM users "
- + "WHERE username = '" + userText.getText().trim() + "'"
- + " AND password = '" + String.valueOf(passwordText.getPassword()) + "';";
- //password.getPassword() returns a char[]
- //System.out.println(query);
- //process result
- ResultSet rs = st.executeQuery(query);
- if (!rs.next()) {
- System.out.println("No results found");
- JOptionPane.showMessageDialog(null, "Account not found. Please try again.");
- } else {
- JOptionPane.showMessageDialog(null, "Welcome " + rs.getString("username"));
- username = rs.getString("username");
- con.close();
- return true;
- }
- //close connection
- con.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- //*************************************
- return false; //not authenticated
- }
- public void close() {
- this.dispose();
- }
- }
- public static void main(String[] args) {
- //create client object
- //we have to give IP address
- //TO TEST THIS ON YOUR PC - use localhost address
- //SET LOOPBACK ADDRESS(this PC) as Server IP to connect to
- //LOOPBACK
- //Client cli1 = new Client("127.0.0.1");
- //SERVER on Another PC (preferably in the same network)
- //Client cli1 = new Client("172.16.10.104");
- //ask for IP
- //String servIP = JOptionPane.showInputDialog("Enter IP address of server (127.0.0.1 if this PC)");
- //String clientName = JOptionPane.showInputDialog("Enter nick name");
- //LoginView login = new LoginView();
- //login.setVisible(true);
- String servIP = "192.168.1.117";
- //Client cli1 = new Client(servIP);
- Client cli1 = new Client("127.0.0.1");
- cli1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- cli1.startRunning();
- }
- }
- SERWER:
- package serwer;
- import java.io.*;
- import java.net.*;
- import java.awt.*;
- import java.awt.event.*;
- import java.nio.charset.StandardCharsets;
- import java.security.InvalidKeyException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- import java.security.SecureRandom;
- import java.util.Base64;
- import javax.crypto.Cipher;
- import javax.crypto.CipherInputStream;
- import javax.crypto.CipherOutputStream;
- import javax.crypto.KeyGenerator;
- import javax.crypto.NoSuchPaddingException;
- import javax.crypto.SecretKey;
- import javax.swing.*;
- import java.io.Serializable;
- public class Serwer extends JFrame implements Serializable{
- private JTextField userText; //where you type message
- private JTextArea chatWindow; // display the conversation
- private JLabel label1;
- //streams
- private ObjectOutputStream output; //stream - binary output
- private ObjectInputStream input;
- // program that goes on the server, waits for everyone to connect
- private ServerSocket server;
- // a connection bet computers
- private Socket socketConnection;
- //constr - GUI
- public Serwer() {
- //CENTER
- chatWindow = new JTextArea();
- chatWindow.setEditable(false);
- add(new JScrollPane(chatWindow)); // window with scroll bar
- //SOUTH
- JPanel p1 = new JPanel();
- p1.setLayout(new FlowLayout());
- userText = (new JTextField("", 25));
- userText.setSize(400, 15);
- userText.setText(" waiting for connection ");
- userText.setEditable(false);
- userText.addActionListener(
- new ActionListener() {
- public void actionPerformed(ActionEvent event) {
- sendMessage(event.getActionCommand()); // get String in the text field
- userText.setText(""); // empty it when after sending
- }
- }
- );
- label1 = new JLabel("Message:");
- label1.setSize(100, 15);
- p1.add(label1);
- p1.add(userText);
- add(p1, BorderLayout.SOUTH); // add to window
- setSize(500, 300);
- setVisible(true);
- }
- //set up and run the server
- public void startRunning() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
- try {
- server = new ServerSocket(6789, 100); // port number 6789,
- //max 100 people sit and wait on port
- //(backlog/ queue length - how many people can wait)
- while (true) {
- try {
- //1. wait for someone to connect
- waitForConnection();
- //2. set up streams (in and out)
- setupStreams();
- //3. allows to send messages back and forth
- whileChatting();
- } catch (EOFException eof) { // when finished, end of stream, end of connection
- //connect and have conversation
- showMessage("\n Server ended connection");
- } finally {
- closeChat();
- }
- }
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- //1. wait for connection, then display connected info
- private void waitForConnection() throws IOException {
- showMessage("Waiting for someone to connect...\n");
- //do this over and over
- // only create socket when connected to someone
- socketConnection = server.accept(); // when someone asks to connect, accept
- showMessage("Now connected to " + socketConnection.getInetAddress().getCanonicalHostName()); // returns IP address or hostname
- userText.setText("");
- }
- //2. get stream to send and receive data
- private void setupStreams() throws IOException {
- output = new ObjectOutputStream(socketConnection.getOutputStream()); //out stream
- output.flush(); //flush leftover data to the other person
- input = new ObjectInputStream(socketConnection.getInputStream()); // in stream
- //only the other one can flush to you, no flush for input
- showMessage("\nStreams are now setup\n");
- }
- //during the chat conversation
- private void whileChatting() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
- String message = "You are now connected";
- sendMessage(message);
- ableToType(true); // let user type
- //loop as long as user doesn't type END, read message and display with a new line
- do {
- // have a conversation
- try {
- decryptMsg();
- message = (String) input.readObject(); //get object from input stream
- //message = getMsg((InputStream) input.readObject());
- showMessage("\n" + message);
- } catch (ClassNotFoundException cnfe) { // some weird object that we don't understand (not a string)
- showMessage("\n IDK what the uscer sent");
- }
- } while (!message.equals("CLIENT - END")); // if user types END, stop
- }
- //close connection
- private void closeChat() throws IOException {
- showMessage("\nClosing connection...\n");
- ableToType(false);
- try {
- //close the streams
- output.close();
- input.close();
- socketConnection.close(); // close socket
- } catch (IOException ioe) {
- ioe.printStackTrace();
- }
- }
- //send message to client
- private void sendMessage(String msg) {
- try {
- output.writeObject("SERVER - " + msg); //create an object and send to output stream
- output.flush(); //left over bytes flush to the user
- showMessage("\nSERVER - " + msg); // show conversation history in text area
- } catch (IOException ioe) {
- chatWindow.append("\n ERROR: Can't send the message");
- }
- }
- //displays chat messages, etc in chat window
- // updates chat window
- private void showMessage(final String text) {
- //update GUI component /dynamic
- // allows to create a thread that updates the GUI
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- chatWindow.append(text); // adds a message to the end
- }
- }
- );
- }
- //let the user type stuff into their box
- private void ableToType(final boolean tof) {
- //like before, we're updating the GUI
- SwingUtilities.invokeLater(
- new Runnable() {
- public void run() {
- userText.setEditable(tof); // allow/disallow user to edit
- }
- }
- );
- }
- /*public String getMsg(InputStream input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
- Cipher cipher = Cipher.getInstance("RC4");
- KeyGenerator generator = KeyGenerator.getInstance("RC4");
- String pass = "haslo";
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
- generator.init(new SecureRandom(klucz));
- SecretKey key = generator.generateKey();
- cipher.init(Cipher.ENCRYPT_MODE, key);
- int port = 12345;
- ServerSocket server = new ServerSocket(port);
- Socket socket = server.accept();
- //InputStream input = socket.getInputStream();
- OutputStream output = socket.getOutputStream();
- try (InputStream in = new CipherInputStream(input, cipher)) {
- byte[] buffer = new byte[256];
- while (true) {
- int count = in.read(buffer);
- if (count == -1) {
- break;
- }
- output.write(buffer, 0, count);
- }
- }
- return output.toString();
- }*/
- public void decryptMsg() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
- Cipher cipher = Cipher.getInstance("RC4");
- KeyGenerator generator = KeyGenerator.getInstance("RC4");
- String pass = "haslo";
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
- generator.init(new SecureRandom(klucz));
- SecretKey key = generator.generateKey();
- cipher.init(Cipher.DECRYPT_MODE, key);
- ByteArrayOutputStream output2 = new ByteArrayOutputStream();
- try (InputStream in = input) {
- try (InputStream out = new CipherInputStream(input, cipher)) {
- byte[] buffer = new byte[256];
- while (true) {
- int count = in.read(buffer);
- if (count == -1) {
- break;
- }
- output2.write(buffer, 0, count);
- }
- }
- }
- ByteArrayInputStream input2 = new ByteArrayInputStream(output2.toByteArray());
- input = new ObjectInputStream(input2);
- //input = output2.toByteArray();
- //output = new ObjectOutputStream(output2);
- }
- public void encryptMsg(String msg) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnknownHostException, IOException {
- Cipher cipher = Cipher.getInstance("RC4");
- KeyGenerator generator = KeyGenerator.getInstance("RC4");
- String pass = "haslo";
- MessageDigest md = MessageDigest.getInstance("SHA-256");
- byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
- generator.init(new SecureRandom(klucz));
- SecretKey key = generator.generateKey();
- cipher.init(Cipher.DECRYPT_MODE, key);
- InetAddress address = InetAddress.getByName("127.0.0.1");
- int port = 12345;
- Socket socket = new Socket(address, port);
- InputStream input = socket.getInputStream();
- System.out.println(input);
- try (InputStream in = input) {
- try (OutputStream out = new CipherOutputStream(new FileOutputStream("test3.txt"), cipher)) {
- byte[] buffer = new byte[256];
- while (true) {
- int count = in.read(buffer);
- if (count == -1) {
- break;
- }
- System.out.println(out);
- out.write(buffer, 0, count);
- }
- }
- }
- }
- public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
- Serwer serw1 = new Serwer(); // constr - GUI
- serw1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- serw1.startRunning(); // start execution
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement