Learn how to program in Python while making and breaking ciphers—algorithms used to create and send secret messages! 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 Vigenere 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!
Author(s): Al Sweigart
Publisher: No Starch Press
Year: 2018
Language: English
Pages: 418
Tags: Programming, Python, Cracking Codes, Breaking Ciphers
Brief Contents......Page 8
Contents in Detail
......Page 10
Acknowledgments......Page 20
Introduction......Page 22
Who Should Read This Book?......Page 23
What’s in This Book?......Page 24
Typing Source Code......Page 25
Downloading and Installing Python......Page 26
Downloading pyperclip.py......Page 27
Starting IDLE......Page 28
Summary......Page 29
Chapter 1: Making Paper
Cryptography Tools......Page 30
What Is Cryptography?......Page 31
Codes vs. Ciphers......Page 32
The Cipher Wheel......Page 33
Encrypting with the Cipher Wheel......Page 34
Decrypting with the Cipher Wheel......Page 35
Encrypting and Decrypting with Arithmetic......Page 36
Summary......Page 37
Practice Questions
......Page 38
Chapter 2: Programming in the Interactive Shell
......Page 40
Some Simple Math Expressions......Page 41
Expressions......Page 42
Evaluating Expressions......Page 43
Storing Values with Variables......Page 44
Overwriting Variables......Page 46
Summary......Page 47
Practice Questions
......Page 48
Chapter 3: Strings and Writing Programs
......Page 50
Working with Text Using String Values......Page 51
String Concatenation with the + Operator......Page 52
Getting Characters from Strings Using Indexes......Page 53
Printing Values with the print() Function......Page 56
Printing Escape Characters......Page 57
Quotes and Double Quotes......Page 58
Writing Programs in IDLE’s File Editor......Page 59
Checking Your Source Code with the Online Diff Tool......Page 60
Saving Your Program......Page 61
Running Your Program......Page 62
Printing Directions to the User......Page 63
Ending the Program......Page 64
Summary......Page 65
Practice Questions
......Page 66
Chapter 4: The Reverse Cipher
......Page 68
Sample Run of the Reverse Cipher Program......Page 69
Finding the Length of a String......Page 70
Introducing the while Loop......Page 71
Comparison Operators......Page 72
Blocks......Page 74
The while Loop Statement......Page 75
“Growing” a String......Page 76
Summary......Page 79
Practice Questions
......Page 80
Chapter 5: The Caesar Cipher
......Page 82
Source Code for the Caesar Cipher Program......Page 83
Sample Run of the Caesar Cipher Program......Page 84
Importing Modules and Setting Up Variables......Page 85
Constants and Variables......Page 86
An Example for Loop......Page 87
The if Statement......Page 88
The else Statement......Page 89
The in and not in Operators......Page 90
The find() String Method......Page 91
Encrypting and Decrypting Symbols......Page 92
Handling Wraparound......Page 93
Displaying and Copying the Translated String......Page 94
Summary......Page 95
Practice Questions......Page 96
Chapter 6: Hacking the Caesar Cipher with Brute-Force
......Page 98
Source Code for the Caesar Cipher Hacker Program......Page 99
Sample Run of the Caesar Cipher Hacker Program......Page 100
Looping with the range() Function......Page 101
Decrypting the Message......Page 102
Using String Formatting to Display the Key and Decrypted Messages......Page 104
Practice Question
......Page 105
Chapter 7: Encrypting with the Transposition Cipher
......Page 106
How the Transposition Cipher Works......Page 107
Encrypting a Message by Hand......Page 108
Creating the Encryption Program......Page 109
Source Code for the Transposition Cipher Encryption Program......Page 110
Creating Your Own Functions with def Statements......Page 111
Defining a Function that Takes Arguments with Parameters......Page 112
Changes to Parameters Only Exist Inside the Function......Page 113
Defining the main() Function......Page 114
The List Data Type......Page 115
Reassigning the Items in Lists......Page 116
Lists of Lists......Page 117
List Concatenation and Replication with the + and * Operators......Page 118
The Transposition Encryption Algorithm......Page 119
Augmented Assignment Operators......Page 120
Moving currentIndex Through the Message......Page 121
The join() String Method......Page 122
A return Statement Example......Page 123
The __name__ Variable......Page 124
Summary......Page 125
Practice Questions
......Page 126
Chapter 8: Decrypting with the Transposition Cipher
......Page 128
How to Decrypt with the Transposition Cipher on Paper......Page 129
Source Code for the Transposition Cipher Decryption Program......Page 130
Importing Modules and Setting Up the main() Function......Page 131
The round(), math.ceil(), and math.floor() Functions......Page 132
The decryptMessage() Function......Page 133
Boolean Operators......Page 135
Adjusting the column and row Variables......Page 138
Summary......Page 139
Practice Questions
......Page 140
Chapter 9: Programming a Program to Test Your Program
......Page 142
Source Code for the Transposition Cipher Tester Program......Page 143
Sample Run of the Transposition Cipher Tester Program......Page 144
Creating Pseudorandom Numbers......Page 145
Duplicating a String a Random Number of Times......Page 147
List Variables Use References......Page 148
Passing References......Page 150
The random.shuffle() Function......Page 151
Testing Each Message......Page 152
Calling the main() Function......Page 153
Summary......Page 154
Practice Questions
......Page 155
Chapter 10: Encrypting and Decrypting Files
......Page 156
Source Code for the Transposition File Cipher Program......Page 157
Working with Files......Page 159
Writing to and Closing Files......Page 160
Setting Up the main() Function......Page 161
The os.path.exists() Function......Page 162
The upper(), lower(), and title() String Methods......Page 163
Using These String Methods in the Program......Page 164
The time Module and time.time() Function......Page 165
Writing the Output File......Page 166
Summary......Page 167
Practice Questions
......Page 168
Chapter 11: Detecting English Programmatically
......Page 170
How Can a Computer Understand English?......Page 171
Source Code for the Detect English Module......Page 172
Instructions and Setting Up Constants......Page 174
The Dictionary Data Type......Page 175
Adding or Changing Items in a Dictionary......Page 176
Using the in Operator with Dictionaries......Page 177
Using for Loops with Dictionaries......Page 178
The split() Method......Page 179
Returning the Dictionary Data......Page 180
Divide-by-Zero Errors......Page 181
Counting the English Word Matches......Page 182
Finding the Ratio of English Words in the Message......Page 183
The append() List Method......Page 184
Detecting English Words......Page 185
Calculating Percentages......Page 186
Summary......Page 188
Practice Questions
......Page 189
Chapter 12: Hacking the
Transposition Cipher
......Page 190
Source Code of the Transposition Cipher Hacker Program......Page 191
Sample Run of the Transposition Cipher Hacker Program......Page 192
Multiline Strings with Triple Quotes......Page 193
Displaying the Results of Hacking the Message......Page 194
Getting the Hacked Message......Page 195
The strip() String Method......Page 196
Failing to Hack the Message......Page 197
Practice Questions
......Page 198
Chapter 13: A Modular Arithmetic Module for the Affine Cipher
......Page 200
Modular Arithmetic......Page 201
Finding Factors to Calculate the Greatest Common Divisor......Page 202
Multiple Assignment......Page 204
Euclid’s Algorithm for Finding the GCD......Page 205
Understanding How the Multiplicative and
Affine Ciphers Work......Page 206
Choosing Valid Multiplicative Keys......Page 207
Decrypting with the Affine Cipher......Page 208
The Integer Division Operator......Page 210
Source Code for the Cryptomath Module......Page 211
Practice Questions
......Page 212
Chapter 14: Programming the Affine Cipher
......Page 214
Source Code for the Affine Cipher Program......Page 215
Setting Up Modules, Constants, and the main() Function......Page 217
Calculating and Validating the Keys......Page 218
Checking for Weak Keys......Page 219
How Many Keys Can the Affine Cipher Have?......Page 220
Writing the Encryption Function......Page 222
Writing the Decryption Function......Page 223
Generating Random Keys......Page 224
Practice Questions
......Page 225
Chapter 15: Hacking the Affine Cipher
......Page 226
Source Code for the Affine Cipher Hacker Program......Page 227
Sample Run of the Affine Cipher Hacker Program......Page 228
Setting Up Modules, Constants, and the main() Function......Page 229
Calculating the Total Number of Possible Keys......Page 230
The continue Statement......Page 231
Using continue to Skip Code......Page 232
Calling the main() Function......Page 233
Practice Questions
......Page 234
Chapter 16: Programming the Simple Substitution Cipher
......Page 236
How the Simple Substitution Cipher Works......Page 237
Source Code for the Simple Substitution Cipher Program......Page 238
Sample Run of the Simple Substitution Cipher Program......Page 239
Setting Up Modules, Constants, and the main() Function......Page 240
The sort() List Method......Page 241
Wrapper Functions......Page 242
The translateMessage() Function......Page 244
The isupper() and islower() String Methods......Page 245
Preserving Cases with isupper()......Page 246
Generating a Random Key......Page 247
Practice Questions
......Page 248
Chapter 17: Hacking the Simple Substitution Cipher
......Page 250
Finding Word Patterns......Page 251
Finding Potential Decryption Letters......Page 252
The Word Pattern Modules......Page 254
Source Code for the Simple Substitution Hacking Program......Page 255
Sample Run of the Simple Substitution Hacking Program......Page 258
Finding Characters with Regular Expressions......Page 259
Setting Up the main() Function......Page 260
Creating a Blank Mapping......Page 261
Adding Letters to a Mapping......Page 262
Intersecting Two Mappings......Page 263
How the Letter-Mapping Helper Functions Work......Page 264
Identifying Solved Letters in Mappings......Page 267
Testing the removeSolvedLetterFromMapping() Function......Page 269
The hackSimpleSub() Function......Page 270
Decrypting the Message......Page 272
Decrypting in the Interactive Shell......Page 273
Calling the main() Function......Page 274
Practice Questions
......Page 275
Chapter 18: Programming
the Vigenère Cipher
......Page 276
Using Multiple Letter Keys in the Vigenère Cipher......Page 277
Longer Vigenère Keys Are More Secure......Page 278
Choosing a Key That Prevents Dictionary Attacks......Page 279
Source Code for the Vigenère Cipher Program......Page 280
Setting Up Modules, Constants, and the main() Function......Page 281
Building Strings with the List-Append-Join Process......Page 282
Encrypting and Decrypting the Message......Page 284
Summary......Page 286
Practice Questions
......Page 287
Chapter 19: Frequency Analysis
......Page 288
Analyzing the Frequency of Letters in Text......Page 289
Calculating the Frequency Match Score for the Simple Substitution Cipher......Page 291
Calculating the Frequency Match Score for the Transposition Cipher......Page 292
Using Frequency Analysis on the Vigenère Cipher......Page 293
Source Code for Matching Letter Frequencies......Page 294
Storing the Letters in ETAOIN Order......Page 295
Counting the Letters in a Message......Page 296
Ordering the Letters in the Message by Frequency......Page 297
Creating a Dictionary of Frequency Counts and Letter Lists......Page 298
Sorting the Letter Lists in Reverse ETAOIN Order......Page 299
Sorting the Dictionary Lists by Frequency......Page 303
Calculating the Frequency Match Score of the Message......Page 305
Summary......Page 306
Practice Questions
......Page 307
Chapter 20: Hacking the Vigenère Cipher
......Page 308
Source Code for the Vigenère Dictionary Hacker Program......Page 309
About the Vigenère Dictionary Hacker Program......Page 310
Finding Repeated Sequences......Page 311
Getting Factors of Spacings......Page 312
Getting Every Nth Letters from a String......Page 313
Using Frequency Analysis to Break Each Subkey......Page 314
Source Code for the Vigenère Hacking Program......Page 316
Sample Run of the Vigenère Hacking Program......Page 322
Finding Repeated Sequences......Page 323
Calculating the Factors of the Spacings......Page 326
Finding the Most Common Factors......Page 327
Finding the Most Likely Key Lengths......Page 329
Extending the repeatedSeqSpacings Dictionary......Page 330
Getting Letters Encrypted with the Same Subkey......Page 331
Attempting Decryption with a Likely Key Length......Page 332
Finding Possible Combinations of Subkeys......Page 335
Printing the Decrypted Text with the Correct Casing......Page 339
Breaking Out of the Loop When a Potential Key Is Found......Page 340
Brute-Forcing All Other Key Lengths......Page 341
Modifying the Constants of the Hacking Program......Page 342
Practice Questions
......Page 343
Chapter 21: The One-Time Pad Cipher
......Page 344
Making Key Length Equal Message Length......Page 345
Making the Key Truly Random......Page 347
Why the Two-Time Pad Is the Vigenère Cipher......Page 348
Practice Questions
......Page 349
Chapter 22: Finding and Generating Prime Numbers
......Page 350
What Is a Prime Number?......Page 351
Source Code for the Prime Numbers Module......Page 353
How the Trial Division Algorithm Works......Page 355
The Sieve of Eratosthenes......Page 357
Generating Prime Numbers with the Sieve of Eratosthenes......Page 359
The Rabin-Miller Primality Algorithm......Page 360
Finding Large Prime Numbers......Page 361
Generating Large Prime Numbers......Page 362
Practice Questions
......Page 363
Chapter 23: Generating Keys for the Public Key Cipher
......Page 364
Public Key Cryptography......Page 365
The Problem with Authentication......Page 366
Digital Signatures......Page 367
Beware the MITM Attack......Page 368
Source Code for the Public Key Generation Program......Page 369
Sample Run of the Public Key Generation Program......Page 371
Generating Keys with the generateKey() Function......Page 372
Calculating a d Value......Page 373
Creating Key Files with the makeKeyFiles() Function......Page 374
Hybrid Cryptosystems......Page 376
Practice Questions
......Page 377
Chapter 24: Programming the Public Key Cipher
......Page 378
Converting a String into a Block......Page 379
The Mathematics of Public Key Cipher Encryption and Decryption......Page 382
Converting a Block to a String......Page 383
Why We Can’t Hack the Public Key Cipher......Page 384
Source Code for the Public Key Cipher Program......Page 386
Sample Run of the Public Key Cipher Program......Page 389
How the Program Determines Whether to Encrypt or Decrypt......Page 391
Converting Strings to Blocks with getBlocksFromText()......Page 392
Storing Blocks in blockInt......Page 393
Using getTextFromBlocks() to Decrypt......Page 395
Writing the encryptMessage() Function......Page 396
Writing the decryptMessage() Function......Page 397
Writing the Encryption to a File......Page 398
Decrypting from a File......Page 400
Summary......Page 402
How the Debugger Works......Page 404
Debugging the Reverse Cipher Program......Page 406
Setting Breakpoints......Page 408
Summary......Page 409
Index
......Page 410