· 9 years ago · Dec 07, 2016, 12:56 PM
1public class AESFileEncryption {
2public static void main(String[] args) throws Exception {
3
4 // file to be encrypted
5 FileInputStream inFile = new FileInputStream("plainfile.txt");
6
7 // encrypted file
8 FileOutputStream outFile = new FileOutputStream("encryptedfile.des");
9
10 // password to encrypt the file
11 String password = "javapapers";
12
13 // password, iv and salt should be transferred to the other end
14 // in a secure manner
15
16 // salt is used for encoding
17 // writing it to a file
18 // salt should be transferred to the recipient securely
19 // for decryption
20 byte[] salt = new byte[8];
21 SecureRandom secureRandom = new SecureRandom();
22 secureRandom.nextBytes(salt);
23 FileOutputStream saltOutFile = new FileOutputStream("salt.enc");
24 saltOutFile.write(salt);
25 saltOutFile.close();
26
27 SecretKeyFactory factory = SecretKeyFactory
28 .getInstance("PBKDF2WithHmacSHA1");
29 KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536,
30 256);
31 SecretKey secretKey = factory.generateSecret(keySpec);
32 SecretKey secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
33
34 //
35 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
36 cipher.init(Cipher.ENCRYPT_MODE, secret);
37 AlgorithmParameters params = cipher.getParameters();
38
39 // iv adds randomness to the text and just makes the mechanism more
40 // secure
41 // used while initializing the cipher
42 // file to store the iv
43 FileOutputStream ivOutFile = new FileOutputStream("iv.enc");
44 byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
45 ivOutFile.write(iv);
46 ivOutFile.close();
47
48 //file encryption
49 byte[] input = new byte[64];
50 int bytesRead;
51
52 while ((bytesRead = inFile.read(input)) != -1) {
53 byte[] output = cipher.update(input, 0, bytesRead);
54 if (output != null)
55 outFile.write(output);
56 }
57
58 byte[] output = cipher.doFinal();
59 if (output != null)
60 outFile.write(output);
61
62 inFile.close();
63 outFile.flush();
64 outFile.close();
65
66 System.out.println("File Encrypted.");
67
68}