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