[英]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.