· 7 years ago · Jun 25, 2018, 05:16 AM
1CLIENT:
2
3package client;
4
5import java.io.*;
6import java.net.*;
7import java.awt.*;
8import java.awt.event.*;
9import java.nio.charset.StandardCharsets;
10import java.security.InvalidKeyException;
11import java.security.MessageDigest;
12import java.security.NoSuchAlgorithmException;
13import java.security.SecureRandom;
14import java.sql.DriverManager;
15import java.sql.PreparedStatement;
16import java.sql.ResultSet;
17import java.sql.Statement;
18import java.util.logging.Level;
19import java.util.logging.Logger;
20import javax.crypto.Cipher;
21import javax.crypto.CipherInputStream;
22import javax.crypto.CipherOutputStream;
23import javax.crypto.IllegalBlockSizeException;
24import javax.crypto.KeyGenerator;
25import javax.crypto.NoSuchPaddingException;
26import javax.crypto.SealedObject;
27import javax.crypto.SecretKey;
28import javax.swing.*;
29import java.io.Serializable;
30
31//@SuppressWarnings("serial")
32public class Client extends JFrame implements Serializable {
33
34 private JTextField userText;
35 private JTextArea chatWindow;
36 private ObjectOutputStream output;
37 private ObjectInputStream input;
38 private OutputStream tempOut;
39 private Serializable object;
40 private String msg = "";
41 private String serverIP; //server IP
42
43 //notice no Server object
44 private Socket socketConnection;
45 private String clientName;
46
47 // public can't connect to the client's PC
48 //constructor and GUI
49 public Client(String host) {
50 super("Client Chat");
51
52 serverIP = host; // init serverIP to passed host, WE USE THE SAME COMPUTER FOR BOTH SERVER AND CLIENT
53 //if not, input the actual server IP here
54
55 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
56
57 //CENTER
58 chatWindow = new JTextArea();
59 add(new JScrollPane(chatWindow), BorderLayout.CENTER);
60
61 //SOUTH
62 userText = new JTextField();
63 userText.setEditable(false); // disable typing until connected
64 userText.addActionListener(
65 new ActionListener() {
66 public void actionPerformed(ActionEvent event) {
67 try {
68 sendMessage(event.getActionCommand()); // get String and send
69 } catch (NoSuchAlgorithmException ex) {
70 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
71 } catch (InvalidKeyException ex) {
72 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
73 } catch (UnknownHostException ex) {
74 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
75 } catch (NoSuchPaddingException ex) {
76 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
77 } catch (IllegalBlockSizeException ex) {
78 Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
79 }
80 userText.setText(""); // reset to blank
81 }
82 }
83 );
84 add(userText, BorderLayout.SOUTH);
85
86 setSize(500, 500);
87
88 LoginView login = new LoginView(this);
89 login.setVisible(true);
90
91 //setVisible(true);
92 }
93
94 //connect to server
95 public void startRunning() {
96 try {
97 //ON SERVER, we wait for connection,
98 // but here the client has to connect to server
99 connectToServer(); //CLIENT counterpart of waitForConnection
100 setupStreams();
101 whileChatting();
102 } catch (EOFException eof) { // client doesn't want to talk anymore
103 showMessage("\nClient Terminated connection");
104 } catch (IOException ioe) { // something went horribly wrong
105 ioe.printStackTrace();
106 } finally { // maintenance - closing streams
107 closeChat();
108 }
109 }
110
111 //connect to server
112 private void connectToServer() throws IOException {
113 showMessage("Attempting connection... \n");
114 //create a socket - IP and port number
115 //connect to server IP and port - 6789
116 socketConnection = new Socket(InetAddress.getByName(serverIP), 6789);
117 //display connection info
118 showMessage("Connected to: " + socketConnection.getInetAddress().getHostName()); //get server IP
119
120 }
121
122 //setup streams to send and receive messages
123 private void setupStreams() throws IOException {
124 output = new ObjectOutputStream(socketConnection.getOutputStream()); //get output stream - client to server
125 output.flush(); //flush all the crap through the pipes
126 input = new ObjectInputStream(socketConnection.getInputStream());
127 showMessage("\n STREAMS ARE setup \n");
128 }
129
130 //while chatting with server
131 private void whileChatting() throws IOException {
132 ableToType(true);
133
134 do {
135
136 try {
137 msg = (String) input.readObject();
138 showMessage("\n" + msg);
139 } catch (ClassNotFoundException cnfe) {
140 showMessage("\n Unknown format");
141 }
142
143 } while (!msg.equals("SERVER - END"));
144 }
145
146 //close streams safely
147 private void closeChat() {
148 showMessage("\n Closing chat...");
149 ableToType(false);
150 try {
151 output.close();
152 input.close();
153
154 socketConnection.close();
155
156 } catch (IOException ioe) {
157 ioe.printStackTrace();
158 }
159 }
160
161 public String decryptMsg(InputStream input2) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
162 Cipher cipher = Cipher.getInstance("RC4");
163 KeyGenerator generator = KeyGenerator.getInstance("RC4");
164 String pass = "haslo";
165 MessageDigest md = MessageDigest.getInstance("SHA-256");
166 byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
167 generator.init(new SecureRandom(klucz));
168 SecretKey key = generator.generateKey();
169 cipher.init(Cipher.ENCRYPT_MODE, key);
170
171 ByteArrayOutputStream output2 = new ByteArrayOutputStream();
172
173 try (InputStream in = input) {
174 try (OutputStream out = new CipherOutputStream(output2, cipher)) {
175 byte[] buffer = new byte[256];
176 while (true) {
177 int count = in.read(buffer);
178 if (count == -1) {
179 break;
180 }
181 System.out.println(out);
182 out.write(buffer, 0, count);
183 }
184 }
185 }
186 return output2.toString();
187 }
188
189 public void encryptMsg(String s) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnknownHostException, IOException, IllegalBlockSizeException {
190 Cipher cipher = Cipher.getInstance("RC4");
191 KeyGenerator generator = KeyGenerator.getInstance("RC4");
192 String pass = "haslo";
193 MessageDigest md = MessageDigest.getInstance("SHA-256");
194 byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
195 generator.init(new SecureRandom(klucz));
196 SecretKey key = generator.generateKey();
197 cipher.init(Cipher.ENCRYPT_MODE, key);
198
199 InputStream stream = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
200
201 //OutputStream out = null;
202 byte[] tempArr = null;
203
204 ByteArrayOutputStream bos = new ByteArrayOutputStream();
205
206 try (InputStream in = new CipherInputStream(stream, cipher)) {
207 byte[] buffer = new byte[256];
208 while (true) {
209 int count = in.read(buffer);
210 if (count == -1) {
211 break;
212 }
213 bos.write(buffer,0,count);
214
215 //tempOut.write(buffer, 0, count);
216 //ByteArrayOutputStream bis = new ByteArrayOutputStream(buffer);
217
218 //tempArr = buffer;
219
220 //output.write
221 //new ObjectOutputStream(output).writeObject(obj);
222 }
223 }
224
225 //ByteArrayOutputStream bos = new ByteArrayOutputStream();
226
227 ObjectOutputStream tempOutput = new ObjectOutputStream(bos);
228
229 //bos.write(klucz, ABORT, WIDTH);
230
231 output.writeObject(tempOutput);
232 output.flush();
233
234 //OutputStream outstream = new ByteArrayOutputStream
235
236 //output.writeObject()
237
238 //output.
239
240 //SealedObject sealedObject = new SealedObject(object, cipher);
241
242 //CipherOutputStream cos = new CipherOutputStream(output, cipher);
243
244 //ObjectOutputStream outputStream = new ObjectOutputStream(cos);
245
246 //output.writeObject(sealedObject);
247 //cObjectOutputStream outputStream = new ObjectOutputStream(cos);
248 }
249
250 //send message to server
251 private void sendMessage(String s) throws NoSuchAlgorithmException, InvalidKeyException, UnknownHostException, NoSuchPaddingException, IllegalBlockSizeException {
252 try {
253 //output.writeObject("CLIENT - " + s);
254
255
256 //object = (clientName + " - " + s);
257
258 encryptMsg(s);
259
260 //output.writeObject(clientName + " - " + s);
261 //utput.flush();
262 //showMessage("\nCLIENT - " + s);
263 showMessage("\n" + clientName + " - " + s);
264 } catch (IOException ioe) {
265 chatWindow.append("\nMESSAGE NOT SENT");
266 }
267 }
268
269 //show message - updates the chat window through a THREAD
270 private void showMessage(final String msg) {
271 SwingUtilities.invokeLater(
272 new Runnable() { // create thread
273 public void run() {
274 chatWindow.append(msg); //add this string to the end
275 }
276 }
277 );
278
279 }
280
281 //ableToType - enables/disable text field for user
282 private void ableToType(final boolean tof) {
283
284 SwingUtilities.invokeLater(
285 new Runnable() { // create thread
286 public void run() {
287 userText.setEditable(tof);
288 }
289 }
290 );
291 }
292
293 public void setClientName(String s) {
294 clientName = s;
295 }
296
297 public String getClientName() {
298 return clientName;
299 }
300
301 @SuppressWarnings("serial")
302 public class LoginView extends JFrame {
303
304 //static String servIP = "localhost";
305 String servIP = "127.0.0.1:3306";
306
307 private JTextField userText;
308
309 private JPasswordField passwordText;
310 private String username;
311
312 public LoginView(Client c) {
313
314 super("Login to Server-Messenger");
315
316 setSize(300, 150);
317 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
318
319 JPanel panel = new JPanel();
320
321 panel.setLayout(null);
322
323 JLabel userLabel = new JLabel("User");
324 userLabel.setBounds(10, 10, 80, 25);
325 panel.add(userLabel);
326
327 userText = new JTextField(20);
328 userText.setBounds(100, 10, 160, 25);
329 panel.add(userText);
330
331 JLabel passwordLabel = new JLabel("Password");
332 passwordLabel.setBounds(10, 40, 80, 25);
333 panel.add(passwordLabel);
334
335 passwordText = new JPasswordField(20);
336 passwordText.setBounds(100, 40, 160, 25);
337 panel.add(passwordText);
338
339 JButton loginButton = new JButton("login");
340 loginButton.setBounds(10, 80, 80, 25);
341
342 loginButton.addActionListener(
343 new ActionListener() {
344 public void actionPerformed(ActionEvent e) {
345 //check credentials through DB connection
346
347 if (verify()) {
348 c.setClientName(username);
349 c.setVisible(true);
350 close();
351 }
352
353 }
354 });
355
356 panel.add(loginButton);
357
358 JButton exitButton = new JButton("exit");
359 exitButton.setBounds(180, 80, 80, 25);
360 panel.add(exitButton);
361
362 add(panel);
363
364 }
365
366 public boolean verify() {
367 try {
368
369 Class.forName("org.sqlite.JDBC");
370 java.sql.Connection con = DriverManager.getConnection("jdbc:sqlite:src/test.db");
371
372// PreparedStatement statement = null;
373// String sql = "INSERT INTO users (username, password) VALUES (?,?)";
374// statement = con.prepareStatement(sql);
375//
376// statement.setString(1,"admin2");
377// statement.setString(2,"test1234");
378// statement.execute();
379//
380 Statement st = con.createStatement();
381
382 //SQL query
383 String query = "SELECT * FROM users "
384 + "WHERE username = '" + userText.getText().trim() + "'"
385 + " AND password = '" + String.valueOf(passwordText.getPassword()) + "';";
386
387 //password.getPassword() returns a char[]
388 //System.out.println(query);
389 //process result
390 ResultSet rs = st.executeQuery(query);
391 if (!rs.next()) {
392 System.out.println("No results found");
393 JOptionPane.showMessageDialog(null, "Account not found. Please try again.");
394
395 } else {
396 JOptionPane.showMessageDialog(null, "Welcome " + rs.getString("username"));
397 username = rs.getString("username");
398 con.close();
399 return true;
400
401 }
402
403 //close connection
404 con.close();
405 } catch (Exception e) {
406 e.printStackTrace();
407 }
408 //*************************************
409
410 return false; //not authenticated
411 }
412
413 public void close() {
414 this.dispose();
415 }
416
417 }
418
419 public static void main(String[] args) {
420
421 //create client object
422 //we have to give IP address
423 //TO TEST THIS ON YOUR PC - use localhost address
424 //SET LOOPBACK ADDRESS(this PC) as Server IP to connect to
425 //LOOPBACK
426 //Client cli1 = new Client("127.0.0.1");
427 //SERVER on Another PC (preferably in the same network)
428 //Client cli1 = new Client("172.16.10.104");
429 //ask for IP
430 //String servIP = JOptionPane.showInputDialog("Enter IP address of server (127.0.0.1 if this PC)");
431 //String clientName = JOptionPane.showInputDialog("Enter nick name");
432 //LoginView login = new LoginView();
433 //login.setVisible(true);
434 String servIP = "192.168.1.117";
435 //Client cli1 = new Client(servIP);
436 Client cli1 = new Client("127.0.0.1");
437
438 cli1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
439 cli1.startRunning();
440 }
441
442}
443
444
445
446
447
448SERWER:
449
450package serwer;
451
452import java.io.*;
453import java.net.*;
454import java.awt.*;
455import java.awt.event.*;
456import java.nio.charset.StandardCharsets;
457import java.security.InvalidKeyException;
458import java.security.MessageDigest;
459import java.security.NoSuchAlgorithmException;
460import java.security.SecureRandom;
461import java.util.Base64;
462import javax.crypto.Cipher;
463import javax.crypto.CipherInputStream;
464import javax.crypto.CipherOutputStream;
465import javax.crypto.KeyGenerator;
466import javax.crypto.NoSuchPaddingException;
467import javax.crypto.SecretKey;
468import javax.swing.*;
469import java.io.Serializable;
470
471public class Serwer extends JFrame implements Serializable{
472
473 private JTextField userText; //where you type message
474 private JTextArea chatWindow; // display the conversation
475 private JLabel label1;
476 //streams
477 private ObjectOutputStream output; //stream - binary output
478 private ObjectInputStream input;
479
480 // program that goes on the server, waits for everyone to connect
481 private ServerSocket server;
482
483 // a connection bet computers
484 private Socket socketConnection;
485
486 //constr - GUI
487 public Serwer() {
488
489 //CENTER
490 chatWindow = new JTextArea();
491 chatWindow.setEditable(false);
492 add(new JScrollPane(chatWindow)); // window with scroll bar
493
494 //SOUTH
495 JPanel p1 = new JPanel();
496 p1.setLayout(new FlowLayout());
497 userText = (new JTextField("", 25));
498 userText.setSize(400, 15);
499 userText.setText(" waiting for connection ");
500 userText.setEditable(false);
501 userText.addActionListener(
502 new ActionListener() {
503 public void actionPerformed(ActionEvent event) {
504 sendMessage(event.getActionCommand()); // get String in the text field
505 userText.setText(""); // empty it when after sending
506 }
507 }
508 );
509
510 label1 = new JLabel("Message:");
511 label1.setSize(100, 15);
512 p1.add(label1);
513 p1.add(userText);
514
515 add(p1, BorderLayout.SOUTH); // add to window
516
517 setSize(500, 300);
518 setVisible(true);
519 }
520
521 //set up and run the server
522 public void startRunning() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
523 try {
524 server = new ServerSocket(6789, 100); // port number 6789,
525 //max 100 people sit and wait on port
526 //(backlog/ queue length - how many people can wait)
527
528 while (true) {
529 try {
530 //1. wait for someone to connect
531 waitForConnection();
532 //2. set up streams (in and out)
533 setupStreams();
534 //3. allows to send messages back and forth
535 whileChatting();
536 } catch (EOFException eof) { // when finished, end of stream, end of connection
537 //connect and have conversation
538 showMessage("\n Server ended connection");
539 } finally {
540 closeChat();
541 }
542 }
543
544 } catch (IOException ioe) {
545 ioe.printStackTrace();
546 }
547 }
548
549 //1. wait for connection, then display connected info
550 private void waitForConnection() throws IOException {
551 showMessage("Waiting for someone to connect...\n");
552
553 //do this over and over
554 // only create socket when connected to someone
555 socketConnection = server.accept(); // when someone asks to connect, accept
556 showMessage("Now connected to " + socketConnection.getInetAddress().getCanonicalHostName()); // returns IP address or hostname
557
558 userText.setText("");
559
560 }
561 //2. get stream to send and receive data
562
563 private void setupStreams() throws IOException {
564 output = new ObjectOutputStream(socketConnection.getOutputStream()); //out stream
565 output.flush(); //flush leftover data to the other person
566 input = new ObjectInputStream(socketConnection.getInputStream()); // in stream
567 //only the other one can flush to you, no flush for input
568 showMessage("\nStreams are now setup\n");
569 }
570
571 //during the chat conversation
572 private void whileChatting() throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
573 String message = "You are now connected";
574 sendMessage(message);
575 ableToType(true); // let user type
576
577 //loop as long as user doesn't type END, read message and display with a new line
578 do {
579 // have a conversation
580 try {
581 decryptMsg();
582 message = (String) input.readObject(); //get object from input stream
583 //message = getMsg((InputStream) input.readObject());
584
585 showMessage("\n" + message);
586 } catch (ClassNotFoundException cnfe) { // some weird object that we don't understand (not a string)
587 showMessage("\n IDK what the uscer sent");
588 }
589 } while (!message.equals("CLIENT - END")); // if user types END, stop
590 }
591
592 //close connection
593 private void closeChat() throws IOException {
594 showMessage("\nClosing connection...\n");
595 ableToType(false);
596 try {
597 //close the streams
598 output.close();
599 input.close();
600 socketConnection.close(); // close socket
601 } catch (IOException ioe) {
602 ioe.printStackTrace();
603 }
604 }
605
606 //send message to client
607 private void sendMessage(String msg) {
608 try {
609 output.writeObject("SERVER - " + msg); //create an object and send to output stream
610 output.flush(); //left over bytes flush to the user
611 showMessage("\nSERVER - " + msg); // show conversation history in text area
612 } catch (IOException ioe) {
613 chatWindow.append("\n ERROR: Can't send the message");
614 }
615 }
616
617 //displays chat messages, etc in chat window
618 // updates chat window
619 private void showMessage(final String text) {
620 //update GUI component /dynamic
621
622 // allows to create a thread that updates the GUI
623 SwingUtilities.invokeLater(
624 new Runnable() {
625 public void run() {
626 chatWindow.append(text); // adds a message to the end
627 }
628 }
629 );
630 }
631
632 //let the user type stuff into their box
633 private void ableToType(final boolean tof) {
634 //like before, we're updating the GUI
635
636 SwingUtilities.invokeLater(
637 new Runnable() {
638 public void run() {
639 userText.setEditable(tof); // allow/disallow user to edit
640 }
641 }
642 );
643 }
644
645 /*public String getMsg(InputStream input) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
646 Cipher cipher = Cipher.getInstance("RC4");
647 KeyGenerator generator = KeyGenerator.getInstance("RC4");
648 String pass = "haslo";
649 MessageDigest md = MessageDigest.getInstance("SHA-256");
650 byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
651 generator.init(new SecureRandom(klucz));
652 SecretKey key = generator.generateKey();
653 cipher.init(Cipher.ENCRYPT_MODE, key);
654
655 int port = 12345;
656 ServerSocket server = new ServerSocket(port);
657 Socket socket = server.accept();
658 //InputStream input = socket.getInputStream();
659 OutputStream output = socket.getOutputStream();
660 try (InputStream in = new CipherInputStream(input, cipher)) {
661 byte[] buffer = new byte[256];
662 while (true) {
663 int count = in.read(buffer);
664 if (count == -1) {
665 break;
666 }
667 output.write(buffer, 0, count);
668 }
669 }
670 return output.toString();
671 }*/
672 public void decryptMsg() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
673 Cipher cipher = Cipher.getInstance("RC4");
674 KeyGenerator generator = KeyGenerator.getInstance("RC4");
675 String pass = "haslo";
676 MessageDigest md = MessageDigest.getInstance("SHA-256");
677 byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
678 generator.init(new SecureRandom(klucz));
679 SecretKey key = generator.generateKey();
680 cipher.init(Cipher.DECRYPT_MODE, key);
681
682 ByteArrayOutputStream output2 = new ByteArrayOutputStream();
683
684 try (InputStream in = input) {
685 try (InputStream out = new CipherInputStream(input, cipher)) {
686 byte[] buffer = new byte[256];
687 while (true) {
688 int count = in.read(buffer);
689 if (count == -1) {
690 break;
691 }
692 output2.write(buffer, 0, count);
693 }
694 }
695 }
696
697
698 ByteArrayInputStream input2 = new ByteArrayInputStream(output2.toByteArray());
699
700 input = new ObjectInputStream(input2);
701
702 //input = output2.toByteArray();
703
704 //output = new ObjectOutputStream(output2);
705 }
706
707 public void encryptMsg(String msg) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, UnknownHostException, IOException {
708 Cipher cipher = Cipher.getInstance("RC4");
709 KeyGenerator generator = KeyGenerator.getInstance("RC4");
710 String pass = "haslo";
711 MessageDigest md = MessageDigest.getInstance("SHA-256");
712 byte[] klucz = md.digest(pass.getBytes(StandardCharsets.UTF_8));
713 generator.init(new SecureRandom(klucz));
714 SecretKey key = generator.generateKey();
715 cipher.init(Cipher.DECRYPT_MODE, key);
716
717 InetAddress address = InetAddress.getByName("127.0.0.1");
718 int port = 12345;
719 Socket socket = new Socket(address, port);
720 InputStream input = socket.getInputStream();
721 System.out.println(input);
722 try (InputStream in = input) {
723 try (OutputStream out = new CipherOutputStream(new FileOutputStream("test3.txt"), cipher)) {
724 byte[] buffer = new byte[256];
725 while (true) {
726 int count = in.read(buffer);
727 if (count == -1) {
728 break;
729 }
730 System.out.println(out);
731 out.write(buffer, 0, count);
732 }
733 }
734 }
735 }
736
737 public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
738 Serwer serw1 = new Serwer(); // constr - GUI
739 serw1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
740 serw1.startRunning(); // start execution
741
742 }
743}