· 7 years ago · Dec 11, 2018, 05:04 PM
1package com.psp.exuf1;
2
3import javax.crypto.Cipher;
4import javax.crypto.SecretKey;
5import javax.crypto.spec.SecretKeySpec;
6
7import java.io.BufferedReader;
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.FileNotFoundException;
11import java.io.FileOutputStream;
12import java.io.FileReader;
13import java.io.IOException;
14import java.security.Key;
15import java.security.KeyFactory;
16import java.security.MessageDigest;
17import java.security.PublicKey;
18import java.security.spec.KeySpec;
19import java.security.spec.X509EncodedKeySpec;
20import java.util.Arrays;
21import java.util.Scanner;
22
23public class Ejercicio6 {
24
25 // CONSTANTES
26 private static String FORMATO = "UTF-8";
27 private static String TIPO_CIFRADO = "AES";
28 private static String FUNCION_CRIPTOGRAFICA = "SHA-256";
29
30 public static void main(String[] args) throws FileNotFoundException {
31
32 Scanner sc = new Scanner(System.in);
33 int numPasswd;
34
35 System.out.println("Dame una contraseña...1 La contraseña tiene que ser ebtre 1 y 99");
36 numPasswd = sc.nextInt();
37
38 if (numPasswd < 1 || numPasswd > 99) {
39 do {
40 System.out.println(
41 "No has introducido el numero correcto, solo se puede cifrar con una contraseña del 1 al 99");
42 numPasswd = sc.nextInt();
43 } while (numPasswd < 1 || numPasswd > 99);
44 }
45
46 cifradoAutomatico(leerFichero(), numPasswd);
47 sc.close();
48
49 }
50
51 public static String leerFichero() {
52 File fichero = new File("D:\\Users\\Raul W\\Desktop\\DAM2\\M09 - PSP\\ficheros\\UF1\\examen\\examen.txt.txt");
53 Scanner s = null;
54 String linea = "";
55 try {
56 // Leemos el contenido del fichero
57 System.out.println("... Leemos el contenido del fichero ...");
58 s = new Scanner(fichero);
59
60 // Leemos linea a linea el fichero
61 while (s.hasNextLine()) {
62 linea = s.nextLine(); // Guardamos la linea en un String
63 System.out.println(linea); // Imprimimos la linea
64 }
65 return linea;
66 } catch (Exception ex) {
67 System.out.println("Mensaje: " + ex.getMessage());
68 } finally {
69 // Cerramos el fichero tanto si la lectura ha sido correcta o no
70 try {
71 if (s != null)
72 s.close();
73 } catch (Exception ex2) {
74 System.out.println("Mensaje 2: " + ex2.getMessage());
75 }
76 }
77 return null;
78 }
79
80 public static void intentoDescifrar(byte[] mensajeInterceptado) throws Exception {
81
82 // **Generamos la posible contraseña y vamos probando dentro del bucle
83 SecretKey posibleContraseñaSecreta = loadKey(
84 "D:\\\\Users\\\\Raul W\\\\Desktop\\\\DAM2\\\\M09 - PSP\\\\ficheros\\\\UF1\\\\examen\\\\clau.txt");
85
86 // **Descifrar en formato AES
87
88 try {
89
90 // desciframos el mensaje
91 Cipher cigfradoManual = Cipher.getInstance("AES/ECB/PKCS5Padding");
92 cigfradoManual.init(Cipher.DECRYPT_MODE, posibleContraseñaSecreta);
93 byte[] datosPosiblesDescrifrados = cigfradoManual.doFinal(mensajeInterceptado);
94
95 System.out.print("");
96
97 String msgDescrifrado = new String(datosPosiblesDescrifrados, FORMATO);
98 System.out.println("\n\n********************************************* \n" + "****** Desciframos: "
99 + msgDescrifrado + " ******\n" + "*********************************************");
100 } catch (Exception ex) {
101
102 }
103
104 }
105
106 public static byte[] cifradoAutomatico(String msgAEncriptar, int numPasswd) {
107
108 String cadena;
109
110 // **controlamos la contraseña para que si es menor a 10 le pongamos un cero, ya
111 // que se necesita 2 bytes para la contraseña
112 if (numPasswd >= 1 && numPasswd <= 9) {
113 cadena = 0 + Integer.toString(numPasswd);
114 } else {
115 cadena = Integer.toString(numPasswd);
116 }
117
118 try {
119 Cipher xifrado = Cipher.getInstance(TIPO_CIFRADO);
120 xifrado.init(Cipher.ENCRYPT_MODE, genLlaveConPasswd(cadena, 192));
121 byte[] msgEnBytes = msgAEncriptar.getBytes(FORMATO);
122 byte[] msgXifradoEnByte = xifrado.doFinal(msgEnBytes);
123
124 System.out.println("El mensaje cifrado es el siguiente(" + msgXifradoEnByte + ")");
125
126 intentoDescifrar(msgXifradoEnByte);
127 return msgXifradoEnByte;
128
129 } catch (Exception e) {
130 System.out.println("");
131 }
132 // **pasamos el texto a byte.
133 return null;
134
135 }
136
137 public static SecretKey genLlaveConPasswd(String passwd, int laLlave) {
138
139 SecretKey claveSecreta = null;
140
141 // ** si la llave no contiene un formato UTF no la inicalizamos y damos un error
142 // controlado.
143 if ((laLlave == 192)) {
144
145 try {
146 // **Convertimos el String passwd con 2 bytes a un Array.
147
148 byte[] data = passwd.getBytes(FORMATO);
149
150 /*
151 * las lineas, se comprimen para conseguir una cantidad limitada de bytes,
152 * ademas copyOFF genera una llave de 16 posciones mediante el tamaño de
153 * "laLlave" que antes hemos generado
154 */
155 MessageDigest md = MessageDigest.getInstance(FUNCION_CRIPTOGRAFICA);
156 byte[] compresion = md.digest(data);
157 byte[] llaveEnArray = Arrays.copyOf(compresion, laLlave / 8);
158 claveSecreta = new SecretKeySpec(llaveEnArray, TIPO_CIFRADO);
159
160 saveKey(claveSecreta, "D:\\Users\\Raul W\\Desktop\\DAM2\\M09 - PSP\\ficheros\\UF1\\examen\\clau.txt");
161
162 } catch (Exception ex) {
163 System.err.println("ERROR al generar la clave..." + ex);
164 }
165 }
166 return claveSecreta;
167 }
168
169 private static void saveKey(SecretKey key, String fileName) throws Exception {
170
171 byte[] publicKeyBytes = key.getEncoded();
172 FileOutputStream fos = new FileOutputStream(fileName);
173 fos.write(publicKeyBytes);
174 fos.close();
175 }
176
177 // CARGAMOS EL FICHERO DE LA LLAVE PUBLICA
178 private static SecretKey loadKey(String fileName) throws Exception {
179 FileInputStream fis = new FileInputStream(fileName);
180 int numBtyes = fis.available();
181 byte[] bytes = new byte[numBtyes];
182 fis.read(bytes);
183 fis.close();
184
185 SecretKey claveSecreta = new SecretKeySpec(bytes, TIPO_CIFRADO);
186
187 return claveSecreta;
188 }
189
190}