· 7 years ago · Sep 18, 2018, 10:28 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{
19Cipher ecipher;
20Cipher dcipher;
21
22public AESEncrypter(SecretKey key)
23{
24// Create an 8-byte initialization vector
25byte[] iv = new byte[]
26{
270x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f
28};
29
30AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
31try
32{
33ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
34dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
35
36// CBC requires an initialization vector
37ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
38dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
39}
40catch (Exception e)
41{
42e.printStackTrace();
43}
44}
45
46// Buffer used to transport the bytes from one stream to another
47byte[] buf = new byte[1024];
48
49public void encrypt(InputStream in, OutputStream out)
50{
51try
52{
53// Bytes written to out will be encrypted
54out = new CipherOutputStream(out, ecipher);
55
56// Read in the cleartext bytes and write to out to encrypt
57int numRead = 0;
58while ((numRead = in.read(buf)) >= 0)
59{
60out.write(buf, 0, numRead);
61}
62out.close();
63}
64catch (java.io.IOException e)
65{
66}
67}
68
69public void decrypt(InputStream in, OutputStream out)
70{
71try
72{
73// Bytes read from in will be decrypted
74in = new CipherInputStream(in, dcipher);
75
76// Read in the decrypted bytes and write the cleartext to out
77int numRead = 0;
78while ((numRead = in.read(buf)) >= 0)
79{
80out.write(buf, 0, numRead);
81}
82out.close();
83}
84catch (java.io.IOException e)
85{
86}
87}
88
89public static void main(String args[])
90{
91try
92{
93// Generate a temporary key. In practice, you would save this key.
94// See also e464 Encrypting with DES Using a Pass Phrase.
95
96KeyGenerator kgen = KeyGenerator.getInstance("AES");
97kgen.init(128);
98SecretKey key = kgen.generateKey();
99
100// Create encrypter/decrypter class
101AESEncrypter encrypter = new AESEncrypter(key);
102
103// Encrypt
104encrypter.encrypt(new FileInputStream("E:\\keeper.txt"),new FileOutputStream("E:\\Encrypted.txt"));
105// Decrypt
106encrypter.decrypt(new FileInputStream("E:\\keeper.txt"),new FileOutputStream("E:\\Decrypted.txt"));
107}
108catch (Exception e)
109{
110e.printStackTrace();
111}
112}
113}