1package com.javapapers.java.security;
2
3import java.io.FileInputStream;
4import java.io.FileOutputStream;
5import java.util.Random;
6
7import javax.crypto.Cipher;
8import javax.crypto.SecretKey;
9import javax.crypto.SecretKeyFactory;
10import javax.crypto.spec.PBEKeySpec;
11import javax.crypto.spec.PBEParameterSpec;
12
13public class FileEncryption {
14
15 public static void main(String[] args) throws Exception {
16
17 FileInputStream inFile = new FileInputStream("plainfile.txt");
18 FileOutputStream outFile = new FileOutputStream("plainfile.des");
19
20 String password = "javapapers";
21 PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
22 SecretKeyFactory secretKeyFactory = SecretKeyFactory
23 .getInstance("PBEWithMD5AndTripleDES");
24 SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);
25
26 byte[] salt = new byte[8];
27 Random random = new Random();
28 random.nextBytes(salt);
29
30 PBEParameterSpec pbeParameterSpec = new PBEParameterSpec(salt, 100);
31 Cipher cipher = Cipher.getInstance("PBEWithMD5AndTripleDES");
32 cipher.init(Cipher.ENCRYPT_MODE, secretKey, pbeParameterSpec);
33 outFile.write(salt);
34
35 byte[] input = new byte[64];
36 int bytesRead;
37 while ((bytesRead = inFile.read(input)) != -1) {
38 byte[] output = cipher.update(input, 0, bytesRead);
39 if (output != null)
40 outFile.write(output);
41 }
42
43 byte[] output = cipher.doFinal();
44 if (output != null)
45 outFile.write(output);
46
47 inFile.close();
48 outFile.flush();
49 outFile.close();
50 }
51
52}