Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RaminMammadzada/af3cbe5f04eaa4ba87fa8537ddefffba to your computer and use it in GitHub Desktop.
Save RaminMammadzada/af3cbe5f04eaa4ba87fa8537ddefffba to your computer and use it in GitHub Desktop.
Brute-force to Caesar’s cipher
"""
Brute-force the following Caesar’s cipher, and find
the plaintext and key of the following
message: kyvtrmrcipnzccrkkrtbwifdkyvefikynvjkrkeffe
"""
alphabet = "abcdefghijklmnopqrstuvwxyz"
def encrypt(plaintext, k):
ciphertext = []
for c in plaintext:
i = alphabet.index(c)
j = (i + k) % len(alphabet)
ciphertext.append(alphabet[j])
return ''.join(ciphertext)
def decrypt(ciphertext, k):
return encrypt(ciphertext, -k)
def brute_force(ciphertext):
plaintext = []
plaintexts = {}
for key in range(26):
for c in ciphertext:
i = alphabet.index(c)
j = (i - key) % len(alphabet)
plaintext.append(alphabet[j])
plaintexts[''.join(plaintext)] = key
plaintext = []
for plaintext, key in plaintexts.items():
print(plaintext + ": " + str(key))
brute_force("kyvtrmrcipnzccrkkrtbwifdkyvefikynvjkrkeffe")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment