Advertisement
Guest User

Untitled

a guest
Dec 9th, 2016
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 19.45 KB | None | 0 0
  1. package Bourdoux.Team;
  2.  
  3. import javax.crypto.KeyGenerator;
  4. import javax.crypto.NoSuchPaddingException;
  5. import javax.crypto.spec.SecretKeySpec;
  6. import javax.swing.*;
  7. import java.awt.Dimension;
  8. import java.awt.Toolkit;
  9. import java.awt.event.ActionEvent;
  10. import java.awt.event.ActionListener;
  11. import java.io.*;
  12. import java.nio.charset.StandardCharsets;
  13. import java.security.*;
  14. import java.util.Scanner;
  15. import javax.swing.JFrame;
  16.  
  17. /**
  18. * Created by Luís on 11/11/2016.
  19. */
  20. public class MainForm extends javax.swing.JFrame {
  21. private JTabbedPane tabbedPane1;
  22. private JPanel rootPanel;
  23. private JTextPane textArea;
  24. private JButton buttonNew;
  25. private JButton buttonSave;
  26. private JButton buttonLoad;
  27. private JButton buttonQuit;
  28. private JTextField statusField;
  29. private JButton signatureButton;
  30. private JButton Sign;
  31.  
  32. public MainForm() {
  33. //-------------------Definições do Painel que aparece na Form-----------------------------------------
  34. setContentPane(rootPanel);
  35. setTitle("Editor Cipher Text");
  36.  
  37. //Coloca a form a meio do ecrã com metade da resolução em altura e largura
  38. Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
  39. int height = screenSize.height;
  40. int width = screenSize.width;
  41. setSize(width / 2, height / 2);
  42. setLocationRelativeTo(null);
  43. setResizable(true);
  44. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  45.  
  46. //Events----------------------------------------------------------------------------------------------
  47. buttonNew.addActionListener(new ActionListener() {
  48. @Override
  49. public void actionPerformed(ActionEvent e) {
  50. textArea.setText("");
  51. statusField.setText("New file");
  52. }
  53. });
  54.  
  55. //-------------------------------------------------------------SAVE BUTTON------------------------------------------------------------
  56. buttonSave.addActionListener(new ActionListener() {
  57. @Override
  58. public void actionPerformed(ActionEvent e) {
  59. JFileChooser chooser = new JFileChooser();
  60. String[] option = new String[]{"Cipher", "Autenticate", "Cipher and Autenticate", "Cancel"};
  61. int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
  62. String s = textArea.getText();
  63.  
  64. if (response == 0) { //------------------------Apenas CIFRAR---------------------------
  65. int chooserValue = chooser.showSaveDialog(null);
  66. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  67. if (Save_and_Load.save_cipher(s, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())) {
  68. JOptionPane.showMessageDialog(null, "File successfull saved! File keys-and-iv.txt created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
  69. } else {
  70. JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Encrypted!", "Error", JOptionPane.ERROR_MESSAGE);
  71. }
  72. }
  73. } else {
  74. if (response == 1) { //--------------------Apenas AUTENTICAR------------------------
  75. int chooserValue = chooser.showSaveDialog(null);
  76. if(chooserValue==JFileChooser.APPROVE_OPTION) {
  77. byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
  78. if (Save_and_Load.saveHmac(stream, chooser.getSelectedFile() + "\"keys.txt\"", chooser.getSelectedFile().toString())) {
  79. JOptionPane.showMessageDialog(null, "File successfull saved! File \"keys-and-iv.txt\" created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
  80. }
  81. else
  82. {
  83. JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Signed!", "Error", JOptionPane.ERROR_MESSAGE);
  84. }
  85. }
  86. } else if (response == 2) { //------------- CIFRA e AUTENTICA-----------------------
  87. int chooserValue = chooser.showSaveDialog(null);
  88. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  89. byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
  90. if (Save_and_Load.save_cipher(s, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())
  91. && Save_and_Load.saveHmac(stream, chooser.getSelectedFile() + "keys.txt", chooser.getSelectedFile().toString())) {
  92. JOptionPane.showMessageDialog(null, "File successfull saved! File keys-and-iv.txt created in the directory!", "Information", JOptionPane.INFORMATION_MESSAGE);
  93. } else {
  94. JOptionPane.showMessageDialog(null, "Something happen!.. File cannot be Encrypted and Signed!", "Error", JOptionPane.ERROR_MESSAGE);
  95. }
  96. }
  97. } else {
  98. //------------------------------------------CANCELA--------------------------------
  99. statusField.setText("Cancelled");
  100. }
  101. }
  102. }
  103. });
  104.  
  105. //-------------------------------------------------------------LOAD BUTTON--------------------------------------------------------------
  106. buttonLoad.addActionListener(new ActionListener() {
  107. @Override
  108. public void actionPerformed(ActionEvent e) {
  109. JFileChooser chooser = new JFileChooser();
  110. String[] option = new String[]{"Cipher", "Autenticate", "Cipher and Autenticate", "Cancel"};
  111. int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
  112.  
  113. if (response == 0 || response == 2 ) { //------------------------Apenas CIFRAR---------------------------
  114. int chooserValue = chooser.showSaveDialog(null);
  115. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  116. ByteArrayOutputStream ous = null;
  117. InputStream ios = null;
  118. byte[] buffer = new byte[4096];
  119. ous = new ByteArrayOutputStream();
  120.  
  121. //Coloca <nome do ficheiro + keys.txt> no URL do ficheiro Key.txt a abrir
  122. String fileUrl = chooser.getSelectedFile() + "keys.txt";
  123.  
  124. String plainfile = String.valueOf(chooser.getSelectedFile());
  125.  
  126. //Verifica se ficheiro key.txt acompanha o ficheiro cifrado
  127. String file = fileUrl;
  128. File f = new File(file);
  129.  
  130. if (!f.exists()) { //Se não encontra o ficheiro keys.txt, pede-o ao utilizador
  131. JOptionPane.showMessageDialog(null, "Key file not found! Select the location of key file!", "Error", JOptionPane.INFORMATION_MESSAGE);
  132. JFileChooser chooser2 = new JFileChooser();
  133.  
  134. int newkeyfile = chooser2.showOpenDialog(null);
  135.  
  136. if (newkeyfile == JFileChooser.APPROVE_OPTION) {
  137. fileUrl = String.valueOf(chooser2.getSelectedFile());
  138. } else {
  139. //Caso queira abrir ficheiro na mesma
  140. JOptionPane.showMessageDialog(null, "Plain text file will open", "Information", JOptionPane.INFORMATION_MESSAGE);
  141. }
  142. }
  143.  
  144. //Lê o ficheiro keys.txt
  145. try {
  146. ios = new FileInputStream(fileUrl);
  147. } catch (FileNotFoundException e1) {
  148. e1.printStackTrace();
  149. }
  150.  
  151. int read = 0;
  152.  
  153. if (ios != null) { //-----------CASO FICHEIRO Keys.txt EXISTA----------------
  154. try {
  155. while ((read = ios.read(buffer)) != -1) {
  156. ous.write(buffer, 0, read);
  157.  
  158. byte[] bytes_from_file = ous.toByteArray();
  159. byte[] key_bytes = new byte[141];
  160. byte[] iv_bytes = new byte[16];
  161. byte[] hmac = new byte[32];
  162.  
  163. System.arraycopy(bytes_from_file, 0, key_bytes, 0, 141);
  164.  
  165. SecretKeySpec key2 = (SecretKeySpec) UtilityByteConvert.bytesToObject(key_bytes);
  166. System.arraycopy(bytes_from_file, 141, iv_bytes, 0, 16);
  167.  
  168. System.arraycopy(bytes_from_file, 157, hmac, 0, 32);
  169.  
  170. //Leitura do ficheiro cifrado
  171. buffer = Read_and_write.read(new FileInputStream(chooser.getSelectedFile()), (int) chooser.getSelectedFile().length());
  172. byte[] buffer_hmac = new byte[buffer.length-32];
  173. byte[] hmacTest = new byte[32];
  174. System.arraycopy(buffer, 0 , hmacTest , 0 , 32);
  175. System.arraycopy(buffer , 32 , buffer_hmac , 0 , buffer_hmac.length);
  176. if ( hmac == hmacTest) {
  177. System.out.println("okapa");
  178. //Decifra o ficheiro
  179.  
  180. }else System.out.println("fodas");
  181. String s = Cipher_Functions.denc_CTR(buffer_hmac, key2, iv_bytes);
  182. if (!Cipher_Functions.verifyHMAC256(hmac, buffer, key2))
  183. statusField.setText("ERRO , ficheiro possivelmente corrompido");
  184. else
  185. statusField.setText("Abertura bem conseguida");
  186.  
  187.  
  188. //Mostra o texto Limpo no Editor
  189. textArea.setText(s);
  190. }//GEN-LAST:event_loadButtonActionPerformed
  191. } catch (IOException | NoSuchPaddingException | NoSuchAlgorithmException | NoSuchProviderException | InvalidAlgorithmParameterException | InvalidKeyException e1) {
  192. e1.printStackTrace();
  193. }
  194. } else {//-----------CASO FICHEIRO Keys.txt SEJA IGNORADO----------------
  195. try {
  196. String plaint = Read_and_write.CleanTextRead(plainfile);
  197. textArea.setText(plaint);
  198. } catch (IOException e1) {
  199. e1.printStackTrace();
  200. }
  201. }
  202. }
  203. } else if (response == 1) {
  204.  
  205.  
  206. int chooserValue = chooser.showSaveDialog(null);
  207. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  208. ByteArrayOutputStream ous = null;
  209. InputStream ios = null;
  210. byte[] buffer = new byte[4096];
  211. ous = new ByteArrayOutputStream();
  212.  
  213. //Coloca <nome do ficheiro + keys.txt> no URL do ficheiro Key.txt a abrir
  214. String fileUrl = chooser.getSelectedFile() + "keys.txt";
  215.  
  216. String plainfile = String.valueOf(chooser.getSelectedFile());
  217.  
  218. //Verifica se ficheiro key.txt acompanha o ficheiro cifrado
  219. String file = fileUrl;
  220. File f = new File(file);
  221.  
  222. if (!f.exists()) { //Se não encontra o ficheiro keys.txt, pede-o ao utilizador
  223. JOptionPane.showMessageDialog(null, "Key file not found! Select the location of key file!", "Error", JOptionPane.INFORMATION_MESSAGE);
  224. JFileChooser chooser2 = new JFileChooser();
  225.  
  226. int newkeyfile = chooser2.showOpenDialog(null);
  227.  
  228. if (newkeyfile == JFileChooser.APPROVE_OPTION) {
  229. fileUrl = String.valueOf(chooser2.getSelectedFile());
  230. } else {
  231. //Caso queira abrir ficheiro na mesma
  232. JOptionPane.showMessageDialog(null, "Plain text file will open", "Information", JOptionPane.INFORMATION_MESSAGE);
  233. }
  234. }
  235.  
  236. //Lê o ficheiro keys.txt
  237. try {
  238. ios = new FileInputStream(fileUrl);
  239. } catch (FileNotFoundException e1) {
  240. e1.printStackTrace();
  241. }
  242.  
  243. int read = 0;
  244.  
  245. if (ios != null) { //-----------CASO FICHEIRO Keys.txt EXISTA----------------
  246. try {
  247. while ((read = ios.read(buffer)) != -1) {
  248. ous.write(buffer, 0, read);
  249.  
  250. byte[] bytes_from_file = ous.toByteArray();
  251. byte[] key_bytes = new byte[141];
  252. byte[] iv_bytes = new byte[16];
  253. byte[] hmac = new byte[32];
  254.  
  255. System.arraycopy(bytes_from_file, 0, key_bytes, 0, 141);
  256.  
  257. SecretKeySpec key2 = (SecretKeySpec) UtilityByteConvert.bytesToObject(key_bytes);
  258. System.arraycopy(bytes_from_file, 141, iv_bytes, 0, 16);
  259.  
  260. System.arraycopy(bytes_from_file, 157, hmac, 0, 32);
  261.  
  262.  
  263. //Leitura do ficheiro cifrado
  264. buffer = Read_and_write.read(new FileInputStream(chooser.getSelectedFile()), (int) chooser.getSelectedFile().length());
  265.  
  266.  
  267. if (!Cipher_Functions.verifyHMAC256(hmac, buffer, key2))
  268. statusField.setText("ERRO , ficheiro possivelmente corrompido");
  269. else
  270. statusField.setText("Abertura bem conseguida");
  271.  
  272. //Mostra o texto Limpo no Editor
  273.  
  274.  
  275. textArea.setText((String) UtilityByteConvert.bytesToObject(buffer));
  276. }
  277. } catch (NoSuchAlgorithmException e1) {
  278. e1.printStackTrace();
  279. } catch (FileNotFoundException e1) {
  280. e1.printStackTrace();
  281. } catch (IOException e1) {
  282. e1.printStackTrace();
  283. } catch (InvalidKeyException e1) {
  284. e1.printStackTrace();
  285. }
  286. }
  287. }
  288. }
  289. else {
  290. //------------------------------------------CANCELA--------------------------------
  291. statusField.setText("Cancelled");
  292. }
  293. }
  294.  
  295. });
  296.  
  297. //-------------------------------------------------------------SIGNATURE BUTTON--------------------------------------------------------------
  298. signatureButton.addActionListener(new ActionListener() {
  299. @Override
  300. public void actionPerformed(ActionEvent e) {
  301. //O que faz este botão
  302. JFileChooser chooser = new JFileChooser();
  303. String[] option = new String[]{"Sign", "Verify" , "Cancel"};
  304. int response = JOptionPane.showOptionDialog(null, "Choose a option please", "Save Options", JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, option, option[0]);
  305. if (response==0){
  306. int chooserValue = chooser.showSaveDialog(null);
  307. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  308. byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
  309.  
  310.  
  311. KeyPairGenerator keyGen = null;
  312. try {
  313. keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
  314. SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
  315. keyGen.initialize(1024, random);
  316. KeyPair keyPair = keyGen.generateKeyPair();
  317. PrivateKey privateKey = keyPair.getPrivate();
  318. PublicKey publicKey = keyPair.getPublic();
  319. byte[] signText = Cipher_Functions.sign(chooser.getSelectedFile().toString(), privateKey, "DSA");
  320.  
  321. FileOutputStream fos = new FileOutputStream(chooser.getSelectedFile() + "PK.txt" );
  322. FileOutputStream fos1 = new FileOutputStream(chooser.getSelectedFile() + "SK.txt" );
  323.  
  324. Read_and_write.writePK(fos ,UtilityByteConvert.objectToBytes( publicKey));
  325. Read_and_write.writeSK(fos1 , UtilityByteConvert.objectToBytes(privateKey));
  326.  
  327. } catch (Exception e1) {
  328. e1.printStackTrace();
  329. }
  330.  
  331. }
  332.  
  333. }
  334. else if (response==1){
  335. // static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[] sigbytes)
  336.  
  337. int chooserValue = chooser.showSaveDialog(null);
  338. if (chooserValue == JFileChooser.APPROVE_OPTION) {
  339. byte[] stream = textArea.getText().getBytes(StandardCharsets.UTF_8);
  340.  
  341.  
  342. }
  343.  
  344. }
  345. });
  346.  
  347. //-------------------------------------------------------------QUIT BUTTON--------------------------------------------------------------
  348. buttonQuit.addActionListener(new ActionListener() {
  349. @Override
  350. public void actionPerformed(ActionEvent e) {
  351. System.exit(0);
  352. }
  353. });
  354.  
  355. }
  356.  
  357. //--------------------------------------------------MAIN--------------------------------------------------
  358. public static void main(String args[]) {
  359. java.awt.EventQueue.invokeLater(new Runnable(){
  360. public void run() {
  361. MainForm mainform = new MainForm();
  362. mainform.setVisible(true); //Mostra a form
  363. }
  364. });
  365. }
  366. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement