
package fortuna;

/**
 *
 * @author Viliam Krizan
 */

import aalg.crypto.AesCipher;
import fortuna.entropySources.EntropySource;
import fortuna.entropySources.keyboard.KeyboardES;
import fortuna.entropySources.microphone.CaptureMicrophoneData;
import fortuna.entropySources.mouse.MouseES;
import fortuna.entropySources.system.SystemES;
import fortuna.entropySources.webcam.CaptureWebcam;
import fortuna.generator.BlockCipherGenerator;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;


public class GUI extends javax.swing.JFrame {
    BlockCipherGenerator aesCipherGenerator;
    Fortuna fortuna;
    EntropySource microphone, webcam, mouse, ses, keyboard;
    javax.swing.Timer timer;
    FileWriter fw;
    String s1,s2;
    JFileChooser chooser;
    
    public GUI() {
        initComponents();
        generateButton.setEnabled(false);
        aesCipherGenerator = new BlockCipherGenerator(new AesCipher(32));
        fortuna = new Fortuna(aesCipherGenerator);
        
        
        chooser = new JFileChooser();
        //File file = new File("C:/untitled.txt");
        //fileChooser.setCurrentDirectory(file);
        try {
                //fw =  new FileWriter(chooser.getSelectedFile()+".txt");
                //fw = new FileWriter(System.clearProperty("user.home"));
                fw =  new FileWriter("CP.txt");
            } catch (Exception e) {
        }
    }

    /**
     * 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() {

        jToggleButton1 = new javax.swing.JToggleButton();
        mouseCheckBox = new javax.swing.JCheckBox();
        keyboardCheckBox = new javax.swing.JCheckBox();
        microphoneCheckBox = new javax.swing.JCheckBox();
        webcamCheckBox = new javax.swing.JCheckBox();
        systemCheckBox = new javax.swing.JCheckBox();
        generateButton = new javax.swing.JButton();
        jTextField1 = new javax.swing.JTextField();
        saveButton = new javax.swing.JButton();

        jToggleButton1.setText("jToggleButton1");

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        mouseCheckBox.setText("Mouse");
        mouseCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mouseCheckBoxActionPerformed(evt);
            }
        });

        keyboardCheckBox.setText("Keyboard");
        keyboardCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                keyboardCheckBoxActionPerformed(evt);
            }
        });

        microphoneCheckBox.setText("Microphone");
        microphoneCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                microphoneCheckBoxActionPerformed(evt);
            }
        });

        webcamCheckBox.setText("Webcam");
        webcamCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                webcamCheckBoxActionPerformed(evt);
            }
        });

        systemCheckBox.setText("System");
        systemCheckBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                systemCheckBoxActionPerformed(evt);
            }
        });

        generateButton.setText("Generate");
        generateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                generateButtonActionPerformed(evt);
            }
        });

        jTextField1.setText("20");
        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(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)
                    .addComponent(mouseCheckBox)
                    .addComponent(keyboardCheckBox)
                    .addComponent(microphoneCheckBox)
                    .addComponent(webcamCheckBox)
                    .addComponent(systemCheckBox)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(saveButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(generateButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap(89, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(mouseCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(keyboardCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(microphoneCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(webcamCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(systemCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(saveButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(generateButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void mouseCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mouseCheckBoxActionPerformed
        mouse = new MouseES();
        fortuna.addEntropySource(mouse);
        mouseCheckBox.setEnabled(false);
        generateButtonEnable();
    }//GEN-LAST:event_mouseCheckBoxActionPerformed

    private void generateButtonEnable(){
            ActionListener onTimer = new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    if(fortuna.reseed()){
                        timer.stop();
                        generateButton.setEnabled(true);
                    }
                }
            };
            timer = new javax.swing.Timer(1000,onTimer);
            timer.start();
    }
        
    
    private void generateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_generateButtonActionPerformed
        
        byte[] result;
        String st = jTextField1.getText();
        try {
            result = new byte[new Integer(st)];
        } catch (Exception e) {
            result = new byte[20];
        }
        fortuna.generateRandomData(result);
        
        for (int i = 0; i < result.length; i++) {
            try {
                //s1 = String.format("%32s", Integer.toBinaryString(result[i] & 0xFF)).replace(' ', '0');
                //s2 = s1.substring(24) + System.lineSeparator();
                
                s1 = Integer.toHexString(result[i] & 0xFF);
                //s2 = s1.substring(8);
                fw.write("0x" + s1 + System.lineSeparator());
                
                
                
                //fw.write(Integer.toBinaryString(new Integer(result[i])).substring(Integer.SIZE - Byte.SIZE));
                //fw.write(Byte.toString(result[i]) + System.lineSeparator());
            } catch (IOException ex) {
            }
        }
               
        //reseed after each request
        generateButton.setEnabled(false);
        generateButtonEnable();
        //fortuna.reseed();
    }//GEN-LAST:event_generateButtonActionPerformed

    private void microphoneCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_microphoneCheckBoxActionPerformed
        microphone = new CaptureMicrophoneData();
        fortuna.addEntropySource(microphone);
        microphoneCheckBox.setEnabled(false);
        generateButtonEnable();
    }//GEN-LAST:event_microphoneCheckBoxActionPerformed

    private void webcamCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_webcamCheckBoxActionPerformed
        webcam = new CaptureWebcam();
        fortuna.addEntropySource(webcam);
        webcamCheckBox.setEnabled(false);
        generateButtonEnable();
    }//GEN-LAST:event_webcamCheckBoxActionPerformed

    private void systemCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_systemCheckBoxActionPerformed
        ses = new SystemES();
        fortuna.addEntropySource(ses);
        systemCheckBox.setEnabled(false);
        generateButtonEnable();
    }//GEN-LAST:event_systemCheckBoxActionPerformed

    private void keyboardCheckBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_keyboardCheckBoxActionPerformed
        keyboard = new KeyboardES();
        fortuna.addEntropySource(keyboard);
        keyboardCheckBox.setEnabled(false);
        generateButtonEnable();
    }//GEN-LAST:event_keyboardCheckBoxActionPerformed

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jTextField1ActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        chooser = new JFileChooser();
        int retrieval = chooser.showSaveDialog(null);
        if(retrieval == JFileChooser.APPROVE_OPTION){
            try {
                fw =  new FileWriter(chooser.getSelectedFile()+".txt");
            } catch (Exception e) {
            }
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    public static void main(String args[]) {

        /* Create and display the form */
        GUI gui = new GUI();
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                gui.setVisible(true);
            }
        });
        
        Runtime.getRuntime().addShutdownHook(new Thread(){
            public void run(){
                try {
                    gui.fw.close();
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
                gui.fortuna.finish();
                }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton generateButton;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    private javax.swing.JCheckBox keyboardCheckBox;
    private javax.swing.JCheckBox microphoneCheckBox;
    private javax.swing.JCheckBox mouseCheckBox;
    private javax.swing.JButton saveButton;
    private javax.swing.JCheckBox systemCheckBox;
    private javax.swing.JCheckBox webcamCheckBox;
    // End of variables declaration//GEN-END:variables
}
