源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python实现通过文件路径获取文件hash值的方法

  • 时间:2020-05-01 15:51 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python实现通过文件路径获取文件hash值的方法
本文实例讲述了Python实现通过文件路径获取文件hash值的方法。分享给大家供大家参考,具体如下:
import hashlib
import os,sys
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")

[b]使用Python进行文件Hash计算有两点必须要注意:[/b] 1、文件打开方式一定要是二进制方式,既打开文件时使用b模式,否则Hash计算是基于文本的那将得到错误的文件Hash(网上看到有人说遇到Python的Hash计算错误在大多是由于这个原因造成的)。 2、对于[code]MD5[/code]如果需要16位(bytes)的值那么调用对象的[code]digest()[/code]而[code]hexdigest()[/code]默认是32位(bytes),同理[code]Sha1[/code]的[code]digest()[/code]和[code]hexdigest()[/code]分别产生20位(bytes)和40位(bytes)的hash值 [b]PS:这里再为大家提供2款hash相关在线工具供大家参考使用:[/b] [b]在线散列/哈希算法加密工具: [/b][url=http://tools.jb51.net/password/hash_encrypt]http://tools.jb51.net/password/hash_encrypt[/url] [b]在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具: [/b][url=http://tools.jb51.net/password/hash_md5_sha]http://tools.jb51.net/password/hash_md5_sha[/url] 更多关于Python相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/788.htm]Python编码操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/663.htm]Python数据结构与算法教程[/url]》、《[url=http://www.1sucai.cn/Special/648.htm]Python Socket编程技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/642.htm]Python函数使用技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/636.htm]Python字符串操作技巧汇总[/url]》、《[url=http://www.1sucai.cn/Special/520.htm]Python入门与进阶经典教程[/url]》及《[url=http://www.1sucai.cn/Special/516.htm]Python文件与目录操作技巧汇总[/url]》 希望本文所述对大家Python程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部