Cracking Codes with Python: An Introduction to Building and Breaking Ciphers
By Al Sweigart
()
About this ebook
After a crash course in Python programming basics, you’ll learn to make, test, and hack programs that encrypt text with classical ciphers like the transposition cipher and Vigenère cipher. You’ll begin with simple programs for the reverse and Caesar ciphers and then work your way up to public key cryptography, the type of encryption used to secure today’s online transactions, including digital signatures, email, and Bitcoin.
Each program includes the full code and a line-by-line explanation of how things work. By the end of the book, you’ll have learned how to code in Python and you’ll have the clever programs to prove it!
You’ll also learn how to:
- Combine loops, variables, and flow control statements into real working programs
- Use dictionary files to instantly detect whether decrypted messages are valid English or gibberish
- Create test programs to make sure that your code encrypts and decrypts correctly
- Code (and hack!) a working example of the affine cipher, which uses modular arithmetic to encrypt a message
- Break ciphers with techniques such as brute-force and frequency analysis
There’s no better way to learn to code than to play with real programs. Cracking Codes with Python makes the learning fun!
Read more from Al Sweigart
The Recursive Book of Recursion: Ace the Coding Interview with Python and JavaScript Rating: 0 out of 5 stars0 ratingsBeyond the Basic Stuff with Python: Best Practices for Writing Clean Code Rating: 0 out of 5 stars0 ratingsInvent Your Own Computer Games with Python, 4th Edition Rating: 4 out of 5 stars4/5Coding with Minecraft: Build Taller, Farm Faster, Mine Deeper, and Automate the Boring Stuff Rating: 5 out of 5 stars5/5
Related to Cracking Codes with Python
Related ebooks
Python Uncoiled: From Print Statements to Power Scripts Rating: 0 out of 5 stars0 ratingsPython Power: For Absolute Beginners Rating: 0 out of 5 stars0 ratingsMastering Python: A Comprehensive Approach for Beginners and Beyond Rating: 0 out of 5 stars0 ratingsMastering Python Rating: 0 out of 5 stars0 ratingsPython Simplified: Learn Programming Through Practical Examples Rating: 0 out of 5 stars0 ratingsPython Made Easy: A First Course in Computer Programming Using Python Rating: 0 out of 5 stars0 ratingsPython for Absolute Beginners: Learn to Code Fast! Rating: 0 out of 5 stars0 ratingsPython Programming: From Zero to Web Development: Python, #1 Rating: 0 out of 5 stars0 ratingsImplementing Cryptography Using Python Rating: 0 out of 5 stars0 ratingsPYTHON PROGRAMMING Rating: 4 out of 5 stars4/5The 1 Page Python Book Rating: 2 out of 5 stars2/5Easy Programming for Everyone Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Python Crash Course for Beginners Rating: 0 out of 5 stars0 ratingsMastering Python in 7 Days Rating: 0 out of 5 stars0 ratingsPython Pranks and Mischief with NLP Rating: 0 out of 5 stars0 ratingsPython 3 Fundamentals: A Complete Guide for Modern Programmers Rating: 0 out of 5 stars0 ratingsPROGRAMMING WITH PYTHON: Master the Basics and Beyond with Hands-On Projects and Expert Guidance (2024 Guide for Beginners) Rating: 0 out of 5 stars0 ratingsPython for Beginners: A Step by Step Guide on How to Program with Python Rating: 0 out of 5 stars0 ratings#1 Book on Python Programming Rating: 0 out of 5 stars0 ratingsProgramming Abc With Python Or Programming The Easy Way Rating: 0 out of 5 stars0 ratingsCryptography Basics for New Coders: A Practical Guide with Examples Rating: 0 out of 5 stars0 ratingsMission Python Rating: 0 out of 5 stars0 ratingsIntroduction to Python Programming: Do your first steps into programming with python Rating: 0 out of 5 stars0 ratingsTiny Python Projects: Learn coding and testing with puzzles and games Rating: 4 out of 5 stars4/5Simplifying Data Science With Python Rating: 0 out of 5 stars0 ratings
Programming For You
Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsHTML in 30 Pages Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Learn SQL in 24 Hours Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Coding All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsPython Data Structures and Algorithms Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Spies, Lies, and Algorithms: The History and Future of American Intelligence Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsAlgorithms For Dummies Rating: 4 out of 5 stars4/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Python 3 Object Oriented Programming Rating: 4 out of 5 stars4/5
Related categories
Reviews for Cracking Codes with Python
0 ratings0 reviews
Book preview
Cracking Codes with Python - Al Sweigart
INTRODUCTION
I couldn’t help but overhear, probably because I was eavesdropping.
—Anonymous
If you could travel back to the early 1990s with this book, the contents of Chapter 23 that implement part of the RSA cipher would be illegal to export out of the United States. Because messages encrypted with RSA are impossible to hack, the export of encryption software like RSA was deemed a matter of national security and required State Department approval. In fact, strong cryptography was regulated at the same level as tanks, missiles, and flamethrowers.
In 1990, Daniel J. Bernstein, a student at the University of California, Berkeley, wanted to publish an academic paper that featured source code of his Snuffle encryption system. The US government informed him that he would need to become a licensed arms dealer before he could post his source code on the internet. The government also told him that it would deny him an export license if he applied for one because his technology was too secure.
The Electronic Frontier Foundation, a young digital civil liberties organization, represented Bernstein in Bernstein v. United States. For the first time ever, the courts ruled that written software code was speech protected by the First Amendment and that the export control laws on encryption violated Bernstein’s First Amendment rights.
Now, strong cryptography is at the foundation of a large part of the global economy, safeguarding businesses and e-commerce sites used by millions of internet shoppers every day. The intelligence community’s predictions that encryption software would become a grave national security threat were unfounded.
But as recently as the 1990s, spreading this knowledge freely (as this book does) would have landed you in prison for arms trafficking. For a more detailed history of the legal battle for freedom of cryptography, read Steven Levy’s book Crypto: How the Code Rebels Beat the Government, Saving Privacy in the Digital Age (Penguin, 2001).
Who Should Read This Book?
Many books teach beginners how to write secret messages using ciphers. A couple of books teach beginners how to hack ciphers. But no books teach beginners how to program computers to hack ciphers. This book fills that gap.
This book is for those who are curious about encryption, hacking, or cryptography. The ciphers in this book (except for the public key cipher in Chapters 23 and 24) are all centuries old, but any laptop has the computational power to hack them. No modern organizations or individuals use these ciphers anymore, but by learning them, you’ll learn the foundations cryptography was built on and how hackers can break weak encryption.
NOTE
The ciphers you’ll learn in this book are fun to play with, but they don’t provide true security. Don’t use any of the encryption programs in this book to secure your actual files. As a general rule, you shouldn’t trust the ciphers that you create. Real-world ciphers are subject to years of analysis by professional cryptographers before being put into use.
This book is also for people who have never programmed before. It teaches basic programming concepts using the Python programming language, which is one of the best languages for beginners. It has a gentle learning curve that novices of all ages can master, yet it’s also a powerful language used by professional software developers. Python runs on Windows, macOS, Linux, and even the Raspberry Pi, and it’s free to download and use. (See "Downloading and Installing Python" on page xxv for instructions.)
In this book, I’ll use the term hacker often. The word has two definitions. A hacker can be a person who studies a system (such as the rules of a cipher or a piece of software) to understand it so well that they’re not limited by that system’s original rules and can modify it in creative ways. A hacker can also be a criminal who breaks into computer systems, violates people’s privacy, and causes damage. This book uses the term in the first sense. Hackers are cool. Criminals are just people who think they’re being clever by breaking stuff.
What’s in This Book?
The first few chapters introduce basic Python and cryptography concepts. Thereafter, chapters generally alternate between explaining a program for a cipher and then explaining a program that hacks that cipher. Each chapter also includes practice questions to help you review what you’ve learned.
Chapter 1: Making Paper Cryptography Tools covers some simple paper tools, showing how encryption was done before computers.
Chapter 2: Programming in the Interactive Shell explains how to use Python’s interactive shell to play around with code one line at a time.
Chapter 3: Strings and Writing Programs covers writing full programs and introduces the string data type used in all programs in this book.
Chapter 4: The Reverse Cipher explains how to write a simple program for your first cipher.
Chapter 5: The Caesar Cipher covers a basic cipher first invented thousands of years ago.
Chapter 6: Hacking the Caesar Cipher with Brute-Force explains the brute-force hacking technique and how to use it to decrypt messages without the encryption key.
Chapter 7: Encrypting with the Transposition Cipher introduces the transposition cipher and a program that encrypts messages with it.
Chapter 8: Decrypting with the Transposition Cipher covers the second half of the transposition cipher: being able to decrypt messages with a key.
Chapter 9: Programming a Program to Test Your Program introduces the programming technique of testing programs with other programs.
Chapter 10: Encrypting and Decrypting Files explains how to write programs that read files from and write files to the hard drive.
Chapter 11: Detecting English Programmatically describes how to make the computer detect English sentences.
Chapter 12: Hacking the Transposition Cipher combines the concepts from previous chapters to hack the transposition cipher.
Chapter 13: A Modular Arithmetic Module for the Affine Cipher explains the math concepts behind the affine cipher.
Chapter 14: Programming the Affine Cipher covers writing an affine cipher encryption program.
Chapter 15: Hacking the Affine Cipher explains how to write a program to hack the affine cipher.
Chapter 16: Programming the Simple Substitution Cipher covers writing a simple substitution cipher encryption program.
Chapter 17: Hacking the Simple Substitution Cipher explains how to write a program to hack the simple substitution cipher.
Chapter 18: Programming the Vigenère Cipher explains a program for the Vigenère cipher, a more complex substitution cipher.
Chapter 19: Frequency Analysis explores the structure of English words and how to use it to hack the Vigenère cipher.
Chapter 20: Hacking the Vigenère Cipher covers a program for hacking the Vigenère cipher.
Chapter 21: The One-Time Pad Cipher explains the one-time pad cipher and why it’s mathematically impossible to hack.
Chapter 22: Finding and Generating Prime Numbers covers how to write a program that quickly determines whether a number is prime.
Chapter 23: Generating Keys for the Public Key Cipher describes public key cryptography and how to write a program that generates public and private keys.
Chapter 24: Programming the Public Key Cipher explains how to write a program for a public key cipher, which you can’t hack using a mere laptop.
The appendix, Debugging Python Code, shows you how to use IDLE’s debugger to find and fix bugs in your programs.
How to Use This Book
Cracking Codes with Python is different from other programming books because it focuses on the source code of complete programs. Instead of teaching you programming concepts and leaving it up to you to figure out how to make your own programs, this book shows you complete programs and explains how they work.
In general, you should read the chapters in this book in order. The programming concepts build on those in the previous chapters. However, Python is such a readable language that after the first few chapters, you can probably jump ahead to later chapters and piece together what the code does. If you jump ahead and feel lost, return to earlier chapters.
Typing Source Code
As you read through this book, I encourage you to manually type the source code from this book into Python. Doing so will definitely help you understand the code better.
When typing the source code, don’t include the line numbers that appear at the beginning of each line. These numbers are not part of the actual programs, and we use them only to refer to specific lines in the code. But aside from the line numbers, be sure to enter the code exactly as it appears, including the uppercase and lowercase letters.
You’ll also notice that some of the lines don’t begin at the leftmost edge of the page but are indented by four, eight, or more spaces. Be sure to enter the correct number of spaces at the beginning of each line to avoid errors.
But if you would rather not type the code, you can download the source code files from this book’s website at https://www.nostarch.com/crackingcodes/.
Checking for Typos
Although manually entering the source code for the programs is helpful for learning Python, you might occasionally make typos that cause errors. These typos can be difficult to spot, especially when your source code is very long.
To quickly and easily check for mistakes in your typed source code, you can copy and paste the text into the online diff tool on the book’s website at https://www.nostarch.com/crackingcodes/. The diff tool shows any differences between the source code in the book and yours.
Coding Conventions in This Book
This book is not designed to be a reference manual; it’s a hands-on guide for beginners. For this reason, the coding style sometimes goes against best practices, but that’s a conscious decision to make the code easier to learn. This book also skips theoretical computer science concepts.
Veteran programmers may point out ways the code in this book could be changed to improve efficiency, but this book is mostly concerned with getting programs to work with the least amount of effort.
Online Resources
This book’s website (https://www.nostarch.com/crackingcodes/) includes many useful resources, including downloadable files of the programs and sample solutions to the practice questions. This book covers classical ciphers thoroughly, but because there is always more to learn, I’ve also included suggestions for further reading on many of the topics introduced in this book.
Downloading and Installing Python
Before you can begin programming, you’ll need to install the Python interpreter, which is software that executes the instructions you’ll write in the Python language. I’ll refer to the Python interpreter
as Python
from now on.
Download Python for Windows, macOS, and Ubuntu for free from https://www.python.org/downloads/. If you download the latest version, all of the programs in this book should work.
NOTE
Be sure to download a version of Python 3 (such as 3.6). The programs in this book are written to run on Python 3 and may not run correctly, if at all, on Python 2.
Windows Instructions
On Windows, download the Python installer, which should have a filename ending with .msi, and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:
Select Install Now to begin the installation.
When the installation is finished, click Close.
macOS Instructions
On macOS, download the .dmg file for your version of macOS from the website and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:
When the DMG package opens in a new window, double-click the Python.mpkg file. You may have to enter your computer’s administrator password.
Click Continue through the Welcome section and click Agree to accept the license.
Select HD Macintosh (or the name of your hard drive) and click Install.
Ubuntu Instructions
If you’re running Ubuntu, install Python from the Ubuntu Software Center by following these steps:
Open the Ubuntu Software Center.
Type Python in the search box in the top-right corner of the window.
Select IDLE (using Python 3.6), or whatever is the latest version.
Click Install.
You may have to enter the administrator password to complete the installation.
Downloading pyperclip.py
Almost every program in this book uses a custom module I wrote called pyperclip.py. This module provides functions that let your programs copy and paste text to the clipboard. It doesn’t come with Python, so you’ll need to download it from https://www.nostarch.com/crackingcodes/.
This file must be in the same folder (also called directory) as the Python program files you write. Otherwise you’ll see the following error message when you try to run your programs:
ImportError: No module named pyperclip
Now that you’ve downloaded and installed the Python interpreter and the pyperclip.py module, let’s look at where you’ll be writing your programs.
Starting IDLE
While the Python interpreter is the software that runs your Python programs, the interactive development environment (IDLE) software is where you’ll write your programs, much like a word processor. IDLE is installed when you install Python. To start IDLE, follow these steps:
On Windows 7 or newer, click the Start icon in the lower-left corner of your screen, enter IDLE in the search box, and select IDLE (Python 3.6 64-bit).
On macOS, open Finder, click Applications, click Python 3.6, and then click the IDLE icon.
On Ubuntu, select Applications▸Accessories▸Terminal and then enter idle3. (You may also be able to click Applications at the top of the screen, select Programming, and then click IDLE 3.)
No matter which operating system you’re running, the IDLE window should look something like Figure 1. The header text may be slightly different depending on your specific version of Python.
Figure 1: The IDLE window
This window is called the interactive shell. A shell is a program that lets you type instructions into the computer, much like the Terminal on macOS or the Windows Command Prompt. Sometimes you’ll want to run short snippets of code instead of writing a full program. Python’s interactive shell lets you enter instructions for the Python interpreter software, which the computer reads and runs immediately.
For example, type the following into the interactive shell next to the >>> prompt:
>>> print('Hello, world!')
Press enter, and the interactive shell should display this in response:
Hello, world!
Summary
Before the introduction of computers ushered in modern cryptography, breaking many codes was impossible using just pencil and paper. Although computing made many of the old, classical ciphers vulnerable to attack, they’re still fun to learn about. Writing cryptanalysis programs that crack these ciphers is a great way to learn how to program.
In Chapter 1, we’ll start with some basic cryptography tools to encrypt and decrypt messages without the aid of computers.
Let’s get hacking.
1
MAKING PAPER CRYPTOGRAPHY TOOLS
The encryption genie is out of the bottle.
—Jan Koum, WhatsApp founder
Before we start writing cipher programs, let’s look at the process of encrypting and decrypting with just pencil and paper. This will help you understand how ciphers work and the math that goes into producing their secret messages. In this chapter, you’ll learn what we mean by cryptography and how codes are different from ciphers. Then you’ll use a simple cipher called the Caesar cipher to encrypt and decrypt messages using paper and pencil.
TOPICS COVERED IN THIS CHAPTER
What is cryptography?
Codes and ciphers
The Caesar cipher
Cipher wheels
Doing cryptography with arithmetic
Double encryption
What Is Cryptography?
Historically, anyone who has needed to share secrets with others, such as spies, soldiers, hackers, pirates, merchants, tyrants, and political activists, has relied on cryptography to make sure their secrets stay secret. Cryptography is the science of using secret codes. To understand what cryptography looks like, look at the following two pieces of text:
The text on the left is a secret message that has been encrypted, or turned into a secret code. It’s completely unreadable to anyone who doesn’t know how to decrypt it, or turn it back into the original English message. The message on the right is random gibberish with no hidden meaning. Encryption keeps a message secret from other people who can’t decipher it, even if they get their hands on the encrypted message. An encrypted message looks exactly like random nonsense.
A cryptographer uses and studies secret codes. Of course, these secret messages don’t always remain secret. A cryptanalyst, also called a code breaker or hacker, can hack secret codes and read other people’s encrypted messages. This book teaches you how to encrypt and decrypt messages using various techniques. But unfortunately (or fortunately), the type of hacking you’ll learn in this book isn’t dangerous enough to get you in trouble with the law.
Codes vs. Ciphers
Unlike ciphers, codes are made to be understandable and publicly available. Codes substitute messages with symbols that anyone should be able to look up to translate into a message.
In the early 19th century, one well-known code came from the development of the electric telegraph, which allowed for near-instant communication across continents through wires. Sending messages by telegraph was much faster than the previous alternative of sending a horseback rider carrying a bag of letters. However, the telegraph couldn’t directly send written letters drawn on paper. Instead, it could send only two types of electric pulses: a short pulse called a dot
and a long pulse called a dash.
To convert letters of the alphabet into these dots and dashes, you need an encoding system to translate English to electric pulses. The process of converting English into dots and dashes to send over a telegraph is called encoding, and the process of translating electric pulses to English when a message is received is called decoding. The code used to encode and decode messages over telegraphs (and later, radio) was called Morse code, as shown in Table 1-1. Morse code was developed by Samuel Morse and Alfred Vail.
Table 1-1: International Morse Code Encoding
By tapping dots and dashes with a one-button telegraph, a telegraph operator could communicate an English message to someone on the other side of the world almost instantly! (To learn more about Morse code, visit https://www.nostarch.com/crackingcodes/.)
In contrast with codes, a cipher is a specific type of code meant to keep messages secret. You can use a cipher to turn understandable English text, called plaintext, into gibberish that hides a secret message, called the ciphertext. A cipher is a set of rules for converting between plaintext and ciphertext. These rules often use a secret key to encrypt or decrypt that only the communicators know. In this book, you’ll learn several ciphers and write programs to use these ciphers to encrypt and decrypt text. But first, let’s encrypt messages by hand using simple paper tools.
The Caesar Cipher
The first cipher you’ll learn is the Caesar cipher, which is named after Julius Caesar who used it 2000 years ago. The good news is that it’s simple and easy to learn. The bad news is that because it’s so simple, it’s also easy for a cryptanalyst to break. However, it’s still a useful learning exercise.
The Caesar cipher works by substituting each letter of a message with a new letter after shifting the alphabet over. For example, Julius Caesar substituted letters in his messages by shifting the letters in the alphabet down by three, and then replacing every letter with the letters in his shifted alphabet.
For example, every A in the message would be replaced by a D, every B would be an E, and so on. When Caesar needed to shift letters at the end of the alphabet, such as Y, he would wrap around to the beginning of the alphabet and shift three places to B. In this section, we’ll encrypt a message by hand using the Caesar cipher.
The Cipher Wheel
To make converting plaintext to ciphertext using the Caesar cipher easier, we’ll use a cipher wheel, also called a cipher disk. The cipher wheel consists of two rings of letters; each ring is split up into 26 slots (for a 26-letter alphabet). The outer ring represents the plaintext alphabet, and the inner ring represents the corresponding letters in the ciphertext. The inner ring also numbers the letters from 0 to 25. These numbers represent the encryption key, which in this case is the number of letters required to shift from A to the corresponding letter on the inner ring. Because the shift is circular, shifting with a key greater than 25 makes the alphabets wrap around, so shifting by 26 would be the same as shifting by 0, shifting by 27 would be the same as shifting by 1, and so on.
You can access a virtual cipher wheel online at https://www.nostarch.com/crackingcodes/. Figure 1-1 shows what it looks like. To spin the wheel, click it and then move the mouse cursor around until the configuration you want is in place. Then click the mouse again to stop the wheel from spinning.
Figure 1-1: The online cipher wheel
A printable paper cipher wheel is also available from the book’s website. Cut out the two circles and lay them on top of each other, placing the smaller one in the middle of the larger one. Insert a pin or brad through the center of both circles so you can spin them around in place.
Using either the paper or the virtual wheel, you can encrypt secret messages by hand.
Encrypting with the Cipher Wheel
To begin encrypting, write your message in English on a piece of paper. For this example, we’ll encrypt the message THE SECRET PASSWORD IS ROSEBUD. Next, spin the inner wheel of the cipher wheel until its slots match up with slots in the outer wheel. Notice the dot next to the letter A in the outer wheel. Take note of the number in the inner wheel next to this dot. This is the encryption key.
For example, in Figure 1-1, the outer circle’s A is over the inner circle’s number 8. We’ll use this encryption key to encrypt the message in our example, as shown in Figure 1-2.
Figure 1-2: Encrypting a message with a Caesar cipher key of 8
For each letter in the message, find it in the outer circle and replace it with the corresponding letter in the inner circle. In this example, the first letter in the message is T (the first T in THE SECRET…
), so find the letter T in the outer circle and then find the corresponding letter in the inner circle, which is the letter B. So the secret message always replaces a T with a B. (If you were using a different encryption key, each T in the plaintext would be replaced with a different letter.) The next letter in the message is H, which turns into P. The letter E turns into M. Each letter on the outer wheel always encrypts to the same letter on the inner wheel. To save time, after you look up the first T in THE SECRET…
and see that it encrypts to B, you can replace every T in the message with B, so you only need to look up a letter once.
After you encrypt the entire message, the original message, THE SECRET PASSWORD IS ROSEBUD, becomes BPM AMKZMB XIAAEWZL QA ZWAMJCL. Notice that non-letter characters, such as the spaces, are not changed.
Now you can send this encrypted message to someone (or keep it for yourself), and nobody will be able to read it unless you tell them the secret encryption key. Be sure to keep the encryption key a secret; the ciphertext can be read by anyone who knows that the message was encrypted with key 8.
Decrypting with the Cipher Wheel
To decrypt a ciphertext, start from the inner circle of the cipher wheel and then move to the outer circle. For example, let’s say you receive the ciphertext IWT CTL EPHHLDGS XH HLDGSUXHW. You wouldn’t be able to decrypt the message unless you knew the key (or unless you were a clever hacker). Luckily, your friend has already told you that they use the key 15 for their messages. The cipher wheel for this key is shown in Figure 1-3.
Figure 1-3: A cipher wheel set to key 15
Now you can line up the letter A on the outer circle (the one with the dot below it) over the letter on the inner circle that has the number 15 (which is the letter P). Then, find the first letter in the secret message on the inner circle, which is I, and look at the corresponding letter on the outer circle, which is T. The second letter in the ciphertext, W, decrypts to the letter H. Decrypt the rest of the letters in the ciphertext back to the plaintext, and you’ll get the message THE NEW PASSWORD IS SWORDFISH, as shown in Figure 1-4.
Figure 1-4: Decrypting a message with a Caesar cipher key of 15
If you used an incorrect key, like 16, the decrypted message would be SGD MDV OZRRVNQC HR RVNQCEHRG, which is unreadable. Unless the correct key is used, the decrypted message won’t be understandable.
Encrypting and Decrypting with Arithmetic
The cipher wheel is a convenient tool for encrypting and decrypting with the Caesar cipher, but you can also encrypt and decrypt using arithmetic. To do so, write the letters of the alphabet from A to Z with the numbers from 0 to 25 under each letter. Begin with 0 under the A, 1 under the B, and so on until 25 is under the Z. Figure 1-5 shows what it should look like.
Figure 1-5: Numbering the alphabet from 0 to 25
You can use this letters-to-numbers code to represent letters. This is a powerful concept, because it allows you to do math on letters. For example, if you represent the letters CAT as the numbers 2, 0, and 19, you can add 3 to get the numbers 5, 3, and 22. These new numbers represent the letters FDW, as shown in Figure 1-5. You have just added
3 to the word cat! Later, we’ll be able to program a computer to do this math for us.
To use arithmetic to encrypt with the Caesar cipher, find the number under the letter you want to encrypt and add the key number to it. The resulting sum is the number under the encrypted letter. For example, let’s encrypt HELLO. HOW ARE YOU? using the key 13. (You can use any number from 1 to 25 for the key.) First, find the number under H, which is 7. Then add 13 to this number: 7 + 13 = 20. Because the number 20 is under the letter U, the letter H encrypts to U.
Similarly, to encrypt the letter E (4), add 4 + 13 = 17. The number above 17 is R, so E gets encrypted to R, and so on.
This process works fine until the letter O. The number under O is 14. But 14 plus 13 is 27, and the list of numbers only goes up to 25. If the sum of the letter’s number and the key is 26 or more, you need to subtract 26 from it. In this case, 27 – 26 = 1. The letter above the number 1 is B, so O encrypts to B using the key 13. When you encrypt each letter in the message, the ciphertext will be URYYB. UBJ NER LBH?
To decrypt the ciphertext, subtract the key instead of adding it. The number of the ciphertext letter B is 1. Subtract 13 from 1 to get –12. Like our subtract 26
rule for encrypting, when the result is less than 0 when decrypting, we need to add 26. Because –12 + 26 = 14, the ciphertext letter B decrypts to O.
NOTE
If you don’t know how to add and subtract with negative numbers, you can read about it at https://www.nostarch.com/crackingcodes/.
As you can see, you don’t need a cipher wheel to use the Caesar cipher. All you need is a pencil, a piece of paper, and some simple arithmetic!
Why Double Encryption Doesn’t Work
You might think encrypting a message twice using two different keys would double the strength of the encryption. But this isn’t the case with the Caesar cipher (and most other ciphers). In fact, the result of double encryption is the same as what you would get after one normal encryption. Let’s try double encrypting a message to see why.
For example, if you encrypt the word KITTEN using the key 3, you’re adding 3 to the plaintext letter’s number, and the resulting ciphertext would be NLWWHQ. If you then encrypt NLWWHQ, this time using the key 4, the resulting ciphertext would be RPAALU because you’re adding 4 to the plaintext letter’s number. But this is the same as encrypting the word KITTEN once with a key of 7.
For most ciphers, encrypting more than once doesn’t provide additional strength. In fact, if you encrypt some plaintext with two keys that add up to 26, the resulting ciphertext will be the same as the original plaintext!
Summary
The Caesar cipher and other ciphers like it were used to encrypt secret information for several centuries. But if you wanted to encrypt a long message—say, an entire book—it could take days or weeks to encrypt it all by hand. This is where programming can help. A computer can encrypt and decrypt a large amount of text in less than a second!
To use a computer for encryption, you need to learn how to program, or instruct, the computer to do the same steps we just did using a language the computer can understand. Fortunately, learning a programming language like Python isn’t nearly as difficult as learning a foreign language like Japanese or Spanish. You also don’t need to know much math besides addition, subtraction, and multiplication. All you need is a computer and this book!
Let’s move on to Chapter 2, where we’ll learn how to use Python’s interactive shell to explore code one line at a time.
PRACTICE QUESTIONS
Answers to the practice questions can be found on the book’s website at https://www.nostarch.com/crackingcodes/.
Encrypt the following entries from Ambrose Bierce’s The Devil’s Dictionary with the given keys:
With key 4: AMBIDEXTROUS: Able to pick with equal skill a right-hand pocket or a left.
With key 17: GUILLOTINE: A machine which makes a Frenchman shrug his shoulders with good reason.
With key 21: IMPIETY: Your irreverence toward my deity.
Decrypt the following ciphertexts with the given keys:
With key 15: ZXAI: P RDHIJBT HDBTIXBTH LDGC QN HRDIRWBTC XC PBTGXRP PCS PBTGXRPCH XC HRDIAPCS.
With key 4: MQTSWXSV: E VMZEP EWTMVERX XS TYFPMG LSRSVW.
Encrypt the following sentence with the key 0: This is a silly example.
Here are some words and their encryptions. Which key was used for each word?
ROSEBUD – LIMYVOX
YAMAMOTO – PRDRDFKF
ASTRONOMY – HZAYVUVTF
What does this sentence encrypted with key 8 decrypt to with key 9? UMMSVMAA: Cvkwuuwv xibqmvkm qv xtivvqvo i zmdmvom bpib qa ewzbp epqtm.
2
PROGRAMMING IN THE INTERACTIVE SHELL
The Analytical Engine has no pretensions whatever to originate anything. It can do whatever we know how to order it to perform.
—Ada Lovelace, October 1842
Before you can write encryption programs, you need to learn some basic programming concepts. These concepts include values, operators, expressions, and variables.
TOPICS COVERED IN THIS CHAPTER
Operators
Values
Integers and floating-point numbers
Expressions
Evaluating expressions
Storing values in variables
Overwriting variables
Let’s start by exploring how to do some simple math in Python’s interactive shell. Be sure to read this book next to your computer so you can enter the short code examples and see what they do. Developing muscle memory from typing programs will help you remember how Python code is constructed.
Some Simple Math Expressions
Start by opening IDLE (see "Starting IDLE" on page xxvii). You’ll see the interactive shell and the cursor blinking next to the >>> prompt. The interactive shell can work just like a calculator. Type 2 + 2 into the shell and press enter on your keyboard. (On some keyboards, this is the return key.) The computer should respond by displaying the number 4, as shown in Figure 2-1.
Figure 2-1: Type 2 + 2 into the shell.
In the example in Figure 2-1, the + sign tells the computer to add the numbers 2 and 2, but Python can do other calculations as well, such as subtract numbers using the minus sign (–), multiply numbers with an asterisk (*), or divide numbers with a forward slash (/). When used in this way, +, -, *, and / are called operators because they tell the computer to perform an operation on the numbers surrounding them. Table 2-1 summarizes the Python math operators. The 2s (or other numbers) are called values.
Table 2-1: Math Operators in Python
By itself, 2 + 2 isn’t a program; it’s just a single instruction. Programs are made of many of these instructions.
Integers and Floating-Point Values
In programming, whole numbers, such as 4, 0, and 99, are called integers. Numbers with decimal points (3.5, 42.1, and 5.0) are called floating-point numbers. In Python, the number 5 is an integer, but if you wrote it as 5.0, it would be a floating-point number.
Integers and floating points are data types. The value 42 is a value of the integer, or int, data type. The value 7.5 is a value of the floating point, or float, data type.
Every value has a data type. You’ll learn about a few other data types (such as strings in Chapter 3), but for now just remember that any time we talk about a value, that value is of a certain data type. It’s usually easy to identify the data type just by looking at how the value is written. Ints are numbers without decimal points. Floats are numbers with decimal points. So 42 is an int, but 42.0 is a float.
Expressions
You’ve already seen Python solve one math problem, but Python can do a lot more. Try typing the following math problems into the shell, pressing the enter key after each one:
➊ >>> 2+2+2+2+2
10
>>> 8*6
48
➋ >>> 10-5+6
11
➌ >>> 2 + 2
4
Figure 2-2: An expression is made up of values (like 2) and operators (like +).
These math problems are called expressions. Computers can solve millions of these problems in seconds. Expressions are made up of values (the numbers) connected by operators (the math signs), as shown in Figure 2-2. You can have as many numbers in an expression as you want ➊, as long as they’re connected by operators; you can even use multiple types of operators in a single expression ➋. You can also enter any number of spaces between the integers and these operators ➌. But be sure to always start an expression at the beginning of the line, with no spaces in front, because spaces at the beginning of a line change how Python interprets instructions. You’ll learn more about spaces at the beginning of a line in Blocks
on page 45.
Order of Operations
You might remember the phrase order of operations
from your math class. For example, multiplication is done before addition. The expression 2 + 4 * 3 evaluates to 14 because multiplication is done first to evaluate 4 * 3, and then 2 is added. Parentheses can make different operators go first. In the expression (2 + 4) * 3, the addition is done first to evaluate (2 + 4), and then that sum is multiplied by 3. The parentheses make the expression evaluate to 18 instead of 14. The order of operations (also called precedence) of Python math operators is similar to that of mathematics. Operations inside parentheses are evaluated first; next the * and / operators are evaluated from left to right; and then the + and - operators are evaluated from left to right.
Evaluating Expressions
When a computer solves the expression 10 + 5 and gets the value 15, we say it has evaluated the expression. Evaluating an expression reduces the expression to a single value, just like solving a math problem