Skip to content

Instantly share code, notes, and snippets.

@NatashaKSS
Last active January 29, 2018 08:20
Show Gist options
  • Save NatashaKSS/a159d867d9ca18479a5ade6f34280d0e to your computer and use it in GitHub Desktop.
Save NatashaKSS/a159d867d9ca18479a5ade6f34280d0e to your computer and use it in GitHub Desktop.
Simple fun Demo of Frequency Analysis w/ a Substitution Cipher
# Sample ciphertext for practice
cipher_text = "muzbpbxyenryzamvrbrzctbmxznhvzeojmvbjjzctbzhnxwrzhnowrzknzqxnovrzqzkxbqczrbqwzuqjcbxzctqvzmczrnbj"
# Function to help you make preliminary guesses of what some cipher symbols are.
# Collects the character frequency of all letters in the ciphertext
def freq(cipher_text):
result = {}
for ch in cipher_text:
if ch in result:
result[ch] += 1
else:
result[ch] = 1
return result
# Gives the plaintext when attempting to decrypt cipher_text using your own
# pattern that's in a dictionary format (see example below)
def substitute(pattern, cipher_text):
cipher_text_chars = list(cipher_text)
pattern_symbols = list(pattern.keys())
result = []
for ch in cipher_text_chars:
if (ch in pattern_symbols):
result.append(pattern[ch].upper())
else:
result.append(ch)
return ''.join(result)
# Cipher to test. Edit values here to try different letter combinations.
# This is what I came up with simply by eyeballing & comparing the ciphertext & hacked plaintext
patt = {
'z': ' ',
'c': 't',
't': 'h',
'b': 'e',
'q': 'a',
'v': 'n',
'm': 'i',
'u': 'f',
'x': 'r',
'j': 's',
'n': 'o',
'o': 'u',
'r': 'd',
'a': 'm',
'h': 'w',
'e': 'b',
'w': 'l',
'p': 'v',
'y': 'y',
'k': 'g'
}
# To analyze the pattern before hacking.
# High frequency letters are typically vowels/space.
print(freq(cipher_text))
# Print out decrypted ciphertext to test
print('Original:\n' + cipher_text + '\n')
print('Hacked:\n' + substitute(patt, cipher_text))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment