Skip to content

Instantly share code, notes, and snippets.

@alpacas9
Created April 9, 2021 17:37
Show Gist options
  • Select an option

  • Save alpacas9/ab81794e7ff82cb6ab05af85910f9f00 to your computer and use it in GitHub Desktop.

Select an option

Save alpacas9/ab81794e7ff82cb6ab05af85910f9f00 to your computer and use it in GitHub Desktop.
SecureDelete
import os
import random
class SecureDelete:
BLOCK_SIZE = 16 << 12
def secure_delete(self, base_path):
if os.path.isdir(base_path):
file_list = self._enum_paths(base_path)
for file_path in file_list:
self.secure_delete(file_path)
self._remove_dirs(base_path)
else:
self._override_random_data(base_path)
self._remove_file(base_path)
def _override_random_data(self, file_path):
random_bytes = []
for _ in range (13):
random_bytes.append(self._random_bytes(self.BLOCK_SIZE))
file_bytes_size = os.path.getsize(file_path)
with open(file_path, "wb", buffering=0) as fp:
write_bytes_size = 0
while write_bytes_size < file_bytes_size:
ch = random.choice(random_bytes)
fp.write(ch)
write_bytes_size += self.BLOCK_SIZE
fp.flush()
fd = fp.fileno()
os.fsync(fd)
return
def _enum_paths(self, root_dir, list_paths=[]):
for sub_path in os.listdir(root_dir):
full_path = os.path.join(root_dir, sub_path)
is_dir = os.path.isdir(full_path)
if is_dir:
self._enum_paths(full_path, list_paths)
list_paths.append(full_path)
else:
list_paths.append(full_path)
return list_paths
def _random_bytes(self, bytes_size):
array = bytearray()
for i in range(bytes_size):
array.append(random.randint(0, 255))
return bytes(array)
def _remove_file(self, file_path):
try:
os.remove(file_path)
except OSError as err:
pass
finally:
pass
def _remove_dirs(self, path):
try:
os.removedirs(path)
except OSError as err:
pass
finally:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment