· 6 years ago · Jun 24, 2019, 07:12 AM
1public class AESFileEncryption {
2
3// password to encrypt the file - how long should password be?
4private static final String password = "UxIpOqSdNmSTuxZaShPu";
5
6public static void main(String args[]) throws Exception {
7
8 // file to be encrypted
9 FileInputStream inF = new FileInputStream(GUI.AESinFile); // 'AESinFile' is a JFileChooser method from my GUI class
10
11 // encrypted file
12 FileOutputStream outF = new FileOutputStream("encrypted_file.des");
13
14 // generate and write the salt
15 SecureRandom sr = new SecureRandom();
16 byte[] salt = new byte[16];
17 sr.nextBytes(salt);
18 outF.write(salt);
19
20 // generate key
21 SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
22 KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); // salt, iteration count, key strength
23 SecretKey tmp = skf.generateSecret(keySpec);
24 SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); // returns key
25
26 // initialise the cipher with secure padding
27 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
28 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
29 AlgorithmParameters p = cipher.getParameters();
30
31 // iv used when initializing the cipher to make text more random
32
33 byte[] iv = p.getParameterSpec(IvParameterSpec.class).getIV();
34 outF.write(iv);
35
36 // file encryption
37 byte[] input = new byte[64];
38 int bytesRead;
39
40 while ((bytesRead = inF.read(input)) != -1) {
41 byte[] output = cipher.update(input, 0, bytesRead);
42 if (output != null)
43 outF.write(output);
44 }
45
46 byte[] output = cipher.doFinal();
47 if (output != null)
48 outF.write(output);
49 System.out.println("file encrypted");
50
51
52 inF.close();
53 outF.flush();
54 outF.close();
55 // inputScanner.close();
56
57}