繁体   English   中英

Python hashlib 给出了不同的结果

[英]Python hashlib is giving different results

出于某种原因,我下面的代码给出了不一致的结果。 文件中的files永远不会改变。 但是,每次运行此 function 时, 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())

我想通了这个问题。 解决方案只是将 hash 摘要存储在另一个文件中,而不是我生成设置的文件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM