1 ImportHashlib2 ImportOs,sys3 4 defCALCSHA1 (filepath):5With open (filepath,'RB') as F:6Sha1obj =hashlib.sha1 ()7 sha1obj.update (F.read ())8hash =sha1obj.hexdigest ()9 Print(hash)Ten returnHash One A defCalcMD5 (filepath): -With open (filepath,'RB') as F: -Md5obj =hashlib.md5 () the md5obj.update (F.read ()) -hash =md5obj.hexdigest () - Print(hash) - returnHash + - if __name__=="__main__": + ifLen (SYS.ARGV) ==2 : AHashfile = sys.argv[1] at if notos.path.exists (hashfile): -Hashfile = Os.path.join (Os.path.dirname (__file__), Hashfile) - if notos.path.exists (hashfile): - Print("cannot found file") - Else - CalcMD5 (hashfile) in Else: - CalcMD5 (hashfile) to #raw_input ("pause") + Else: - Print("no filename")
Using Python for file hash calculations there are two points to note:
1, file Open the way must be binary mode, both open the file when using B mode, or hash calculation is based on the text that will get the wrong file hash (online to see someone said to have encountered a Python hash calculation error in most is due to this cause).
2, for MD5 if you need 16-bit (bytes) value then call the object's Digest () and hexdigest () default is 32 bits (bytes), the same SHA1 digest () and hexdigest () respectively produce 20 bits (bytes) and 40 bits ( bytes) hash value
Python gets file hash value via file path