· 6 years ago · Jun 27, 2019, 08:38 AM
1private static void cifra (String file, SecretKey key) {
2 try {
3 Cipher c = Cipher.getInstance("AES");
4 c.init(Cipher.ENCRYPT_MODE, key);
5 FileInputStream fis;
6 FileOutputStream fos;
7 CipherOutputStream cos;
8 fis = new FileInputStream(file);
9 fos = new FileOutputStream(file);
10 cos = new CipherOutputStream(fos, c);
11 byte[] b = new byte[16];
12 int i;
13 while ((i=fis.read(b) )!= -1) {
14 cos.write(b, 0, i);
15 }
16 cos.close();
17 fos.close();
18 fis.close();
19 }catch (Exception e) {
20 e.printStackTrace();
21 }
22}
23
24public static void decifra (String file, SecretKey key) {
25 try {
26 byte[] keyEncoded = key.getEncoded();
27 SecretKeySpec keySpec2 = new SecretKeySpec(keyEncoded, "AES");
28 Cipher c = Cipher.getInstance("AES");
29 c.init(Cipher.DECRYPT_MODE, keySpec2);
30 FileInputStream fis;
31 FileOutputStream fos;
32 CipherInputStream cos;
33 fis = new FileInputStream(file + ".cif");
34 cos = new CipherInputStream(fis, c);
35 byte[] b = new byte[16];
36 int i;
37 while ((i=fis.read(b) )!= -1) {
38 cos.read(b, 0, i);
39 }
40 cos.close();
41 fis.close();
42 }catch (Exception e) {
43 // TODO: handle exception
44 }
45}
46
47private static SecretKey chaveSimetrica () {
48
49 try {
50 KeyGenerator kg = KeyGenerator.getInstance("AES");
51 kg.init(128);
52 SecretKey key = kg.generateKey();
53 return key;
54 } catch (NoSuchAlgorithmException e) {
55 e.printStackTrace();
56 }
57 return null;
58}