Python uses the file path to obtain the file hash value,

Source: Internet
Author: User

Python uses the file path to obtain the file hash value,

This example describes how to obtain the file hash value through the file path in Python. We will share this with you for your reference. The details are as follows:

import hashlibimport os,sysdef CalcSha1(filepath):  with open(filepath,'rb') as f:    sha1obj = hashlib.sha1()    sha1obj.update(f.read())    hash = sha1obj.hexdigest()    print(hash)    return hashdef CalcMD5(filepath):  with open(filepath,'rb') as f:    md5obj = hashlib.md5()    md5obj.update(f.read())    hash = md5obj.hexdigest()    print(hash)    return hashif __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")

Note the following before using Python for file Hash calculation:

1. The file must be opened in binary mode, that is, B mode is used when the file is opened, otherwise, the Hash calculation is text-based, and the file Hash will be incorrect (it is said on the Internet that most of the Hash calculation errors in Python are caused by this reason ).

2.MD5If a 16-bit (bytes) value is requireddigest()Whilehexdigest()The default value is 32 bits (bytes ).Sha1Ofdigest()Andhexdigest()Generate the 20-bit (bytes) and 40-bit (bytes) hash values respectively.

PS: Here are two hash-related online tools for your reference:

Online hash/hash algorithm encryption tool:
Http://tools.jb51.net/password/hash_encrypt

Online MD5/hash/SHA-1/SHA-2/SHA-256/SHA-512/SHA-3/RIPEMD-160 encryption tools:
Http://tools.jb51.net/password/hash_md5_sha

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.