繁体   English   中英

Python MD5 与终端中的 md5 不匹配

[英]Python MD5 not matching md5 in terminal

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

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

虽然当我去终端并做一个

md5 file

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

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()
$ 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'

尝试这个

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM