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