加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 08:25:54 所属栏目:Python 来源:网络整理
导读:本篇章节讲解Python实现通过文件路径获取文件hash值的方法。供大家参考研究具体如下: import hashlibimport os,sysdef CalcSha1(filepath): with open(filepath,'rb') as f: sha1obj = hashlib.sha1() sha1obj.update(f.read()) hash = sha1obj.h

本篇章节讲解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")

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

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

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

PS:这里再为大家提供2款hash相关在线工具供大家参考使用:

在线散列/哈希算法加密工具:
http://tools.aspzz.cn/password/hash_encrypt

在线MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160加密工具:
http://tools.aspzz.cn/password/hash_md5_sha

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读