views:

667

answers:

3

How do I securely delete files in java? I tried the code at javafaq.nu, but the problem is you can't actually delete the file on windows once it has been mapped due to this bug.

Then I tried just using sysinternals sdelete on windows, but you have to click a usage agreement the first time you use it which I want to avoid.

A: 

Maybe do deleteOnExit() on the file?

alamar
That wont help if the file is mapped - it will need to be deleted after the JVM process has exited.
Tom Hawtin - tackline
+1  A: 

On a journaling filesystem like NTFS there is actually no way to securely erase a single file without wiping all the free space on the drive. The problem is that the new blocks (which you've presumably overwritten with random data) are not guaranteed to be in the same place on disk as the old ones.

Utilities like sdelete might work for you, but one could simply replace that executable with one that does nothing to thwart that method of defence.

In order to keep your data secure, the only real solution you have is to completely encrypt the drive.

Gerco Dries
A: 

I coded and tried this function, and it seemed to work:

public static void secureDelete(File file) throws IOException {
 if (file.exists()) {
  long length = file.length();
  SecureRandom random = new SecureRandom();
  RandomAccessFile raf = new RandomAccessFile(file, "rws");
  raf.seek(0);
  raf.getFilePointer();
  byte[] data = new byte[64];
  int pos = 0;
  while (pos < length) {
   random.nextBytes(data);
   raf.write(data);
   pos += data.length;
  }
  raf.close();
  file.delete();
 }
}
Emre