· 4 years ago · Feb 21, 2021, 01:16 AM
1/*
2 * To change this license header, choose License Headers in Project Properties.
3 * To change this template file, choose Tools | Templates
4 * and open the template in the editor.
5 */
6package jimenez_mateo_jose_manuel_psp07_tarea;
7
8import java.io.BufferedReader;
9import java.io.BufferedWriter;
10import java.io.File;
11import java.io.FileInputStream;
12import java.io.FileOutputStream;
13import java.io.FileReader;
14import java.io.FileWriter;
15import java.io.IOException;
16import java.security.InvalidKeyException;
17import java.security.NoSuchAlgorithmException;
18import java.security.SecureRandom;
19import java.util.logging.Level;
20import java.util.logging.Logger;
21import javax.crypto.Cipher;
22import javax.crypto.KeyGenerator;
23import javax.crypto.NoSuchPaddingException;
24import javax.crypto.SecretKey;
25
26
27/**
28 *
29 * @author goget
30 */
31public class Archivo extends Thread{
32
33 File f =null;
34 BufferedWriter bw = null;
35 FileWriter fw = null;
36 BufferedReader br = null;
37 FileReader fr = null;
38 String mensajeTexto = "";
39 String creadenciales = "user1234";
40 KeyGenerator keygen = null;
41 SecureRandom sr = null;
42 SecretKey claveMaestra = null;
43 Cipher cifrador = null;
44
45 public Archivo(File f){
46 try {
47 this.f = f;
48 this.fw = new FileWriter(this.f,true);
49 this.bw = new BufferedWriter(this.fw);
50 this.fr = new FileReader(this.f);
51 this.br = new BufferedReader(this.fr);
52 this.mensajeTexto = "What is Lorem Ipsum?\r\n" +
53 "Lorem Ipsum is simply dummy text of the printing and typesetting industry. "
54 + "\r\nLorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. "
55 + "\r\nIt has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. "
56 + "\r\nIt was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
57 } catch (IOException ex) {
58 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
59 } catch (Exception ex) {
60 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
61 }
62 }
63
64 private void escribirFichero(){
65 try {
66 System.out.println("Escribiendo fichero");
67 this.bw.write(cifrarMensaje(this.mensajeTexto));
68 System.out.println("El texto se ha escrito en el fichero ya cifrado.");
69 if (!f.exists())
70 f.createNewFile();
71
72 } catch (IOException ex) {
73 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
74 }
75 }
76
77 private String cifrarMensaje(String mensaje) {
78 String mensajeCifrado = "";
79 KeyGenerator keyGen = null;
80 SecretKey clave = null;
81 Cipher cifrador = null;
82 byte[] bufferCifrado;
83 FileInputStream fe = null; //fichero de entrada
84 FileOutputStream fs = null; //fichero de salida
85 SecureRandom sr = null;
86 int bytesLeidos;
87 byte[] buffer = new byte[1000]; //array de bytes
88
89 try {
90 /*---------------******************-----------------
91 System.out.println("Cifrando mensaje");
92 keyGen = KeyGenerator.getInstance("AES");//algoritmo AES
93 //keyGen.init(128);
94 sr = SecureRandom.getInstance("SHA1PRNG"); //SHA1
95 //sr.setSeed(128);
96 sr.setSeed(this.creadenciales.getBytes()); //Generar
97 //seedProgramada = sr.generateSeed(16); //establecer tamano o longitud 128
98 //keyGen.init(sr);
99 //seedProgramada = sr.generateSeed(128); //establecer tamano o longitud 128
100 keyGen.init(128, sr);
101
102 clave = keyGen.generateKey();
103 //System.out.println(clave);
104 //mostrarBytes(clave.getEncoded());
105
106 //cifrador = Cipher.getInstance("AES/ECB/PKCS5Padding"); esto estba antes
107 cifrador = Cipher.getInstance("Rijndael/ECB/PKCS5Padding");
108 cifrador.init(Cipher.ENCRYPT_MODE, clave);
109
110 //esta parte funciona
111 bufferCifrado = cifrador.update(mensaje.getBytes());
112 fs = new FileOutputStream(this.f); //fichero de salida
113 fs.write(bufferCifrado);
114----------------*******************--------------------*/
115
116 cifrador = Cipher.getInstance("AES/ECB/PKCS5Padding");
117 cifrador.init(Cipher.ENCRYPT_MODE, this.claveMaestra);
118 bufferCifrado = cifrador.update(mensaje.getBytes());
119 fs = new FileOutputStream(this.f); //fichero de salida
120 fs.write(bufferCifrado);
121
122 } /*catch (NoSuchAlgorithmException ex) {
123 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
124 } catch (NoSuchPaddingException ex) {
125 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
126 }*/ catch (IOException ex) {
127 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
128 } catch (NoSuchAlgorithmException ex) {
129 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
130 } catch (InvalidKeyException ex) {
131 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
132 } catch (NoSuchPaddingException ex) {
133 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
134 } finally {
135 try {
136 fs.close();
137 } catch (IOException ex) {
138 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
139 }
140 }
141
142 return mensajeCifrado;
143 }
144
145 //método que muestra bytes
146 public static void mostrarBytes(byte[] buffer) {
147 System.out.write(buffer, 0, buffer.length);
148 }
149
150 private void cerrarFlujos(){
151 try {
152 this.bw.close();
153 this.fw.close();
154 this.br.close();
155 this.fr.close();
156 } catch (IOException ex) {
157 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
158 }
159 }
160
161 private void leerficheroDesencritado() {
162 KeyGenerator keyGen = null;
163 SecretKey clave = null;
164 Cipher cifrador = null;
165 byte[] bufferDesCifrado;
166 FileInputStream fe = null; //fichero de entrada
167 SecureRandom sr = null;
168 int bytesLeidos;
169 byte[] buffer = new byte[1000];
170
171 try {
172
173 /***--------------------************************--------------*************
174 System.out.println("Leyendo fichero desencriptado:");
175 keyGen = KeyGenerator.getInstance("AES");//algoritmo AES
176 //keyGen.init(128);
177 sr = SecureRandom.getInstance("SHA1PRNG"); //SHA1
178 //sr.nextBytes(new byte[16]); //128 bit
179 //sr.setSeed(128);
180 sr.setSeed(this.creadenciales.getBytes()); //Generar
181 //seedProgramada = sr.generateSeed(128); //establecer tamano o longitud 128
182 keyGen.init(128, sr);
183
184 clave = keyGen.generateKey();
185 //System.out.println(clave);
186 //mostrarBytes(clave.getEncoded());
187
188 //cifrador = Cipher.getInstance("AES/ECB/PKCS5Padding"); esto estaba antes
189 cifrador = Cipher.getInstance("Rijndael/ECB/PKCS5Padding");
190 cifrador.init(Cipher.DECRYPT_MODE, clave);
191
192 fe = new FileInputStream(this.f);
193 bytesLeidos = fe.read(buffer, 0, 1000);
194
195 while (bytesLeidos != -1) {//mientras no se llegue al final del fichero
196 //pasa texto cifrado al cifrador y lo descifra, asignándolo a bufferClaro
197 bufferDesCifrado = cifrador.update(buffer, 0, bytesLeidos);
198 mostrarBytes(bufferDesCifrado); //mostrar mensaje sin cifrar
199 bytesLeidos = fe.read(buffer, 0, 1000);
200 }
201
202 bufferDesCifrado = cifrador.doFinal(); //Completa el descifrado hasta el final del fichero
203 mostrarBytes(bufferDesCifrado); //mostrar mensaje sin cifrar
204 */
205
206 cifrador = Cipher.getInstance("AES/ECB/PKCS5Padding");
207 cifrador.init(Cipher.DECRYPT_MODE, this.claveMaestra);
208 fe = new FileInputStream(this.f);
209 bytesLeidos = fe.read(buffer, 0, 1000);
210
211 while (bytesLeidos != -1) {//mientras no se llegue al final del fichero
212 //pasa texto cifrado al cifrador y lo descifra, asignándolo a bufferClaro
213 bufferDesCifrado = cifrador.update(buffer, 0, bytesLeidos);
214 mostrarBytes(bufferDesCifrado); //mostrar mensaje sin cifrar
215 bytesLeidos = fe.read(buffer, 0, 1000);
216 }
217
218 bufferDesCifrado = cifrador.doFinal(); //Completa el descifrado hasta el final del fichero
219 mostrarBytes(bufferDesCifrado); //mostrar mensaje sin cifrar
220
221 System.out.println("");
222
223 } /*catch (IOException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException ex) {
224 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
225 } */catch (Exception ex) {
226 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
227 }finally{
228 try {
229 //cierra archivos
230 fe.close(); //entrada
231 } catch (IOException ex) {
232 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
233 }
234 }
235 }
236
237 private void generarClave() {
238
239 try {
240 this.keygen = KeyGenerator.getInstance("AES");//algoritmo AES
241 this.sr = SecureRandom.getInstance("SHA1PRNG"); //SHA1 algoritmo
242 this.sr.setSeed(this.creadenciales.getBytes());//semilla
243 this.keygen.init(128, this.sr);//inicializacion
244 this.claveMaestra = this.keygen.generateKey();
245 //this.cifrador = Cipher.getInstance("Rijndael/ECB/PKCS5Padding");//AES/ECB/PKCS5Padding
246 //this.cifrador.init(Cipher.DECRYPT_MODE, this.claveMaestra);
247 } catch (NoSuchAlgorithmException ex) {
248 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
249 } catch (Exception ex) {
250 Logger.getLogger(Archivo.class.getName()).log(Level.SEVERE, null, ex);
251 }
252 }
253
254 @Override
255 public void run ()
256 {
257 this.generarClave();
258 this.escribirFichero();
259 this.leerficheroDesencritado();
260 this.cerrarFlujos();
261 }
262
263
264
265
266}
267