破譯換位加密法

思路

要破譯換位加密法,採用暴力破解方案,衆多密鑰中,正確的密鑰很可能產生可讀英文,通過英文檢測來判斷正確密鑰。
字典文件可以在博主資源裏免費下載。

代碼實例

# 換位思考加密代碼文件名稱爲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.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章