· 9 years ago · Nov 09, 2016, 05:28 PM
1package m9.uf1.e2.SergiBallesteros;
2
3import java.io.File;
4import java.io.FileInputStream;
5import java.io.FileOutputStream;
6import java.io.IOException;
7import java.io.InputStream;
8import java.io.OutputStream;
9import java.security.InvalidKeyException;
10import java.security.MessageDigest;
11import java.security.NoSuchAlgorithmException;
12import java.util.Arrays;
13import java.util.Scanner;
14import javax.crypto.BadPaddingException;
15import javax.crypto.Cipher;
16import javax.crypto.IllegalBlockSizeException;
17import javax.crypto.NoSuchPaddingException;
18import javax.crypto.SecretKey;
19import javax.crypto.spec.SecretKeySpec;
20
21
22
23public class A08_XifrarDesxifrarFitxerAES {
24 public static void main(String[] args) throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
25 Scanner sc = new Scanner(System.in);
26
27 String fitxer = "", clau = "";
28 SecretKey sKey;
29
30 System.out.print("Entra el nom del fitxer: ");
31 fitxer = sc.nextLine();
32
33
34 File file = new File (fitxer);
35
36
37 if(file.exists()){
38 System.out.print("Entra una clau: ");
39 clau = sc.nextLine();
40
41 sKey = passwordkeygeneration(clau);
42
43 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
44
45 if ( fitxer.endsWith(".aes") ){
46 cipher.init(Cipher.DECRYPT_MODE, sKey);
47 InputStream arxiu = new FileInputStream(file);
48 OutputStream arxiu_sortida = new FileOutputStream (file + ".txt");
49
50 byte[] buffer = new byte [1024];
51 byte[] bloc;
52 int bytesLlegits = 0;
53
54 bytesLlegits = arxiu.read(buffer);
55
56 while ( bytesLlegits != -1 ){
57 bloc = cipher.update(buffer, 0, bytesLlegits);
58 arxiu_sortida.write(bloc);
59 bytesLlegits = arxiu.read(buffer);
60 }
61
62 arxiu.close();
63 arxiu_sortida.write(cipher.doFinal());
64 arxiu_sortida.close();
65
66
67 }
68 else{
69 cipher.init(Cipher.ENCRYPT_MODE, sKey);
70 InputStream arxiu = new FileInputStream(file);
71 OutputStream arxiu_sortida = new FileOutputStream (file + ".aes");
72
73 byte[] buffer = new byte [1024];
74 byte[] bloc;
75 int bytesLlegits = 0;
76
77 bytesLlegits = arxiu.read(buffer);
78
79 while ( bytesLlegits != -1 ){
80 bloc = cipher.update(buffer, 0, bytesLlegits);
81 arxiu_sortida.write(bloc);
82 bytesLlegits = arxiu.read(buffer);
83 }
84
85 arxiu.close();
86 arxiu_sortida.write(cipher.doFinal());
87 arxiu_sortida.close();
88 }
89 }
90 else{
91 System.out.println("No existeix cap fitxer amb aquest nom.");
92 }
93
94 sc.close();
95 file.delete();
96 }
97
98 public static SecretKey passwordkeygeneration(String clau) throws NoSuchAlgorithmException{
99 byte[] data = clau.getBytes();
100 MessageDigest md = MessageDigest.getInstance("SHA-256");
101 byte[] hash = md.digest(data);
102 byte[] key = Arrays.copyOf(hash, 128 / 8);
103 SecretKey skey = new SecretKeySpec(key, "AES");
104 return skey;
105 }
106}