com.cactus.ClientChatGUI.java Source code

Java tutorial

Introduction

Here is the source code for com.cactus.ClientChatGUI.java

Source

package com.cactus;

import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

import javax.swing.GroupLayout;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.WindowConstants;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.security.*;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.*;
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author imdak_000
 */
public class ClientChatGUI extends JFrame {

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private JButton Send_Button; //Send_Button
    private JButton Back_Button; //Back_Button
    private JScrollPane jScrollPane1;
    private JTextArea Chat_Area; //Chat_Area
    private JTextField Message_Area; //Message_Area
    private User user;
    // End of variables declaration//GEN-END:variables

    /**
     * Creates new form ClientChatGUI
     */

    public ClientChatGUI(User user) {
        this.user = user;
        setResizable(false);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        Message_Area = new JTextField();
        Send_Button = new JButton();
        Back_Button = new JButton();
        jScrollPane1 = new JScrollPane();
        Chat_Area = new JTextArea();

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Send_Button.setText("Send");
        Send_Button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                try {
                    Send_ButtonActionPerformed(evt);
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });

        Chat_Area.setColumns(20);
        Chat_Area.setRows(5);
        Chat_Area.setEditable(false);
        jScrollPane1.setViewportView(Chat_Area);

        try {
            updateChatBox();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Back_Button.setText("Back");
        Back_Button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                Back_ButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new GroupLayout(getContentPane());
        layout.setHorizontalGroup(layout.createParallelGroup(Alignment.TRAILING).addGroup(layout
                .createSequentialGroup().addContainerGap()
                .addGroup(layout.createParallelGroup(Alignment.TRAILING)
                        .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 412, Short.MAX_VALUE)
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(
                                        Message_Area, GroupLayout.PREFERRED_SIZE, 337, GroupLayout.PREFERRED_SIZE)
                                .addGap(18)
                                .addGroup(layout.createParallelGroup(Alignment.TRAILING, false)
                                        .addComponent(Back_Button, 0, 0, Short.MAX_VALUE).addComponent(Send_Button,
                                                GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE,
                                                Short.MAX_VALUE))))
                .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(Alignment.TRAILING).addGroup(layout
                .createSequentialGroup().addContainerGap()
                .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE).addGap(18)
                .addGroup(layout.createParallelGroup(Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addComponent(Send_Button)
                                .addPreferredGap(ComponentPlacement.RELATED, GroupLayout.DEFAULT_SIZE,
                                        Short.MAX_VALUE)
                                .addComponent(Back_Button))
                        .addComponent(Message_Area, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE))
                .addContainerGap()));
        getContentPane().setLayout(layout);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    //updates the chat window to fill it with messages from the database between the two users.   
    private void updateChatBox() throws ClientProtocolException, IOException, JSONException {
        //httpGet Get Messages
        Chat_Area.setText("");

        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(
                "https://teamcactus.us/Get_Message.php?conversation=" + user.getconversation());

        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-type", "application/json");
        httpGet.setHeader("Authorization", "Bearer " + user.getJWT());

        HttpResponse response = client.execute(httpGet);

        // Getting the status code.
        //int statusCode = response.getStatusLine().getStatusCode();

        // Getting the response body.
        String responseBody = EntityUtils.toString(response.getEntity());

        System.out.println(responseBody);
        System.out.println(user.getconversation());
        JSONObject obj = new JSONObject(responseBody);

        //System.out.println(obj);

        String status = obj.getString("status");

        if (status.equals("success")) {

            ArrayList<String> conversation = new ArrayList<String>();
            JSONArray messagearray = obj.getJSONArray("messages");

            System.out.println(messagearray);

            //takes each message JSONArray and converts it into a readable chat message format
            if (messagearray != null) {
                int len = messagearray.length();
                System.out.println(len);
                for (int i = 0; i < len; i++) {

                    JSONObject messageobject = messagearray.getJSONObject(i);

                    String time_stamp = messageobject.getString("time_stamp");
                    String sender = messageobject.getString("sender");
                    String message = messageobject.getString("message");
                    String messageKey = messageobject.getString("messageKey");

                    //turn the message back into a byte[]
                    byte[] cipherTextAndTag = Base64.decodeBase64(message);
                    //turn messageKey back into byte[]
                    byte[] keysCipherText = Base64.decodeBase64(messageKey);

                    /*
                     * DECRYPT THE ENCRYPTED MESSAGE HERE
                     * 
                     * 
                     */

                    String message_block = "[" + time_stamp + "] " + sender + " : " + message;
                    conversation.add(message_block);
                    System.out.println(message_block);
                }
                //displays every message to the chat window text area
                for (Object temp : conversation) {
                    Chat_Area.append(temp.toString() + "\n");
                }
            } else {
                //error where the list of messages from the database is null
            }
        } else {
            //error in pulling messages from the database for this conversation
        }
    }

    private void Send_ButtonActionPerformed(ActionEvent evt)
            throws ClientProtocolException, IOException, Exception, UnsupportedEncodingException {//GEN-FIRST:event_Send_ButtonActionPerformed
        //posts message
        String message = Message_Area.getText();
        //AES functions
        AES AESmanager = new AES();
        //Generate two AES keys and encrypt the message with one of them
        byte[] messageByte = message.getBytes();
        SecretKey aesEncryptKey = AESmanager.generateKey();
        SecretKey aesHMACKey = AESmanager.generateKey();
        byte[] cipherTextByte = AESmanager.encrypt(aesEncryptKey, messageByte);
        //Turn generated keys into bytes
        byte[] aesEncryptKeyByte = aesEncryptKey.getEncoded();
        byte[] aesHMACKeyByte = aesHMACKey.getEncoded();
        //HMAC functions and create integrity tag from HMAC key and ciphertext
        HMAC HMACmanager = new HMAC();
        byte[] HMACintegrityTag = HMACmanager.encrypt(aesHMACKeyByte, cipherTextByte);
        //concatenate generated aes keys to make keys plaintext
        byte[] keysPlaintext = new byte[aesEncryptKeyByte.length + aesHMACKeyByte.length];
        System.arraycopy(aesEncryptKeyByte, 0, keysPlaintext, 0, aesEncryptKeyByte.length);
        System.arraycopy(aesHMACKeyByte, 0, keysPlaintext, aesEncryptKeyByte.length, aesHMACKeyByte.length);
        //concatenate ciphertext with the integrity tag
        byte[] cipherTextAndTag = new byte[cipherTextByte.length + HMACintegrityTag.length];
        System.arraycopy(cipherTextByte, 0, cipherTextAndTag, 0, cipherTextByte.length);
        System.arraycopy(HMACintegrityTag, 0, cipherTextAndTag, cipherTextByte.length, HMACintegrityTag.length);
        //encrypt keys plaintext using RSA OAEP
        RSA RSAmanager = new RSA();
        byte[] keysCipherText = RSAmanager.encryptKeysPlaintext(keysPlaintext, user.getFriendPublicKey());

        //turns CipherTextandTag into a String
        String encryptedMessage = Base64.encodeBase64String(cipherTextAndTag);
        //turns keysCipherText into a String
        String messageKey = Base64.encodeBase64String(keysCipherText);

        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost("https://teamcactus.us/Post_Message.php");

        String json = "{\"message\":\"" + encryptedMessage + "\",\"receiver\":\"" + user.getfriend()
                + "\",\"conversation_id\":\"" + user.getconversation() + "\",\"messageKey\":\"" + messageKey
                + "\"}";
        StringEntity entity = new StringEntity(json);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setHeader("Authorization", "Bearer " + user.getJWT());

        HttpResponse response = client.execute(httpPost);

        String responseBody = EntityUtils.toString(response.getEntity());

        JSONObject obj = new JSONObject(responseBody);

        String status = obj.getString("status");

        if (status.equals("success")) {
            System.out.print("message sent!");

            updateChatBox();

            Message_Area.setText("");
        }
        // TODO add your handling code here:
    }//GEN-LAST:event_Send_ButtonActionPerformed

    private void Back_ButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_Back_ButtonActionPerformed
        //goes back to homepage
        this.dispose();
        new ClientHomeGUI(user).setVisible(true);
        // TODO add your handling code here:
    }//GEN-LAST:event_Back_ButtonActionPerformed
}