· 9 years ago · Nov 11, 2016, 04:08 PM
1
2package Bourdoux.Team;
3
4import com.sun.xml.internal.bind.v2.runtime.output.SAXOutput;
5import com.sun.xml.internal.bind.v2.schemagen.Util;
6import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;
7
8import java.io.*;
9import java.nio.charset.StandardCharsets;
10import java.nio.file.Files;
11import java.security.*;
12import java.util.Base64;
13import java.util.Scanner;
14import java.util.logging.Level;
15import java.util.logging.Logger;
16import javax.crypto.KeyGenerator;
17import javax.crypto.NoSuchPaddingException;
18import javax.crypto.SecretKey;
19import javax.crypto.spec.IvParameterSpec;
20import javax.crypto.spec.SecretKeySpec;
21import javax.swing.JFileChooser;
22import javax.swing.JOptionPane;
23
24/**
25 *
26 * @author sjw
27 */
28public class Editor extends javax.swing.JFrame {
29
30 /**
31 * Creates new form TextEditorFrame
32 */
33 public Editor() {
34 initComponents();
35 }
36
37 /**
38 * This method is called from within the constructor to initialize the form.
39 * WARNING: Do NOT modify this code. The content of this method is always
40 * regenerated by the Form Editor.
41 */
42 @SuppressWarnings("unchecked")
43 // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
44 /**
45 *
46 */
47 private void initComponents() {
48
49 newButton = new javax.swing.JButton();
50 saveButton = new javax.swing.JButton();
51 loadButton = new javax.swing.JButton();
52 quitButton = new javax.swing.JButton();
53 statusField = new javax.swing.JTextField();
54 jScrollPane1 = new javax.swing.JScrollPane();
55 textArea = new javax.swing.JTextArea();
56
57 setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
58
59 newButton.setText("New");
60 newButton.addActionListener(new java.awt.event.ActionListener() {
61 public void actionPerformed(java.awt.event.ActionEvent evt) {
62 newButtonActionPerformed(evt);
63 }
64 });
65
66 saveButton.setText("Save");
67 saveButton.addActionListener(new java.awt.event.ActionListener() {
68 public void actionPerformed(java.awt.event.ActionEvent evt) {
69 try {
70 saveButtonActionPerformed(evt);
71 } catch (Exception e) {
72 e.printStackTrace();
73 }
74 }
75 });
76
77 loadButton.setText("Load");
78 loadButton.addActionListener(new java.awt.event.ActionListener() {
79 public void actionPerformed(java.awt.event.ActionEvent evt) {
80 try {
81 loadButtonActionPerformed(evt);
82 } catch (IOException | NoSuchProviderException | NoSuchAlgorithmException | InvalidAlgorithmParameterException | NoSuchPaddingException | InvalidKeyException e) {
83 e.printStackTrace();
84 }
85 }
86 });
87
88 quitButton.setText("Quit");
89 quitButton.addActionListener(new java.awt.event.ActionListener() {
90 public void actionPerformed(java.awt.event.ActionEvent evt) {
91 quitButtonActionPerformed(evt);
92 }
93 });
94
95 statusField.setEditable(false);
96
97 textArea.setColumns(20);
98 textArea.setLineWrap(true);
99 textArea.setRows(5);
100 textArea.setWrapStyleWord(true);
101 jScrollPane1.setViewportView(textArea);
102
103 javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
104 getContentPane().setLayout(layout);
105 layout.setHorizontalGroup(
106 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
107 .addGroup(layout.createSequentialGroup()
108 .addContainerGap()
109 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
110 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
111 .addGroup(layout.createSequentialGroup()
112 .addComponent(newButton)
113 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
114 .addComponent(saveButton)
115 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
116 .addComponent(loadButton)
117 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
118 .addComponent(quitButton)
119 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
120 .addComponent(statusField)))
121 .addContainerGap())
122 );
123 layout.setVerticalGroup(
124 layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
125 .addGroup(layout.createSequentialGroup()
126 .addContainerGap()
127 .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
128 .addComponent(newButton)
129 .addComponent(saveButton)
130 .addComponent(loadButton)
131 .addComponent(quitButton)
132 .addComponent(statusField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
133 .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
134 .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 239, Short.MAX_VALUE)
135 .addContainerGap())
136 );
137
138 pack();
139 }// </editor-fold>//GEN-END:initComponents
140
141 private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
142 textArea.setText("");
143 statusField.setText("New file");
144 }//GEN-LAST:event_newButtonActionPerformed
145
146 private void quitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quitButtonActionPerformed
147 System.exit(0);
148 }//GEN-LAST:event_quitButtonActionPerformed
149
150 /**
151 *
152 * @param evt
153 */
154 private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception {//GEN-FIRST:event_saveButtonActionPerformed
155 JFileChooser chooser = new JFileChooser();
156 String[] option = new String[] {"Cipher" , "autenticate" , "both" , "cancel"};
157 int response = JOptionPane.showOptionDialog(null , "Choose a option please" , "Save Options" , JOptionPane.DEFAULT_OPTION , JOptionPane.PLAIN_MESSAGE , null , option , option[0] );
158
159 if ( response==0) {
160 int chooserValue = chooser.showSaveDialog(this);
161 if(chooserValue==JFileChooser.APPROVE_OPTION) {
162 try {
163
164 final int AES_KEYLENGTH = 128;
165 byte[] iv = new byte[AES_KEYLENGTH / 8]; // Save the IV bytes or send it in plaintext with the encrypted data so you can decrypt the data later
166 SecureRandom prng = new SecureRandom();
167 prng.nextBytes(iv);
168
169 KeyGenerator keyGen = KeyGenerator.getInstance("AES");
170 keyGen.init(128);
171 SecretKeySpec secretKey = (SecretKeySpec) keyGen.generateKey();
172
173 String txt = textArea.getText();
174
175 ByteArrayInputStream stream = new ByteArrayInputStream(txt.getBytes(StandardCharsets.UTF_8));
176 byte[] ciphertext = Chypher_Functions.enc_CTR(stream, secretKey , iv);
177
178 byte[] Hmac = Chypher_Functions.generateHMAC256(ciphertext , secretKey );
179
180 byte[] key_byte_array = Utility.objectToBytes(secretKey);
181 FileOutputStream fos = new FileOutputStream(chooser.getCurrentDirectory() + "/keys.txt");
182 Read_and_write.writeKeyAndIV(fos, key_byte_array , iv , Hmac);
183
184
185 fos = new FileOutputStream(chooser.getSelectedFile());
186 Read_and_write.writeciphertext(fos, ciphertext);
187
188 statusField.setText("Saved " + chooser.getCurrentDirectory());
189
190 } catch ( NoSuchAlgorithmException | IOException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchPaddingException | NoSuchProviderException e) {
191 e.printStackTrace();
192 }
193
194 }
195 } else
196 if (response == 1) {
197 int chooserValue = chooser.showSaveDialog(this);
198 if(chooserValue==JFileChooser.APPROVE_OPTION) {
199
200
201 KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
202 kpg.initialize(512); // 512 is the keysize.
203 KeyPair kp = kpg.generateKeyPair();
204 PublicKey pubk = kp.getPublic();
205 PrivateKey prvk = kp.getPrivate();
206
207 String txt = textArea.getText();
208 ByteArrayInputStream stream = new ByteArrayInputStream(txt.getBytes(StandardCharsets.UTF_8));
209
210
211 byte[] chypehrText = Chypher_Functions.sign(stream ,prvk , "DSA");
212 System.out.println(chypehrText);
213 FileOutputStream fos = new FileOutputStream(chooser.getCurrentDirectory() + "/keys.txt");
214 FileOutputStream fos1 = new FileOutputStream(chooser.getSelectedFile());
215 Read_and_write.writePubAndPrvKeys(fos , Utility.objectToBytes(kp));
216 Read_and_write.writeciphertext(fos1 , chypehrText);
217
218
219
220
221 }
222
223 }
224 else
225 if (response == 2){
226 //ambos 1 assina depois cifra
227 }
228 else {
229 //cancel
230 }
231 }//GEN-LAST:event_saveButtonActionPerformed
232
233 /**
234 *
235 * @param evt
236 * @throws IOException
237 * @throws NoSuchProviderException
238 * @throws InvalidAlgorithmParameterException
239 * @throws NoSuchAlgorithmException
240 * @throws InvalidKeyException
241 * @throws NoSuchPaddingException
242 */
243 private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) throws IOException, NoSuchProviderException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException {//GEN-FIRST:event_loadButtonActionPerformed
244 JFileChooser chooser = new JFileChooser();
245 int chooserValue = chooser.showOpenDialog(this);
246
247
248
249
250
251
252 if (chooserValue == JFileChooser.APPROVE_OPTION) {
253
254 ByteArrayOutputStream ous = null;
255 InputStream ios = null;
256 byte[] buffer = new byte[4096];
257 ous = new ByteArrayOutputStream();
258 ios = new FileInputStream(chooser.getCurrentDirectory() + "/keys.txt");
259 int read = 0;
260 while ((read = ios.read(buffer)) != -1) {
261 ous.write(buffer, 0, read);
262
263
264 byte[] bytes_from_file = ous.toByteArray();
265 byte[] key_bytes = new byte[141];
266 byte[] iv_bytes = new byte[16];
267 byte[] hmac = new byte[32];
268
269 System.out.println(bytes_from_file.length);
270 System.out.println(buffer.length);
271 System.arraycopy(bytes_from_file, 0, key_bytes, 0, 141);
272 SecretKeySpec key2 = (SecretKeySpec) Utility.bytesToObject(key_bytes);
273 System.arraycopy(bytes_from_file, 141, iv_bytes, 0, 16);
274 System.arraycopy(bytes_from_file, 157 , hmac , 0 , 32);
275
276 buffer = Read_and_write.read(new FileInputStream(chooser.getSelectedFile()), (int) chooser.getSelectedFile().length());
277
278 byte[] teste1 = new byte[10] ;
279
280 System.arraycopy(buffer , 0 , teste1 , 0 , 10);
281 String x = Chypher_Functions.denc_CTR(teste1, key2 , iv_bytes);
282 System.out.println(x);
283
284
285
286
287 String s = Chypher_Functions.denc_CTR(buffer, key2, iv_bytes);
288 System.out.println(s);
289
290 if(!Chypher_Functions.verifyHMAC256(hmac, buffer , key2))
291
292 statusField.setText("ERRO , ficheiro possivelmente corrompido");
293
294 else
295 statusField.setText("Abertura bem conceguida");
296
297 textArea.setText(s);
298 //statusField.setText("Load " + chooser.getSelectedFile().getAbsolutePath());
299
300
301 }//GEN-LAST:event_loadButtonActionPerformed
302 }
303 }
304
305 /**
306 *
307 * @param args
308 */
309 public static void main(String args[]) {
310 try {
311 for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
312 if ("Nimbus".equals(info.getName())) {
313 javax.swing.UIManager.setLookAndFeel(info.getClassName());
314 break;
315 }
316 }
317 } catch (ClassNotFoundException | javax.swing.UnsupportedLookAndFeelException | InstantiationException | IllegalAccessException ex) {
318 java.util.logging.Logger.getLogger(Editor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
319 }
320 java.awt.EventQueue.invokeLater(new Runnable() {
321 public void run() {
322 new Editor().setVisible(true);
323 }
324 });
325 }
326
327 private javax.swing.JScrollPane jScrollPane1;
328 private javax.swing.JButton loadButton;
329 private javax.swing.JButton newButton;
330 private javax.swing.JButton quitButton;
331 private javax.swing.JButton saveButton;
332 private javax.swing.JTextField statusField;
333 private javax.swing.JTextArea textArea;
334 }