python对文件内容计算md5值不正确问题


最近在做一个对文件签名的小系统,一开始先使用简单的md5进行签名,一边使用php签名,另一边使用python验证签名。当两边都完工对比签名结果的的时候,收到了意外的惊喜,两边对文件内容计算的md5值不一致。

我就单独测了两个程序直接处理字符串的结果,发现是一致的,唯独读取文件内容后再处理会出问题。

最后发现php的file_get_contents是二进制安全的,python读取文件需要使用二进制模式。

看了一下python的文档open()函数:
Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (including 'b' in the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when 't' is included in the mode argument), the contents of the file are returned as unicode strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given

默认情况下读取模式为文本模式,在此模式下读取字符串后会对字符串进行decode转换成unicode,这就是问题症结了。在open的时候模式设置成rb就可以了。

Archives