首页 > 编程语言 > 详细

Python提取MD5

时间:2017-06-14 21:02:52      阅读:335      评论:0      收藏:0      [点我收藏+]

使用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

原文:http://www.cnblogs.com/jjzd/p/7010801.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!