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

问题描述 投票:0回答:1

我一直在尝试制作一个文件粉碎机,该文件粉碎机将使用新的随机文件覆盖任何文件的每个字节,对其进行重命名,然后将其删除。我禁用了删除功能以检查输出是什么样的,并且由于某种原因,输出文件的大小小于原始文件的大小(恰好是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)
python file byte file-writing
1个回答
0
投票

已解决。我将编码更改为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

现在,我修复了它,我想知道这是一种有效的切碎方法,还是我可以做得更好

© www.soinside.com 2019 - 2024. All rights reserved.