zoukankan      html  css  js  c++  java
  • Python 文件Hash(MD5,SHA1)

     

    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),同理Sha1的digest()和hexdigest()分别产生20位(bytes)和40位(bytes)的hash值

  • 相关阅读:
    防止特殊html字符的问题(xxs攻击)方法
    asp.net 服务器Button控件使用(onclick和onclientclick使用)
    Asp:Button控件onclick事件无刷新页面提示消息
    动态添加Marquee标签,并动态赋值与属性
    asp.net 前台通过Eval()绑定动态显示样式
    asp.net 中json字符串转换
    近况
    C# fixed语句固定变量详解
    fixed说明
    Net架构必备工具列表
  • 原文地址:https://www.cnblogs.com/luolizhi/p/5596769.html
Copyright © 2011-2022 走看看