Python hashlib给出了不同的结果

kmbjn2e3  于 2023-01-16  发布在  Python
关注(0)|答案(1)|浏览(184)

由于某种原因,下面的代码给出了不一致的结果。files中的文件永远不会更改。但是,hasher.hexdigest()的结果是每次运行这个函数时给出不同的值。我的目标是只有当当前设置文件中的校验和/散列与hashlib散列的三个设置文件的结果不匹配时,才生成一个新的设置文件。有人知道我做错了什么吗?

def should_generate_new_settings(qt_settings_generated_path: Path) -> tuple[bool, str]:
    """ compare checksum of user_settings.json and the current ini file to what is stored in the currently generated settings file """
    generate = False
    hasher = hashlib.new('md5')
    if not qt_settings_generated_path.exists():
        generate = True

    try:
        # if the file is corrupt, it may have a filesize of 0.
        generated_file = qt_settings_generated_path.stat()
        if generated_file.st_size < 1:
            generate = True

        files = [paths.user_settings_path, paths.settings_generated_path, Path(__file__)]
        for path in files:
            file_contents = path.read_bytes()
            hasher.update(file_contents)

        with qt_settings_generated_path.open('r') as file:
            lines = file.read().splitlines()

        checksum_prefix = '# checksum: '
        for line in lines:
            if line.startswith(checksum_prefix):
                file_checksum = line.lstrip(checksum_prefix)
                if file_checksum != hasher.hexdigest():
                    generate = True
                    break
    except FileNotFoundError:
        generate = True

    return (generate, hasher.hexdigest())
r7knjye2

r7knjye21#

我发现了这个问题,解决方案就是把哈希摘要存储在另一个文件中,而不是我生成设置的文件中。

相关问题