· 7 years ago · Apr 26, 2018, 03:16 AM
1private void cipherFile(Path filePath) {
2 try {
3 KeyGenerator kg = KeyGenerator.getInstance("AES");
4 kg.init(128);
5 SecretKey key = kg.generateKey();
6
7 Cipher symC = Cipher.getInstance("AES");
8 symC.init(Cipher.ENCRYPT_MODE, key);
9
10 FileInputStream fich = new FileInputStream(new File(filePath.toString()));
11 FileOutputStream cifFile = new FileOutputStream(filePath+".cif");
12 CipherOutputStream cos = new CipherOutputStream(cifFile, symC);
13 byte[] b = new byte[16];
14 int i = fich.read(b);
15 while(i != -1){
16 cos.write(b, 0, i);
17 i = fich.read(b);
18 }
19
20 cos.close();
21 fich.close();
22
23 Cipher asymC = Cipher.getInstance("RSA");
24 asymC.init(Cipher.WRAP_MODE, pubKey);
25
26 ObjectOutputStream keyOut = new ObjectOutputStream(new FileOutputStream(filePath+".key"));
27 byte[] wrappedKey = asymC.wrap(key);
28 keyOut.writeObject(wrappedKey);
29
30 keyOut.close();
31
32 Files.delete(filePath);
33
34 } catch (Exception e) {
35 e.printStackTrace();
36 }
37
38 }
39
40 private void decipherFile(Path filePath) {
41 try {
42 ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(filePath+".key"));
43 byte[] wrappedKey = (byte[]) keyIn.readObject();
44
45 Cipher c = Cipher.getInstance("RSA");
46 c.init(Cipher.UNWRAP_MODE, priKey);
47 //Faz o unwrap da chave simetrica
48 Key unwrappedKey = c.unwrap(wrappedKey, "RSA", Cipher.SECRET_KEY);
49
50 c = Cipher.getInstance("AES");
51 c.init(Cipher.DECRYPT_MODE, unwrappedKey);
52
53 File newFile = new File(filePath.toString());
54 newFile.createNewFile();
55 FileOutputStream fos = new FileOutputStream(newFile, true);
56
57 FileInputStream cifFile = new FileInputStream(filePath+".cif");
58 CipherOutputStream cos = new CipherOutputStream(fos, c);
59 byte[] b = new byte[16];
60 int i = cifFile.read(b);
61 while(i != -1){
62 cos.write(b, 0, i);
63 }
64
65 keyIn.close();
66 cos.close();
67 cifFile.close();
68 fos.close();
69 } catch (Exception e) {
70 // TODO Auto-generated catch block
71 e.printStackTrace();
72 }
73
74 }