
本文介绍如何扩展基础字典攻击,通过生成目标单词所有大小写组合(如 "joejoe" → "joejoe", "joejoe" 等),显著提升 sha-1 哈希逆向成功率,尤其适用于含大小写字母但原始字典仅存小写形式的场景。
本文介绍如何扩展基础字典攻击,通过生成目标单词所有大小写组合(如 "joejoe" → "joejoe", "joejoe" 等),显著提升 sha-1 哈希逆向成功率,尤其适用于含大小写字母但原始字典仅存小写形式的场景。
在实际密码哈希破解中,单纯依赖原始字典(如全小写的 wordlist.txt)往往失败——因为真实密码可能包含大小写混合(如 "JoeJoe"、"j0ej0e"),而哈希值对大小写极度敏感(SHA-1("joejoe") ≠ SHA-1("JoeJoe"))。为解决该问题,需在字典攻击中动态生成每个单词的所有大小写变体,而非仅比对原词。
核心思路是:对字典中每个纯小写候选词(如 "joejoe"),穷举其每一位字符的大小写状态(小写或大写),共产生 $2^n$ 种组合($n$ 为字符长度)。例如 6 字符词将生成 64 个变体。以下为优化后的完整实现:
import hashlib
def permutecase(word):
"""生成单词所有大小写排列(仅字母参与变换,数字/符号保持不变)"""
word = word.lower() # 统一转小写作为基准
n = len(word)
results = []
# 遍历 0 到 2^n - 1 的所有整数,每位二进制位表示对应位置是否大写
for i in range(2 ** n):
variant = ""
for j, char in enumerate(word):
if char.isalpha(): # 仅对字母应用大小写变换
if (i >> j) & 1: # 检查第 j 位是否为 1
variant += char.upper()
else:
variant += char
else: # 数字、符号等保持原样
variant += char
results.append(variant)
return results
def dictionary_attack_with_case_permutation(target_hash, dictionary_file):
with open(dictionary_file, 'r', encoding='utf-8') as file:
for line in file:
base_word = line.strip()
if not base_word:
continue
# 生成该词所有大小写组合
for candidate in permutecase(base_word):
candidate_hash = hashlib.sha1(candidate.encode()).hexdigest()
if candidate_hash == target_hash:
print(f"✅ Found match: '{candidate}' → {target_hash}")
return candidate
# 可选:显示进度(避免长时间无响应)
print(f"⚠️ Tested '{base_word}' and all {2**len(base_word)} case variants — no match.")
print("❌ Exhausted dictionary + case permutations. No match found.")
return None
# 使用示例
if __name__ == "__main__":
target_hash = input("Enter the target SHA-1 hash: ").strip().lower()
dictionary_file = r'C:\Users\johnny\Documents\Security\src\wordlist.txt'
# 安全提示:确保字典文件合理(建议长度 ≤ 8 字符,否则 2^8=256 变体尚可接受;2^12=4096 已显著增重)
result = dictionary_attack_with_case_permutation(target_hash, dictionary_file)
关键注意事项:
- ⚠️ 性能权衡:大小写全排列使时间复杂度呈指数增长($O(N \times 2^L)$,$N$=字典行数,$L$=单词长度)。实践中应限制字典中单词长度(推荐 ≤ 8),或优先处理高频短词。
- ? 字符智能处理:
permutecase()函数已优化,仅对字母字符切换大小写,数字(如"j0ej0e"中的0)和符号保持不变,避免无效变形。 - ?️ 编码与健壮性:代码显式指定
encoding='utf-8'防止读取字典时乱码;添加空行跳过与.strip()防止空白干扰。 - ? 可扩展方向:如需进一步提升覆盖率,可结合常见替换(如
e→3,o→0)或首字母大写规则,但需谨慎评估计算开销。
此方法在红队演练、CTF 密码学挑战及安全意识培训中被广泛验证——它不改变哈希算法本身,而是通过更全面的明文空间探索,弥补传统字典攻击的覆盖盲区。











