python 通過文件路徑獲取文件hash值


 1 import hashlib
 2 import os,sys
 3 
 4 def CalcSha1(filepath):
 5     with open(filepath,'rb') as f:
 6         sha1obj = hashlib.sha1()
 7         sha1obj.update(f.read())
 8         hash = sha1obj.hexdigest()
 9         print(hash)
10         return hash
11 
12 def CalcMD5(filepath):
13     with open(filepath,'rb') as f:
14         md5obj = hashlib.md5()
15         md5obj.update(f.read())
16         hash = md5obj.hexdigest()
17         print(hash)
18         return hash
19 
20 if __name__ == "__main__":
21     if len(sys.argv)==2 :
22         hashfile = sys.argv[1]
23         if not os.path.exists(hashfile):
24             hashfile = os.path.join(os.path.dirname(__file__),hashfile)
25             if not os.path.exists(hashfile):
26                 print("cannot found file")
27             else
28             CalcMD5(hashfile)
29     else:
30         CalcMD5(hashfile)
31         #raw_input("pause")
32 else:
33     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值


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM