· 5 years ago · Dec 09, 2019, 06:10 PM
1import java.io.*;
2import java.util.*;
3
4import java.security.*;
5
6import javax.crypto.Cipher;
7import javax.crypto.KeyGenerator;
8import javax.crypto.SecretKey;
9import javax.crypto.spec.SecretKeySpec;
10
11public class CryptoAES extends Files
12{
13 private int i;
14 private String StringKey;
15 private byte[] key;
16
17 public String GetKey()
18 {
19 return this.StringKey;
20 }
21
22 public void SetKey(byte[] key)
23 {
24 this.key = key;
25 }
26
27 /*public void EncryptSentence(String text)
28 {
29 Cipher cipher = Cipher.getInstance("AES");
30 cipher.init(Cipher.ENCRYPT_MODE, this.key);
31 byte[] plaintext = text.getBytes("UTF-8");
32 }*/
33
34 public void EncryptFile(File inFile, File oFile)
35 {
36 try
37 { Key secretKey = new SecretKeySpec(this.key, "AES");
38 Cipher cipher = Cipher.getInstance("AES");
39 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
40
41 FileInputStream istream = new FileInputStream(inFile);
42 byte[] inBytes = new byte[(int) inFile.length()];
43
44 long byteL = inFile.length();
45 int byteLength = (int) byteL;
46 istream.read(inBytes, 0, byteLength);
47 byte[] outBytes = cipher.doFinal(inBytes);
48
49 FileOutputStream ostream = new FileOutputStream(oFile);
50 ostream.write(outBytes);
51
52 istream.close();
53 ostream.close();
54 System.out.println("Encryption complete.");
55 }
56 catch (Exception e)
57 {
58 System.out.println(e.toString());
59 System.out.println("Error encrypting file.");
60 }
61 }
62
63 public void DecryptFile(File inFile, File oFile)
64 {
65 try
66 {
67 Key secretKey = new SecretKeySpec(this.key, "AES");
68 Cipher cipher = Cipher.getInstance("AES");
69 cipher.init(Cipher.DECRYPT_MODE, secretKey);
70
71 FileInputStream istream = new FileInputStream(inFile);
72 byte[] inBytes = new byte[(int) inFile.length()];
73
74 istream.read(inBytes);
75 byte[] outBytes = cipher.doFinal(inBytes);
76 String outputtext = new String (outBytes, "UTF-8");
77
78 FileWriter ostream = new FileWriter(oFile);
79 ostream.write(outputtext);
80
81 istream.close();
82 ostream.close();
83 }
84 catch (Exception e)
85 {
86 System.out.println("Error decrypting file.");
87 }
88 }
89
90
91}