Python实现通过文件路径获取文件hash值的方法
本文实例讲述了Python实现通过文件路径获取文件hash值的方法。分享给大家供大家参考,具体如下:
importhashlib
importos,sys
defCalcSha1(filepath):
withopen(filepath,'rb')asf:
sha1obj=hashlib.sha1()
sha1obj.update(f.read())
hash=sha1obj.hexdigest()
print(hash)
returnhash
defCalcMD5(filepath):
withopen(filepath,'rb')asf:
md5obj=hashlib.md5()
md5obj.update(f.read())
hash=md5obj.hexdigest()
print(hash)
returnhash
if__name__=="__main__":
iflen(sys.argv)==2:
hashfile=sys.argv[1]
ifnotos.path.exists(hashfile):
hashfile=os.path.join(os.path.dirname(__file__),hashfile)
ifnotos.path.exists(hashfile):
print("cannotfoundfile")
else
CalcMD5(hashfile)
else:
CalcMD5(hashfile)
#raw_input("pause")
else:
print("nofilename")
使用Python进行文件Hash计算有两点必须要注意:
1、文件打开方式一定要是二进制方式,既打开文件时使用b模式,否则Hash计算是基于文本的那将得到错误的文件Hash(网上看到有人说遇到Python的Hash计算错误在大多是由于这个原因造成的)。
2、对于MD5如果需要16位(bytes)的值那么调用对象的digest()而hexdigest()默认是32位(bytes),同理Sha1的digest()和hexdigest()分别产生20位(bytes)和40位(bytes)的hash值
PS:这里再为大家提供2款hash相关在线工具供大家参考使用:
在线散列/