Hashlib的md5为相同的inpu生成不同的输出

2024-04-26 08:22:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个脚本,为指定根目录中的所有文件名和目录名生成哈希值。 这是我目前为止的剧本:

import hashlib
import os
import sys

class Hasher:
    def __init__(self):
        self.hash_func = hashlib.md5()

    def hash_file(self, file_path):
        with open(file_path, "rb") as file:
            self.hash_func.update(file.read())
        return self.hash_func.digest()

    def hash_dir(self, dir_path):
        for dirpath, dirnames, filenames in os.walk(dir_path):
            self.hash_func.update(dirpath.encode("utf-8"))
            for file_path in filenames:
                self.hash_func.update(file_path.encode("utf-8"))
        return self.hash_func.digest()

hasher = Hasher()
root_dir = "D:/folder/"
hash_1 = str(hasher.hash_dir(root_dir))
hash_2 = str(hasher.hash_dir(root_dir))
print(hash_1)
print(hash_2)

由于某些原因,它为同一个目录生成两个不同的哈希值,而不会对目录进行任何更改。如果目录保持不变,我如何使它产生相同的哈希值?在


Tags: pathimportself目录osdefdirupdate
1条回答
网友
1楼 · 发布于 2024-04-26 08:22:03

问题是hashlib.md5对象每次都会被重用,因此返回累积数据的散列值,而不仅仅是上一个/预期的数据。在

您可以通过每次创建一个新的Hasher对象来解决这个问题(因此在本例中调用Hasher().hash_dir(root_dir)两次)。但是由于您的Hasher类只包含md5对象和两个可能是静态的方法之外的任何其他数据,我建议将这两个类方法都设为静态的,并在方法本身中创建hashlib.md5对象:

import hashlib
import os


class Hasher:

    @staticmethod  # make it a static method
    def hash_file(file_path):  # no 'self' as first argument
        hash_func = hashlib.md5()  # create the hashlib.md5 object here
        with open(file_path, "rb") as file:
            hash_func.update(file.read())
        return hash_func.digest()

    @staticmethod  # make it a static method
    def hash_dir(dir_path):  # no 'self' as first argument
        hash_func = hashlib.md5()  # create the hashlib.md5 object here
        for dirpath, _, filenames in os.walk(dir_path):
            hash_func.update(dirpath.encode("utf-8"))
            for file_path in filenames:
                hash_func.update(file_path.encode("utf-8"))
        return hash_func.digest()


def main():
    root_dir = "D:/folder/"
    hash_1 = str(Hasher.hash_dir(root_dir))
    hash_2 = str(Hasher.hash_dir(root_dir))
    print(hash_1)
    print(hash_2)


if __name__ == "__main__":
    main()

相关问题 更多 >