You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 01:30:01