Advertisement
acclivity

pyBestCaesarDecrypt by letter frequency

Apr 18th, 2022 (edited)
1,186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. # Caesar Cypher Decoding
  2. # Decode some text by finding out what Caesar offset produces the best result based on the
  3. # characters in the resultant text, scored by their frequency in typical English text
  4.  
  5.  
  6. def caesar_decrypt(intext):
  7.     # Arrange alphabet in reverse order of frequency, so that the index position corresponds to a score for that letter
  8.     LetterDistr = "xqjzvkywgfbpmculdrhsnioate"
  9.     # letters occurring near the front of LetterDistr score low. Letters towards the end score high.
  10.  
  11.     # Decode the input text using all possible Caesar offsets, 0 to 25, in turn
  12.     # For each of the 26 results, compute the sum of the scores for the letters
  13.     # For example, every "e" in the output scores 25*25, whereas "x" scores 0
  14.  
  15.     bestscore = 0
  16.     for off in range(0, 26):            # Try each offset (0 to 25) in turn
  17.         otext = ""
  18.         score = 0
  19.         for ch in intext:
  20.             x = ord(ch) - ord('a')      # compute the distance of ch from 'a' in alphabet
  21.             x += off                    # add the current Caesar offset
  22.             x %= 26                     # wrap around 26 letters
  23.             char = chr(x + ord('a'))
  24.             otext += char               # build the decoded output text
  25.             if char in LetterDistr:
  26.                 weight = LetterDistr.index(char)        # get letter weight based on frequency in English
  27.                 score += weight * weight    # exaggerate the weight variance and accumulate a message score
  28.         if score > bestscore:
  29.             bestscore = score           # remember the best score so far
  30.             bestkey = off               # remember the offset that gave the best score so far
  31.             bestout = otext             # remember the best decyphered text so far
  32.         # print(off, score, otext)          # optional progress print
  33.     print("Best Offset: ", bestkey)
  34.     print("Decrypted text: ", bestout)
  35.  
  36.  
  37. encrypted_text = "kyvfecpkzdvjyvljvurjtivnuizmvinrjpvjkviurp"
  38. caesar_decrypt(encrypted_text)
  39.  
  40. # Output
  41. # Best Offset:  9
  42. # Decrypted text:  theonlytimesheusedascrewdriverwasyesterday
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement