Rabu, 23 April 2014

J2SE Encrypt MD5 with GUI


/** 9022fb1f3cf3e595b6ef6deb22d5528e **/

/**
 * Wednesday, 23 April 2014 09:36:25 PM
 * Java Encrypt MD5 
 * Dengan File Format .txt
 *
 **/

/**
 * Studi Kasus:
 *
 * Terdapat sebuah Universitas yang membuat sistem dengan model enkripsi data nilai Mahasiswa.
 * Kemudian nilai asli diberikan kepada Mahasiswa tersebut jika terjadi perubahan
 * pada Nilai yang dilakukan oleh Mahasiswa dapat dilakukan pengujian enkripsi dengan
 * melakukan perbandingan enkripsi yang sebelumnya sudah disimpan pada database.
 *
 **/

/**
 * Logika:
 *
 * Pilih File (Format: .txt) -> Ambil Isi File ->
 * Pindahkan ke Variabel -> Fungsi MD5 -> Hasil Output
 *
 **/

/**
 * Link:
 * 
 * http://stackoverflow.com/questions/21870607/java-test-for-md5-using-a-file
 * http://www.asjava.com/core-java/java-md5-example/
 * 
 **/

/**
 * Hasil Program:
 * 
 * File: JavaMD5Doc.txt
 * MD5: 2211309a572e1764490356784565f4dd
 * Isi File: Firmansyah Maulana
 * 
 * File: JavaMD5Doc.txt
 * MD5: 9ba13c41ceb4d3f211df4da7f106663b
 * Isi File: Firmansyah Maulana 2
 * 
 * File: JavaMD5Doc2.txt
 * MD5: 2211309a572e1764490356784565f4dd 
 * Isi File: Firmansyah Maulana
 * 
 * File: JavaMD5Doc2.txt
 * MD5: 9ba13c41ceb4d3f211df4da7f106663b 
 * Isi File: Firmansyah Maulana 2
 * 
 **/

/** 9022fb1f3cf3e595b6ef6deb22d5528e **/

/**
 * Tampilan Program:
 * 
 **/


Gambar 1 Tampilan Awal Aplikasi.

Gambar 2 Ambil File Dari Direktori.

Gambar 3 Tampil Isi File.


Gambar 4 Hasil Encrypt MD5.


/**
 * Code Program:
 * 
 **/

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javamd5example2;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author firmansyahMYE
 * firmansyahmye@gmail.com
 * 
 */
public class JavaMD5Example2 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new JavaMD5Example2();
    }
    
    public JavaMD5Example2() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("J2SE Encrypt MD5");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridx = 0;
                gbc.gridy = 0;
                gbc.weighty = 1;
                gbc.weightx = 1;
                gbc.fill = GridBagConstraints.BOTH;

                final FilePane sourcePane = new FilePane(true);
                final FilePane encryptPane = new FilePane(false);

                frame.add(sourcePane, gbc);
                gbc.gridx = 2;
                frame.add(encryptPane, gbc);

                JButton encrypt = new JButton("Encrypt >>");
                JPanel panel = new JPanel(new GridBagLayout());
                panel.add(encrypt);

                encrypt.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        File source = sourcePane.getFile();
                        try (BufferedReader br = new BufferedReader(new FileReader(source))) {
                            char[] buffer = new char[1024];
                            StringBuilder sb = new StringBuilder(1024);
                            int bytesRead = -1;
                            while ((bytesRead = br.read(buffer)) != -1) {
                                sb.append(buffer, 0, bytesRead);
                            }
                            String encrypted = encryptionMD5(sb.toString());

                            File enrypt = new File(source.getPath() + ".enrypted");
                            try (BufferedWriter bw = new BufferedWriter(new FileWriter(enrypt))) {
                                bw.write(encrypted);
                            } catch (Exception exp) {
                                exp.printStackTrace();
                            }

                            encryptPane.setFile(enrypt);

                        } catch (Exception exp) {
                            exp.printStackTrace();
                        }
                    }
                });

                gbc.gridx = 1;
                gbc.weighty = 1;
                gbc.weightx = 0;
                gbc.fill = GridBagConstraints.VERTICAL;
                frame.add(panel, gbc);

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
    
    public static String encryptionMD5(String token) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(token.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    
    public class FilePane extends JPanel {

        private JTextField field;
        private JButton browse;
        private JTextArea content;

        private File file;

        public FilePane(boolean canOpen) {
            setLayout(new BorderLayout());

            field = new JTextField();
            field.setEditable(false);

            content = new JTextArea(20, 20);
            content.setEditable(false);

            add(new JScrollPane(content));

            JPanel header = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.weightx = 1;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            header.add(field, gbc);
            gbc.gridx = 1;
            gbc.weightx = 0;
            gbc.fill = GridBagConstraints.NONE;
            if (canOpen) {
                browse = new JButton("...");
                browse.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JFileChooser chooser = new JFileChooser();
                        chooser.setCurrentDirectory(new File(System.getProperty("user.dir")));
                        chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
                        switch (chooser.showOpenDialog(FilePane.this)) {
                            case JFileChooser.APPROVE_OPTION:
                                setFile(chooser.getSelectedFile());
                                break;
                        }
                    }
                });
                header.add(browse, gbc);
            }

            add(header, BorderLayout.NORTH);

        }

        public File getFile() {
            return file;
        }

        public void setFile(File f) {
            file = f;
            field.setText(file.getPath());
            if (file != null) {
                try (Reader r = new FileReader(file)) {
                    content.read(r, file);
                } catch (Exception exp) {
                }
            } else {
                content.setText(null);
            }
            content.setCaretPosition(0);
        }

    }
}


/** 9022fb1f3cf3e595b6ef6deb22d5528e **/