Cracking Codes with Python: An Introduction to Building and Breaking Ciphers
The Electronic Frontier Foundation a young digital civil liberties orga nization 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 vio lated 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 pre dictions 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 compu tational 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 no t e 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 lan guage 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 power ful language used by professional software developers Python runs on Windows macOS Linux and even the Raspberry Pi and it’s free to down load 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 defini tions 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 xxii Introduction
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 chap ter 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 pro gram for your first cipher Chapter 5 The Caesar Cipher covers a basic cipher first invented thou sands 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 sec ond 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 pro gram to hack the affine cipher Introduction xxiii
Chapter 16 Programming the Simple Substitution Cipher covers writ ing 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 hack ing 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 pub lic 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 xxiv Introduction
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 thor oughly but because there is always more to learn I’ve also included sugges tions 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 inter preter 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 no t e 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 Introduction xxv