5

Is there a Gem or means of securely erasing a file in Ruby? I'd like to avoid external programs that may not be present on the system.

By "secure erase" I'm referring to overwriting the file contents.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Paul R Rogers
  • 914
  • 1
  • 9
  • 19

3 Answers3

3

If you are on *nix, a pretty good way would be to just call shred using exec/open3/open4:

`shred -fxuz #{filename}`

http://www.gnu.org/s/coreutils/manual/html_node/shred-invocation.html

Check this similar post:

Writing a file shredder in python or ruby?

Community
  • 1
  • 1
Andrew Kuklewicz
  • 10,621
  • 1
  • 34
  • 42
  • 2
    _"I'd like to avoid external programs that may not be present on the system."_ I assume that means one cannot assume what OS is used, but desired to run wherever Ruby runs. – Phrogz Dec 14 '11 at 18:58
3

Something like this will get you started:

#!/usr/bin/env ruby

abort "Missing filename" if (ARGV.empty?)

ARGV.each do |filename|
  filesize = File.size(filename)
  [0x00, 0xff].each do |byte|
    File.open(filename, 'wb') do |fo|
      filesize.times { fo.print(byte.chr) }
    end
  end
end

It should get you close.

For more thoroughness, you could also use 0xaa and 0x55 for alternating 0 and 1 bits in the byte. Random.rand(0xff) will give you a random value from 0 to 255.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
  • This is not guaranteed to actually affect the physical storage previously used for the file - the old data will likely still be on the drive, with the new data written elsewhere. – user2357112 Oct 22 '20 at 19:57
2

just

  1. open the file
  2. write some garbage at least in amount equal to current file size
  3. flush() and close()
  4. repeat N times, mixing garbage with zeroes and 0xff's on different passes
zed_0xff
  • 32,417
  • 7
  • 53
  • 72