[英]python 3.9 - unable to get correct sha1 hash for multiple files in loop
通過引用以下鏈接中的解決方案中給出的代碼,在循環中沒有為第二個以后的文件獲取正確的 SHA1 哈希。 為什么說不正確,因為
使用下面給出的代碼: -
正確 -> 嘗試單獨為同一文件生成 SHA1 哈希(通過執行代碼兩次)然后獲得不同的 SHA1 哈希(正確)和
INCORRECT -> 在單次執行中為多個文件生成哈希時,包括此文件,然后為此文件獲取不同的哈希(不正確)->
請建議是否在此代碼中進行任何修改或需要選擇任何其他方法?
通過引用底部給出的鏈接編寫的代碼->
import glob
import hashlib
import os
path = input("Please provide path to search for file pattern (search will be in this path sub-directories also: ")
filepattern = input("Please provide the file pattern to search in given path. Example *.jar, *abc*.jar.: ")
assert os.path.exists(path), "I did not find the path " + str(path)
path = path.rstrip("/")
tocheck = (f'{path}/**/{filepattern}')
hash_obj = hashlib.sha1()
searched_file_list = glob.iglob(tocheck, recursive=True)
for file in searched_file_list:
print(f'{file}')
try:
checksum = ""
file_for_sha1 = ""
file_for_sha1 = open(file, 'rb')
hash_obj.update(file_for_sha1.read())
checksum = hash_obj.hexdigest()
print(f'sha1 for file ({file})= {checksum}')
finally:
file_for_sha1.close()
示例文件-> abc.txt,在 /home/test/git/reader/cabin/ 創建以下文本: - 您好,這是為了測試 SHA1 代碼。
然后將此文件復制到另一個位置,即/home/test/git/reader/check/cabin/
Linux 控制台輸出顯示兩個文件的 SHA1 相同:-
:~/git/reader/check/cabin$ sha1sum abc.txt
fc4db67f46711b2c18bd133abd67965649edfffc abc.txt
:~/git/reader/check/cabin$ cd ../..
:~/git/reader$ cd cabin/
:~/git/reader/cabin$ sha1sum abc.txt
fc4db67f46711b2c18bd133abd67965649edfffc abc.txt
單次執行中的循環代碼- 從兩個位置為此 abc.txt 文件生成兩個不同的 SHA1:-
通過給出各自的位置(一次一個文件)然后生成相同且正確的 SHA1 哈希,對同一文件執行兩次代碼:
sha1 文件 (/home/test/git/reader/check/cabin/abc.txt)= fc4db67f46711b2c18bd133abd67965649edfffc
sha1 文件 (/home/test/git/reader/cabin/abc.txt)= fc4db67f46711b2c18bd133abd67965649edfffc
參考代碼鏈接 -> 在 Python 中生成多個文件的一個 MD5/SHA1 校驗和
引用update
方法的文檔
重復調用等效於連接所有參數的單個調用:
m.update(a); m.update(b)
m.update(a); m.update(b)
等價於m.update(a+b)
。
因此,不是單獨查找兩個文件的哈希,而是查找連接的兩個文件的哈希。 這就是您鏈接的問題正在做的事情 - 多個文件的單個哈希。 您需要每個文件的哈希值,因此不要在同一個hash_obj
實例上多次使用update
方法,而是為每個文件創建一個新實例,所以
hash_obj = hashlib.sha1()
searched_file_list = glob.iglob(tocheck, recursive=True)
for file in searched_file_list:
print(f'{file}')
try:
...
hash_obj.update(file_for_sha1.read())
會變成
searched_file_list = glob.iglob(tocheck, recursive=True)
for file in searched_file_list:
print(f'{file}')
try:
hash_obj = hashlib.sha1()
...
hash_obj.update(file_for_sha1.read())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.