Caesar Hacker

Tags: tiny, beginner, cryptography, math

This program can hack messages encrypted with the Caesar cipher from Project 6, even if you don’t know the key. There are only 26 possible keys for the Caesar cipher, so a computer can easily try all possible decryptions and display the results to the user. In cryptography, we call this technique a brute-force attack.

caesar_hacker.py
 1"""Caesar Cipher Hacker, by Al Sweigart al@inventwithpython.com
 2This programs hacks messages encrypted with the Caesar cipher by doing
 3a brute force attack against every possible key.
 4More info at:
 5https://en.wikipedia.org/wiki/Caesar_cipher#Breaking_the_cipher
 6This code is available at https://nostarch.com/big-book-small-python-programming
 7Tags: tiny, beginner, cryptography, math"""
 8
 9print('Caesar Cipher Hacker, by Al Sweigart al@inventwithpython.com')
10
11# Let the user specify the message to hack:
12print('Enter the encrypted Caesar cipher message to hack.')
13message = input('> ')
14
15# Every possible symbol that can be encrypted/decrypted:
16# (This must match the SYMBOLS used when encrypting the message.)
17SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
18
19for key in range(len(SYMBOLS)):  # Loop through every possible key.
20    translated = ''
21
22    # Decrypt each symbol in the message:
23    for symbol in message:
24        if symbol in SYMBOLS:
25            num = SYMBOLS.find(symbol)  # Get the number of the symbol.
26            num = num - key  # Decrypt the number.
27
28            # Handle the wrap-around if num is less than 0:
29            if num < 0:
30                num = num + len(SYMBOLS)
31
32            # Add decrypted number's symbol to translated:
33            translated = translated + SYMBOLS[num]
34        else:
35            # Just add the symbol without decrypting:
36            translated = translated + symbol
37
38    # Display the key being tested, along with its decrypted text:
39    print('Key #{}: {}'.format(key, translated))

https://inventwithpython.com/bigbookpython/project7.html