ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Python实现替换密码原理与频率分析破解

Python实现替换密码原理与频率分析破解 1. 替换密码基础原理替换密码是最古老的加密技术之一其核心思想是将明文中的每个字母按照特定规则替换为另一个字母。这种加密方式可以追溯到古罗马时期的凯撒密码当时凯撒大帝在军事通信中就将字母表中的每个字母向后移动3位进行替换A→DB→E...Z→C。现代替换密码通常采用更复杂的替换规则单字母替换建立字母表的一一映射关系如A→XB→Z...多字母替换允许一个字母对应多个密文字母混合替换结合字母移位、倒序等复杂规则在Python中实现替换密码破解我们需要先理解其数学本质。假设明文字母集P {p₁, p₂,..., pₙ}密文字母集C {c₁, c₂,..., cₙ}加密函数EP→C解密函数DC→P对于简单的单字母替换加密过程可以表示为 cᵢ E(pᵢ) (pᵢ k) mod 26 其中k是替换偏移量2. 频率分析破解法2.1 英语字母频率特征英语文本中字母出现频率具有明显统计规律。根据牛津英语语料库统计标准英语字母频率从高到低大致为E(12.7%), T(9.1%), A(8.2%), O(7.5%), I(7.0%), N(6.7%), S(6.3%), H(6.1%), R(6.0%), D(4.3%), L(4.0%), C(2.8%), U(2.8%), M(2.4%), W(2.4%), F(2.2%), G(2.0%), Y(2.0%), P(1.9%), B(1.5%), V(1.0%), K(0.8%), J(0.2%), X(0.2%), Q(0.1%), Z(0.1%)2.2 Python实现步骤from collections import Counter def frequency_analysis(ciphertext): # 过滤非字母字符 filtered [c.upper() for c in ciphertext if c.isalpha()] total len(filtered) # 统计频率 freq Counter(filtered) sorted_freq sorted(freq.items(), keylambda x: x[1], reverseTrue) # 打印结果 for char, count in sorted_freq: print(f{char}: {count/total:.2%}) # 示例用法 ciphertext BQQMF FTQDQ # 替换密码加密的文本 frequency_analysis(ciphertext)2.3 频率匹配算法获取密文中各字母出现频率与标准英语频率表进行对比建立初步的字母映射假设通过上下文验证和调整映射关系3. 暴力破解与优化3.1 全排列尝试法对于短密文可以尝试所有可能的字母排列组合import itertools def brute_force(ciphertext, max_tries1000): alphabet ABCDEFGHIJKLMNOPQRSTUVWXYZ attempts 0 for perm in itertools.permutations(alphabet): mapping dict(zip(alphabet, perm)) decrypted .join([mapping.get(c, c) for c in ciphertext.upper()]) if looks_like_english(decrypted): print(fPossible solution: {decrypted}) return mapping attempts 1 if attempts max_tries: break return None3.2 字典辅助破解结合常用英语单词库提高破解效率english_words set([THE, AND, FOR, ARE, YOU]) def is_meaningful(text, threshold0.5): words text.split() if not words: return False meaningful sum(1 for word in words if word.upper() in english_words) return meaningful / len(words) threshold4. 完整破解流程实现4.1 破解脚本架构class SubstitutionCracker: def __init__(self): self.english_freq { E: 0.127, T: 0.091, A: 0.082, O: 0.075, # ...其他字母频率 } def decrypt(self, ciphertext, methodfrequency): if method frequency: return self._frequency_attack(ciphertext) elif method bruteforce: return self._bruteforce_attack(ciphertext) else: raise ValueError(Unsupported method) def _frequency_attack(self, ciphertext): # 实现频率分析破解 pass def _bruteforce_attack(self, ciphertext): # 实现暴力破解 pass4.2 实战示例假设我们收到密文QWE RTY UIO PAS DFG HJK LZX CVB NMcracker SubstitutionCracker() plaintext cracker.decrypt(QWE RTY UIO PAS DFG HJK LZX CVB NM) print(fDecrypted: {plaintext})5. 进阶技巧与优化5.1 双字母组合分析英语中常见的双字母组合(th, he, in, er等)可以提供额外线索def digram_analysis(ciphertext): digrams [ciphertext[i:i2] for i in range(len(ciphertext)-1)] freq Counter(digrams) return freq.most_common(5) # 返回前5常见的双字母组合5.2 可视化辅助工具使用matplotlib绘制频率对比图import matplotlib.pyplot as plt def plot_frequencies(cipher_freq): english sorted(self.english_freq.items(), keylambda x: x[1], reverseTrue) cipher sorted(cipher_freq.items(), keylambda x: x[1], reverseTrue) fig, (ax1, ax2) plt.subplots(2, 1) ax1.bar([x[0] for x in english], [x[1] for x in english]) ax2.bar([x[0] for x in cipher], [x[1] for x in cipher]) plt.show()6. 实际应用中的挑战6.1 短文本问题当密文长度不足50个字符时频率分析方法可能失效。此时可以结合暴力破解尝试常见单词组合利用标点符号和空格位置信息分析密文的重复模式6.2 非标准英语文本处理包含专有名词、缩写或非英语文本时def adapt_frequency_table(sample_text): 根据样本文本调整频率表 counter Counter(c.upper() for c in sample_text if c.isalpha()) total sum(counter.values()) return {k: v/total for k, v in counter.items()}7. 密码安全性增强虽然我们讨论的是破解方法但从防御角度可以采取以下措施增强替换密码安全性使用多表替换如Vigenère密码定期更换替换规则结合其他加密方式故意插入干扰字符8. 完整代码示例以下是一个整合了上述所有技术的完整破解脚本import re from collections import Counter import itertools import matplotlib.pyplot as plt class AdvancedSubstitutionCracker: def __init__(self, corpusNone): self.english_freq { E: 0.127, T: 0.091, A: 0.082, O: 0.075, I: 0.070, N: 0.067, S: 0.063, H: 0.061, R: 0.060, D: 0.043, L: 0.040, C: 0.028, U: 0.028, M: 0.024, W: 0.024, F: 0.022, G: 0.020, Y: 0.020, P: 0.019, B: 0.015, V: 0.010, K: 0.008, J: 0.002, X: 0.002, Q: 0.001, Z: 0.001 } self.common_words { THE, AND, FOR, ARE, YOU, THAT, WITH, HAVE, THIS, FROM, THEY, WOULD, THERE } if corpus: self.adapt_frequency(corpus) def adapt_frequency(self, text): counter Counter(c.upper() for c in text if c.isalpha()) total max(1, sum(counter.values())) self.english_freq {k: v/total for k, v in counter.items()} def decrypt(self, ciphertext, methodhybrid): ciphertext ciphertext.upper() if method frequency: return self._frequency_attack(ciphertext) elif method bruteforce: return self._bruteforce_attack(ciphertext) elif method hybrid: return self._hybrid_attack(ciphertext) else: raise ValueError(Invalid method) def _frequency_attack(self, ciphertext): # 实现频率分析略 pass def _bruteforce_attack(self, ciphertext): # 实现暴力破解略 pass def _hybrid_attack(self, ciphertext): # 结合多种技术的混合破解略 pass def plot_frequency_comparison(self, ciphertext): # 绘制频率对比图略 pass # 使用示例 if __name__ __main__: cracker AdvancedSubstitutionCracker() cipher QWE RTY UIO PAS DFG HJK LZX CVB NM result cracker.decrypt(cipher) print(fDecryption result: {result})
返回列表