· 2 years ago · Oct 07, 2023, 08:50 AM
1// EJERCICIO 10
2
3****************
4----- MAIN -----
5****************
6
7import static com.mycompany.ejercicio10.Funciones.*;
8import java.io.File;
9import java.io.UnsupportedEncodingException;
10import java.util.Scanner;
11
12public class Ejercicio10 {
13
14 public static void main(String[] args) throws UnsupportedEncodingException {
15
16 // Variables
17 Scanner sc = new Scanner(System.in);
18 File f;
19 File f2;
20 String fileName;
21 String path;
22 int opcion;
23 boolean finalizar = false;
24 byte[] mensaje;
25 byte[] msjCifrado;
26 byte[] msjDescifrado;
27 String strMsj;
28
29 crearKey();
30
31 System.out.println("****DES-CIFRADOR****\n");
32 System.out.println("Este programa le permite cifrar sus archivos");
33 System.out.println("para proteger su información de agentes externos");
34 System.out.println("Podrá también descifrar la información que haya");
35 System.out.println("sido cifrada mediante este programa.\n");
36
37 System.out.println("A continuación elija una opción del menú:");
38
39 do{
40
41 System.out.println("-------------------------------------------");
42 System.out.println("Opción 1: Cifrar");
43 System.out.println("Opción 2: Descifrar");
44 System.out.println("Opción 3: Salir");
45 System.out.println("-------------------------------------------");
46
47 opcion = sc.nextInt();
48 sc.nextLine();
49
50 switch(opcion){
51 // CIFRAR
52 case 1 ->{
53 // Pedir input al usuario
54 System.out.println("\nIndique la ruta del archivo: ");
55 path = sc.nextLine();
56
57 System.out.println("\nIndique el nombre del archivo: ");
58 fileName = sc.nextLine();
59
60 // Instanciar objeto File para la lectura.
61 f = crearArchivo(path, fileName);
62
63 // Leer objeto File y almacenar contenido en variable mensaje
64 mensaje = leerArchivo(f);
65
66 // Cifrar mensaje
67 msjCifrado = cifrarMensaje(mensaje);
68 System.out.println("\nMensaje cifrado correctamente.");
69
70 // Instanciar objeto File para escribir el mensaje cifrado
71 System.out.println("\nIndique la ruta del nuevo archivo cifrado: ");
72 path = sc.nextLine();
73
74 System.out.println("\nIndique el nombre del archivo: ");
75 fileName = sc.nextLine();
76
77 f2 = crearArchivo(path,fileName);
78
79 // Escribir mensaje cifrado en objeto File
80 escribirArchivo(f2, msjCifrado);
81 System.out.println("\nMensaje cifrado guardado en " + f2.getName());
82
83 }
84 // DESCIFRAR
85 case 2 ->{
86 // Pedir input al usuario
87 System.out.println("\nIndique la ruta del archivo: ");
88 path = sc.nextLine();
89
90 System.out.println("\nIndique el nombre del archivo: ");
91 fileName = sc.nextLine();
92
93 // Instanciar objeto File para la lectura.
94 f = crearArchivo(path, fileName);
95
96 // Leer objeto File y almacenar contenido en String mensaje
97 mensaje = leerArchivo(f);
98
99 // Descifrar mensaje
100 msjDescifrado = descifrarMensaje(mensaje);
101 System.out.println("\nMensaje descifrado correctamente.");
102
103 // Convertir bytes[] en String con codificación UTF-8
104 strMsj = new String(msjDescifrado, "UTF-8");
105
106 System.out.println("\nContenido del mensaje descifrado:\n");
107 System.out.println(strMsj);
108
109 }
110 case 3 ->{
111 // Código de finalización
112 finalizar = true;
113 }
114 default -> {}
115 }
116
117 }while(!finalizar);
118
119 System.out.println("El programa ha finalizado.");
120
121
122 }
123}
124
125*******************
126---- FUNCIONES ----
127*******************
128
129import java.io.File;
130import java.io.FileOutputStream;
131import java.io.IOException;
132import java.nio.file.Files;
133import java.nio.file.Path;
134import java.nio.file.Paths;
135import java.security.InvalidKeyException;
136import java.security.NoSuchAlgorithmException;
137import java.util.logging.Level;
138import java.util.logging.Logger;
139import javax.crypto.*;
140
141public class Funciones {
142
143 // Variables
144 private static File f;
145 private static FileOutputStream fos;
146 private static KeyGenerator keygen;
147 private static SecretKey key;
148 private static Cipher desCipher;
149 private static byte[] lectura;
150 private static byte[] msjCifrado;
151 private static byte[] msjDescifrado;
152
153 // Función CREAR ARCHIVO
154 public static File crearArchivo(String path, String fileName) {
155
156 // Añadir extensión al nombre
157 fileName += ".txt";
158 // Concatenar ruta con nombre del archivo
159 path += fileName;
160 // Instanciar objeto File
161 f = new File(path);
162
163 return f;
164 }
165
166 // Función LEER ARCHIVO
167 public static byte[] leerArchivo(File f) {
168
169 lectura = null;
170 try {
171 Path ruta = Paths.get(f.getPath());
172 lectura = Files.readAllBytes(ruta);
173
174 } catch (IOException ex) {
175 Logger.getLogger(Funciones.class.getName()).log(Level.SEVERE, null, ex);
176 }
177
178 return lectura;
179
180 }
181
182 // Función ESCRIBIR ARCHIVO
183 public static void escribirArchivo(File f, byte[] contenido) {
184
185 try {
186
187 fos = new FileOutputStream(f,true);
188 fos.write(contenido);
189 fos.close();
190
191 } catch (IOException e) {
192 Logger.getLogger(Funciones.class.getName()).log(Level.SEVERE, null, e);
193 }
194
195 }
196
197 // Función CREAR KEY
198 public static void crearKey() {
199
200 try {
201 // Generar key simétrica para DES
202 keygen = KeyGenerator.getInstance("DES");
203 // Aplicar opacidad a la key
204 key = keygen.generateKey();
205 } catch (NoSuchAlgorithmException ex) {
206 Logger.getLogger(Funciones.class.getName()).log(Level.SEVERE, null, ex);
207 }
208
209 }
210
211 // Función ENCRIPTAR
212 public static byte[] cifrarMensaje(byte[] mensaje) {
213
214 try {
215 // Activar cifrador DES
216 desCipher = Cipher.getInstance("DES");
217 // Activar cifrador DES con la key
218 desCipher.init(Cipher.ENCRYPT_MODE, key);
219 // Cifrar
220 msjCifrado = desCipher.doFinal(mensaje);
221
222 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException ex) {
223 Logger.getLogger(Funciones.class.getName()).log(Level.SEVERE, null, ex);
224 }
225
226 return msjCifrado;
227 }
228
229 // Función DESENCRIPTAR
230 public static byte[] descifrarMensaje(byte[] mensaje) {
231
232 try {
233 // Activar cifrador DES
234 desCipher = Cipher.getInstance("DES");
235 // Activar cifrador DES con la key
236 desCipher.init(Cipher.DECRYPT_MODE, key);
237 // Descifrar
238 msjDescifrado = desCipher.doFinal(mensaje);
239
240 } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException | NoSuchAlgorithmException | NoSuchPaddingException ex) {
241 Logger.getLogger(Funciones.class.getName()).log(Level.SEVERE, null, ex);
242 }
243
244 return msjDescifrado;
245 }
246
247}
248