md5sum与python生成的md5不匹配。

问题描述 投票:0回答:2

我有一个奇怪的问题,我的流媒体文件的md5哈希值不匹配。md5sum. 奇怪的是,如果我把文件读进去,然后写到第二个文件中,python的md5和 md5sum second_file.txt 同意。这是哈希码

import hashlib 
import sys

file_hash = hashlib.md5()
with open(sys.argv[1], 'r') as f, open(sys.argv[2], 'w') as w:
    while True:
        c = f.read(1)
        w.write(c)
        file_hash.update(c.encode(encoding='utf-8'))

        if c == '':
            # end of file
            break

print(file_hash.hexdigest())

两个文件都在 UTF-8 并在docker容器中运行。我有点不知所措。有什么好办法吗?

python linux file hash md5
2个回答
2
投票

打开文件 "rb" 模式来获取原始字节,并跳过了 encode 位......当你这样做的时候,你实际上是改变了md5比较的字节。


0
投票

一般来说,问题可能出在 python 或 linux 的 md5sum 函数上,因此,如果你能提供 linux 的命令行来显示不同的哈希值,那就更好了。根据我的经验,这种情况很可能发生在试图用 "echo "来做管道,但忘记了 "echo "会在任何回文中添加一个换行符。

例如,这些不匹配。

>> echo 'thing' | md5sum
>> python -c "import hashlib;print(hashlib.md5(b'thing').hexdigest())"

使用 "printf "来防止换行符被添加. 这些都是匹配的。

>> printf 'thing' | md5sum
>> python -c "import hashlib;print(hashlib.md5(b'thing').hexdigest())"

你也可以把数据放在一个文件中。

>> printf 'thing' > temp
>> cat temp | md5sum
>> python -c "import hashlib;print(hashlib.md5(b'thing').hexdigest())"
© www.soinside.com 2019 - 2024. All rights reserved.