Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Caesar Cypher Decoding
- # Decode some text by finding out what Caesar offset produces the best result based on the
- # characters in the resultant text, scored by their frequency in typical English text
- def caesar_decrypt(intext):
- # Arrange alphabet in reverse order of frequency, so that the index position corresponds to a score for that letter
- LetterDistr = "xqjzvkywgfbpmculdrhsnioate"
- # letters occurring near the front of LetterDistr score low. Letters towards the end score high.
- # Decode the input text using all possible Caesar offsets, 0 to 25, in turn
- # For each of the 26 results, compute the sum of the scores for the letters
- # For example, every "e" in the output scores 25*25, whereas "x" scores 0
- bestscore = 0
- for off in range(0, 26): # Try each offset (0 to 25) in turn
- otext = ""
- score = 0
- for ch in intext:
- x = ord(ch) - ord('a') # compute the distance of ch from 'a' in alphabet
- x += off # add the current Caesar offset
- x %= 26 # wrap around 26 letters
- char = chr(x + ord('a'))
- otext += char # build the decoded output text
- if char in LetterDistr:
- weight = LetterDistr.index(char) # get letter weight based on frequency in English
- score += weight * weight # exaggerate the weight variance and accumulate a message score
- if score > bestscore:
- bestscore = score # remember the best score so far
- bestkey = off # remember the offset that gave the best score so far
- bestout = otext # remember the best decyphered text so far
- # print(off, score, otext) # optional progress print
- print("Best Offset: ", bestkey)
- print("Decrypted text: ", bestout)
- encrypted_text = "kyvfecpkzdvjyvljvurjtivnuizmvinrjpvjkviurp"
- caesar_decrypt(encrypted_text)
- # Output
- # Best Offset: 9
- # Decrypted text: theonlytimesheusedascrewdriverwasyesterday
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement