【问题标题】:Python MD5 not matching md5 in terminalPython MD5 与终端中的 md5 不匹配
【发布时间】:2010-02-09 13:22:54
【问题描述】:

我正在使用 python 函数获取几个文件的 MD5:

filehash = hashlib.md5(file)
print "FILE HASH: " + filehash.hexdigest()

虽然当我去终端做一个

md5 file

我得到的结果与我的 python 脚本输出的结果不同(它们不匹配)。有人知道为什么吗?

【问题讨论】:

    标签: python hash md5


    【解决方案1】:

    hashlib.md5() 获取文件的内容而不是文件名。

    http://docs.python.org/library/hashlib.html

    您需要打开文件,并在散列之前读取其内容。

    f = open(filename,'rb')
    m = hashlib.md5()
    while True:
        ## Don't read the entire file at once...
        data = f.read(10240)
        if len(data) == 0:
            break
        m.update(data)
    print m.hexdigest()
    

    【讨论】:

    • @Douglas Leeder:f.read(10240) 中读取的 10240 字节有什么神奇之处吗?对最佳尺寸有任何想法吗?
    • 10K 只是一个任意值。我不确定最快的尺寸是多少,或者空间和尺寸之间的最佳权衡是什么。我怀疑 10K 就足够了,读取调用的开销不会太大。
    • @drewk 所以一个神奇的数字,但不是神奇地选择 - 只是任意的。如果这对你很重要,那么你可以做一个微基准测试,但我怀疑它与光盘速度有很大不同。
    • @Douglas Leeder:我做了一点测试。 MD5 是 128 字节块大小,我认为 m.update(data) 不适用于不是 128 倍数的卡盘。我的磁盘有 4096 字节扇区,因此使用该扇区大小的倍数可能是有意义的128. 我使用f.read(128*4096) 或 512k 作为缓冲区。工作得快一点。我尝试了比这更小的,比如只有 128*5、128*10,但速度要慢得多。我会说您使用的 10K 大小(128*80 btw)是可能的最佳速度与大小权衡。对我来说,更大的速度大约快 5% 或 10%。
    • 计算md5可以看这个答案:stackoverflow.com/questions/1131220/…
    【解决方案2】:
    $ md5 test.py
    MD5 (test.py) = 04523172fa400cb2d45652d818103ac3
    $ python
    Python 2.6.1 (r261:67515, Jul  7 2009, 23:51:51) 
    [GCC 4.2.1 (Apple Inc. build 5646)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import hashlib
    >>> s = open('test.py','rb').read()
    >>> hashlib.md5(s).hexdigest()
    '04523172fa400cb2d45652d818103ac3'
    

    【讨论】:

      【解决方案3】:

      试试这个

      filehash = hashlib.md5(open('filename','rb').read())
      print "FILE HASH: " + filehash.hexdigest()
      

      【讨论】:

        【解决方案4】:

        file 是什么?它应该等于open(filename, 'rb').read()。是吗?

        【讨论】:

          猜你喜欢
          • 2022-01-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-16
          • 2012-06-17
          • 1970-01-01
          • 1970-01-01
          • 2014-05-19
          相关资源
          最近更新 更多