python md5_Python提取MD5
使用Python的hashlib模塊提取MD5,網上參考,覺得這個還不錯,可以作為模塊直接使用。
# -*- coding: utf-8 -*-
import hashlib
import sys
import os
def md5hex(word):
""" MD5加密算法,返回32位小寫16進制符號 """
if isinstance(word, unicode):
word = word.encode("utf-8")
elif not isinstance(word, str):
word = str(word)
m = hashlib.md5()
m.update(word)
return m.hexdigest()
def md5sum(fname):
""" 計算文件的MD5值 """
def read_chunks(fh):
fh.seek(0)
chunk = fh.read(8096)
while chunk:
yield chunk
chunk = fh.read(8096)
else: #最后要將游標放回文件開頭
fh.seek(0)
m = hashlib.md5()
if isinstance(fname, basestring) and os.path.exists(fname):
with open(fname, "rb") as fh:
for chunk in read_chunks(fh):
m.update(chunk)
#上傳的文件緩存 或 已打開的文件流
elif fname.__class__.__name__ in ["StringIO", "StringO"] or isinstance(fname, file):
for chunk in read_chunks(fname):
m.update(chunk)
else:
return ""
return m.hexdigest()
if __name__ == "__main__":
print (md5hex(sys.argv[1]))
print (md5sum(sys.argv[2]))
Linux上驗證:
總結
以上是生活随笔為你收集整理的python md5_Python提取MD5的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python运行的原理_Python运行
- 下一篇: python信号分析_Python频谱分