ROT13 Cipher

Tags: tiny, cryptography

The ROT13 cipher, one of the simplest encryption algorithms, stands for “rotate 13 spaces.” The cypher represents the letters A to Z as the numbers 0 to 25 in such a way that the encrypted letter is 13 spaces from the plaintext letter: A becomes N, B becomes O, and so on. The encryption process is identical to the decryption process, making it trivial to program. However, the encryption is also trivial to break. Because of this, you’ll most often find ROT13 used to conceal non-sensitive information, such as spoilers or trivia answers, so it’s not read unintentionally. More information about the ROT13 cipher can be found at https://en.wikipedia.org/wiki/ROT13. If you’d like to learn about ciphers and code breaking more generally, you can read my book Cracking Codes with Python (No Starch Press, 2018; https://nostarch.com/crackingcodes/).

rot13_cipher.py
 1"""ROT13 Cipher, by Al Sweigart al@inventwithpython.com
 2The simplest shift cipher for encrypting and decrypting text.
 3More info at https://en.wikipedia.org/wiki/ROT13
 4This code is available at https://nostarch.com/big-book-small-python-programming
 5Tags: tiny, cryptography"""
 6
 7try:
 8    import pyperclip  # pyperclip copies text to the clipboard.
 9except ImportError:
10    pass  # If pyperclip is not installed, do nothing. It's no big deal.
11
12# Set up the constants:
13UPPER_LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
14LOWER_LETTERS = 'abcdefghijklmnopqrstuvwxyz'
15
16print('ROT13 Cipher, by Al Sweigart al@inventwithpython.com')
17print()
18
19while True:  # Main program loop.
20    print('Enter a message to encrypt/decrypt (or QUIT):')
21    message = input('> ')
22
23    if message.upper() == 'QUIT':
24        break  # Break out of the main program loop.
25
26    # Rotate the letters in message by 13 characters.
27    translated = ''
28    for character in message:
29        if character.isupper():
30            # Concatenate uppercase translated character.
31            transCharIndex = (UPPER_LETTERS.find(character) + 13) % 26
32            translated += UPPER_LETTERS[transCharIndex]
33        elif character.islower():
34            # Concatenate lowercase translated character.
35            transCharIndex = (LOWER_LETTERS.find(character) + 13) % 26
36            translated += LOWER_LETTERS[transCharIndex]
37        else:
38            # Concatenate the character untranslated.
39            translated += character
40
41    # Display the translation:
42    print('The translated message is:')
43    print(translated)
44    print()
45
46    try:
47        # Copy the translation to the clipboard:
48        pyperclip.copy(translated)
49        print('(Copied to clipboard.)')
50    except:
51        pass

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