· 6 years ago · Jun 22, 2019, 11:52 PM
1// author @Alex Matheakis
2public static void main(String[] args) throws Exception {
3
4 // file to be encrypted
5 Scanner inputScanner = new Scanner(System.in);
6 System.out.println("Enter filename");
7 String filename = inputScanner.nextLine();
8
9 FileInputStream inputFile = new FileInputStream("C:\Documents\Encryptor\" + filename + ".txt");
10
11 // encrypted file
12 FileOutputStream outputFile = new FileOutputStream("C:\Documents\Encryptor\encryptedfile.des");
13
14 // password to encrypt the file
15 String passKey = "tkfhkggovubm";
16 byte[] salt = new byte[8];
17 Random r = new Random();
18 r.nextBytes(salt);
19 PBEKeySpec pbeKeySpec = new PBEKeySpec(passKey.toCharArray());
20 SecretKeyFactory secretKeyFactory = SecretKeyFactory
21 .getInstance("PBEWithSHA1AndDESede");
22 SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
23
24
25 PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 99999);
26 Cipher cipher = Cipher.getInstance("PBEWithSHA1AndDESede");
27 cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
28 outputFile.write(salt);
29
30 byte[] input = new byte[64];
31 int bytesRead;
32 while ((bytesRead = inputFile.read(input)) != -1) {
33 byte[] output = cipher.update(input, 0, bytesRead);
34 if (output != null)
35 outputFile.write(output);
36 }
37
38 byte[] output = cipher.doFinal();
39 if (output != null)
40 outputFile.write(output);
41
42 inputFile.close();
43 outputFile.flush();
44 outputFile.close();
45 inputScanner.close();
46 System.out.println("File has been Encrypted.");
47}