根据字母频率破解替换加密

0

最近在做Jarvis OJ上的CTF题,有一道字母频率密码,题目描述如下:

nit yqmg mqrqn bxw mtjtm nq rqni fiklvbxu mqrqnl xwg dvmnzxu lqjnyxmt xatwnl, rzn nit uxnntm xmt zlzxuuk mtjtmmtg nq xl rqnl. nitmt vl wq bqwltwlzl qw yivbi exbivwtl pzxuvjk xl mqrqnl rzn nitmt vl atwtmxu xamttetwn xeqwa tsftmnl, xwg nit fzruvb, nixn mqrqnl ntwg nq gq lqet qm xuu qj nit jquuqyvwa: xbbtfn tutbnmqwvb fmqamxeevwa, fmqbtll gxnx qm fiklvbxu ftmbtfnvqwl tutbnmqwvbxuuk, qftmxnt xznqwqeqzluk nq lqet gtamtt, eqdt xmqzwg, qftmxnt fiklvbxu fxmnl qj vnltuj qm fiklvbxu fmqbtlltl, ltwlt xwg exwvfzuxnt nitvm twdvmqwetwn, xwg tsivrvn vwntuuvatwn rtixdvqm - tlftbvxuuk rtixdvqm yivbi evevbl izexwl qm qnitm xwvexul. juxa vl lzrlnvnzntfxllvldtmktxlkkqzaqnvn. buqltuk mtuxntg nq nit bqwbtfn qj x mqrqn vl nit jvtug qj lkwnitnvb rvquqak, yivbi lnzgvtl twnvnvtl yiqlt wxnzmt vl eqmt bqefxmxrut nq rtvwal nixw nq exbivwtl.

以下是python写的解密脚本:

#!/usr/bin/python
#encoding:utf-8
import sys
FILENAME = 'encrypt.txt'
 
def get_freq(encrypt_str):
    freq={}
    for letter in encrypt_str:
        freq[letter]=freq.get(letter,0)+1
    return freq
     
encrypt_str = open(FILENAME,'r').read()
print encrypt_str
freq = get_freq(encrypt_str)
letters = 'abdefgijklmnpqrstuvwxyz,:-. '#没有c h o这三个字母
for letter in letters:
    print '%s: %d' % (letter,freq[letter])
dict = {'a':'g','b':'c','d':'v','e':'m','f':'p','g':'d','i':'h','j':'f','k':'y',
'l':'s','m':'r','n':'t','p':'p','q':'o','r':'b','s':'x','t':'e','u':'l','v':'i',
'w':'n','x':'a','y':'w','z':'u',',':',',':':':','-':'-','.':'.',' ':' '}#没有c h o这三个字母
for i in range(len(encrypt_str)):
    sys.stdout.write(dict[encrypt_str[i]])

代码运行结果:

the word robot can refer to both physical robots and virtual software agents, but the latter are usually referred to as bots. there is no consensus on which machines pualify as robots but there is general agreement among experts, and the public, that robots tend to do some or all of the following: accept electronic programming, process data or physical perceptions electronically, operate autonomously to some degree, move around, operate physical parts of itself or physical processes, sense and manipulate their environment, and exhibit intelligent behavior - especially behavior which mimics humans or other animals. flag is substitutepassisveryeasyyougotit. closely related to the concept of a robot is the field of synthetic biology, which studies entities whose nature is more comparable to beings than to machines. 

题目分析: 既然是字母替换加密,那么先统计密文中各个字母出现的次数,代码中初始的dictionary可以为一一对应本身。 理论上出现频率最高的字母是e,统计密文中次数最多的字母是t,所以将字典更新:'t':'e'。 按此思路继续,常用的单词如:the,to这类可直接识别出来,最终所有字母对应结束,明文自然显示出来了。 编程时注意点: 密文中出现了:-两个符号,但没有出现c,h和o这三个字母,这个需要在dictionary中定义。

Leave A Reply

苏ICP备16066660号-1

苏公网安备 32011502010432号