How to securely delete files in java

我的未来我决定 提交于 2019-12-29 04:59:25

问题


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?



来源:https://stackoverflow.com/questions/858036/how-to-securely-delete-files-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!