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.MD5
If a 16-bit (bytes) value is requireddigest()
Whilehexdigest()
The default value is 32 bits (bytes ).Sha1
Ofdigest()
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