Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Bourdoux.Team;
- import javax.crypto.KeyGenerator;
- import javax.crypto.NoSuchPaddingException;
- import javax.crypto.spec.SecretKeySpec;
- import javax.swing.*;
- import java.awt.Dimension;
- import java.awt.Toolkit;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.io.*;
- import java.nio.charset.StandardCharsets;
- import java.security.*;
- import java.util.Scanner;
- import javax.swing.JFrame;
- /**
- * Created by Luís on 11/11/2016.
- */
- public class MainForm extends javax.swing.JFrame {
- private JTabbedPane tabbedPane1;
- private JPanel rootPanel;
- private JTextPane textArea;
- private JButton buttonNew;
- private JButton buttonSave;
- private JButton buttonLoad;
- private JButton buttonQuit;
- private JTextField statusField;
- private JButton signatureButton;
- private JButton Sign;
- public MainForm() {
- //-------------------Definições do Painel que aparece na Form-----------------------------------------
- setContentPane(rootPanel);
- setTitle("Editor Cipher Text");
- //Coloca a form a meio do ecrã com metade da resolução em altura e largura
- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
- int height = screenSize.height;
- int width = screenSize.width;
- setSize(width / 2, height / 2);
- setLocationRelativeTo(null);
- setResizable(true);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- //Events----------------------------------------------------------------------------------------------
- buttonNew.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- textArea.setText("");
- statusField.setText("New file");
- }
- });
- //-------------------------------------------------------------SAVE BUTTON------------------------------------------------------------
- buttonSave.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JFileChooser chooser = new JFileChooser();
- String[] option = new String[]{"Cipher", "Autenticate", "Cipher and Autenticate", "Cancel"};
- int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
- String s = textArea.getText();
- if (response == 0) { //------------------------Apenas CIFRAR---------------------------
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- if (Save_and_Load.save_cipher(s, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())) {
- JOptionPane.showMessageDialog(null, "File successfull saved! File keys-and-iv.txt created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
- } else {
- JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Encrypted!", "Error", JOptionPane.ERROR_MESSAGE);
- }
- }
- } else {
- if (response == 1) { //--------------------Apenas AUTENTICAR------------------------
- int chooserValue = chooser.showSaveDialog(null);
- if(chooserValue==JFileChooser.APPROVE_OPTION) {
- byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
- if (Save_and_Load.saveHmac(stream, chooser.getSelectedFile() + "\"keys.txt\"", chooser.getSelectedFile().toString())) {
- JOptionPane.showMessageDialog(null, "File successfull saved! File \"keys-and-iv.txt\" created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
- }
- else
- {
- JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Signed!", "Error", JOptionPane.ERROR_MESSAGE);
- }
- }
- } else if (response == 2) { //------------- CIFRA e AUTENTICA-----------------------
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
- if (Save_and_Load.save_cipher(s, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())
- && Save_and_Load.saveHmac(stream, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())) {
- JOptionPane.showMessageDialog(null, "File successfull saved! File keys-and-iv.txt created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
- } else {
- JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Encrypted and Signed!", "Error", JOptionPane.ERROR_MESSAGE);
- }
- }
- } else {
- //------------------------------------------CANCELA--------------------------------
- statusField.setText("Cancelled");
- }
- }
- }
- });
- //-------------------------------------------------------------LOAD BUTTON--------------------------------------------------------------
- buttonLoad.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JFileChooser chooser = new JFileChooser();
- String[] option = new String[]{"Cipher", "Autenticate", "Cipher and Autenticate", "Cancel"};
- int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
- if (response == 0 || response == 2 ) { //------------------------Apenas CIFRAR---------------------------
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- ByteArrayOutputStream ous = null;
- InputStream ios = null;
- byte[] buffer = new byte[4096];
- ous = new ByteArrayOutputStream();
- //Coloca <nome do ficheiro + keys.txt> no URL do ficheiro Key.txt a abrir
- String fileUrl = chooser.getSelectedFile() + "keys.txt";
- String plainfile = String.valueOf(chooser.getSelectedFile());
- //Verifica se ficheiro key.txt acompanha o ficheiro cifrado
- String file = fileUrl;
- File f = new File(file);
- if (!f.exists()) { //Se não encontra o ficheiro keys.txt, pede-o ao utilizador
- JOptionPane.showMessageDialog(null, "Key file not found! Select the location of key file!", "Error", JOptionPane.INFORMATION_MESSAGE);
- JFileChooser chooser2 = new JFileChooser();
- int newkeyfile = chooser2.showOpenDialog(null);
- if (newkeyfile == JFileChooser.APPROVE_OPTION) {
- fileUrl = String.valueOf(chooser2.getSelectedFile());
- } else {
- //Caso queira abrir ficheiro na mesma
- JOptionPane.showMessageDialog(null, "Plain text file will open", "Information", JOptionPane.INFORMATION_MESSAGE);
- }
- }
- //Lê o ficheiro keys.txt
- try {
- ios = new FileInputStream(fileUrl);
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
- int read = 0;
- if (ios != null) { //-----------CASO FICHEIRO Keys.txt EXISTA----------------
- try {
- while ((read = ios.read(buffer)) != -1) {
- ous.write(buffer, 0, read);
- byte[] bytes_from_file = ous.toByteArray();
- byte[] key_bytes = new byte[141];
- byte[] iv_bytes = new byte[16];
- byte[] hmac = new byte[32];
- System.arraycopy(bytes_from_file, 0, key_bytes, 0, 141);
- SecretKeySpec key2 = (SecretKeySpec) UtilityByteConvert.bytesToObject(key_bytes);
- System.arraycopy(bytes_from_file, 141, iv_bytes, 0, 16);
- System.arraycopy(bytes_from_file, 157, hmac, 0, 32);
- //Leitura do ficheiro cifrado
- buffer = Read_and_write.read(new FileInputStream(chooser.getSelectedFile()), (int) chooser.getSelectedFile().length());
- byte[] buffer_hmac = new byte[buffer.length-32];
- byte[] hmacTest = new byte[32];
- System.arraycopy(buffer, 0 , hmacTest , 0 , 32);
- System.arraycopy(buffer , 32 , buffer_hmac , 0 , buffer_hmac.length);
- if ( hmac == hmacTest) {
- System.out.println("okapa");
- //Decifra o ficheiro
- }else System.out.println("fodas");
- String s = Cipher_Functions.denc_CTR(buffer_hmac, key2, iv_bytes);
- if (!Cipher_Functions.verifyHMAC256(hmac, buffer, key2))
- statusField.setText("ERRO , ficheiro possivelmente corrompido");
- else
- statusField.setText("Abertura bem conseguida");
- //Mostra o texto Limpo no Editor
- textArea.setText(s);
- }//GEN-LAST:event_loadButtonActionPerformed
- } catch (IOException | NoSuchPaddingException | NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | InvalidKeyException e1) {
- e1.printStackTrace();
- }
- } else {//-----------CASO FICHEIRO Keys.txt SEJA IGNORADO----------------
- try {
- String plaint = Read_and_write.CleanTextRead(plainfile);
- textArea.setText(plaint);
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- }
- }
- } else if (response == 1) {
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- ByteArrayOutputStream ous = null;
- InputStream ios = null;
- byte[] buffer = new byte[4096];
- ous = new ByteArrayOutputStream();
- //Coloca <nome do ficheiro + keys.txt> no URL do ficheiro Key.txt a abrir
- String fileUrl = chooser.getSelectedFile() + "keys.txt";
- String plainfile = String.valueOf(chooser.getSelectedFile());
- //Verifica se ficheiro key.txt acompanha o ficheiro cifrado
- String file = fileUrl;
- File f = new File(file);
- if (!f.exists()) { //Se não encontra o ficheiro keys.txt, pede-o ao utilizador
- JOptionPane.showMessageDialog(null, "Key file not found! Select the location of key file!", "Error", JOptionPane.INFORMATION_MESSAGE);
- JFileChooser chooser2 = new JFileChooser();
- int newkeyfile = chooser2.showOpenDialog(null);
- if (newkeyfile == JFileChooser.APPROVE_OPTION) {
- fileUrl = String.valueOf(chooser2.getSelectedFile());
- } else {
- //Caso queira abrir ficheiro na mesma
- JOptionPane.showMessageDialog(null, "Plain text file will open", "Information", JOptionPane.INFORMATION_MESSAGE);
- }
- }
- //Lê o ficheiro keys.txt
- try {
- ios = new FileInputStream(fileUrl);
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- }
- int read = 0;
- if (ios != null) { //-----------CASO FICHEIRO Keys.txt EXISTA----------------
- try {
- while ((read = ios.read(buffer)) != -1) {
- ous.write(buffer, 0, read);
- byte[] bytes_from_file = ous.toByteArray();
- byte[] key_bytes = new byte[141];
- byte[] iv_bytes = new byte[16];
- byte[] hmac = new byte[32];
- System.arraycopy(bytes_from_file, 0, key_bytes, 0, 141);
- SecretKeySpec key2 = (SecretKeySpec) UtilityByteConvert.bytesToObject(key_bytes);
- System.arraycopy(bytes_from_file, 141, iv_bytes, 0, 16);
- System.arraycopy(bytes_from_file, 157, hmac, 0, 32);
- //Leitura do ficheiro cifrado
- buffer = Read_and_write.read(new FileInputStream(chooser.getSelectedFile()), (int) chooser.getSelectedFile().length());
- if (!Cipher_Functions.verifyHMAC256(hmac, buffer, key2))
- statusField.setText("ERRO , ficheiro possivelmente corrompido");
- else
- statusField.setText("Abertura bem conseguida");
- //Mostra o texto Limpo no Editor
- textArea.setText((String) UtilityByteConvert.bytesToObject(buffer));
- }
- } catch (NoSuchAlgorithmException e1) {
- e1.printStackTrace();
- } catch (FileNotFoundException e1) {
- e1.printStackTrace();
- } catch (IOException e1) {
- e1.printStackTrace();
- } catch (InvalidKeyException e1) {
- e1.printStackTrace();
- }
- }
- }
- }
- else {
- //------------------------------------------CANCELA--------------------------------
- statusField.setText("Cancelled");
- }
- }
- });
- //-------------------------------------------------------------SIGNATURE BUTTON--------------------------------------------------------------
- signatureButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- //O que faz este botão
- JFileChooser chooser = new JFileChooser();
- String[] option = new String[]{"Sign", "Verify" , "Cancel"};
- int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
- if (response==0){
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
- KeyPairGenerator keyGen = null;
- try {
- keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
- SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
- keyGen.initialize(1024, random);
- KeyPair keyPair = keyGen.generateKeyPair();
- PrivateKey privateKey = keyPair.getPrivate();
- PublicKey publicKey = keyPair.getPublic();
- byte[] signText = Cipher_Functions.sign(chooser.getSelectedFile().toString(), privateKey, "DSA");
- FileOutputStream fos = new FileOutputStream(chooser.getSelectedFile() + "PK.txt" );
- FileOutputStream fos1 = new FileOutputStream(chooser.getSelectedFile() + "SK.txt" );
- Read_and_write.writePK(fos ,UtilityByteConvert.objectToBytes( publicKey));
- Read_and_write.writeSK(fos1 , UtilityByteConvert.objectToBytes(privateKey));
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- }
- else if (response==1){
- // static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[] sigbytes)
- int chooserValue = chooser.showSaveDialog(null);
- if (chooserValue == JFileChooser.APPROVE_OPTION) {
- byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
- }
- }
- });
- //-------------------------------------------------------------QUIT BUTTON--------------------------------------------------------------
- buttonQuit.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- System.exit(0);
- }
- });
- }
- //--------------------------------------------------MAIN--------------------------------------------------
- public static void main(String args[]) {
- java.awt.EventQueue.invokeLater(new Runnable(){
- public void run() {
- MainForm mainform = new MainForm();
- mainform.setVisible(true); //Mostra a form
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement