文件粉碎无法正常工作(粉碎后的文件与原始文件大小不同)

File shredding not working properly (the shredded file is not the same size as the original)

我一直在尝试制作一个文件粉碎机,它将用一个新的随机字节覆盖任何文件的每个字节,重命名它,然后删除它。我禁用删除以检查输出是什么样的,并且由于某种原因,输出文件大小小于原始文件大小(恰好 1 个字节的大小)。在此之前,它实际上变得比原始文件大小更大。我已经弄乱代码几个小时了,但还没有发现错误。是什么导致它变小了?

def shred_file(path : str, passes : int, max_filename : int):
    global dir_char
    valid_chars = string.ascii_letters + string.digits
    valid_bytes = [ b"%c" %byte for byte in range(0x0, 0xFF+1)]
    filename_len = range(1, max_filename + 1)
    if(os.path.isfile(path) == True):
        filesize = os.path.getsize(path)
        for temp in range(0, passes):
            file = open(path, "wb")
            #Overwrite bytes
            for i in range(0, filesize + 1):
                file.seek(i)
                file.write(b"%c" %random.choice(valid_bytes))
            file.close()

            #Rename file
            new_name = str("".join(random.choices(valid_chars, k=random.choice(filename_len))))
            new_path = ""
            if(len(path.split(f"{dir_char}")) > 1):
                new_path = f"{dir_char}".join(path.split(f"{dir_char}")[0:-1]) + f"{dir_char}{new_name}"
            else:
                new_path = f"{dir_char}".join(path.split(f"{dir_char}")[0:-1]) + f"{new_name}"
            os.rename(path, new_path)
            path = new_path
        #os.remove(path)

已解决。我将编码更改为 latin1 并且它起作用了。现在输出文件与输入文件大小相同:

def shred_file(path : str, passes : int, max_filename : int):
    print(f"[*] Current file: {path}")
    valid_chars = string.ascii_letters + string.digits
    valid_bytes = [chr(c) for c in range(0xFF+1)]
    raw_byte_encode = "latin1"
    filesize = os.path.getsize(path)
    if(os.path.isfile(path) == True and filesize > 0):
        for temp in range(passes):
            #Overwrite file with random raw bytes
            for i in range(filesize):
                fd = os.open(path, os.O_WRONLY|os.O_NOCTTY)
                os.pwrite(fd, random.choice(valid_bytes).encode(raw_byte_encode), i)
                os.close(fd)

            #Rename File
            new_name = "".join(random.choices(valid_chars, k=random.choice(range(1, max_filename + 1))))
            new_path = f"{dir_char}".join(path.split(f"{dir_char}")[0:-1]) + f"{dir_char}{new_name}"
            if(len(path.split(f"{dir_char}")) == 1):
                new_path = new_name
            os.rename(path, new_path)
            path = new_path

        #Remove file after completing all passes
        os.remove(path)

完整代码:https://github.com/rdbo/shredder.py .

现在我修复了它,我想知道这是否是一种有效的粉碎方式,或者我可以做得更好