破译换位加密法

思路

要破译换位加密法,采用暴力破解方案,众多密钥中,正确的密钥很可能产生可读英文,通过英文检测来判断正确密钥。
字典文件可以在博主资源里免费下载。

代码实例

# 换位思考加密代码文件名称为transpositionEncrypt.py
import transpositionEncrypt

UPPERLETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
LETTERS_AND_SPACE = UPPERLETTERS + UPPERLETTERS.lower() + ' \t\n'

# 加载单词字典到内存
def loadDictionary():
    dictionryFile = open('dictionary.txt')
    englishWords = {}
    for word in dictionryFile.read().split('\n'):
        englishWords[word] = None
    dictionryFile.close()
    return englishWords

ENGLISH_WORDS = loadDictionary()

# 将非字母字符串剔除
def removeNonLetters(message):
    lettersOnly = []
    for symbol in message:
        if symbol in LETTERS_AND_SPACE:
            lettersOnly.append(symbol)
    return ''.join(lettersOnly)

# 将剔除非字母字符串通过 ' ' 将字符串切片 返回是单词占总片段的百分比
def getEnglishCount(message):
    message = message.upper()
    message = removeNonLetters(message)
    possibleWords = message.split()
    if possibleWords==[]:
        return 0.0
    matches = 0
    for word in possibleWords:
        if word in ENGLISH_WORDS:
            matches += 1
    return float(matches)/len(possibleWords)

# 如果单词比例大于20% 且 剔除非字母字符串占总字符串的 85% 则 认为是可能已破译
def isEnglish(message,wordPercentage = 20,letterPercentage = 85):
    wordsMatch = getEnglishCount(message) * 100 >= wordPercentage
    numLetters = len(removeNonLetters(message))
    messageLettersPercentage = float(numLetters) / len(message) * 100
    letterMatch = messageLettersPercentage >= letterPercentage
    return wordsMatch and letterMatch

# 穷举破译
def hackTransposition(message):
    print('Hacking...')
    print('(Press Ctrl-C or Ctrl-D to quit at any time.)')
    # 密钥用穷举来实现,最大值便是整个密文的长度
    for key in range(1, len(message)):
        print('Trying key #%s...' % (key))
        #通过换位解密的算法来返回明文,并且判断返回的明文是否是英语单词
        decryptedText = transpositionEncrypt.decryptMessage(key, message)
        if isEnglish(decryptedText):
            print()
            print('Possible encryption hack:')
            print('Key %s: %s' % (key, decryptedText[:100]))
            print()
            print('Enter D for done, or just press Enter to continue hacking:')
            response = input('> ')
            # 如果是 输入D 则打印破解后的明文
            if response.strip().upper().startswith('D'):
                return decryptedText
    return None

def main():
    myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu  plri ch nitaalr eiuengiteehb(e1  hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad   l t oisn sit u1rnd stara nvhn fsedbh ee,n  e necrg6  8nmisv l nc muiftegiitm tutmg cm shSs9fcie ebintcaets h  aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po  droB wtinue r Pieno nc ayieeto'lulcih sfnc  ownaSserbereiaSm-eaiah, nnrttgcC  maciiritvledastinideI  nn rms iehn tsigaBmuoetcetias rn"""

    hackedMessage = hackTransposition(myMessage)
    if hackedMessage == None:
        print('Failed to hack encryption.')
    else:
        print(hackedMessage)

if __name__ == '__main__':
    main()
    

结果

Hacking…
(Press Ctrl-C or Ctrl-D to quit at any time.)
Trying key #1…
Trying key #2…
Trying key #3…
Trying key #4…
Trying key #5…
Trying key #6…
Trying key #7…
Trying key #8…
Trying key #9…
Trying key #10…

Possible encryption hack:
Key 10: Charles Babbage, FRS (26 December 1791 - 18 October 1871) was an English mathematician, philosopher,

Enter D for done, or just press Enter to continue hacking:
·>D
Charles Babbage, FRS (26 December 1791 - 18 October 1871) was an English mathematician, philosopher, inventor and mechanical engineer who originated the concept of a programmable computer. Considered a “father of the computer”, Babbage is credited with inventing the first mechanical computer that eventually led to more complex designs. Parts of his uncompleted mechanisms are on display in the London Science Museum. In 1991, a perfectly functioning difference engine was constructed from Babbage’s original plans. Built to tolerances achievable in the 19th century, the success of the finished engine indicated that Babbage’s machine would have worked. Nine years later, the Science Museum completed the printer Babbage had designed for the difference engine.

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值