KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > snow > FileEncryptor > SimpleFileEncryptor


1 package snow.FileEncryptor;
2
3 import javax.swing.*;
4 import javax.swing.filechooser.*;
5 import java.util.*;
6 import java.util.zip.*;
7
8 import java.security.*;
9 import java.security.spec.*;
10 import javax.crypto.spec.*;
11 import javax.crypto.*;
12
13 import snow.utils.gui.*;
14 import snow.utils.storage.*;
15 import snow.crypto.*;
16 import snow.Language.Language;
17
18 import java.io.*;
19
20
21 /** encrypt/decrypt a file
22 */

23 public final class SimpleFileEncryptor
24 {
25
26   private SimpleFileEncryptor()
27   {
28
29   } // Constructor
30

31
32
33   /** overwrite the file content with a random buffer
34   */

35   public static void wipeFile(File f, int bufferSize, ProgressModalDialog progressDialog, int passes)
36   {
37     long count = 0; // for the progress
38
RandomAccessFile raf = null;
39     for(int p=0; p<passes; p++)
40     {
41        try
42        {
43            raf = new RandomAccessFile(f, "rw");
44
45            raf.seek(0);
46            byte[] buffer = new byte[bufferSize];
47            int blocks = (int)(raf.length()/bufferSize)+1;
48            for(int i=0; i<blocks; i++)
49            {
50              fillRandom(buffer);
51              raf.write(buffer);
52              if(count%passes==1)
53              {
54                progressDialog.incrementProgress(1);
55              }
56              count++;
57            }
58        }
59        catch(Exception JavaDoc e)
60        {
61          e.printStackTrace();
62        }
63        finally
64        {
65          if(raf!=null)
66          {
67            try
68            {
69              raf.close();
70            }
71            catch(Exception JavaDoc ee){ ee.printStackTrace(); }
72          }
73        }
74     }
75
76     f.delete();
77     if(f.exists())
78     {
79       System.out.println("Cannot delete the file "+f);
80       f.deleteOnExit();
81     }
82   }
83
84   public static void fillRandom(byte[] buf)
85   {
86     for(int i=0; i<buf.length; i++)
87     {
88       buf[i] = (byte) (Math.random()*256);
89     }
90   }
91
92
93   public static void encryptDirectory(File in, File out, boolean delete, SecretKey key, int bufferSize, ProgressModalDialog progressDialog) throws Exception JavaDoc
94   {
95      // 1) Collect all directory files and zip them
96
//
97
Vector<File> allFilesToZip = new Vector<File>();
98      FileUtils.getAllFilesRecurse(in, allFilesToZip);
99
100      ZipOutputStream zos = null;
101      File tempZipFile = new File(in.getParentFile(), "tempZip.zip");
102      tempZipFile.deleteOnExit();
103      try
104      {
105        FileOutputStream fos = new FileOutputStream(tempZipFile);
106        zos = new ZipOutputStream(fos);
107        for(File f: allFilesToZip)
108        {
109          FileUtils.addToZip(zos,f,f.getAbsolutePath());
110        }
111      }
112      catch(Exception JavaDoc ze)
113      {
114        throw ze;
115      }
116      finally
117      {
118        if(zos!=null) zos.close();
119      }
120
121      // 2) encrypt the zip
122
//
123
try
124      {
125        encryptFile(tempZipFile, out, key, bufferSize, progressDialog);
126      }
127      catch(Exception JavaDoc ex)
128      {
129        throw ex;
130      }
131
132      // 3) delete the zip file
133
//
134
wipeFile(tempZipFile, bufferSize, progressDialog, 2);
135
136      if(delete)
137      {
138        for(File f: allFilesToZip)
139        {
140          wipeFile(f, bufferSize, progressDialog, 2);
141        }
142      }
143
144
145
146
147   }
148
149   /** the progress must be set
150   */

151   public static void encryptFile(File in, File out, SecretKey key, int bufferSize, ProgressModalDialog progressDialog) throws Exception JavaDoc
152   {
153     Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
154     cipher.init(Cipher.ENCRYPT_MODE, key);
155
156     FileInputStream fis = null;
157     FileOutputStream fos = null;
158     DataOutputStream dos = null;
159     GZIPOutputStream zos = null;
160     CipherOutputStream cos = null;
161     try
162     {
163       fis = new FileInputStream(in);
164       fos = new FileOutputStream(out);
165       dos = new DataOutputStream(fos);
166       dos.writeInt(2);
167       dos.writeUTF("B");
168       dos.writeInt(key.getEncoded().length);
169       SecretKeyID ski = SecretKeyUtilities.computeSignature(key);
170       dos.write(ski.signature,0,4);
171
172       cos = new CipherOutputStream(dos, cipher);
173       zos = new GZIPOutputStream(cos);
174
175       byte[] buf = new byte[bufferSize];
176       int read =1;
177       while((read=fis.read(buf))!=-1)
178       {
179         zos.write(buf,0,read);
180         //if(read!=bufferSize) System.out.println(""+read);
181
progressDialog.incrementProgress(1);
182       }
183
184
185       zos.close();
186     }
187     catch(Exception JavaDoc e)
188     {
189       throw e;
190     }
191     finally
192     {
193       if(fos!=null) try { fos.close(); } catch(Exception JavaDoc ex) {ex.printStackTrace();}
194       if(fis!=null) try { fis.close(); } catch(Exception JavaDoc ex) {ex.printStackTrace();}
195       out.setLastModified( in.lastModified() );
196     }
197   }
198
199   public static void decryptFile(File in, File out, SecretKey key, int bufferSize, ProgressModalDialog progressDialog) throws Exception JavaDoc
200   {
201     FileOutputStream fos = null;
202     FileInputStream fis = null;
203     DataInputStream dis = null;
204     CipherInputStream cis = null;
205     GZIPInputStream zis = null;
206
207     try
208     {
209       fos = new FileOutputStream(out);
210
211       fis = new FileInputStream(in);
212       dis = new DataInputStream(fis);
213
214       // (clear) header read
215
//
216
int version = dis.readInt();
217       if(version==2)
218       {
219         // custom pass (or default, if not set...
220
String JavaDoc algo = dis.readUTF();
221         int keyLength = dis.readInt();
222         byte[] sign = new byte[4];
223         dis.readFully(sign,0,4);
224         SecretKeyID ski = new SecretKeyID(sign, keyLength);
225         if(!SecretKeyUtilities.computeSignature(key).equals(ski))
226         {
227           throw new BadPasswordException(Language.translate("Bad key"));
228         }
229       }
230
231       else
232       {
233         throw new Exception JavaDoc("Bad file version "+version);
234       }
235
236       // read cipher vector part
237
//
238

239       Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
240       cipher.init(Cipher.DECRYPT_MODE, key);
241
242       cis = new CipherInputStream(dis, cipher);
243       zis = new GZIPInputStream(cis);
244
245       byte[] buf = new byte[bufferSize];
246       int read = -1;
247       while((read=zis.read(buf))!=-1)
248       {
249         fos.write(buf,0,read);
250         progressDialog.incrementProgress(1);
251       }
252
253
254       zis.close();
255     }
256     catch(Exception JavaDoc e)
257     {
258       throw e;
259     }
260     finally
261     {
262       if(fis!=null) try{ fis.close(); } catch(Exception JavaDoc ex) {ex.printStackTrace();}
263       if(fos!=null) try{ fos.close(); } catch(Exception JavaDoc ex) {ex.printStackTrace();}
264
265       out.setLastModified( in.lastModified() );
266     }
267   }
268
269
270   /** @return null if ok, an error message otherwise
271   */

272   public static String JavaDoc verifyEncryptedFile(File source, File encrypted, SecretKey key, int bufferSize, ProgressModalDialog progressDialog) throws Exception JavaDoc
273   {
274     FileInputStream fis = null;
275     DataInputStream dis = null;
276     CipherInputStream cis = null;
277     GZIPInputStream zis = null;
278
279     try
280     {
281       fis = new FileInputStream(encrypted);
282       dis = new DataInputStream(fis);
283
284       // (clear) header read
285
//
286
int version = dis.readInt();
287       if(version==2)
288       {
289         // custom pass (or default, if not set...)
290
String JavaDoc algo = dis.readUTF();
291         int keyLength = dis.readInt();
292         byte[] sign = new byte[4];
293         dis.readFully(sign,0,4);
294         SecretKeyID ski = new SecretKeyID(sign, keyLength);
295         if(!SecretKeyUtilities.computeSignature(key).equals(ski))
296         {
297           throw new BadPasswordException(Language.translate("Bad key"));
298         }
299       }
300
301       else
302       {
303         throw new Exception JavaDoc("Bad file version "+version);
304       }
305
306       // read cipher vector part
307
//
308

309       Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
310       cipher.init(Cipher.DECRYPT_MODE, key);
311
312       cis = new CipherInputStream(dis, cipher);
313       zis = new GZIPInputStream(cis);
314
315       byte[] buf = new byte[bufferSize];
316       int read = -1;
317       long decrypetdLength = 0;
318       MessageDigest md = MessageDigest.getInstance("SHA1");
319       while((read=zis.read(buf))!=-1)
320       {
321         progressDialog.incrementProgress(1);
322         md.update(buf,0,read);
323         decrypetdLength += read;
324       }
325       zis.close();
326
327       // verif 1
328
if(decrypetdLength!=source.length())
329       {
330         return "Decrpyted file has different length !";
331       }
332
333       // verif2
334
byte[] md1 = md.digest();
335       byte[] md2 = calculateSHA1Hash(source);
336
337       if(!Arrays.equals(md1,md2))
338       {
339         return "Decrypted file has different checksum !";
340       }
341     }
342     catch(Exception JavaDoc e)
343     {
344       throw e;
345     }
346     finally
347     {
348       if(fis!=null) fis.close();
349     }
350     return null;
351   }
352
353
354   public static byte[] calculateSHA1Hash(File f) throws Exception JavaDoc
355   {
356     FileInputStream fis = null;
357     MessageDigest md = MessageDigest.getInstance("SHA1");
358     try
359     {
360       fis = new FileInputStream(f);
361       byte[] buf = new byte[256];
362       int read = 0;
363       while((read=fis.read(buf))!=-1)
364       {
365         md.update(buf,0,read);
366       }
367       return md.digest();
368     }
369     catch(Exception JavaDoc e)
370     {
371       throw e;
372     }
373     finally
374     {
375      if(fis!=null) fis.close();
376     }
377   }
378
379
380
381   /** @return the keyID of the enciphered file
382   */

383   public static SecretKeyID getKeyIDFromFile(File in) throws Exception JavaDoc
384   {
385     FileInputStream fis = null;
386     DataInputStream dis = null;
387     try
388     {
389        fis = new FileInputStream(in);
390        dis = new DataInputStream(fis);
391        // header read
392
int version = dis.readInt();
393        if(version>=2)
394        {
395           String JavaDoc algo = dis.readUTF(); // actually ignored
396
int keyLength = dis.readInt();
397           byte[] sign = new byte[4];
398           dis.readFully(sign,0,4);
399           dis.close();
400
401           SecretKeyID ski = new SecretKeyID(sign, keyLength);
402           return ski;
403        }
404        else
405        {
406          throw new Exception JavaDoc(Language.translate("Bad version %",""+version));
407        }
408     }
409     catch(Exception JavaDoc e)
410     {
411       throw e;
412     }
413     finally
414     {
415        if(fis!=null) try { fis.close(); } catch(Exception JavaDoc ex) {ex.printStackTrace();}
416     }
417
418   }
419
420
421 } // SimpleFileEncryptor
Popular Tags