secureemailclient.applet.ViewMailFrame.java Source code

Java tutorial

Introduction

Here is the source code for secureemailclient.applet.ViewMailFrame.java

Source

/*
 * 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.
 */
package secureemailclient.applet;

import com.google.api.client.util.Base64;
import com.google.api.services.gmail.model.Message;
import com.google.api.services.gmail.model.MessagePart;
import com.google.api.services.gmail.model.MessagePartHeader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.apache.commons.lang3.StringEscapeUtils;
import secureemailclient.crypto.CryptoHelper;
import secureemailclient.crypto.blockcipher.BlockCipher;
import secureemailclient.crypto.ecc.ECC;
import secureemailclient.crypto.ecc.PairRS;
import secureemailclient.crypto.ecc.PrivateKey;
import secureemailclient.crypto.ecc.PublicKey;

/**
 *
 * @author Toshiba
 */
public class ViewMailFrame extends javax.swing.JFrame {

    /**
     * Creates new form ViewMailFrame
     */
    public ViewMailFrame(String messageId) {
        initComponents();

        setTitle(SecureEmailClient.APP_NAME + " - View Mail");
        // 
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        // load message
        loadMessage(messageId);
    }

    /**
     * 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.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabelSubject = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabelFrom = new javax.swing.JLabel();
        jLabelTo = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextAreaBody = new javax.swing.JTextArea();
        jLabel6 = new javax.swing.JLabel();
        jLabelDate = new javax.swing.JLabel();
        jButtonReply = new javax.swing.JButton();
        jButtonForward = new javax.swing.JButton();
        jButtonDecrypt = new javax.swing.JButton();
        jButtonVerify = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabelSubject.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabelSubject.setText("Email Subject");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel2.setText("from");

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel3.setText("to");

        jLabelFrom.setText("from");

        jLabelTo.setText("to");

        jTextAreaBody.setColumns(20);
        jTextAreaBody.setRows(5);
        jScrollPane1.setViewportView(jTextAreaBody);

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel6.setText("date");

        jLabelDate.setText("date");

        jButtonReply.setText("Reply");
        jButtonReply.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonReplyActionPerformed(evt);
            }
        });

        jButtonForward.setText("Forward");
        jButtonForward.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonForwardActionPerformed(evt);
            }
        });

        jButtonDecrypt.setText("Decrypt");
        jButtonDecrypt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonDecryptActionPerformed(evt);
            }
        });

        jButtonVerify.setText("Verify");
        jButtonVerify.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerifyActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 37,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 37,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jLabelFrom, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabelDate, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addComponent(jScrollPane1)
                        .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 37,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabelTo, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup().addComponent(jLabelSubject).addGap(0, 0,
                                Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup().addComponent(jButtonReply)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonForward)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 177,
                                        Short.MAX_VALUE)
                                .addComponent(jButtonDecrypt)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonVerify)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jLabelSubject)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel6).addComponent(jLabelDate))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel2).addComponent(jLabelFrom))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jLabel3).addComponent(jLabelTo, javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(18, 18, 18)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 231,
                                javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jButtonReply).addComponent(jButtonForward).addComponent(jButtonVerify)
                                .addComponent(jButtonDecrypt))
                        .addContainerGap()));

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

    private void jButtonDecryptActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonDecryptActionPerformed
        String body = jTextAreaBody.getText();
        if (!CryptoHelper.isBase64Encoded(body)) {
            JOptionPane.showMessageDialog(rootPane, "The body message cannot be decrypted!");
            return;
        }
        byte[] ciphertext = Base64.decodeBase64(body);

        (new MailDecryptFrame(this)).setVisible(true);

    }//GEN-LAST:event_jButtonDecryptActionPerformed

    private void jButtonVerifyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerifyActionPerformed
        String body = jTextAreaBody.getText();
        BufferedReader reader = new BufferedReader(new StringReader(body));
        List<String> lines = new ArrayList<>();
        try {
            String line;
            do {
                line = reader.readLine();
                if (line != null) {
                    lines.add(line);
                }
            } while (line != null);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // check the last three lines
        String[] signature = new String[3];
        if (lines.size() < 3) {
            signature = null;
        } else {
            for (int i = 0; i < 3; ++i) {
                signature[i] = lines.get(lines.size() - 3 + i);
            }
        }

        if (signature == null || !signature[0].equalsIgnoreCase("//DIGITAL SIGNATURE//")) {
            JOptionPane.showMessageDialog(rootPane, "The body message is not signed!");
            return;
        }

        // construct body without signature
        String bodyWithoutSignature = body.substring(0, body.indexOf("\n//DIGITAL SIGNATURE//"));

        PairRS rs = new PairRS(new BigInteger(signature[1], 16), new BigInteger(signature[2], 16));

        PublicKey pk;
        JFileChooser chooser = new JFileChooser();
        chooser.setDialogTitle("Select Public Key");
        int returnVal = chooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            String path = chooser.getSelectedFile().getAbsolutePath();
            pk = new PublicKey(path);
        } else {
            return;
        }

        try {
            boolean verified = ECC.verify(bodyWithoutSignature, pk, rs);
            if (verified) {
                JOptionPane.showMessageDialog(rootPane, "The message is verified!");
            } else {
                JOptionPane.showMessageDialog(rootPane, "The message is not valid or the public key is incorrect!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButtonVerifyActionPerformed

    private void jButtonReplyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonReplyActionPerformed
        JOptionPane.showMessageDialog(rootPane, "Replying email is not available in this beta version");
    }//GEN-LAST:event_jButtonReplyActionPerformed

    private void jButtonForwardActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonForwardActionPerformed
        JOptionPane.showMessageDialog(rootPane, "Forwarding email is not available in this beta version");
    }//GEN-LAST:event_jButtonForwardActionPerformed

    public void loadMessage(String messageId) {
        Map messageDetails = GmailHelper.getMessageDetails(GmailAuth.getService(), messageId);

        jLabelDate.setText(toHtml((String) messageDetails.get("date")));
        jLabelFrom.setText(toHtml((String) messageDetails.get("from")));
        jLabelTo.setText(toHtml((String) messageDetails.get("to")));
        jLabelSubject.setText(toHtml((String) messageDetails.get("subject")));
        jTextAreaBody.setText((String) messageDetails.get("body"));

        // get message components
        //        try {
        //            MessagePart payload = message.getPayload();
        //
        //            String date = null, from = null, to = null, subject = null, body = null;
        //
        //            List<MessagePartHeader> headers = payload.getHeaders();
        //            for (MessagePartHeader header : headers) {
        //                switch (header.getName()) {
        //                    case "To":
        //                        to = header.getValue();
        //                        break;
        //                    case "From":
        //                        from = header.getValue();
        //                        break;
        //                    case "Subject":
        //                        subject = header.getValue();
        //                        break;
        //                    case "Date":
        //                        date = header.getValue();
        //                        break;
        //                }
        //            }
        //
        //            System.out.println(payload.toPrettyString());
        //            
        //            List<MessagePart> parts = payload.getParts();
        ////            body = "";
        //            if (parts == null) {
        //                body = new String(payload.getBody().decodeData(), "UTF-8");
        //            } else {
        //                if (!parts.isEmpty()) {
        //                    body = new String(parts.get(0).getBody().decodeData(), "UTF-8");
        //                }
        //            }
        //
        //            jLabelDate.setText(toHtml(date));
        //            jLabelFrom.setText(toHtml(from));
        //            jLabelTo.setText(toHtml(to));
        //            jLabelSubject.setText(toHtml(subject));
        //            jTextAreaBody.setText(body);
        //
        //        } catch (IOException e) {
        //            e.printStackTrace();
        //        }
    }

    public void decrypt(byte[] key) {
        String body = jTextAreaBody.getText();
        byte[] ciphertext = Base64.decodeBase64(body);
        byte[] plaintext;
        try {
            plaintext = (new BlockCipher()).decrypt(ciphertext, key);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "The passphrase is incorrect!");
            return;
        }
        jTextAreaBody.setText(new String(plaintext));
    }

    public String toHtml(String s) {
        return "<html>" + StringEscapeUtils.escapeHtml4(s) + "</html>";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ViewMailFrame(null).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonDecrypt;
    private javax.swing.JButton jButtonForward;
    private javax.swing.JButton jButtonReply;
    private javax.swing.JButton jButtonVerify;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelDate;
    private javax.swing.JLabel jLabelFrom;
    private javax.swing.JLabel jLabelSubject;
    private javax.swing.JLabel jLabelTo;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextAreaBody;
    // End of variables declaration//GEN-END:variables
}