Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1742828
  • 博文数量: 297
  • 博客积分: 285
  • 博客等级: 二等列兵
  • 技术积分: 3006
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-06 22:04
个人简介

Linuxer, ex IBMer. GNU https://hmchzb19.github.io/

文章分类

全部博文(297)

文章存档

2020年(11)

2019年(15)

2018年(43)

2017年(79)

2016年(79)

2015年(58)

2014年(1)

2013年(8)

2012年(3)

分类: Python/Ruby

2017-05-10 11:50:17

最近再看这本书,感觉这书的作者知识面很广.写的书都是以实际的例子教人写代码.
可以从中学到不少知识. 例如求最大公约数欧几里得定律以及扩展的欧几里得定律.
参看这个页面:

点击(此处)折叠或打开

  1. http://invpy.com/euclid/
有这两个函数.

点击(此处)折叠或打开

  1. def gcd(a, b):
  2.     #return the GCD of a and b using Euclid's Algorithm

  3.     while a != 0:
  4.         a, b = b % a, a
  5.     return b



  6. def findModInverse(a, m):
  7.     #return the modular inverse of a % m , which is the
  8.     #number x such that a * x % m = 1

  9.     if gcd (a, m ) != 1:
  10.         return None
  11.         #no mod inverse if a & m are not relatively prime

  12.     #calculating using the Extended Euclidean Algorithm

  13.     u1, u2, u3 = 1, 0, a
  14.     v1, v2, v3 = 0, 1, m

  15.     while v3 != 0:
  16.         q = u3 // v3 #// is the integer division operator
  17.         v1, v2, v3 , u1, u2, u3 = (u1 - q * v1),(u2 - q * v2), (u3 - q * v3),v1,v2,v3

  18.     return u1 % m

2.我倒是发现有个很奇怪的地方.在SimpleSubCipher如果使用不同的LETTERS会影响最后的Hack代码例如:
这个代码中的LETTERS只有26个大写字母.


点击(此处)折叠或打开

  1. import pyperclip
  2. import sys
  3. import random

  4. LETTERS = "ABCDEFGHIJKLMNOQPRSTUVWXYZ"

  5. #LETTERS = r""" !'#$%&"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" # note the space at the front

  6. def main():
  7.     
  8.     myMessage = "If a man is offered a fact which goes against his instincts, he will scrutinize it closely, and unless the evidence is overwhelming, he will refuse to believe it. If, on the other hand, he is offered something which affords a reason for acting in accordance to his instincts, he will accept it even on the slightest evidence. The origin of myths is explained in this way. -Bertrand Russell"

  9.     #myKey = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
  10.     myKey = getRandomKey()

  11.     myMode = "encrypt"
  12.     checkValidKey(myKey)

  13.     if myMode == "encrypt":
  14.         translated = encryptMessage(myKey, myMessage)
  15.     elif myMode == "decrypt":
  16.         translated = decryptMessage(myKey, myMessage)

  17.     print("Using key {}\n".format(myKey))
  18.     print("The {0}ed message is ".format(myMode))

  19.     print(translated)
  20.     pyperclip.copy(translated)
  21.     print()
  22.     print("This messsage has been copied to the clipboard.")

  23. def checkValidKey(key):
  24.     keyList = list(key)
  25.     lettersList = list(LETTERS)
  26.     keyList.sort()
  27.     lettersList.sort()
  28.     if keyList != lettersList:
  29.         sys.exit("There is an error in the key or symbol set.")

  30. def encryptMessage(key, message):
  31.     return translateMessage(key, message, "encrypt")

  32. def decryptMessage(key, message):
  33.     return translateMessage(key, message, "decrypt")


  34. def translateMessage(key, message, mode):
  35.     translated = ""
  36.     charsA = LETTERS
  37.     charsB = key
  38.     if mode == "decrypt":
  39.         #For decrypting, we can use the same code as encrypting,
  40.         #we just need to swap the key and LETTERS strings are used
  41.         charsA, charsB = charsB, charsA
  42.     #loop through each symbol in the message
  43.     for symbol in message:
  44.         if symbol.upper() in charsA:
  45.             #encrypt/decrypt the symbol
  46.             symIndex = charsA.find(symbol.upper())
  47.             if symbol.isupper():
  48.                 translated += charsB[symIndex].upper()
  49.             else:
  50.                 translated += charsB[symIndex].lower()
  51.         else:
  52.             #symbol is not in LETTERS, just add it
  53.             translated += symbol
  54.             
  55.         """
  56.         if symbol in charsA:
  57.             symIndex = charsA.find(symbol)
  58.             translated += charsB[symIndex]
  59.         """
  60.     return translated

  61. def getRandomKey():
  62.     key = list(LETTERS)
  63.     random.shuffle(key)
  64.     return "".join(key)

  65. if __name__== "__main__"
  66.     main()
这是破解SimpleSub cipher的代码:

点击(此处)折叠或打开

  1. import os
  2. import re
  3. import copy
  4. import pprint
  5. import pyperclip
  6. import simpleSubCipher
  7. import makeWordPatterns

  8. if not os.path.exists("wordPatterns.py"):
  9.     #create the wordPatterns.py file
  10.     makeWordPatterns.main()

  11. import wordPatterns
  12. LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  13. nonLettersOrSpacePattern = re.compile("[^A-Z\s]")

  14. def main():
  15.     message = "Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm"
  16.     print("Hacking...")
  17.     letterMapping = hackSimpleSub(message)

  18.     #Display the results to the user
  19.     print("Mapping:")
  20.     pprint.pprint(letterMapping)
  21.     print()
  22.     print("Original ciphertext:")
  23.     print(message)
  24.     print()
  25.     print("Copying hacked message to clipboard:")
  26.     hackedMessage = decryptWithCipherletterMapping(message, letterMapping)
  27.     pyperclip.copy(hackedMessage)

  28.     print("hackedMessage :{}".format(hackedMessage))


  29. def getBlankCipherletterMapping():
  30.     #Returns a dictionary value that is a blank cipher mapping
  31.     """
  32.     LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  33.     dict1 = {}
  34.     for letter in LETTERS:
  35.         dict1[letter]=[]
  36.     return dict1
  37.     """
  38.     return {"A": [], "B": [], "C": [], "D": [], "E": [], "F": [], "G": [], "H": [], "I":
  39.     [], "J": [], "K": [], "L": [], "M": [], "N": [], "O": [], "P": [], "Q": [], "R": [], "S": [],
  40.     "T": [], "U": [], "V": [], "W": [], "X": [], "Y": [], "Z": []}
  41.     
  42. def addLettersToMapping(letterMapping, cipherword, candidate):
  43.     """
  44.     The letterMapping: is a "cipherletter mapping" dictionary
  45.     value that the return value of this function starts as a copy
  46.     of.
  47.     the cipherword: is a string value of the ciphertext
  48.     word.
  49.     The candidate: is a possible English word that the cipherword
  50.     could decrypt to.
  51.     This function adds the letters of the candidate as potential
  52.     decryption letters for the cipherletters in the cipherletter
  53.     mapping.
  54.     """

  55.     letterMapping = copy.deepcopy(letterMapping)
  56.     for i in range(len(cipherword)):
  57.         if candidate[i] not in letterMapping[cipherword[i]]:
  58.             letterMapping[cipherword[i]].append(candidate[i])
  59.     return letterMapping

  60. def intersectMapping(mapA, mapB):
  61.     #To intersect two maps, create a blank map, then add only the
  62.     #potential decryption letters if they exist in BOTH maps
  63.     
  64.     intersectedMapping = getBlankCipherletterMapping()
  65.     for letter in LETTERS:
  66.         #An empty list means "any letter is possible", in this case just
  67.         #copy the other map entirely
  68.         if mapA[letter] == []:
  69.             intersectedMapping[letter] = copy.deepcopy(mapB[letter])
  70.         elif mapB[letter] == []:
  71.             intersectedMapping[letter] = copy.deepcopy(mapA[letter])
  72.         else:
  73.             #if a letter in mapA[letter] exists in mapB[letter], and
  74.             #that letter to insertsectedMapping[letter]
  75.             for mappedLetter in mapA[letter]:
  76.                 if mappedLetter in mapB[letter]:
  77.                     intersectedMapping[letter].append(mappedLetter)

  78.     return intersectedMapping

  79. def removeSolvedLettersFromMapping(letterMapping):
  80.     #Cipher letters in the mapping that map to only one letter are
  81.     #"solved" and can be removed from the other letters
  82.     #For example if "A" mamps to potential letters["M","N"] and
  83.     #"B" maps to ["N"] , then we know that "B" must map to "N",
  84.     #so we can remove "N" from the list of what "A" could map to,
  85.     #so "A" then map to ["M"], Note that now that "A" maps to only
  86.     #one letter, we can remove "M" from the list of letters for every
  87.     #other letter.
  88.     #That is why there is a loop that keeps reducing the map.

  89.     letterMapping = copy.deepcopy(letterMapping)

  90.     loopAgain = True
  91.     while loopAgain:
  92.         #First assume that we will not loop again
  93.         loopAgain = False

  94.         #solvedLetters will be a list of uppercase letters have one
  95.         #and only one possible mapping in letterMapping
  96.         solvedLetters = []
  97.         for cipherletter in LETTERS:
  98.             if len(letterMapping[cipherletter])== 1:
  99.                 solvedLetters.append(letterMapping[cipherletter][0])

  100.         #if a letter is solved, that it can not possibly a potential
  101.         #decryption letter for a different ciphertext letter,
  102.         #so we should remove it from those other lists
  103.         for cipherletter in LETTERS:
  104.             for s in solvedLetters:
  105.                 if len(letterMapping[cipherletter]) != 1 and s in letterMapping[cipherletter]:
  106.                     letterMapping[cipherletter].remove(s)
  107.                     if len(letterMapping[cipherletter]) == 1:
  108.                         #A new letter is now solved, so loop again
  109.                         loopAgain = True

  110.     return letterMapping

  111. def hackSimpleSub(message):
  112.     intersectedMap = getBlankCipherletterMapping()
  113.     cipherwordList = nonLettersOrSpacePattern.sub("", message.upper()).split()
  114.     for cipherword in cipherwordList:
  115.         #get a new cipherletter mapping for each ciphertext word
  116.         newMap = getBlankCipherletterMapping()

  117.         wordPattern = makeWordPatterns.getWordPattern(cipherword)
  118.         if wordPattern not in wordPatterns.allPatterns:
  119.             #This word was not in our dictionary, so continue
  120.             continue

  121.         #and the letters of each candidate to the mapping
  122.         for candidate in wordPatterns.allPatterns[wordPattern]:
  123.             newMap = addLettersToMapping(newMap, cipherword, candidate)

  124.         #intersect the new mapping with the existing intersected mapping
  125.         intersectedMap = intersectMapping(intersectedMap, newMap)

  126.     #remove any solved letters from the other lists
  127.     return removeSolvedLettersFromMapping(intersectedMap)

  128. def decryptWithCipherletterMapping(ciphertext, letterMapping):
  129.     #return a string of the ciphertext decrypted with the letter mapping
  130.     #with any ambiguous decrypted letters replaced with an _ underscore.

  131.     #First create a simple sub key from the letterMapping mapping
  132.     key = ["x"] * len(LETTERS)
  133.     for cipherletter in LETTERS:
  134.         if len(letterMapping[cipherletter])==1:
  135.             #if there is only one letter, add it to the key
  136.             keyIndex = LETTERS.find(letterMapping[cipherletter][0])
  137.             key[keyIndex]= cipherletter
  138.         else:
  139.             ciphertext = ciphertext.replace(cipherletter.lower(), "_")
  140.             ciphertext = ciphertext.replace(cipherletter.upper(), "_")
  141.     key = "".join(key)

  142.     #with the key we have created, decrypt the cipher text

  143.     return simpleSubCipher.decryptMessage(key, ciphertext)

  144. if __name__== "__main__":
  145.     main()

注意这里面的代码用的常量LETTERS是26个大写字母,因而是可以工作的.

点击(此处)折叠或打开

  1. ./simpleSubHacker.py
  2. Hacking...
  3. Mapping:
  4. {'A': ['E'],
  5.  'B': ['Y', 'P', 'B'],
  6.  'C': ['R'],
  7.  'D': [],
  8.  'E': ['W'],
  9.  'F': ['B', 'P'],
  10.  'G': ['B', 'Q', 'X', 'P', 'Y'],
  11.  'H': ['P', 'Y', 'K', 'X', 'B'],
  12.  'I': ['H'],
  13.  'J': ['T'],
  14.  'K': [],
  15.  'L': ['A'],
  16.  'M': ['L'],
  17.  'N': ['M'],
  18.  'O': ['D'],
  19.  'P': ['O'],
  20.  'Q': ['V'],
  21.  'R': ['S'],
  22.  'S': ['I'],
  23.  'T': ['U'],
  24.  'U': ['G'],
  25.  'V': [],
  26.  'W': ['C'],
  27.  'X': ['N'],
  28.  'Y': ['F'],
  29.  'Z': ['Z']}

  30. Original ciphertext:
  31. Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm

  32. Copying hacked message to clipboard:
  33. hackedMessage :If a man is offered a fact which goes against his instincts, he will scrutinize it closel_, and unless the evidence is overwhelming, he will refuse to _elieve it. If, on the other hand, he is offered something which affords a reason for acting in accordance to his instincts, he will acce_t it even on the slightest evidence. The origin of m_ths is e__lained in this wa_. -_ertrand Russell

然后我把常量LETTERS改成了95个可见字符:

点击(此处)折叠或打开

  1. import pyperclip
  2. import sys
  3. import random

  4. #LETTERS = "ABCDEFGHIJKLMNOQPRSTUVWXYZ"

  5. LETTERS = r""" !'#$%&"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" # note the space at the front

  6. def main():
  7.     
  8.     myMessage = "If a man is offered a fact which goes against his instincts, he will scrutinize it closely, and unless the evidence is overwhelming, he will refuse to believe it. If, on the other hand, he is offered something which affords a reason for acting in accordance to his instincts, he will accept it even on the slightest evidence. The origin of myths is explained in this way. -Bertrand Russell"

  9.     #myKey = "LFWOAYUISVKMNXPBDCRJTQEGHZ"
  10.     myKey = getRandomKey()

  11.     myMode = "encrypt"
  12.     checkValidKey(myKey)

  13.     if myMode == "encrypt":
  14.         translated = encryptMessage(myKey, myMessage)
  15.     elif myMode == "decrypt":
  16.         translated = decryptMessage(myKey, myMessage)

  17.     print("Using key {}\n".format(myKey))
  18.     print("The {0}ed message is ".format(myMode))

  19.     print(translated)
  20.     pyperclip.copy(translated)
  21.     print()
  22.     print("This messsage has been copied to the clipboard.")

  23. def checkValidKey(key):
  24.     keyList = list(key)
  25.     lettersList = list(LETTERS)
  26.     keyList.sort()
  27.     lettersList.sort()
  28.     if keyList != lettersList:
  29.         sys.exit("There is an error in the key or symbol set.")

  30. def encryptMessage(key, message):
  31.     return translateMessage(key, message, "encrypt")

  32. def decryptMessage(key, message):
  33.     return translateMessage(key, message, "decrypt")


  34. def translateMessage(key, message, mode):
  35.     translated = ""
  36.     charsA = LETTERS
  37.     charsB = key
  38.     if mode == "decrypt":
  39.         #For decrypting, we can use the same code as encrypting,
  40.         #we just need to swap the key and LETTERS strings are used
  41.         charsA, charsB = charsB, charsA
  42.     #loop through each symbol in the message
  43.     for symbol in message:
  44.         """
  45.         if symbol.upper() in charsA:
  46.             #encrypt/decrypt the symbol
  47.             symIndex = charsA.find(symbol.upper())
  48.             if symbol.isupper():
  49.                 translated += charsB[symIndex].upper()
  50.             else:
  51.                 translated += charsB[symIndex].lower()
  52.         else:
  53.             #symbol is not in LETTERS, just add it
  54.             translated += symbol
  55.         """
  56.         if symbol in charsA:
  57.             symIndex = charsA.find(symbol)
  58.             translated += charsB[symIndex]
  59.         
  60.     return translated

  61. def getRandomKey():
  62.     key = list(LETTERS)
  63.     random.shuffle(key)
  64.     return "".join(key)

  65. if __name__== "__main__"
  66.     main()
再看simpleSubHacker2.py

点击(此处)折叠或打开

  1. import os, re, copy, pprint, pyperclip, simpleSubCipher2, makeWordPatterns

  2. if not os.path.exists("wordPatterns.py"):
  3.     makeWordPatterns.main() # create the wordPatterns.py file
  4. import wordPatterns

  5. #LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  6. LETTERS = r""" !'#$%&"()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~""" # note the space at the front
  7. nonLettersOrSpacePattern = re.compile("[^A-Z\s]")

  8. def main():
  9.     message = "Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm"

  10.     # Determine the possible valid ciphertext translations.
  11.     print("Hacking...")
  12.     letterMapping = hackSimpleSub(message)

  13.     # Display the results to the user.
  14.     print("Mapping:")
  15.     pprint.pprint(letterMapping)
  16.     print()
  17.     print("Original ciphertext:")
  18.     print(message)
  19.     print()
  20.     print("Copying hacked message to clipboard:")
  21.     hackedMessage = decryptWithCipherletterMapping(message, letterMapping)
  22.     pyperclip.copy(hackedMessage)
  23.     print(hackedMessage)


  24. def getBlankCipherletterMapping():
  25.     # Returns a dictionary value that is a blank cipherletter mapping.
  26.     dict1 = {}
  27.     for i in LETTERS:
  28.         dict1[i]=[]
  29.     return dict1
  30.     """
  31.     return {"A": [], "B": [], "C": [], "D": [], "E": [], "F": [], "G": [], "H": [], "I": [], "J": [], "K": [], "L": [], "M": [], "N": [], "O": [], "P": [], "Q": [], "R": [], "S": [], "T": [], "U": [], "V": [], "W": [], "X": [], "Y": [], "Z": []}
  32.     """

  33. def addLettersToMapping(letterMapping, cipherword, candidate):
  34.     # The letterMapping parameter is a "cipherletter mapping" dictionary
  35.     # value that the return value of this function starts as a copy of.
  36.     # The cipherword parameter is a string value of the ciphertext word.
  37.     # The candidate parameter is a possible English word that the
  38.     # cipherword could decrypt to.

  39.     # This function adds the letters of the candidate as potential
  40.     # decryption letters for the cipherletters in the cipherletter
  41.     # mapping.

  42.     letterMapping = copy.deepcopy(letterMapping)
  43.     for i in range(len(cipherword)):
  44.         if candidate[i] not in letterMapping[cipherword[i]]:
  45.             letterMapping[cipherword[i]].append(candidate[i])
  46.     return letterMapping


  47. def intersectMappings(mapA, mapB):
  48.     # To intersect two maps, create a blank map, and then add only the
  49.     # potential decryption letters if they exist in BOTH maps.
  50.     intersectedMapping = getBlankCipherletterMapping()
  51.     for letter in LETTERS:

  52.         # An empty list means "any letter is possible". In this case just
  53.         # copy the other map entirely.
  54.         if mapA[letter] == []:
  55.             intersectedMapping[letter] = copy.deepcopy(mapB[letter])
  56.         elif mapB[letter] == []:
  57.             intersectedMapping[letter] = copy.deepcopy(mapA[letter])
  58.         else:
  59.             # If a letter in mapA[letter] exists in mapB[letter], add
  60.             # that letter to intersectedMapping[letter].
  61.             for mappedLetter in mapA[letter]:
  62.                 if mappedLetter in mapB[letter]:
  63.                     intersectedMapping[letter].append(mappedLetter)

  64.     return intersectedMapping


  65. def removeSolvedLettersFromMapping(letterMapping):
  66.     # Cipher letters in the mapping that map to only one letter are
  67.     # "solved" and can be removed from the other letters.
  68.     # For example, if "A" maps to potential letters ["M", "N"], and "B"
  69.     # maps to ["N"], then we know that "B" must map to "N", so we can
  70.     # remove "N" from the list of what "A" could map to. So "A" then maps
  71.     # to ["M"]. Note that now that "A" maps to only one letter, we can
  72.     # remove "M" from the list of letters for every other
  73.     # letter. (This is why there is a loop that keeps reducing the map.)
  74.     letterMapping = copy.deepcopy(letterMapping)
  75.     loopAgain = True
  76.     while loopAgain:
  77.         # First assume that we will not loop again:
  78.         loopAgain = False

  79.         # solvedLetters will be a list of uppercase letters that have one
  80.         # and only one possible mapping in letterMapping
  81.         solvedLetters = []
  82.         for cipherletter in LETTERS:
  83.             if len(letterMapping[cipherletter]) == 1:
  84.                 solvedLetters.append(letterMapping[cipherletter][0])

  85.         # If a letter is solved, than it cannot possibly be a potential
  86.         # decryption letter for a different ciphertext letter, so we
  87.         # should remove it from those other lists.
  88.         for cipherletter in LETTERS:
  89.             for s in solvedLetters:
  90.                 if len(letterMapping[cipherletter]) != 1 and s in letterMapping[cipherletter]:
  91.                     letterMapping[cipherletter].remove(s)
  92.                     if len(letterMapping[cipherletter]) == 1:
  93.                         # A new letter is now solved, so loop again.
  94.                         loopAgain = True
  95.     return letterMapping


  96. def hackSimpleSub(message):
  97.     intersectedMap = getBlankCipherletterMapping()
  98.     cipherwordList = nonLettersOrSpacePattern.sub("", message.upper()).split()
  99.     for cipherword in cipherwordList:
  100.         # Get a new cipherletter mapping for each ciphertext word.
  101.         newMap = getBlankCipherletterMapping()

  102.         wordPattern = makeWordPatterns.getWordPattern(cipherword)
  103.         if wordPattern not in wordPatterns.allPatterns:
  104.             continue # This word was not in our dictionary, so continue.

  105.         # Add the letters of each candidate to the mapping.
  106.         for candidate in wordPatterns.allPatterns[wordPattern]:
  107.             newMap = addLettersToMapping(newMap, cipherword, candidate)

  108.         # Intersect the new mapping with the existing intersected mapping.
  109.         intersectedMap = intersectMappings(intersectedMap, newMap)

  110.     # Remove any solved letters from the other lists.
  111.     return removeSolvedLettersFromMapping(intersectedMap)


  112. def decryptWithCipherletterMapping(ciphertext, letterMapping):
  113.     # Return a string of the ciphertext decrypted with the letter mapping,
  114.     # with any ambiguous decrypted letters replaced with an _ underscore.

  115.     # First create a simple sub key from the letterMapping mapping.
  116.     key = ["x"] * len(LETTERS)
  117.     for cipherletter in LETTERS:
  118.         if len(letterMapping[cipherletter]) == 1:
  119.             # If there"s only one letter, add it to the key.
  120.             keyIndex = LETTERS.find(letterMapping[cipherletter][0])
  121.             key[keyIndex] = cipherletter
  122.         else:
  123.             ciphertext = ciphertext.replace(cipherletter.lower(), "_")
  124.             ciphertext = ciphertext.replace(cipherletter.upper(), "_")
  125.     key = "".join(key)

  126.     # With the key we"ve created, decrypt the ciphertext.
  127.     return simpleSubCipher2.decryptMessage(key, ciphertext)


  128. if __name__ == "__main__"
  129.     main()
如果使用这个代码,就无法破解.
看我跑这段代码的结果.

点击(此处)折叠或打开

  1. ./simpleSubHacker2.py
  2. Hacking...
  3. Mapping:
  4. {' ': [],
  5.  '!': [],
  6.  '"': [],
  7.  '#': [],
  8.  '$': [],
  9.  '%': [],
  10.  '&': [],
  11.  "'": [],
  12.  '(': [],
  13.  ')': [],
  14.  '*': [],
  15.  '+': [],
  16.  ',': [],
  17.  '-': [],
  18.  '.': [],
  19.  '/': [],
  20.  '0': [],
  21.  '1': [],
  22.  '2': [],
  23.  '3': [],
  24.  '4': [],
  25.  '5': [],
  26.  '6': [],
  27.  '7': [],
  28.  '8': [],
  29.  '9': [],
  30.  ':': [],
  31.  ';': [],
  32.  '<': [],
  33.  '=': [],
  34.  '>': [],
  35.  '?': [],
  36.  '@': [],
  37.  'A': ['E'],
  38.  'B': ['Y', 'P', 'B'],
  39.  'C': ['R'],
  40.  'D': [],
  41.  'E': ['W'],
  42.  'F': ['B', 'P'],
  43.  'G': ['B', 'Q', 'X', 'P', 'Y'],
  44.  'H': ['P', 'Y', 'K', 'X', 'B'],
  45.  'I': ['H'],
  46.  'J': ['T'],
  47.  'K': [],
  48.  'L': ['A'],
  49.  'M': ['L'],
  50.  'N': ['M'],
  51.  'O': ['D'],
  52.  'P': ['O'],
  53.  'Q': ['V'],
  54.  'R': ['S'],
  55.  'S': ['I'],
  56.  'T': ['U'],
  57.  'U': ['G'],
  58.  'V': [],
  59.  'W': ['C'],
  60.  'X': ['N'],
  61.  'Y': ['F'],
  62.  'Z': ['Z'],
  63.  '[': [],
  64.  '\\': [],
  65.  ']': [],
  66.  '^': [],
  67.  '_': [],
  68.  '`': [],
  69.  'a': [],
  70.  'b': [],
  71.  'c': [],
  72.  'd': [],
  73.  'e': [],
  74.  'f': [],
  75.  'g': [],
  76.  'h': [],
  77.  'i': [],
  78.  'j': [],
  79.  'k': [],
  80.  'l': [],
  81.  'm': [],
  82.  'n': [],
  83.  'o': [],
  84.  'p': [],
  85.  'q': [],
  86.  'r': [],
  87.  's': [],
  88.  't': [],
  89.  'u': [],
  90.  'v': [],
  91.  'w': [],
  92.  'x': [],
  93.  'y': [],
  94.  'z': [],
  95.  '{': [],
  96.  '|': [],
  97.  '}': [],
  98.  '~': []}

  99. Original ciphertext:
  100. Sy l nlx sr pyyacao l ylwj eiswi upar lulsxrj isr sxrjsxwjr, ia esmm rwctjsxsza sj wmpramh, lxo txmarr jia aqsoaxwa sr pqaceiamnsxu, ia esmm caytra jp famsaqa sj. Sy, px jia pjiac ilxo, ia sr pyyacao rpnajisxu eiswi lyypcor l calrpx ypc lwjsxu sx lwwpcolxwa jp isr sxrjsxwjr, ia esmm lwwabj sj aqax px jia rmsuijarj aqsoaxwa. Jia pcsusx py nhjir sr agbmlsxao sx jisr elh. -Facjclxo Ctrramm

  101. Copying hacked message to clipboard:








阅读(1590) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~