· 8 years ago · Dec 02, 2017, 01:50 PM
1import java.io.InputStream;
2import java.io.OutputStream;
3import java.io.FileInputStream;
4import java.io.FileOutputStream;
5import java.io.ObjectOutputStream;
6import java.io.ObjectInputStream;
7
8import javax.crypto.Cipher;
9import javax.crypto.SecretKey;
10import javax.crypto.spec.IvParameterSpec;
11import javax.crypto.CipherInputStream;
12import javax.crypto.CipherOutputStream;
13import javax.crypto.KeyGenerator;
14
15import java.security.spec.AlgorithmParameterSpec;
16
17public class AESEncrypter
18{
19 Cipher ecipher;
20 Cipher dcipher;
21
22 public AESEncrypter(SecretKey key)
23 {
24 byte[] iv = new byte[]
25 {
26 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
27 };
28
29 AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
30 try
31 {
32 ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
33 dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
34
35 ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
36 dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
37 }
38 catch (Exception e)
39 {
40 e.printStackTrace();
41 }
42 }
43
44 byte[] buf = new byte[1024];
45
46 public void encrypt(InputStream in, OutputStream out)
47 {
48 try
49 {
50 out = new CipherOutputStream(out, ecipher);
51
52 int numRead = 0;
53 while ((numRead = in.read(buf)) >= 0)
54 {
55 out.write(buf, 0, numRead);
56 }
57 out.close();
58 }
59 catch (java.io.IOException e)
60 {
61 }
62 }
63
64 public void decrypt(InputStream in, OutputStream out)
65 {
66 try
67 {
68
69 in = new CipherInputStream(in, dcipher);
70
71 int numRead = 0;
72 while ((numRead = in.read(buf)) >= 0)
73 {
74 out.write(buf, 0, numRead);
75 }
76 out.close();
77 }
78 catch (java.io.IOException e)
79 {
80 }
81 }
82
83 public static void main(String args[])
84 {
85 try
86 {
87 // Generate a temporary key. In practice, you would save this key.
88 // See also e464 Encrypting with DES Using a Pass Phrase.
89
90 KeyGenerator kgen = KeyGenerator.getInstance("AES");
91 kgen.init(256);
92 SecretKey key = kgen.generateKey();
93
94 // Create encrypter/decrypter class
95 AESEncrypter encrypter = new AESEncrypter(key);
96
97 // Encrypt
98 //encrypter.encrypt(new FileInputStream("DESTest.txt"),new FileOutputStream("Encrypted.txt"));
99 // Decrypt
100 encrypter.decrypt(new FileInputStream("settings.lua"),new FileOutputStream("Decrypted.txt"));
101 }
102 catch (Exception e)
103 {
104 e.printStackTrace();
105 }
106 }
107}