Caesar Cipher Hacker

Hacking The Caesar Cipher with Brute Force
#Hacking The Caesar Cipher with Brute Force
print('Input an encrypted message:')
message=input()
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 !?.,'

print('\n')
print('---BEGIN DECRYPTION------------------------------')
print('All possible decryptions:')
#Loop through every possible key
for key in range(len(SYMBOLS)):
    translated=''

    for symbol in message:
        #ONLY SYMBOLS STORED IN THE VARIABLE SYMBOLS CAN BE DECRYPTED
        if symbol in SYMBOLS:
            symbolIndex = SYMBOLS.find(symbol)

            #PERFORM ENCRYPTION/DECRYPTION
            translatedIndex = symbolIndex - key

            #HANDLE WRAP AROUND IF NEEDED
            if translatedIndex >= len(SYMBOLS):
                translatedIndex = translatedIndex -len(SYMBOLS)
            elif translatedIndex < 0:
                translatedIndex = translatedIndex + len(SYMBOLS)

            translated = translated + SYMBOLS[translatedIndex]

        else:
            #APPEND THE SYMBOL WITHOUT ENCRYPTING OR DECRYPTING
            translated = translated + symbol

    #Display every possible decryption
    #print('Key #%s: %s' %(key, translated))
    key=str(key)
    print('Key #' + key + ': ' + translated)

print('---END OF DECRYPTION------------------------------')

Looping with the range() Function
for key in range(len(SYMBOLS))
The range function runs the for loop depending on how many characters are stored inside the variable SYMBOLS. The first time the loop runs, it will set the value of key to zero (0), and the cipher text is decrypted with the key zero. It will decrypt with all the possible keys until done with the total number of characters in SYMBOLS.

Additional knowledge: you can also pass 2 integers to range(). Example:
for i in range(2,4)
The first is the index where the range should start, and the second is the index before the second integer, where the loop should stop. So for example, 2 -> 4, meaning index 2, and index 3 (not including 4).

 

String Formatting or String Interpolation
print(‘Key #%s: %s’ %(key, translated))
%s – this places ‘key’ and ‘translated’ inside the string ‘Key# :’. The first %s is for the ‘key’, and the second %s is for the ‘translated’. In other words, it allows placing the variables inside the string.
Another way of displaying the output:
key=str(key)
print(‘Key #’ + key + ‘: ‘ + translated)
It basically does the same thing, but will cost you an additional line since you have to convert the key into a string type of variable.