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

时间:2010-08-02 18:07:07

标签: 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()

任何想法或建议都表示赞赏。

2 个答案:

答案 0 :(得分:23)

open(filePath)更改为open(filePath, 'rb'),其中b用于二进制模式。您目前正在以文本模式打开,这可能会导致可移植性问题。

答案 1 :(得分:0)

检查这两个文件是否使用相同的编码和lineendings

相关问题