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