Tuesday, August 24, 2010

File Scrubber

File Scrubber is a secure data removal java class. It allows you to securely delete files/directories from your hard drive by overwriting it random data 'n' number of times.

Usage:


FileScrubber scrubber= new FileScrubber();
   try
   {
//overwrites the given directory 5 times
       scrubber.scrub(new File("C:\\fileOrDir\\to\\delete"), 5);
   }
   catch(Exception ex)
   {
       System.err.println(ex.getMessage());
   } 
 
 
Code Sample for scrubFile:
private void scrubFile(File fileToTerminate, int overwriteTimes) throws FileNotFoundException, IOException {
SecureRandom random = new SecureRandom();
//open a randomaccessfile in rw mode
RandomAccessFile raf = new RandomAccessFile(fileToTerminate, "rw");
FileChannel channel = raf.getChannel();
long length = raf.length() ;
if(length == 0)
    length = 10; //
length = length +  random.nextInt((int) length / 2);
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, length);

for (int i = 0; i < overwriteTimes; i++) {
    // overwrite with zeros
    while (buffer.hasRemaining()) 
       {
           buffer.put((byte) 0);
       }
    buffer.force();
    buffer.rewind();
    // overwrite with ones
    while (buffer.hasRemaining()) 
       {
           buffer.put((byte) 1);
       }
    buffer.force();
    buffer.rewind();
    // overwriting with random bytes
    byte[] data = new byte[1];
    while (buffer.hasRemaining()) 
       {
           random.nextBytes(data);
           buffer.put(data[0]);
        }
     buffer.force();
}

buffer = null;
channel.close();

raf.close();
/*
 * yes, i know System.gc() is not guaranteed and just
 * hints the JVM for garbage collection. But i was not able to delete
 * a file (on windows) without calling System.gc() though
 * works perfectly fine on  Ubuntu without calling System.gc()
 * if any one knows a better way, plz lemme know. ;)
 */
System.gc();
boolean deleted =  fileToTerminate.delete();
}
}

If  the given file object () is a file then the above method is called directly and if the given file object is directory then this method is called recursively for each file in the directory.

Code Sample


private void scrubDirectory(File dirToTerminate, int overwriteTimes) throws FileNotFoundException, IOException {
        File[] files = dirToTerminate.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                scrubFile(files[i],overwriteTimes);
            } else {
                scrubDirectory(files[i],overwriteTimes);
                boolean deleted =  files[i].delete();
            }
        }
        dirToTerminate.delete();

    }

The complete source code can be downloaded from here


Reference: http://www.javafaq.nu/java-example-code-1121.html

No comments:

Post a Comment