Python implements the method of getting the hash value of a file through the file path

  • 2020-05-30 20:31:04
  • OfStack

This article illustrates how the Python implementation gets the hash value from the file path. I will share it with you for your reference as follows:


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")

Using Python for file Hash calculation there are two important points to note:

1. File opening mode 1 must be in the base 2 mode, since b mode is used when opening the file, otherwise the calculation of Hash is based on text and you will get the wrong Hash file (some people on the Internet say that the calculation error of Hash of Python is mostly caused by this reason).

2, for MD5 If you need a 16-bit (bytes) value, call the object's digest() while hexdigest() The default is 32-bit (bytes), and so on Sha1 the digest() and hexdigest() Generate hash values of 20 bits (bytes) and 40 bits (bytes), respectively

PS: here are two more hash related online tools for your reference:

Online hash/hash algorithm encryption tool:
http://tools.ofstack.com/password/hash_encrypt

MD5/hash/ SHA-1 / SHA-2 / SHA-256 / SHA-512 / SHA-3 / RIPEMD-160 encryption tools:
http://tools.ofstack.com/password/hash_md5_sha

More about Python related topics: interested readers to view this site "Python coding skills summary", "Python data structure and algorithm tutorial", "Python Socket programming skills summary", "Python function using techniques", "Python string skills summary", "Python introduction and advanced tutorial" and "Python file and directory skills summary"

I hope this article is helpful for you to design Python program.


Related articles: