Wednesday, May 13, 2009

Deleting files securely in Java

It is possible to delete a file securely in Java. I wrote this small java utility function. It utilizes a workaround in order to avoid this bug. After running this code I undeleted the file with Undelete Plus 2.9.8. The file was filled with random bytes, not the original content, so it worked. But further testing might me needed before production.

Here is the code:

public void secureDelete(File file) throws IOException {
if (file.exists()) {
long length = file.length();
SecureRandom random = new SecureRandom();
RandomAccessFile raf = new RandomAccessFile(file, "rws");;
byte[] data = new byte[64];
int pos = 0;
while (pos <>
pos += data.length;