· 7 years ago · Nov 16, 2018, 07:26 AM
1public static void ChipherDecipherAES(String claveString, File origen, File destino, boolean cifrar){
2 try {
3 String tipoEncriptado = "AES";
4 byte[] clave = new byte[16];
5 System.arraycopy(cipherToMD5ShaString(claveString,"MD5"),0,clave,0,16);
6
7 SecretKey key = new SecretKeySpec(clave, tipoEncriptado);
8
9 Cipher desCipher = Cipher.getInstance(tipoEncriptado);
10 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(origen));
11 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destino));
12 byte mensajeEnBytes[] = new byte[1024];
13 if(cifrar){
14 //Cifrar
15 desCipher.init(Cipher.ENCRYPT_MODE, key);
16 String mensaje = "Mensaje que se va a cifrar";
17 while(true){
18 int i = bis.read(mensajeEnBytes);
19 if(i == -1)
20 break;
21 byte[] temp = new byte[i];
22 System.arraycopy(mensajeEnBytes, 0, temp, 0, i);
23 //System.out.println(i);
24 //System.out.println(temp.length);
25 //System.out.println(Arrays.toString(temp));
26 //System.out.println(Arrays.toString(mensajeEnBytes));
27 if(i<1024)
28 bos.write(desCipher.doFinal(temp));
29 else
30 bos.write(desCipher.update(temp));
31 }
32 System.out.println("Mensaje cifrado y guardado en "+destino.getAbsolutePath());
33 bos.flush();
34 }else{
35 //desencriptado
36 desCipher.init(Cipher.DECRYPT_MODE, key);
37 while(true){
38 int i = bis.read(mensajeEnBytes);
39 if(i == -1)
40 break;
41 byte[] temp = new byte[i];
42 //System.arraycopy(mensajeEnBytes, 0, temp, 0, i);
43 //System.out.println(i);
44 //System.out.println(temp.length);
45 //System.out.println(Arrays.toString(temp));
46 //System.out.println(Arrays.toString(mensajeEnBytes));
47 if(i < 1024)
48 bos.write(desCipher.doFinal(temp));
49 else
50 bos.write(desCipher.update(temp));
51 }
52 System.out.println("Descifrado y guardado en " + destino.getAbsolutePath());
53 bos.flush();
54 }
55 } catch (Exception e) {
56 System.out.println(e.toString());
57 System.out.println(Arrays.toString(e.getStackTrace()));
58 }
59 }