python md5使用例子

hashlib是个专门提供hash算法的库,现在里面包括md5, sha1, sha224, sha256, sha384, sha512,使用非常简单、方便。 md5经常用来做用户密码的存储。而sha1则经常用作数字签名

使用Python进行文件Hash计算有两点必须要注意:

1、文件打开方式一定要是二进制方式,既打开文件时使用b模式,否则Hash计算是基于文本的那将得到错误的文件Hash(网上看到有人说遇到Python的Hash计算错误在大多是由于这个原因造成的)。

2、对于MD5如果需要16位(bytes)的值那么调用对象的digest()而hexdigest()默认是32位(bytes),同理Sha1的digest()和hexdigest()分别产生20位(bytes)和40位(bytes)的hash值

import hashlib 

a = "a test string"

print hashlib.md5(a).hexdigest()

print hashlib.sha1(a).hexdigest()

print hashlib.sha224(a).hexdigest()

print hashlib.sha256(a).hexdigest()

print hashlib.sha384(a).hexdigest()


 

#python 检测文件MD5值

#python version 2.6 


import hashlib

import os,sys


#简单的测试一个字符串的MD5值

def GetStrMd5(src):

    m0=hashlib.md5()

    m0.update(src)

    print m0.hexdigest() 

    pass


#大文件的MD5值

def GetFileMd5(filename):

    if not os.path.isfile(filename):

        return

    myhash = hashlib.md5()

    f = file(filename,'rb')

    while True:

        b = f.read(8096)

        if not b :

            break

        myhash.update(b)

    f.close()

    return myhash.hexdigest()


def CalcSha1(filepath):

    with open(filepath,'rb') as f:

        sha1obj = hashlib.sha1()

        sha1obj.update(f.read())

        hash = sha1obj.hexdigest()

        print(hash)

        return hash 


def CalcMD5(filepath):

    with open(filepath,'rb') as f:

        md5obj = hashlib.md5()

        md5obj.update(f.read())

        hash = md5obj.hexdigest()

        print(hash)

        return hash         


if __name__ == "__main__":

    if len(sys.argv)==2 :

        hashfile = sys.argv[1]

        if not os.path.exists(hashfile):

            hashfile = os.path.join(os.path.dirname(__file__),hashfile)

            if not os.path.exists(hashfile):

                print("cannot found file")

            else

                CalcMD5(hashfile)

        else:

            CalcMD5(hashfile)

            #raw_input("pause")

    else:

        print("no filename")

posted @ 2013-03-30 20:11  godjob  Views(3596)  Comments(0Edit  收藏  举报