· 6 years ago · Mar 14, 2019, 09:46 PM
1private void btnEncriptarActionPerformed(java.awt.event.ActionEvent evt) {
2
3 sv.edu.ufg.LogicaDes.textoPlano texto = new sv.edu.ufg.LogicaDes.textoPlano();
4 sv.edu.ufg.LogicaDes.Encriptado cifrado = new sv.edu.ufg.LogicaDes.Encriptado();
5
6 String nombreTxt, msj, clave;
7
8 nombreTxt = txtNombreArchivo.getText();
9 msj = txtMensaje.getText();
10 clave = txtClave.getText();
11
12 texto.escribir(nombreTxt, msj);//SE CREA EL NOMBRE DEL ARCHIVO Y EL MENSAJE
13 cifrado.imprimir(nombreTxt, clave);//SE MANDA EL NOMBRE DEL ARCHIVO PARA ENCONTRARLO Y PASAR ENCRIPTAR
14 //SE PASA LA CLAVE PARA CONCATENAR EL CIFRADO Y HACERLO MAS SEGURO
15
16 File archivo = new File("C:\Users\Ana\Desktop\algoritmoDes\archivos textos\Encriptados\" + nombreTxt + "_encript" + ".txt");
17
18 try {
19 BufferedReader leer = new BufferedReader(new FileReader(archivo) );
20 String mensaje = leer.readLine();
21 while (mensaje != null) {
22 jtaEncriptar.append(mensaje);
23 mensaje = leer.readLine();
24 }
25
26 } catch (Exception ex) {
27 JOptionPane.showMessageDialog(null, "Chingados ahora el error es en encriptar" + ex);
28 }
29
30public void imprimir(String nombre, String clave)
31{
32 File plaintext = new File("C:\Users\Ana\Desktop\algoritmoDes\archivos textos\ARCHIVOS\"+nombre+".txt");
33 File encrypted = new File("C:\Users\Ana\Desktop\algoritmoDes\archivos textos\Encriptados\"+nombre+"_encript"+".txt");
34 try {
35 encryptDecrypt(clave, Cipher.ENCRYPT_MODE, plaintext,encrypted);
36 } catch (InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchPaddingException | IOException e) {
37 e.printStackTrace();
38 }
39}
40public void encryptDecrypt(String key, int cipherMode, File in, File out)
41 throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IOException {
42 FileInputStream fis = new FileInputStream(in);
43 FileOutputStream fos = new FileOutputStream(out);
44
45 DESKeySpec desKeySpec = new DESKeySpec(key.getBytes());
46 SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
47 SecretKey secretKey = skf.generateSecret(desKeySpec);
48
49 Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
50
51 if (cipherMode == Cipher.ENCRYPT_MODE) {
52 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
53 CipherInputStream cis = new CipherInputStream(fis, cipher);
54 write(cis, fos);
55 } else if (cipherMode == Cipher.DECRYPT_MODE) {
56 cipher.init(Cipher.DECRYPT_MODE, secretKey);
57 CipherOutputStream cos = new CipherOutputStream(fos, cipher);
58 write(fis, cos);
59 }
60}
61
62private static void write(InputStream in, OutputStream out) throws IOException {
63 byte[] buffer = new byte[64];
64 int numOfBytesRead;
65 while ((numOfBytesRead = in.read(buffer)) != -1) {
66 out.write(buffer, 0, numOfBytesRead);
67 }
68 out.close();
69 in.close();
70}