Docsity

Hackin_code_with_python, Transcriptions of Computer Security

Toggle sidebar
bg1
CRACKING CODES
WITH PYTHON
CRACKING CODES
WITH PYTHON
AN INTRODUCTION TO
BUILDING AND BREAKING CIPHERS
AL SWEIGART
SECRET CIPHERS
BY HACKING
LEARN PYTHON
SECRET CIPHERS
BY HACKING
LEARN PYTHON
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 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!
ABOUT THE AUTHOR
Al Sweigart is a professional software developer
who teaches programming to kids and adults. He is
the author of Automate the Boring Stuff with Python,
Invent Your Own Computer Games with Python,
and Scratch Pro gramming Pl ayground, also from
No Starch Press. His programming tutorials can
be found at inventwithpython.com.
ww w.n os tar ch .co m
TH E FINE ST IN GEEK E NT ERTA I N M E N T ™
“I L IE F LAT .”
Thi s book uses a durable binding t hat won ’t sn ap shut.
FSC F PO
SHELVE IN: PROGRAMMING
LANGUAGES/PYTHON
$29.95 ($39.95 CDN)
COVERS
PYTHON 3
CRACKING CODES WITH PYTHON
CRACKING CODES WITH PYTHON SWEIGART
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download Hackin_code_with_python and more Transcriptions Computer Security in PDF only on Docsity!

C R A C K I N G C O D E S

W I T H P Y T H O N

C R A C K I N G C O D E S

W I T H P Y T H O N

A N I N T R O D U C T I O N T O

B U I L D I N G A N D B R E A K I N G C I P H E R S

A L S W E I G A R T

C r a C k i n g

C o d e s w i t h

P y t h o n

a n i n t r o d u c t i o n t o B u i l d i n g

a n d B r e a k i n g C i p h e r s

by Al Sweigart

San Francisco

Dedicated to Aaron Swartz, 1986–

“Aaron was part of an army of citizens that believes democracy only

works when the citizenry are informed, when we know about our rights—and our obligations. An army that believes we must make justice and knowledge available to all—not just the well born or those that have grabbed the reins of power—so that we may govern

ourselves more wisely. When I see our army, I see Aaron Swartz and

my heart is broken. We have truly lost one of our better angels.” —Carl Malamud

about the author

Al Sweigart is a software developer and tech book author living in San

Francisco. Python is his favorite programming language, and he is the

developer of several open source modules for it. His other books are

freely available under a Creative Commons license on his website https://

inventwithpython.com/. His cat weighs 12 pounds.

about the technical reviewers

Ari Lacenski creates mobile apps and Python software. She lives in Seattle.

Jean-Philippe Aumasson (Chapters 22–24) is Principal Research Engineer at

Kudelski Security, Switzerland. He speaks regularly at information security

conferences such as Black Hat, DEF CON, Troopers, and Infiltrate. He is

the author of Serious Cryptography (No Starch Press, 2017).

C o n t e n t s i n d e t a i l

aCknowledgments xix

introduCtion xxi

Who Should Read This Book? xxii What’s in This Book? xxiii How to Use This Book xxiv Typing Source Code xxiv Checking for Typos xxv Coding Conventions in This Book xxv Online Resources xxv Downloading and Installing Python xxv Windows Instructions xxvi macOS Instructions xxvi Ubuntu Instructions xxvi Downloading pyperclip py xxvi Starting IDLE xxvii Summary xxviii

making PaPer CryPtograPhy tools 1

What Is Cryptography? 2 Codes vs Ciphers 3 The Caesar Cipher 4 The Cipher Wheel 4 Encrypting with the Cipher Wheel 5 Decrypting with the Cipher Wheel 6 Encrypting and Decrypting with Arithmetic 7 Why Double Encryption Doesn’t Work 8 Summary 8 Practice Questions 9

Programming in the interaCtive shell 11

Some Simple Math Expressions 12 Integers and Floating-Point Values 13 Expressions 13 Order of Operations 14 Evaluating Expressions 14 Storing Values with Variables 15 Overwriting Variables 17 Variable Names 18 Summary 18 Practice Questions 19

xii Contents in Detail

Contents in Detail xv

  • Chapter 1: Making Paper Cryptography Tools Introduction xxi
  • Chapter 2: Programming in the Interactive Shell
  • Chapter 3: Strings and Writing Programs
  • Chapter 4: The Reverse Cipher
  • Chapter 5: The Caesar Cipher
  • Chapter 6: Hacking the Caesar Cipher with Brute-Force
  • Chapter 7: Encrypting with the Transposition Cipher
  • Chapter 8: Decrypting with the Transposition Cipher
  • Chapter 9: Programming a Program to Test Your Program
  • Chapter 10: Encrypting and Decrypting Files
  • Chapter 11: Detecting English Programmatically
  • Chapter 12: Hacking the Transposition Cipher
  • Chapter 13: A Modular Arithmetic Module for the Affine Cipher
  • Chapter 14: Programming the Affine Cipher
  • Chapter 15: Hacking the Affine Cipher
  • Chapter 16: Programming the Simple Substitution Cipher
  • Chapter 17: Hacking the Simple Substitution Cipher
  • Chapter 18: Programming the Vigenère Cipher
  • Chapter 19: Frequency Analysis
  • Chapter 20: Hacking the Vigenère Cipher
  • Chapter 21: The One-Time Pad Cipher viii Brief Contents
  • Chapter 22: Finding and Generating Prime Numbers
  • Chapter 23: Generating Keys for the Public Key Cipher
  • Chapter 24: Programming the Public Key Cipher
  • Appendix: Debugging Python Code
  • Index
  • strings and writing Programs
  • Working with Text Using String Values
  • String Concatenation with the + Operator
  • String Replication with the * Operator
  • Getting Characters from Strings Using Indexes
  • Printing Values with the print() Function
  • Printing Escape Characters
  • Quotes and Double Quotes
  • Writing Programs in IDLE’s File Editor
  • Source Code for the “Hello, World!” Program
  • Checking Your Source Code with the Online Diff Tool
  • Using IDLE to Access Your Program Later
  • Saving Your Program
  • Running Your Program
  • Opening the Programs You’ve Saved
  • How the “Hello, World!” Program Works
  • Comments
  • Printing Directions to the User
  • Taking a User’s Input
  • Ending the Program
  • Summary
  • Practice Questions
  • the reverse CiPher
  • Source Code for the Reverse Cipher Program
  • Sample Run of the Reverse Cipher Program
  • Setting Up Comments and Variables
  • Finding the Length of a String
  • Introducing the while Loop
  • The Boolean Data Type
  • Comparison Operators
  • Blocks
  • The while Loop Statement
  • “Growing” a String
  • Improving the Program with an input() Prompt
  • Summary
  • Practice Questions
  • the Caesar CiPher
  • Source Code for the Caesar Cipher Program
  • Sample Run of the Caesar Cipher Program
  • Importing Modules and Setting Up Variables
  • Constants and Variables
  • The for Loop Statement
  • An Example for Loop
  • A while Loop Equivalent of a for Loop
  • The if Statement Contents in Detail xi
  • An Example if Statement
  • The else Statement
  • The elif Statement
  • The in and not in Operators
  • The find() String Method
  • Encrypting and Decrypting Symbols
  • Handling Wraparound
  • Handling Symbols Outside of the Symbol Set
  • Displaying and Copying the Translated String
  • Encrypting Other Symbols
  • Summary
  • Practice Questions
  • haCking the Caesar CiPher with Brute-ForCe
  • Source Code for the Caesar Cipher Hacker Program
  • Sample Run of the Caesar Cipher Hacker Program
  • Setting Up Variables
  • Looping with the range() Function
  • Decrypting the Message
  • Using String Formatting to Display the Key and Decrypted Messages
  • Summary
  • Practice Question
  • enCryPting with the transPosition CiPher
  • How the Transposition Cipher Works
  • Encrypting a Message by Hand
  • Creating the Encryption Program
  • Source Code for the Transposition Cipher Encryption Program
  • Sample Run of the Transposition Cipher Encryption Program
  • Creating Your Own Functions with def Statements
  • Defining a Function that Takes Arguments with Parameters
  • Changes to Parameters Exist Only Inside the Function
  • Defining the main() Function
  • Passing the Key and Message As Arguments
  • The List Data Type
  • Reassigning the Items in Lists
  • Lists of Lists
  • Using len() and the in Operator with Lists
  • List Concatenation and Replication with the + and * Operators
  • The Transposition Encryption Algorithm
  • Augmented Assignment Operators
  • Moving currentIndex Through the Message
  • The join() String Method
  • Return Values and return Statements
  • A return Statement Example
  • Returning the Encrypted Ciphertext
  • The name Variable
  • Summary
  • Practice Questions
  • deCryPting with the transPosition CiPher
  • How to Decrypt with the Transposition Cipher on Paper
  • Source Code for the Transposition Cipher Decryption Program
  • Sample Run of the Transposition Cipher Decryption Program
  • Importing Modules and Setting Up the main() Function
  • Decrypting the Message with the Key
  • The round(), math ceil(), and math floor() Functions
  • The decryptMessage() Function
  • Boolean Operators
  • Adjusting the column and row Variables
  • Calling the main() Function
  • Summary
  • Practice Questions
  • Programming a Program to test your Program
  • Source Code for the Transposition Cipher Tester Program
  • Sample Run of the Transposition Cipher Tester Program
  • Importing the Modules
  • Creating Pseudorandom Numbers
  • Creating a Random String
  • Duplicating a String a Random Number of Times
  • List Variables Use References
  • Passing References
  • Using copy deepcopy() to Duplicate a List
  • The random shuffle() Function
  • Randomly Scrambling a String
  • Testing Each Message
  • Checking Whether the Cipher Worked and Ending the Program
  • Calling the main() Function
  • Testing the Test Program
  • Summary
  • Practice Questions
  • enCryPting and deCryPting Files
  • Plain Text Files
  • Source Code for the Transposition File Cipher Program
  • Sample Run of the Transposition File Cipher Program
  • Working with Files
  • Opening Files
  • Writing to and Closing Files
  • Reading from a File
  • Setting Up the main() Function
  • Checking Whether a File Exists
  • The os path exists() Function
  • Checking Whether the Input File Exists with the os path exists() Function
  • Using String Methods to Make User Input More Flexible
  • The upper(), lower(), and title() String Methods
  • The startswith() and endswith() String Methods
  • Using These String Methods in the Program
  • Reading the Input File Contents in Detail xiii
  • Measuring the Time It Took to Encrypt or Decrypt
  • The time Module and time time() Function
  • Using the time time() Function in the Program
  • Writing the Output File
  • Calling the main() Function
  • Summary
  • Practice Questions
  • deteCting english ProgrammatiCally
  • How Can a Computer Understand English?
  • Source Code for the Detect English Module
  • Sample Run of the Detect English Module
  • Instructions and Setting Up Constants
  • The Dictionary Data Type
  • The Difference Between Dictionaries and Lists
  • Adding or Changing Items in a Dictionary
  • Using the len() Function with Dictionaries
  • Using the in Operator with Dictionaries
  • Finding Items Is Faster with Dictionaries than with Lists
  • Using for Loops with Dictionaries
  • Implementing the Dictionary File
  • The split() Method
  • Splitting the Dictionary File into Individual Words
  • Returning the Dictionary Data
  • Counting the Number of English Words in message
  • Divide-by-Zero Errors
  • Counting the English Word Matches
  • The float(), int(), and str() Functions and Integer Division
  • Finding the Ratio of English Words in the Message
  • Removing Non-Letter Characters
  • The append() List Method
  • Creating a String of Letters
  • Detecting English Words
  • Using Default Arguments
  • Calculating Percentages
  • Summary
  • Practice Questions
  • haCking the transPosition CiPher
  • Source Code of the Transposition Cipher Hacker Program
  • Sample Run of the Transposition Cipher Hacker Program
  • Importing the Modules
  • Multiline Strings with Triple Quotes
  • Displaying the Results of Hacking the Message
  • Getting the Hacked Message
  • The strip() String Method
  • Applying the strip() String Method
  • Failing to Hack the Message
  • Calling the main() Function xiv Contents in Detail
  • Summary
  • Practice Questions
  • a modular arithmetiC module For the aFFine CiPher
  • Modular Arithmetic
  • The Modulo Operator
  • Finding Factors to Calculate the Greatest Common Divisor
  • Multiple Assignment
  • Euclid’s Algorithm for Finding the GCD
  • Understanding How the Multiplicative and Affine Ciphers Work
  • Choosing Valid Multiplicative Keys
  • Encrypting with the Affine Cipher
  • Decrypting with the Affine Cipher
  • Finding Modular Inverses
  • The Integer Division Operator
  • Source Code for the Cryptomath Module
  • Summary
  • Practice Questions
  • Programming the aFFine CiPher
  • Source Code for the Affine Cipher Program
  • Sample Run of the Affine Cipher Program
  • Setting Up Modules, Constants, and the main() Function
  • Calculating and Validating the Keys
  • The Tuple Data Type
  • Checking for Weak Keys
  • How Many Keys Can the Affine Cipher Have?
  • Writing the Encryption Function
  • Writing the Decryption Function
  • Generating Random Keys
  • Calling the main() Function
  • Summary
  • Practice Questions
  • haCking the aFFine CiPher
  • Source Code for the Affine Cipher Hacker Program
  • Sample Run of the Affine Cipher Hacker Program
  • Setting Up Modules, Constants, and the main() Function
  • The Affine Cipher Hacking Function
  • The Exponent Operator
  • Calculating the Total Number of Possible Keys
  • The continue Statement
  • Using continue to Skip Code
  • Calling the main() Function
  • Summary
  • Practice Questions
  • Programming the simPle suBstitution CiPher
  • How the Simple Substitution Cipher Works
  • Source Code for the Simple Substitution Cipher Program
  • Sample Run of the Simple Substitution Cipher Program
  • Setting Up Modules, Constants, and the main() Function
  • The sort() List Method
  • Wrapper Functions
  • The translateMessage() Function
  • The isupper() and islower() String Methods
  • Preserving Cases with isupper()
  • Generating a Random Key
  • Calling the main() Function
  • Summary
  • Practice Questions
  • haCking the simPle suBstitution CiPher
  • Using Word Patterns to Decrypt
  • Finding Word Patterns
  • Finding Potential Decryption Letters
  • Overview of the Hacking Process
  • The Word Pattern Modules
  • Source Code for the Simple Substitution Hacking Program
  • Sample Run of the Simple Substitution Hacking Program
  • Setting Up Modules and Constants
  • Finding Characters with Regular Expressions
  • Setting Up the main() Function
  • Displaying Hacking Results to the User
  • Creating a Cipherletter Mapping
  • Creating a Blank Mapping
  • Adding Letters to a Mapping
  • Intersecting Two Mappings
  • How the Letter-Mapping Helper Functions Work
  • Identifying Solved Letters in Mappings
  • Testing the removeSolvedLetterFromMapping() Function
  • The hackSimpleSub() Function
  • The replace() String Method
  • Decrypting the Message
  • Decrypting in the Interactive Shell
  • Calling the main() Function
  • Summary
  • Practice Questions
  • Programming the vigenère CiPher
  • Using Multiple Letter Keys in the Vigenère Cipher
  • Longer Vigenère Keys Are More Secure
  • Choosing a Key That Prevents Dictionary Attacks
  • Source Code for the Vigenère Cipher Program
  • Sample Run of the Vigenère Cipher Program
  • Setting Up Modules, Constants, and the main() Function xvi Contents in Detail
  • Building Strings with the List-Append-Join Process
  • Encrypting and Decrypting the Message
  • Calling the main() Function
  • Summary
  • Practice Questions
  • FrequenCy analysis
  • Analyzing the Frequency of Letters in Text
  • Matching Letter Frequencies
  • Calculating the Frequency Match Score for the Simple Substitution Cipher
  • Calculating the Frequency Match Score for the Transposition Cipher
  • Using Frequency Analysis on the Vigenère Cipher
  • Source Code for Matching Letter Frequencies
  • Storing the Letters in ETAOIN Order
  • Counting the Letters in a Message
  • Getting the First Member of a Tuple
  • Ordering the Letters in the Message by Frequency
  • Counting the Letters with getLetterCount()
  • Creating a Dictionary of Frequency Counts and Letter Lists
  • Sorting the Letter Lists in Reverse ETAOIN Order
  • Sorting the Dictionary Lists by Frequency
  • Creating a List of the Sorted Letters
  • Calculating the Frequency Match Score of the Message
  • Summary
  • Practice Questions
  • haCking the vigenère CiPher
  • Using a Dictionary Attack to Brute-Force the Vigenère Cipher
  • Source Code for the Vigenère Dictionary Hacker Program
  • Sample Run of the Vigenère Dictionary Hacker Program
  • About the Vigenère Dictionary Hacker Program
  • Using Kasiski Examination to Find the Key’s Length
  • Finding Repeated Sequences
  • Getting Factors of Spacings
  • Getting Every Nth Letters from a String
  • Using Frequency Analysis to Break Each Subkey
  • Brute-Forcing Through the Possible Keys
  • Source Code for the Vigenère Hacking Program
  • Sample Run of the Vigenère Hacking Program
  • Importing Modules and Setting Up the main() Function
  • Finding Repeated Sequences
  • Calculating the Factors of the Spacings
  • Removing Duplicates with the set() Function
  • Removing Duplicate Factors and Sorting the List
  • Finding the Most Common Factors
  • Finding the Most Likely Key Lengths
  • The extend() List Method
  • Extending the repeatedSeqSpacings Dictionary
  • Getting the Factors from factorsByCount
  • Getting Letters Encrypted with the Same Subkey Contents in Detail xvii
  • Attempting Decryption with a Likely Key Length
  • The end Keyword Argument for print()
  • Running the Program in Silent Mode or Printing Information to the User
  • Finding Possible Combinations of Subkeys
  • Printing the Decrypted Text with the Correct Casing
  • Returning the Hacked Message
  • Breaking Out of the Loop When a Potential Key Is Found
  • Brute-Forcing All Other Key Lengths
  • Calling the main() Function
  • Modifying the Constants of the Hacking Program
  • Summary
  • Practice Questions
  • the one-time Pad CiPher
  • The Unbreakable One-Time Pad Cipher
  • Making Key Length Equal Message Length
  • Making the Key Truly Random
  • Avoiding the Two-Time Pad
  • Why the Two-Time Pad Is the Vigenère Cipher
  • Summary
  • Practice Questions
  • Finding and generating Prime numBers
  • What Is a Prime Number?
  • Source Code for the Prime Numbers Module
  • Sample Run of the Prime Numbers Module
  • How the Trial Division Algorithm Works
  • Implementing the Trial Division Algorithm Test
  • The Sieve of Eratosthenes
  • Generating Prime Numbers with the Sieve of Eratosthenes
  • The Rabin-Miller Primality Algorithm
  • Finding Large Prime Numbers
  • Generating Large Prime Numbers
  • Summary
  • Practice Questions
  • generating keys For the PuBliC key CiPher
  • Public Key Cryptography
  • The Problem with Authentication
  • Digital Signatures
  • Beware the MITM Attack
  • Steps for Generating Public and Private Keys
  • Source Code for the Public Key Generation Program
  • Sample Run of the Public Key Generation Program
  • Creating the main() Function
  • Generating Keys with the generateKey() Function xviii Contents in Detail
  • Calculating an e Value
  • Calculating a d Value
  • Returning the Keys
  • Creating Key Files with the makeKeyFiles() Function
  • Calling the main() Function
  • Hybrid Cryptosystems
  • Summary
  • Practice Questions
  • Programming the PuBliC key CiPher
  • How the Public Key Cipher Works
  • Creating Blocks
  • Converting a String into a Block
  • The Mathematics of Public Key Cipher Encryption and Decryption
  • Converting a Block to a String
  • Why We Can’t Hack the Public Key Cipher
  • Source Code for the Public Key Cipher Program
  • Sample Run of the Public Key Cipher Program
  • Setting Up the Program
  • How the Program Determines Whether to Encrypt or Decrypt
  • Converting Strings to Blocks with getBlocksFromText()
  • The min() and max() Functions
  • Storing Blocks in blockInt
  • Using getTextFromBlocks() to Decrypt
  • Using the insert() List Method
  • Merging the Message List into One String
  • Writing the encryptMessage() Function
  • Writing the decryptMessage() Function
  • Reading in the Public and Private Keys from Their Key Files
  • Writing the Encryption to a File
  • Decrypting from a File
  • Calling the main() Function
  • Summary
  • deBugging Python Code aPPendix
  • How the Debugger Works
  • Debugging the Reverse Cipher Program
  • Setting Breakpoints
  • Summary
  • index