How to securely delete files in java

2019-01-25 01:24发布

问题:

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.

回答1:

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.



回答2:

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();
    }
}


回答3:

Maybe do deleteOnExit() on the file?