Python哈希校验脚本字符串比较失效,值一致却匹配失败如何解决
问题根因
- 核心错误:读取哈希集后的去空白操作无效。你遍历
lines执行line.strip()时仅修改了循环内的临时变量,没有更新原列表,导致lines中存储的每个哈希值末尾都带有换行符\n,和计算得到的无换行哈希字符串无法匹配。 - 潜在问题:未处理哈希值大小写不一致的场景,部分哈希集可能存储大写哈希,而Python的
hexdigest()默认返回小写字符串,也会导致匹配失败。 - 其他隐藏风险:直接用
+ "/"拼接路径不兼容Windows系统,遍历到子目录时打开路径会报错,大文件一次性读取会占用过多内存。
修复方案
首先替换原有读取哈希集的无效代码:
# 原有代码 f1 = open(hashset_path,'r',encoding='UTF-8') lines = f1.readlines() for line in lines: line = line.strip() f1.close()
替换为如下实现,读取时直接处理所有哈希值:
# 读取哈希集时直接去空白、过滤空行、统一转小写 with open(hashset_path, 'r', encoding='UTF-8') as f1: lines = [line.strip().lower() for line in f1 if line.strip()]
其次可优化哈希校验逻辑,避免重复计算、提升兼容性:
# compare file file_lst = os.listdir(dir_path) count = 0 matchedfile = [] for file in file_lst: # 用系统原生方法拼接路径,兼容全平台 filepath = os.path.join(dir_path, file) # 跳过子目录,仅处理文件 if not os.path.isfile(filepath): continue # 大文件分块读取,避免内存溢出 hash_obj = temp() with open(filepath, 'rb') as f: while chunk := f.read(4096): hash_obj.update(chunk) file_hash = hash_obj.hexdigest().lower() # 匹配哈希,命中后直接跳出避免重复判断 for line_hash in lines: if file_hash == line_hash: matchedfile.append(f"filename : {file} calculated hash : {file_hash} hash of hashset.txt : {line_hash}") count += 1 break
完整修复后代码
import hashlib import os dir_path = input("Input directory : ") hashset_path = input("Input hashset directory (ex: C:/../user/hashset.txt) : ") hash_type = int(input("1:MD5 2.SHA-1 3.SHA-256\n choose hash : ")) if hash_type == 1: hash_type = "md5" elif hash_type == 2: hash_type = "sha1" elif hash_type == 3: hash_type = "sha256" else: print("somethig is wrong") exit() temp = getattr(hashlib, hash_type) # 读取哈希集 with open(hashset_path, 'r', encoding='UTF-8') as f1: lines = [line.strip().lower() for line in f1 if line.strip()] # 校验文件 file_lst = os.listdir(dir_path) count = 0 matchedfile = [] for file in file_lst: filepath = os.path.join(dir_path, file) if not os.path.isfile(filepath): continue hash_obj = temp() with open(filepath, 'rb') as f: while chunk := f.read(4096): hash_obj.update(chunk) file_hash = hash_obj.hexdigest().lower() for line_hash in lines: if file_hash == line_hash: matchedfile.append(f"filename : {file} calculated hash : {file_hash} hash of hashset.txt : {line_hash}") count += 1 break if count == 0: print("no matched hash") else: for item in matchedfile: print(item)
内容的提问来源于stack exchange,提问作者foreaser
相关产品推荐
相关产品推荐

