Python - Hashlib MD5在linux/windows之间有所不同

Tom*_*rma 11 python

我有一个python应用程序,我在windows中创建要使用的包,然后在linux python应用程序中进行比较.我正在为Windows中的文件创建一个md5,以便稍后在linux中进行检查.问题是同一文件上的相同代码在每个环境中给出不同的Md5哈希结果.下面是我用来计算Md5的方法.(每个端口都是相同的代码,我在两个Windows/Linux环境中都使用Python 2.6.5)当我在不同环境中的同一个文件上运行它时,我得到了不匹配的md5哈希值.

def md5_for_file(filePath):
        md5 = hashlib.md5()
        file = open(filePath)
        while True:
            data = file.read(8192)
            if not data:
                break
            md5.update(data)

        file.close()   
        return md5.hexdigest()
Run Code Online (Sandbox Code Playgroud)

任何想法或建议表示赞赏.

Cor*_*sky 23

更改open(filePath)open(filePath, 'rb'),b二进制模式的位置.您目前正在以文本模式打开,这可能会导致可移植性问题.