破译换位加密法

思路

要破译换位加密法,采用暴力破解方案,众多密钥中,正确的密钥很可能产生可读英文,通过英文检测来判断正确密钥。

代码实例

# 换位思考加密代码文件名称为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.

发布了23 篇原创文章 · 获赞 2 · 访问量 1023

猜你喜欢

转载自blog.csdn.net/youngdianfeng/article/details/104364560