为什么md5比python 2.7.11中的sha1慢

时间:2016-03-02 03:45:43

标签: python hash

我已经测试了md5,sha1,crc32的速度,结果显示md5比sha1慢,我很担心它因为sha1比md5更加复杂。

我执行了我的测试python脚本来散列png图像(你可以随意使用图像)10000次像: crc_vs_md5.py C:\ Users \ bigwalnut \ Desktop \ def.png 10000

结果(单位:s): md5:0.122737341241 sha1:0.0984247229759 crc32:0.0577822398549

以下是代码:

from hashlib import md5, sha1
from zlib import crc32
import sys
import time

numberoftime = 0
content = None

def getMd5():
    for x in range(0, numberoftime):
        mdfive = md5()
        mdfive.update(content)
        mdfive.hexdigest()

def getSha1():
    for x in range(0, numberoftime):
        sha1Obj = sha1()
        sha1Obj.update(content)
        sha1Obj.hexdigest()


def getCrc32():
    for x in range(0, numberoftime):
        crc32(content) & 0xffffffff


if len(sys.argv) < 3:
    print('You must enter: filename, numberoftime')
    exit(1)
elif len(sys.argv) > 3:
    print('Only filename, numberoftime is permitted')
    exit(1)

filename = sys.argv[1]
numberoftime = int(sys.argv[2])
print filename, numberoftime

with open(filename, 'rb') as f:
    content = f.read()

start = time.clock()
getMd5()
stop = time.clock()
print "md5: ", stop - start

start = time.clock()
getSha1()
stop = time.clock()
print "sha1: ", stop - start

start = time.clock()
getCrc32()
stop = time.clock()
print "crc32: ", stop - start

1 个答案:

答案 0 :(得分:0)

Python借用OpenSSL原语用于大多数加密目的;虽然它不是明确的,但this post意味着OpenSSL开发人员知道MD5已经崩溃,可能还没有花费太多精力优化MD5,而SHA1则经过了大量优化; MD5在算法上可能更简单,但如果代码的优化程度低于SHA1代码,那么MD5已经很小的优势就不会引人注意。

On another post comparing OpenSSL's MD5 and SHA1 implementations (without the Python wrapping),看起来核心OpenSSL在SHA1上通常更快,但它因版本/版本而异(OSX 10.8和10.10上的SHA1更快,10.9上更慢)。