Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (13 votes)
62 views

PDF Hacking Secret Ciphers with Python A beginner s guide to cryptography and computer programming with Python 1st Edition Al Sweigart download

beginner

Uploaded by

glutzatackq3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (13 votes)
62 views

PDF Hacking Secret Ciphers with Python A beginner s guide to cryptography and computer programming with Python 1st Edition Al Sweigart download

beginner

Uploaded by

glutzatackq3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

Download the full version of the ebook at

https://ebookfinal.com

Hacking Secret Ciphers with Python A beginner


s guide to cryptography and computer
programming with Python 1st Edition Al
Sweigart
https://ebookfinal.com/download/hacking-secret-
ciphers-with-python-a-beginner-s-guide-to-
cryptography-and-computer-programming-with-
python-1st-edition-al-sweigart/

Explore and download more ebook at https://ebookfinal.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Programming Python with CD 2nd Edition Mark Lutz

https://ebookfinal.com/download/programming-python-with-cd-2nd-
edition-mark-lutz/

ebookfinal.com

Programming Google App Engine with Python Build and Run


Scalable Python Apps on Google s Infrastructure 1st
Edition Dan Sanderson
https://ebookfinal.com/download/programming-google-app-engine-with-
python-build-and-run-scalable-python-apps-on-google-s-
infrastructure-1st-edition-dan-sanderson/
ebookfinal.com

More Python Programming for the Absolute Beginner 1st


Edition Jonathan S. Harbour

https://ebookfinal.com/download/more-python-programming-for-the-
absolute-beginner-1st-edition-jonathan-s-harbour/

ebookfinal.com

Beginning Programming With Python For Dummies 1st Edition


John Paul Mueller

https://ebookfinal.com/download/beginning-programming-with-python-for-
dummies-1st-edition-john-paul-mueller/

ebookfinal.com
Head First Programming A Learner s Guide to Programming
Using the Python Language 1st Edition David Griffiths

https://ebookfinal.com/download/head-first-programming-a-learner-s-
guide-to-programming-using-the-python-language-1st-edition-david-
griffiths/
ebookfinal.com

Introduction to Computation and Programming Using Python


with Application to Understanding Data 2nd edition Edition
Guttag
https://ebookfinal.com/download/introduction-to-computation-and-
programming-using-python-with-application-to-understanding-data-2nd-
edition-edition-guttag/
ebookfinal.com

Professional Python Frameworks Web 2 0 Programming with


Django and Turbogears Programmer to Programmer 1st Edition
Moore
https://ebookfinal.com/download/professional-python-frameworks-
web-2-0-programming-with-django-and-turbogears-programmer-to-
programmer-1st-edition-moore/
ebookfinal.com

Learning OpenCV 5 Computer Vision with Python Fourth


Edition Joseph Howse & Joe Minichino

https://ebookfinal.com/download/learning-opencv-5-computer-vision-
with-python-fourth-edition-joseph-howse-joe-minichino/

ebookfinal.com

Practical Programming An Introduction to Computer Science


Using Python 3 Second Edition Paul Gries

https://ebookfinal.com/download/practical-programming-an-introduction-
to-computer-science-using-python-3-second-edition-paul-gries/

ebookfinal.com
Hacking Secret Ciphers with Python A beginner s guide
to cryptography and computer programming with Python
1st Edition Al Sweigart Digital Instant Download
Author(s): Al Sweigart
ISBN(s): 9781482614374, 1482614375
Edition: 1
File Details: PDF, 6.61 MB
Year: 2013
Language: english
Hacking Secret
Ciphers with Python

By Al Sweigart
Copyright © 2013 by Al Sweigart

Some Rights Reserved. “Hacking Secret Ciphers with Python” is licensed under a Creative
Commons Attribution-Noncommercial-Share Alike 3.0 United States License.

You are free:

To Share — to copy, distribute, display, and perform the work

To Remix — to make derivative works

Under the following conditions:

Attribution — You must attribute the work in the manner specified by the author or
licensor (but not in any way that suggests that they endorse you or your use of the work).
(Visibly include the title and author's name in any excerpts of this work.)

Noncommercial — You may not use this work for commercial purposes.

Share Alike — If you alter, transform, or build upon this work, you may distribute
the resulting work only under the same or similar license to this one.

This summary is located here: http://creativecommons.org/licenses/by-nc-sa/3.0/us/ Your fair use and other rights are
in no way affected by the above. There is a human-readable summary of the Legal Code (the full license), located here:
http://creativecommons.org/licenses/by-nc-sa/3.0/us/legalcode

Book Version 3

Special thanks to Ari Lacenski. I can’t thank her enough. Without her efforts there’d be typos literally on every page.

Thanks to Jason Kibbe. Cover lock photo by “walknboston” http://www.flickr.com/photos/walkn/3859852351/ Romeo


& Juliet and other public domain texts from Project Gutenberg. Various image resources from Wikipedia. Wrinkled
paper texture by Pink Sherbet Photography http://www.flickr.com/photos/pinksherbet/2978651767/ Computer User
icon by Katzenbaer.

If you've downloaded this book from a torrent, it’s probably out of date. Go
to http://inventwithpython.com/hacking to download the latest version.

ISBN 978-1482614374
1st Edition
Nedroid Picture Diary by Anthony Clark, http://nedroid.com

Movies and TV shows always make hacking look exciting with furious typing and meaningless
ones and zeros flying across the screen. They make hacking look like something that you have to
be super smart to learn. They make hacking look like magic.

It’s not magic. It’s based on computers, and everything computers do have logical
principles behind them which can be learned and understood. Even when you don’t
understand or when the computer does something frustrating or mysterious, there is always,
always, always a reason why.

And it’s not hard to learn. This book assumes you know nothing about cryptography or
programming, and helps you learn, step by step, how to write programs that can hack encrypted
messages. Good luck and have fun!
100% of the profits from this book are donated
to the Electronic Frontier Foundation, the Creative Commons, and the Tor Project.
Dedicated to Aaron Swartz, 1986 – 2013

“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.”

- C.M.
ABOUT THIS BOOK
There are many books that teach beginners how to write secret messages using ciphers. There are
a couple books that teach beginners how to hack ciphers. As far as I can tell, there are no books to
teach beginners how to write programs to hack ciphers. This book fills that gap.

This book is for complete beginners who do not know anything about encryption, hacking, or
cryptography. The ciphers in this book (except for the RSA cipher in the last chapter) are all
centuries old, and modern computers now have the computational power to hack their encrypted
messages. No modern organization or individuals use these ciphers anymore. As such, there’s no
reasonable context in which you could get into legal trouble for the information in this book.

This book is for complete beginners who have never programmed before. This book teaches basic
programming concepts with the Python programming language. Python is the best language for
beginners to learn programming: it is simple and readable yet also a powerful programming
language used by professional software developers. The Python software can be downloaded for
free from http://python.org and runs on Linux, Windows, OS X, and the Raspberry Pi.

There are two definitions of “hacker”. A hacker is 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 are not limited by the
original rules of that system and can creatively modify it to work in new ways. “Hacker” is also
used to mean criminals who break into computer systems, violate people’s privacy, and cause
damage. This book uses “hacker” in the first sense. Hackers are cool. Criminals are just people
who think they’re being clever by breaking stuff. Personally, my day job as a software
developer pays me way more for less work than writing a virus or doing an Internet scam would.

On a side note, don’t use any of the encryption programs in this book for your actual files.
They’re fun to play with but they don’t provide true security. And in general, you shouldn’t trust
the ciphers that you yourself make. As legendary cryptographer Bruce Schneier put it, “Anyone,
from the most clueless amateur to the best cryptographer, can create an algorithm that he himself
can’t break. It’s not even hard. What is hard is creating an algorithm that no one else can break,
even after years of analysis. And the only way to prove that is to subject the algorithm to years of
analysis by the best cryptographers around.”

This book is released under a Creative Commons license and is free to copy and distribute (as
long as you don’t charge money for it). The book can be downloaded for free from its website at
http://inventwithpython.com/hacking. If you ever have questions about how these programs work,
feel free to email me at al@inventwithpython.com.
TABLE OF CONTENTS
About This Book ....................................................................................................................... 6
Table of Contents ..................................................................................................................... 7
Chapter 1 - Making Paper Cryptography Tools ...................................................................... 1
What is Cryptography? ................................................................................................................................................ 2
Codes vs. Ciphers ........................................................................................................................................................ 3
Making a Paper Cipher Wheel ..................................................................................................................................... 4
A Virtual Cipher Wheel ............................................................................................................................................... 7
How to Encrypt with the Cipher Wheel ....................................................................................................................... 8
How to Decrypt with the Cipher Wheel ....................................................................................................................... 9
A Different Cipher Tool: The St. Cyr Slide ............................................................................................................... 10
Practice Exercises, Chapter 1, Set A .......................................................................................................................... 11
Doing Cryptography without Paper Tools ................................................................................................................. 11
Practice Exercises, Chapter 1, Set B .......................................................................................................................... 13
Double-Strength Encryption?..................................................................................................................................... 13
Programming a Computer to do Encryption .............................................................................................................. 14
Chapter 2 - Installing Python ................................................................................................. 16
Downloading and Installing Python ........................................................................................................................... 17
Downloading pyperclip.py ......................................................................................................................................... 18
Starting IDLE ............................................................................................................................................................. 18
The Featured Programs .............................................................................................................................................. 19
Line Numbers and Spaces .......................................................................................................................................... 20
Text Wrapping in This Book ..................................................................................................................................... 20
Tracing the Program Online ....................................................................................................................................... 21
Checking Your Typed Code with the Online Diff Tool ............................................................................................. 21
Copying and Pasting Text .......................................................................................................................................... 21
More Info Links ......................................................................................................................................................... 22
Programming and Cryptography ................................................................................................................................ 22
Chapter 3 - The Interactive Shell .......................................................................................... 26
Some Simple Math Stuff ............................................................................................................................................ 26
Integers and Floating Point Values ............................................................................................................................ 27
Expressions ................................................................................................................................................................ 27
Order of Operations ................................................................................................................................................... 28
Evaluating Expressions .............................................................................................................................................. 29
Errors are Okay!......................................................................................................................................................... 29
Practice Exercises, Chapter 3, Set A .......................................................................................................................... 30
Every Value has a Data Type ..................................................................................................................................... 30
Storing Values in Variables with Assignment Statements ......................................................................................... 30
Overwriting Variables ................................................................................................................................................ 32
Using More Than One Variable ................................................................................................................................. 33
Variable Names.......................................................................................................................................................... 34
Practice Exercises, Chapter 3, Set B .......................................................................................................................... 35
Summary - But When Are We Going to Start Hacking?............................................................................................ 35
Chapter 4 - Strings and Writing Programs ........................................................................... 36
Strings ........................................................................................................................................................................ 36
String Concatenation with the + Operator ................................................................................................................. 38
String Replication with the * Operator ...................................................................................................................... 39
Printing Values with the print() Function ............................................................................................................ 39
Escape Characters ...................................................................................................................................................... 40
Quotes and Double Quotes ........................................................................................................................................ 41
Practice Exercises, Chapter 4, Set A .......................................................................................................................... 42
Indexing ..................................................................................................................................................................... 42
Negative Indexes........................................................................................................................................................ 44
Slicing ........................................................................................................................................................................ 44
Blank Slice Indexes.................................................................................................................................................... 45
Practice Exercises, Chapter 4, Set B .......................................................................................................................... 46
Writing Programs in IDLE’s File Editor .................................................................................................................... 46
Hello World! .............................................................................................................................................................. 47
Source Code of Hello World ...................................................................................................................................... 47
Saving Your Program ................................................................................................................................................ 48
Running Your Program .............................................................................................................................................. 49
Opening The Programs You’ve Saved ....................................................................................................................... 50
How the “Hello World” Program Works ................................................................................................................... 50
Comments .................................................................................................................................................................. 50
Functions.................................................................................................................................................................... 51
The print() function ............................................................................................................................................. 51
The input() function ............................................................................................................................................. 51
Ending the Program ................................................................................................................................................... 52
Practice Exercises, Chapter 4, Set C .......................................................................................................................... 52
Summary .................................................................................................................................................................... 53
Chapter 5 - The Reverse Cipher ............................................................................................ 54
The Reverse Cipher.................................................................................................................................................... 54
Source Code of the Reverse Cipher Program ............................................................................................................. 55
Sample Run of the Reverse Cipher Program.............................................................................................................. 55
Checking Your Source Code with the Online Diff Tool ............................................................................................ 56
How the Program Works............................................................................................................................................ 56
The len() Function ................................................................................................................................................. 57
Introducing the while Loop ..................................................................................................................................... 58
The Boolean Data Type ............................................................................................................................................. 59
Comparison Operators ............................................................................................................................................... 59
Conditions .................................................................................................................................................................. 62
Blocks ........................................................................................................................................................................ 62
The while Loop Statement ...................................................................................................................................... 63
“Growing” a String .................................................................................................................................................... 64
Tracing Through the Program, Step by Step .............................................................................................................. 67
Using input() In Our Programs............................................................................................................................. 68
Practice Exercises, Chapter 5, Section A ................................................................................................................... 69
Summary .................................................................................................................................................................... 69
Chapter 6 - The Caesar Cipher.............................................................................................. 70
Implementing a Program ............................................................................................................................................ 70
Source Code of the Caesar Cipher Program ............................................................................................................... 71
Sample Run of the Caesar Cipher Program................................................................................................................ 72
Checking Your Source Code with the Online Diff Tool ............................................................................................ 73
Practice Exercises, Chapter 6, Set A .......................................................................................................................... 73
How the Program Works............................................................................................................................................ 73
Importing Modules with the import Statement ....................................................................................................... 73
Constants.................................................................................................................................................................... 74
The upper() and lower() String Methods ........................................................................................................ 75
The for Loop Statement ........................................................................................................................................... 76
A while Loop Equivalent of a for Loop................................................................................................................ 77
Practice Exercises, Chapter 6, Set B .......................................................................................................................... 78
The if Statement ...................................................................................................................................................... 78
The else Statement .................................................................................................................................................. 79
The elif Statement .................................................................................................................................................. 79
The in and not in Operators ................................................................................................................................. 80
The find() String Method ...................................................................................................................................... 81
Practice Exercises, Chapter 6, Set C .......................................................................................................................... 82
Back to the Code ........................................................................................................................................................ 82
Displaying and Copying the Encrypted/Decrypted String ......................................................................................... 85
Encrypt Non-Letter Characters .................................................................................................................................. 86
Summary .................................................................................................................................................................... 87
Chapter 7 - Hacking the Caesar Cipher with the Brute-Force Technique .......................... 88
Hacking Ciphers ........................................................................................................................................................ 88
The Brute-Force Attack ............................................................................................................................................. 89
Source Code of the Caesar Cipher Hacker Program .................................................................................................. 89
Sample Run of the Caesar Cipher Hacker Program ................................................................................................... 90
How the Program Works............................................................................................................................................ 91
The range() Function ............................................................................................................................................ 91
Back to the Code ........................................................................................................................................................ 93
String Formatting ....................................................................................................................................................... 94
Practice Exercises, Chapter 7, Set A .......................................................................................................................... 95
Summary .................................................................................................................................................................... 95
Chapter 8 - Encrypting with the Transposition Cipher ........................................................ 96
Encrypting with the Transposition Cipher ................................................................................................................. 96
Practice Exercises, Chapter 8, Set A .......................................................................................................................... 98
A Transposition Cipher Encryption Program ............................................................................................................. 98
Source Code of the Transposition Cipher Encryption Program ................................................................................. 98
Sample Run of the Transposition Cipher Encryption Program .................................................................................. 99
How the Program Works.......................................................................................................................................... 100
Creating Your Own Functions with def Statements ............................................................................................... 100
The Program’s main() Function ........................................................................................................................... 101
Parameters................................................................................................................................................................ 102
Variables in the Global and Local Scope ................................................................................................................. 104
The global Statement ........................................................................................................................................... 104
Practice Exercises, Chapter 8, Set B ........................................................................................................................ 106
The List Data Type .................................................................................................................................................. 106
Using the list() Function to Convert Range Objects to Lists ............................................................................. 109
Reassigning the Items in Lists.................................................................................................................................. 110
Reassigning Characters in Strings ............................................................................................................................ 110
Lists of Lists ............................................................................................................................................................ 110
Practice Exercises, Chapter 8, Set C ........................................................................................................................ 111
Using len() and the in Operator with Lists ......................................................................................................... 111
List Concatenation and Replication with the + and * Operators.............................................................................. 112
Practice Exercises, Chapter 8, Set D ........................................................................................................................ 113
The Transposition Encryption Algorithm ................................................................................................................ 113
Augmented Assignment Operators .......................................................................................................................... 115
Back to the Code ...................................................................................................................................................... 116
The join() String Method .................................................................................................................................... 118
Return Values and return Statements .................................................................................................................. 119
Practice Exercises, Chapter 8, Set E ........................................................................................................................ 120
Back to the Code ...................................................................................................................................................... 120
The Special __name__ Variable ............................................................................................................................ 120
Key Size and Message Length ................................................................................................................................. 121
Summary .................................................................................................................................................................. 122
Chapter 9 - Decrypting with the Transposition Cipher ...................................................... 123
Decrypting with the Transposition Cipher on Paper ................................................................................................ 124
Practice Exercises, Chapter 9, Set A ........................................................................................................................ 125
A Transposition Cipher Decryption Program........................................................................................................... 126
Source Code of the Transposition Cipher Decryption Program ............................................................................... 126
How the Program Works.......................................................................................................................................... 127
The math.ceil(), math.floor() and round() Functions ......................................................................... 128
The and and or Boolean Operators ........................................................................................................................ 132
Practice Exercises, Chapter 9, Set B ........................................................................................................................ 133
Truth Tables ............................................................................................................................................................. 133
The and and or Operators are Shortcuts ................................................................................................................ 134
Order of Operations for Boolean Operators ............................................................................................................. 135
Back to the Code ...................................................................................................................................................... 135
Practice Exercises, Chapter 9, Set C ........................................................................................................................ 137
Summary .................................................................................................................................................................. 137
Chapter 10 - Programming a Program to Test Our Program ............................................ 138
Source Code of the Transposition Cipher Tester Program ....................................................................................... 139
Sample Run of the Transposition Cipher Tester Program ........................................................................................ 140
How the Program Works.......................................................................................................................................... 141
Pseudorandom Numbers and the random.seed() Function ............................................................................... 141
The random.randint() Function ..................................................................................................................... 143
References................................................................................................................................................................ 143
The copy.deepcopy() Functions ...................................................................................................................... 147
Practice Exercises, Chapter 10, Set A ...................................................................................................................... 148
The random.shuffle() Function ..................................................................................................................... 148
Randomly Scrambling a String ................................................................................................................................ 149
Back to the Code ...................................................................................................................................................... 149
The sys.exit() Function ................................................................................................................................... 150
Testing Our Test Program ........................................................................................................................................ 151
Summary .................................................................................................................................................................. 152
Chapter 11 - Encrypting and Decrypting Files ................................................................... 153
Plain Text Files ........................................................................................................................................................ 154
Source Code of the Transposition File Cipher Program ........................................................................................... 154
Sample Run of the Transposition File Cipher Program ........................................................................................... 157
Reading From Files .................................................................................................................................................. 157
Writing To Files ....................................................................................................................................................... 158
How the Program Works.......................................................................................................................................... 159
The os.path.exists() Function ..................................................................................................................... 160
The startswith() and endswith() String Methods ..................................................................................... 161
The title() String Method ................................................................................................................................. 162
The time Module and time.time() Function .................................................................................................. 163
Back to the Code ...................................................................................................................................................... 164
Practice Exercises, Chapter 11, Set A ...................................................................................................................... 165
Summary .................................................................................................................................................................. 165
Chapter 12 - Detecting English Programmatically ............................................................ 166
How Can a Computer Understand English?............................................................................................................. 167
Practice Exercises, Chapter 12, Section A ............................................................................................................... 169
The Detect English Module ..................................................................................................................................... 169
Source Code for the Detect English Module ............................................................................................................ 169
How the Program Works.......................................................................................................................................... 170
Dictionaries and the Dictionary Data Type .............................................................................................................. 171
Adding or Changing Items in a Dictionary .............................................................................................................. 172
Practice Exercises, Chapter 12, Set B ...................................................................................................................... 173
Using the len() Function with Dictionaries .......................................................................................................... 173
Using the in Operator with Dictionaries ................................................................................................................. 173
Using for Loops with Dictionaries ........................................................................................................................ 174
Practice Exercises, Chapter 12, Set C ...................................................................................................................... 174
The Difference Between Dictionaries and Lists ....................................................................................................... 174
Finding Items is Faster with Dictionaries Than Lists ............................................................................................... 175
The split() Method ............................................................................................................................................ 175
The None Value ...................................................................................................................................................... 176
Back to the Code ...................................................................................................................................................... 177
“Divide by Zero” Errors ........................................................................................................................................... 179
The float(), int(), and str() Functions and Integer Division ..................................................................... 179
Practice Exercises, Chapter 12, Set D ...................................................................................................................... 180
Back to the Code ...................................................................................................................................................... 180
The append() List Method ..................................................................................................................................... 182
Default Arguments ................................................................................................................................................... 183
Calculating Percentage............................................................................................................................................. 184
Practice Exercises, Chapter 12, Set E ...................................................................................................................... 185
Summary .................................................................................................................................................................. 186
Chapter 13 - Hacking the Transposition Cipher ................................................................ 187
Source Code of the Transposition Cipher Hacker Program ..................................................................................... 187
Sample Run of the Transposition Breaker Program ................................................................................................. 189
How the Program Works.......................................................................................................................................... 190
Multi-line Strings with Triple Quotes ...................................................................................................................... 190
Back to the Code ...................................................................................................................................................... 191
The strip() String Method ................................................................................................................................. 193
Practice Exercises, Chapter 13, Set A ...................................................................................................................... 195
Summary .................................................................................................................................................................. 195
Chapter 14 - Modular Arithmetic with the Multiplicative and Affine Ciphers ................. 196
Oh No Math! ............................................................................................................................................................ 197
Math Oh Yeah! ........................................................................................................................................................ 197
Modular Arithmetic (aka Clock Arithmetic) ............................................................................................................ 197
The % Mod Operator ............................................................................................................................................... 199
Practice Exercises, Chapter 14, Set A ...................................................................................................................... 199
GCD: Greatest Common Divisor (aka Greatest Common Factor) ........................................................................... 199
Visualize Factors and GCD with Cuisenaire Rods................................................................................................... 200
Practice Exercises, Chapter 14, Set B ...................................................................................................................... 202
Multiple Assignment ................................................................................................................................................ 202
Swapping Values with the Multiple Assignment Trick ............................................................................................ 203
Euclid’s Algorithm for Finding the GCD of Two Numbers..................................................................................... 203
“Relatively Prime” ................................................................................................................................................... 205
Practice Exercises, Chapter 14, Set C ...................................................................................................................... 205
The Multiplicative Cipher ........................................................................................................................................ 205
Practice Exercises, Chapter 14, Set D ...................................................................................................................... 207
Multiplicative Cipher + Caesar Cipher = The Affine Cipher ................................................................................... 207
The First Affine Key Problem.................................................................................................................................. 207
Decrypting with the Affine Cipher........................................................................................................................... 208
Finding Modular Inverses ........................................................................................................................................ 209
The // Integer Division Operator ........................................................................................................................... 210
Source Code of the cryptomath Module ............................................................................................................. 210
Practice Exercises, Chapter 14, Set E ...................................................................................................................... 211
Summary .................................................................................................................................................................. 211
Chapter 15 - The Affine Cipher ........................................................................................... 213
Source Code of the Affine Cipher Program ............................................................................................................. 214
Sample Run of the Affine Cipher Program .............................................................................................................. 216
Practice Exercises, Chapter 15, Set A ...................................................................................................................... 216
How the Program Works.......................................................................................................................................... 216
Splitting One Key into Two Keys ............................................................................................................................ 218
The Tuple Data Type ............................................................................................................................................... 218
Input Validation on the Keys ................................................................................................................................... 219
The Affine Cipher Encryption Function .................................................................................................................. 220
The Affine Cipher Decryption Function .................................................................................................................. 221
Generating Random Keys ........................................................................................................................................ 222
The Second Affine Key Problem: How Many Keys Can the Affine Cipher Have? ................................................. 223
Summary .................................................................................................................................................................. 225
Chapter 16 - Hacking the Affine Cipher ............................................................................. 226
Source Code of the Affine Cipher Hacker Program ................................................................................................. 226
Sample Run of the Affine Cipher Hacker Program.................................................................................................. 228
How the Program Works.......................................................................................................................................... 228
The Affine Cipher Hacking Function....................................................................................................................... 230
The ** Exponent Operator ...................................................................................................................................... 230
The continue Statement ...................................................................................................................................... 231
Practice Exercises, Chapter 16, Set A ...................................................................................................................... 234
Summary .................................................................................................................................................................. 234
Chapter 17 - The Simple Substitution Cipher .................................................................... 235
The Simple Substitution Cipher with Paper and Pencil ........................................................................................... 236
Practice Exercises, Chapter 17, Set A ...................................................................................................................... 236
Source Code of the Simple Substitution Cipher ....................................................................................................... 237
Sample Run of the Simple Substitution Cipher Program ......................................................................................... 239
How the Program Works.......................................................................................................................................... 239
The Program’s main() Function ........................................................................................................................... 240
The sort() List Method ....................................................................................................................................... 241
Wrapper Functions ................................................................................................................................................... 242
The Program’s translateMessage() Function ............................................................................................... 243
The isupper() and islower() String Methods .............................................................................................. 245
Practice Exercises, Chapter 17, Set B ...................................................................................................................... 247
Generating a Random Key ....................................................................................................................................... 247
Encrypting Spaces and Punctuation ......................................................................................................................... 248
Practice Exercises, Chapter 17, Set C ...................................................................................................................... 249
Summary .................................................................................................................................................................. 249
Chapter 18 - Hacking the Simple Substitution Cipher ...................................................... 250
Computing Word Patterns ........................................................................................................................................ 251
Getting a List of Candidates for a Cipherword ........................................................................................................ 252
Practice Exercises, Chapter 18, Set A ...................................................................................................................... 253
Source Code of the Word Pattern Module ............................................................................................................... 253
Sample Run of the Word Pattern Module ................................................................................................................ 255
How the Program Works.......................................................................................................................................... 256
The pprint.pprint() and pprint.pformat() Functions ........................................................................ 256
Building Strings in Python with Lists ...................................................................................................................... 257
Calculating the Word Pattern ................................................................................................................................... 258
The Word Pattern Program’s main() Function ..................................................................................................... 259
Hacking the Simple Substitution Cipher .................................................................................................................. 262
Source Code of the Simple Substitution Hacking Program...................................................................................... 262
Hacking the Simple Substitution Cipher (in Theory) ............................................................................................... 266
Explore the Hacking Functions with the Interactive Shell ....................................................................................... 266
How the Program Works.......................................................................................................................................... 271
Import All the Things............................................................................................................................................... 272
A Brief Intro to Regular Expressions and the sub() Regex Method ......................................................................... 272
The Hacking Program’s main() Function ............................................................................................................. 273
Partially Hacking the Cipher .................................................................................................................................... 274
Blank Cipherletter Mappings ................................................................................................................................... 275
Adding Letters to a Cipherletter Mapping ............................................................................................................... 276
Intersecting Two Letter Mappings ........................................................................................................................... 277
Removing Solved Letters from the Letter Mapping ................................................................................................. 278
Hacking the Simple Substitution Cipher .................................................................................................................. 281
Creating a Key from a Letter Mapping .................................................................................................................... 283
Couldn’t We Just Encrypt the Spaces Too? ............................................................................................................. 285
Summary .................................................................................................................................................................. 286
Chapter 19 - The Vigenère Cipher ...................................................................................... 287
Le Chiffre Indéchiffrable ......................................................................................................................................... 288
Multiple “Keys” in the Vigenère Key ...................................................................................................................... 288
Source Code of Vigenère Cipher Program ............................................................................................................... 291
Sample Run of the Vigenère Cipher Program .......................................................................................................... 294
How the Program Works.......................................................................................................................................... 294
Summary .................................................................................................................................................................. 298
Chapter 20 - Frequency Analysis ........................................................................................ 299
The Code for Matching Letter Frequencies ............................................................................................................. 304
How the Program Works.......................................................................................................................................... 306
The Most Common Letters, “ETAOIN” .................................................................................................................. 307
The Program’s getLettersCount() Function ................................................................................................. 307
The Program’s getItemAtIndexZero() Function .......................................................................................... 308
The Program’s getFrequencyOrder() Function ............................................................................................ 308
The sort() Method’s key and reverse Keyword Arguments ......................................................................... 310
Passing Functions as Values .................................................................................................................................... 311
Converting Dictionaries to Lists with the keys(), values(), items() Dictionary Methods ......................................... 313
Sorting the Items from a Dictionary ......................................................................................................................... 315
The Program’s englishFreqMatchScore() Function ................................................................................... 316
Summary .................................................................................................................................................................. 317
Chapter 21 - Hacking the Vigenère Cipher ........................................................................ 318
The Dictionary Attack.............................................................................................................................................. 319
Source Code for a Vigenère Dictionary Attack Program ......................................................................................... 319
Sample Run of the Vigenère Dictionary Hacker Program ....................................................................................... 320
The readlines() File Object Method ................................................................................................................ 321
The Babbage Attack & Kasiski Examination........................................................................................................... 321
Kasiski Examination, Step 1 – Find Repeat Sequences’ Spacings ........................................................................... 321
Kasiski Examination, Step 2 – Get Factors of Spacings .......................................................................................... 322
Get Every Nth Letters from a String ........................................................................................................................ 323
Frequency Analysis .................................................................................................................................................. 323
Brute-Force through the Possible Keys .................................................................................................................... 325
Source Code for the Vigenère Hacking Program ..................................................................................................... 326
Sample Run of the Vigenère Hacking Program ....................................................................................................... 332
How the Program Works.......................................................................................................................................... 334
Finding Repeated Sequences ................................................................................................................................... 335
Calculating Factors .................................................................................................................................................. 337
Removing Duplicates with the set() Function .......................................................................................................... 338
The Kasiski Examination Algorithm........................................................................................................................ 341
The extend() List Method................................................................................................................................... 342
The end Keyword Argument for print() ........................................................................................................... 347
The itertools.product() Function .............................................................................................................. 348
The break Statement ............................................................................................................................................. 352
Practice Exercises, Chapter 21, Set A ...................................................................................................................... 354
Modifying the Constants of the Hacking Program ................................................................................................... 354
Summary .................................................................................................................................................................. 355
Chapter 22 - The One-Time Pad Cipher .............................................................................. 356
The Unbreakable One-Time Pad Cipher .................................................................................................................. 357
Why the One-Time Pad is Unbreakable ................................................................................................................... 357
Beware Pseudorandomness ...................................................................................................................................... 358
Beware the Two-Time Pad ...................................................................................................................................... 358
The Two-Time Pad is the Vigenère Cipher.............................................................................................................. 359
Practice Exercises, Chapter 22, Set A ...................................................................................................................... 360
Summary .................................................................................................................................................................. 360
Chapter 23 - Finding Prime Numbers ................................................................................. 361
Prime Numbers ........................................................................................................................................................ 362
Composite Numbers................................................................................................................................................. 363
Source Code for The Prime Sieve Module ............................................................................................................... 363
How the Program Works.......................................................................................................................................... 364
How to Calculate if a Number is Prime ................................................................................................................... 365
The Sieve of Eratosthenes ........................................................................................................................................ 366
The primeSieve() Function............................................................................................................................... 368
Detecting Prime Numbers ........................................................................................................................................ 369
Source Code for the Rabin-Miller Module............................................................................................................... 370
Sample Run of the Rabin Miller Module ................................................................................................................. 372
How the Program Works.......................................................................................................................................... 372
The Rabin-Miller Primality Algorithm .................................................................................................................... 372
The New and Improved isPrime() Function ...................................................................................................... 373
Summary .................................................................................................................................................................. 375
Chapter 24 - Public Key Cryptography and the RSA Cipher .............................................. 378
Public Key Cryptography......................................................................................................................................... 379
The Dangers of “Textbook” RSA ............................................................................................................................ 381
A Note About Authentication .................................................................................................................................. 381
The Man-In-The-Middle Attack .............................................................................................................................. 382
Generating Public and Private Keys......................................................................................................................... 383
Source Code for the RSA Key Generation Program ................................................................................................ 383
Sample Run of the RSA Key Generation Program .................................................................................................. 385
How the Key Generation Program Works ............................................................................................................... 386
The Program’s generateKey() Function ........................................................................................................... 387
RSA Key File Format .............................................................................................................................................. 390
Hybrid Cryptosystems ............................................................................................................................................. 391
Source Code for the RSA Cipher Program .............................................................................................................. 391
Sample Run of the RSA Cipher Program ................................................................................................................. 395
Practice Exercises, Chapter 24, Set A ...................................................................................................................... 397
Digital Signatures .................................................................................................................................................... 397
How the RSA Cipher Program Works ..................................................................................................................... 398
ASCII: Using Numbers to Represent Characters ..................................................................................................... 400
The chr() and ord() Functions .......................................................................................................................... 400
Practice Exercises, Chapter 24, Set B ...................................................................................................................... 401
Blocks ...................................................................................................................................................................... 401
Converting Strings to Blocks with getBlocksFromText() ............................................................................. 404
The encode() String Method and the Bytes Data Type ....................................................................................... 405
The bytes() Function and decode() Bytes Method ........................................................................................ 405
Practice Exercises, Chapter 24, Set C ...................................................................................................................... 406
Back to the Code ...................................................................................................................................................... 406
The min() and max() Functions .......................................................................................................................... 407
The insert() List Method................................................................................................................................... 410
The Mathematics of RSA Encrypting and Decrypting ............................................................................................. 411
The pow() Function ............................................................................................................................................... 411
Reading in the Public & Private Keys from their Key Files ..................................................................................... 413
The Full RSA Encryption Process ........................................................................................................................... 413
The Full RSA Decryption Process ........................................................................................................................... 416
Practice Exercises, Chapter 24, Set D ...................................................................................................................... 418
Why Can’t We Hack the RSA Cipher ...................................................................................................................... 418
Summary .................................................................................................................................................................. 420
About the Author .................................................................................................................. 422
Chapter 1 – Making Paper Cryptography Tools 1

MAKING PAPER
CRYPTOGRAPHY TOOLS
Topics Covered In This Chapter:
 What is cryptography?
 Codes and ciphers
 The Caesar cipher
 Cipher wheels
 St. Cyr slides
 Doing cryptography with paper and pencil
 “Double strength” encryption

“I couldn’t help but overhear, probably because I


was eavesdropping.”

Anonymous
2 http://inventwithpython.com/hacking

What is Cryptography?
Look at the following two pieces of text:

“Zsijwxyfsi niqjsjxx gjyyjw. Ny “Flwyt tsytbbnz jqtw yjxndwri


nx jnymjw ktqqd tw bnxitr; ny iyn fqq knqrqt xj mh ndyn
nx anwyzj ns bjfqym fsi anhj ns jxwqswbj. Dyi jjkxxx sg ttwt
utajwyd. Ns ymj bnsyjw tk tzw gdhz js jwsn; wnjyiyb aijnn
qnkj, bj hfs jsotd ns ujfhj ymj snagdqt nnjwww, xstsxsu jdnxzz
kwznyx bmnhm ns nyx xuwnsl tzw xkw znfs uwwh xni xjzw jzwyjy
nsizxywd uqfsyji. Htzwynjwx tk jwnmns mnyfjx. Stjj wwzj ti
lqtwd, bwnyjwx tw bfwwntwx, fnu, qt uyko qqsbay jmwskj.
xqzrgjw nx ujwrnyyji dtz, gzy Sxitwru nwnqn nxfzfbl yy
tsqd zuts qfzwjqx.” hnwydsj mhnxytb myysyt.”

The text on the left side is a secret message. The message has been encrypted, or turned into a
secret code. It will be completely unreadable to anyone who doesn’t know how to decrypt it
(that is, turn it back into the plain English message.) This book will teach you how to encrypt and
decrypt messages.

The message on the right is just random gibberish with no hidden meaning whatsoever.
Encrypting your written messages is one way to keep them secret from other people, even if they
get their hands on the encrypted message itself. It will look exactly like random nonsense.

Cryptography is the science of using secret codes. A cryptographer is someone who uses and
studies secret codes. This book will teach you what you need to know to become a cryptographer.

Of course, these secret messages don’t always stay secret. A cryptanalyst is someone who can
hack secret codes and read other people’s encrypted messages. Cryptanalysts are also called code
breakers or hackers. This book will also teach you what you need to know to become a
cryptanalyst. Unfortunately the type of hacking you learn in this book isn’t dangerous enough to
get you in trouble with the law. (I mean, fortunately.)

Spies, soldiers, hackers, pirates, royalty, merchants, tyrants, political activists, Internet shoppers,
and anyone who has ever needed to share secrets with trusted friends have relied on cryptography
to make sure their secrets stay secret.

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 3

Codes vs. Ciphers


The development of the electric telegraph in the early 19th century allowed for near-instant
communication through wires across continents. This was much faster than 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 electric pulses. A short pulse is called a “dot” and a long pulse is
called a “dash”.

Figure 1-1. Samuel Morse Figure 1-2. Alfred Vail


April 27, 1791 – April 2, 1872 September 25, 1807 – January 18, 1859
In order to convert these dots and dashes to A ●▬ T ▬
English letters of the alphabet, an encoding B ▬●●● U ●●▬
system (or code) is needed to translate from C ▬●▬● V ●●●▬
English to electric pulse code (called D ▬●● W ●▬▬
E ● X ▬●●▬
encoding) and at the other end translate F ●●▬● Y ▬●▬▬
electric pulses to English (called decoding). G ▬▬● Z ▬▬●●
The code to do this over telegraphs (and later, H ●●●●
radio) was called Morse Code, and was I ●●
developed by Samuel Morse and Alfred Vail. J ●▬▬▬ 1 ●▬▬▬▬
By tapping out dots and dashes with a one- K ▬●▬ 2 ●●▬▬▬
button telegraph, a telegraph operator could L ●▬●● 3 ●●●▬▬
communicate an English message to someone M ▬▬ 4 ●●●●▬
N ▬● 5 ●●●●●
on the other side of the world almost instantly!
O ▬▬▬ 6 ▬●●●●
(If you’d like to learn Morse code, visit
P ●▬▬● 7 ▬▬●●●
http://invpy.com/morse.) Q ▬▬●▬ 8 ▬▬▬●●
R ●▬● 9 ▬▬▬▬●
S ●●● 0 ▬▬▬▬▬
Figure 1-3. International Morse Code, with
characters represented as dots and dashes.
4 http://inventwithpython.com/hacking

Codes are made to be understandable and publicly available. Anyone should be able to look
up what a code’s symbols mean to decode an encoded message.

Making a Paper Cipher Wheel


Before we learn how to program computers to do encryption and decryption for us, let’s learn
how to do it ourselves with simple paper tools. It is easy to turn the understandable English text
(which is called the plaintext) into the gibberish text that hides a secret code (called the
ciphertext). A cipher is a set of rules for converting between plaintext and ciphertext. These
rules often use a secret key. We will learn several different ciphers in this book.

Let’s learn a cipher called the Caesar cipher. This cipher was used by Julius Caesar two thousand
years ago. The good news is that it is simple and easy to learn. The bad news is that because it is
so simple, it is also easy for a cryptanalyst to break it. But we can use it as a simple learning
exercise. More information about the Caesar cipher is given on Wikipedia:
http://en.wikipedia.org/wiki/Caesar_cipher.

To convert plaintext to ciphertext using the Caesar cipher, we will create something called a
cipher wheel (also called a cipher disk). You can either photocopy the cipher wheel that
appears in this book, or print out the one from http://invpy.com/cipherwheel. Cut out the two
circles and lay them on top of each other like in Figure 1-8.

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 5

Figure 1-4. The inner circle of the cipher wheel cutout.


6 http://inventwithpython.com/hacking

Figure 1-5. The outer circle of the cipher wheel cutout.

Don’t cut out the page from this book!

Just make a photocopy of this page or print it from http://invpy.com/cipherwheel.

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 7

Figure 1-6. Cutting out Figure 1-7. The cut-out circles. Figure 1-8. The
the cipher wheel completed cipher
circles. wheel.

After you cut out the circles, place the smaller one in the middle of the larger one. Put a pin or
brad through the center of both circles so you can spin them around in place. You now have a tool
for creating secret messages with the Caesar cipher.

A Virtual Cipher Wheel


There is also a virtual cipher wheel online if you
don’t have scissors and a photocopier handy.
Open a web browser to
http://invpy.com/cipherwheel to use the software
version of the cipher wheel.

To spin the wheel around, click on it with the


mouse and then move the mouse cursor around
until the key you want is in place. Then click the
mouse again to stop the wheel from spinning.

Figure 1-9. The online cipher wheel.


8 http://inventwithpython.com/hacking

How to Encrypt with the Cipher Wheel


First, write out your message in English on paper. For this example we will encrypt the message,
“The secret password is Rosebud.” Next, spin the inner wheel around until its letters match up
with letters in the outer wheel. Notice in the outer wheel there is a dot next to the letter A. Look at
the number in the inner wheel next to the dot in the outer wheel. This number is known the
encryption key.

The encryption key is the secret to encrypting or decrypting the message. Anyone who reads this
book can learn about the Caesar cipher, just like anyone who reads a book about locks can learn
how a door lock works. But like a regular lock and key, unless they have the encryption key, they
will not be able to unlock (that is, decrypt) the secret encrypted message. In Figure 1-9, the outer
circle’s A is over the inner circle’s number 8. That means we will be using the key 8 to encrypt
our message. The Caesar cipher uses the keys from 0 to 25. Let’s use the key 8 for our example.
Keep the encryption key a secret; the ciphertext can be read by anyone who knows that the
message was encrypted with key 8.

T H E S E C R E T P A S S W O R D
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
B P M A M K Z M B X I A A E W Z L

I S R O S E B U D .
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
Q A Z W A M J C L .

For each letter in our message, we will find where it is in the outer circle and replace it with the
lined-up letter in the inner circle. The first letter in our message is T (the first “T” in “The
secret…”), so we find the letter T in the outer circle, and then find the lined-up letter in the inner
circle. This letter is B, so in our secret message we will always replace T’s with B’s. (If we were
using some other encryption key besides 8, then the T’s in our plaintext would be replaced with a
different letter.)

The next letter in our message is H, which turns into P. The letter E turns into M. When we have
encrypted the entire message, the message has transformed from “The secret password is
Rosebud.” to “Bpm amkzmb xiaaewzl qa Zwamjcl.” Now you can send this message to someone
(or keep it written down for yourself) and nobody will be able to read it unless you tell them the
secret encryption key (the number 8).

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 9

Figure 1-10. A message encrypted with the cipher wheel.


Each letter on the outer wheel will always be encrypted 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. This way you only need to look up a letter once.

How to Decrypt with the Cipher Wheel


To decrypt a ciphertext, go from the inner circle to the outer circle. Let’s say you receive this
ciphertext from a friend, “Iwt ctl ephhldgs xh Hldgsuxhw.” You and everyone else won’t be able
to decrypt it unless you know the key (or unless you are a clever hacker). But your friend has
decided to use the key 15 for each message she sends you.

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). The first letter in the secret message is I, so
we find I on the inner circle and look at the letter next to it on the outer circle, which is T. The W
in the ciphertext will decrypt to the letter H. One by one, we can decrypt each letter in the
ciphertext back to the plaintext, “The new password is Swordfish.”

I W T C T L E P H H L D G S
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
T H E N E W P A S S W O R D

X H H L D G S U X H W .
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
I S S W O R D F I S H .

If we use an incorrect key like 16 instead of the correct key 15, the decrypted message is “Sgd
mdv ozrrvnqc hr Rvnqcehrg.” This plaintext doesn’t look plain at all. Unless the correct key is
used, the decrypted message will never be understandable English.
10 http://inventwithpython.com/hacking

A Different Cipher Tool: The St. Cyr Slide


There’s another paper tool that can be used to do encryption and
decryption, called the St. Cyr slide. It’s like the cipher wheel
except in a straight line.

Photocopy the image of the St. Cyr slide on the following page (or
print it out from http://invpy.com/stcyrslide) and cut out the three
strips.

Tape the two alphabet strips together, with the black box A next to
the white box Z on the other strip. Cut out the slits on either side of
the main slide box so that the taped-together strip can feed through
it. It should look like this:

Figure 1-12. The completed St. Cyr Slide


When the black box A is underneath the letter H (and the number
7), then to encrypt you must find where the plaintext letter is on
the long strip, and replace it with the letter above it. To decrypt,
find the ciphertext letter on the top row of letters and replace it
with the letter on the long strip below it.

The two slits on the larger box will hide any extra letters so that
you only see one of each letter on the slide for any key.

The benefit of the St. Cyr slide is that it might be easier to find the
letters you are looking for, since they are all in a straight line and
will never be upside down like they sometimes are on the cipher
wheel.

A virtual and printable St. Cyr slide can be found at


Figure 1-11. Photocopy http://invpy.com/stcyrslide.
these strips to make a St.
Cyr Slide.

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 11

Practice Exercises, Chapter 1, Set A


Practice exercises can be found at http://invpy.com/hackingpractice1A.

Don’t ignore the practice exercises!


There isn’t enough room in this book to put in all the practice
exercises, but they’re still important.

You don’t become a hacker by just reading about hacking and


programming. You have to actually do it!

Doing Cryptography without Paper Tools


The cipher wheel and St. Cyr slide are nice tools to do encryption and decryption with the Caesar
cipher. But we can implement the Caesar cipher with just pencil and paper.

Write out the letters of the alphabet from A to Z with the numbers from 0 to 25 under each letter.
0 goes underneath the A, 1 goes under the B, and so on until 25 is under Z. (There are 26 letters
in the alphabet, but our numbers only go up to 25 because we started at 0, not 1.) It will end up
looking something like this:

A B C D E F G H I J K L M
0 1 2 3 4 5 6 7 8 9 10 11 12

N O P Q R S T U V W X Y Z
13 14 15 16 17 18 19 20 21 22 23 24 25

With the above letters-to-numbers code, we can use numbers to represent letters. This is a very
powerful concept, because math uses numbers. Now we have a way to do math on letters.

Now to encrypt we find the number under the letter we wish to encrypt and add the key number
to it. This sum will be the number under the encrypted letter. For example, we encrypt, “Hello.
How are you?” with the key 13. First we find the number under the H, which is 7. Then we add
the key to this number. 7 + 13 = 20. The number 20 is under the letter U, which means the letter
H encrypts to the letter U. To encrypt the letter E, we add the 4 under E to 13 to get 17. The
number above 17 is R, so E gets encrypted to R. And so on.

This works fine until we get to the letter O. The number under O is 14. But when we add 14 + 13
we get 27. But our list of numbers only goes up to 25. If the sum of the letter’s number and the
12 http://inventwithpython.com/hacking

key is 26 or more, we should subtract 26 from it. So 27 – 26 is 1. The letter above the number 1 is
B. So the letter O encrypts to the letter B when we are using the key 13. One by one, we can then
encrypt the letters in, “Hello. How are you?” to “Uryyb. Ubj ner lbh?”

So the steps to encrypt a letter are:

1. Decide on a key from 1 to 25. Keep this key secret!

2. Find the plaintext letter’s number.

3. Add the key to the plaintext letter’s number.

4. If this number is larger than 26, subtract 26.

5. Find the letter for the number you’ve calculated. This is the ciphertext letter.

6. Repeat steps 2 to 5 for every letter in the plaintext message.

Look at the following table to see how this is done with each letter in “Hello. How are you?” with
key 13. Each column shows the steps for turning the plaintext letter on the left to the ciphertext
letter on the right.

Table 1-1. The steps to encrypt “Hello. How are you?” with paper and pencil.
Plaintext Plaintext + Key Result Subtract Result Ciphertext
Letter Number 26? Letter
H 7 + 13 = 20 = 20 20 = U
E 4 + 13 = 17 = 17 17 = R
L 11 + 13 = 24 = 24 24 = Y
L 11 + 13 = 24 = 24 24 = Y
O 14 + 13 = 27 - 26 =1 1=B

H 7 + 13 = 20 = 20 20 = U
O 14 + 13 = 27 - 26 =1 1=B
W 22 + 13 = 35 - 26 =9 9=J

A 0 + 13 = 13 = 13 13 = N
R 17 + 13 = 30 - 26 =4 4=E
E 4 + 13 = 17 = 17 17 = R

Y 24 + 13 = 37 - 26 = 11 11 = L
O 14 + 13 = 27 - 26 =1 1=B
U 20 + 13 = 33 - 26 =7 7=H

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 13

To decrypt, you will have to understand what negative numbers are. If you don’t know how to
add and subtract with negative numbers, there is a tutorial on it here: http://invpy.com/neg.

To decrypt, subtract the key instead of adding it. For the ciphertext letter B, the number is 1.
Subtract 1 – 13 to get -12. Like our “subtract 26” rule for encrypting, when we are decrypting and
the result is less than 0, we have an “add 26” rule. -12 + 26 is 14. So the ciphertext letter B
decrypts back to letter O.

Table 1-2. The steps to decrypt the ciphertext with paper and pencil.
Ciphertext Ciphertext - Key Result Add Result Plaintext
Letter Number 26? Letter
U 20 - 13 =7 =7 7=H
R 17 - 13 =4 =4 4=E
Y 24 - 13 = 11 = 11 11 = L
Y 24 - 13 = 11 = 11 11 = L
B 1 - 13 = -12 + 26 = 14 14 = O

U 20 - 13 =7 =7 7=H
B 1 - 13 = -12 + 26 = 14 14 = O
J 9 - 13 = -4 + 26 = 22 22 = W

N 13 - 13 =0 =0 0=A
E 4 - 13 = -9 + 26 = 17 17 = R
R 17 - 13 =4 =4 4=E

L 11 - 13 = -2 + 26 = 24 24 = Y
B 1 - 13 = -12 + 26 = 14 14 = O
H 7 - 13 = -6 + 26 = 20 20 = U

As you can see, we don’t need an actual cipher wheel to do the Caesar cipher. If you memorize
the numbers and letters, then you don’t even need to write out the alphabet with the numbers
under them. You could just do some simple math in your head and write out secret messages.

Practice Exercises, Chapter 1, Set B


Practice exercises can be found at http://invpy.com/hackingpractice1B.

Double-Strength Encryption?
You might think that encrypting a message twice with two different keys would double the
strength of our encryption. But this turns out not to be the case with the Caesar cipher (and most
other ciphers). Let’s try double-encrypting a message to see why.
14 http://inventwithpython.com/hacking

If we encrypt the word “KITTEN” with the key 3, the resulting cipher text would be
“NLWWHQ”. If we encrypt the word “NLWWHQ” with the key 4, the resulting cipher text of
that would be “RPAALU”. But this is exactly the same as if we had encrypted the word
“KITTEN” once with a key of 7. Our “double” encryption is the same as normal encryption, so it
isn’t any stronger.

The reason is that when we encrypt with the key 3, we are adding 3 to plaintext letter’s number.
Then when we encrypt with the key 4, we are adding 4 to the plaintext letter’s number. But
adding 3 and then adding 4 is the exact same thing as adding 7. Encrypting twice with keys 3 and
4 is the same as encrypting once with the key 7.

For most encryption ciphers, encrypting more than once does not provide additional
strength to the cipher. In fact, if you encrypt some plaintext with two keys that add up to 26, the
ciphertext you end up with will be the same as the original plaintext!

Programming a Computer to do Encryption


The Caesar cipher, or ciphers like it, were used to encrypt secret information for several centuries.
Here’s a cipher disk of a design invented by Albert Myer that was used in the American Civil
War in 1863.

Figure 1-13. American Civil War Union Cipher Disk at the National Cryptologic Museum.
If you had a very long message that you wanted to encrypt (say, an entire book) it would take you
days or weeks to encrypt it all by hand. This is how programming can help. A computer could do

Email questions to the author: al@inventwithpython.com


Chapter 1 – Making Paper Cryptography Tools 15

the work for a large amount of text in less than a second! But we need to learn how to instruct
(that is, program) the computer to do the same steps we just did.

We will have to be able to speak a language the computer can understand. Fortunately, learning a
programming language isn’t nearly as hard as learning a foreign language like Japanese or
Spanish. You don’t even need to know much math besides addition, subtraction, and
multiplication. You just need to download some free software called Python, which we will cover
in the next chapter.
16 http://inventwithpython.com/hacking

INSTALLING PYTHON
Topics Covered In This Chapter:
 Downloading and installing Python
 Downloading the Pyperclip module
 How to start IDLE
 Formatting used in this book
 Copying and pasting text

“Privacy in an open society also requires


cryptography. If I say something, I want it
heard only by those for whom I intend it. If the
content of my speech is available to the world, I
have no privacy.”

Eric Hughes, “A Cypherpunk’s Manifesto”, 1993


http://invpy.com/cypherpunk

The content of this chapter is very similar to the first chapter of Invent Your Own Computer
Games with Python. If you have already read that book or have already installed Python, you only
need to read the “Downloading pyperclip.py” section in this chapter.

Email questions to the author: al@inventwithpython.com


Chapter 2 – Downloading and Installing Python 17

Downloading and Installing Python


Before we can begin programming, you’ll need to install software called the Python interpreter.
(You may need to ask an adult for help here.) The interpreter is a program that understands the
instructions that you’ll write in the Python language. Without the interpreter, your computer won't
understand these instructions. (We'll refer to “the Python interpreter” as “Python” from now on.)

Because we’ll be writing our programs in the Python language we need to download Python from
the official website of the Python programming language, http://www.python.org. The installation
is a little different depending on if your computer’s operating system is Windows, OS X, or a
Linux distribution such as Ubuntu. You can also find videos of people installing the Python
software online at http://invpy.com/installing.

Important Note! Be sure to install Python 3, and not Python 2. The programs in this book use
Python 3, and you’ll get errors if you try to run them with Python 2. It is so important, I am
adding a cartoon penguin telling you to install Python 3 so that you do not miss this message:

Figure 2-1. “Be sure to install Python 3, not Python 2!”, says the incongruous penguin.

Windows Instructions
There is a list of links on the left side of the web page at http://www.python.org. Click on the
Download link to go to the download page, then look for the file called Python 3.3.0 Windows
Installer (“Windows binary — does not include source”) and click on its link to download Python
for Windows. (If there is a newer version than Python 3.3.0, you can download that one.)
Double-click on the python-3.3.0.msi file that you’ve just downloaded to start the Python
installer. (If it doesn’t start, try right-clicking the file and choosing Install.) Once the installer
starts up, click the Next button and accept the choices in the installer as you go. There’s no need
to make any changes. When the installer is finished, click Finish.
18 http://inventwithpython.com/hacking

OS X Instructions
The installation for OS X is similar. Instead of downloading the .msi file from the Python
website, download the .dmg Mac Installer Disk Image file instead. The link to this file will look
something like “Python 3.3.0 Mac OS X” on the “Download Python Software” web page.

Ubuntu and Linux Instructions


If your operating system is Ubuntu, you can install Python by opening a terminal window (click
on Applications ► Accessories ► Terminal) and entering sudo apt-get install
python3.3 then pressing Enter. You will need to enter the root password to install Python, so
ask the person who owns the computer to type in this password.

You also need to install the IDLE software. From the terminal, type in sudo apt-get
install idle3. You will also need the root password to install IDLE.

Downloading pyperclip.py
Almost every program in this book uses a custom module I wrote called pyperclip.py. This
module provides functions for letting your program copy and paste text to the clipboard. This
module does not come with Python, but you can download it from: http://invpy.com/pyperclip.py

This file must be in the same folder as the Python program files that you type. (A folder is also
called a directory.) Otherwise you will see this error message when you try to run your program:

ImportError: No module named pyperclip

Starting IDLE
We will be using the IDLE software to type in our programs and run them. IDLE stands for
Interactive DeveLopment Environment. While Python is the software that interprets and runs
your Python programs, the IDLE software is what you type your programs in.

If your operating system is Windows XP, you should be able to run Python by clicking the Start
button, then selecting Programs ► Python 3.3 ► IDLE (Python GUI). For Windows Vista or
Windows 7, click the Windows button in the lower left corner, type “IDLE” and select “IDLE
(Python GUI)”.

If your operating system is Max OS X, start IDLE by opening the Finder window and clicking on
Applications, then click Python 3.3, then click the IDLE icon.

Email questions to the author: al@inventwithpython.com


Chapter 2 – Downloading and Installing Python 19

If your operating system is Ubuntu or Linux, start IDLE by clicking Applications ► Accessories
► Terminal and then type idle3. You may also be able to click on Applications at the top of
the screen, and then select Programming and then IDLE 3.

Figure 2-2. IDLE running on Windows (left), OS X (center), and Ubuntu Linux (right).
The window that appears will be mostly blank except for text that looks something like this:

Python 3.3.0 (v3.3.0:bd8afb90ebf2, Sep 29 2012, 10:57:17) [MSC v.1600 64 bit


(AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>>

The window that appears when you first run IDLE is called the interactive shell. A shell is a
program that lets you type instructions into the computer. The Python shell lets you type Python
instructions in and then sends these instructions to the Python interpreter software to run. We can
type Python instructions into the shell and, because the shell is interactive, the computer will read
our instructions and perform them immediately.

The Featured Programs


“Hacking Secret Ciphers with Python” is different from other programming books because it
focuses on the source code for 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.

As you read through this book, type the source code from this book into IDLE yourself. But you
can also download the source code files from this book’s website. Go to the web site
http://invpy.com/hackingsource and follow the instructions to download the source code files.

In general, you should read this book from front to back. The programming concepts build on
the previous chapters. However, Python is such a readable language that after the first few
chapters you can probably piece together what the code does. If you jump ahead and feel lost, try
20 http://inventwithpython.com/hacking

going back to the previous chapters. Or email your programming questions to the author at
al@inventwithpython.com.

Line Numbers and Spaces


When entering the source code yourself, do not type the line numbers that appear at the beginning
of each line. For example, if you see this in the book:

1. number = random.randint(1, 20)


2. spam = 42
3. print('Hello world!')

…then you do not need to type the “1.” on the left side, or the space that immediately follows it.
Just type it like this:

number = random.randint(1, 20)


spam = 42
print('Hello world!')

Those numbers are only used so that this book can refer to specific lines in the code. They are not
a part of the actual program. Aside from the line numbers, be sure to enter the code exactly as it
appears. This includes the letter casing. In Python, HELLO and hello and Hello could refer to
three different things.

Notice that some of the lines don’t begin at the leftmost edge of the page, but are indented by four
or eight spaces. Be sure to put in the correct number of spaces at the start of each line. (Since each
character in IDLE is the same width, you can count the number of spaces by counting the number
of characters above or below the line you’re looking at.)

For example, you can see that the second line is indented by four spaces because the four
characters (“whil”) on the line above are over the indented space. The third line is indented by
another four spaces (the four characters “if n” are above the third line’s indented space):

while spam < 10:


if number == 42:
print('Hello')

Text Wrapping in This Book


Some lines of code are too long to fit on one line on the page, and the text of the code will wrap
around to the next line. When you type these lines into the file editor, enter the code all on one
line without pressing Enter.

Email questions to the author: al@inventwithpython.com


Random documents with unrelated
content Scribd suggests to you:
Who came at length, with proud presumpteous[390] gate, xiv
Into the field, as if he fearelesse were,
All armed in a cote of yron plate,
Of great defence to ward the deadly feare,
And on his head a steele cap he did weare
Of colour rustie browne, but sure and strong;
And in his hand an huge Polaxe did beare,
Whose steale[391] was yron studded, but not long,
With which he wont to fight, to iustifie his wrong.

Of stature huge and hideous he was, xv


Like to a Giant for his monstrous hight,
And did in strength most sorts of men surpas,
Ne euer any found his match in might;
Thereto he had great skill in single fight:
His face was vgly, and his countenance sterne,
That could haue frayd one with the very sight,
And gaped like a gulfe, when he did gerne,
That whether man or monster one could scarse discerne.

Soone as he did within the listes appeare, xvi


With dreadfull looke he Artegall beheld,
As if he would haue daunted him with feare,
And grinning griesly, did against him weld
His deadly weapon, which in hand he held.
But th’Elfin swayne, that oft had seene like sight,
Was with his ghastly count’nance nothing queld,
But gan him streight to buckle to the fight,
And cast his shield about, to be in readie plight.

The trompets sound, and they together goe, xvii


With dreadfull terror, and with fell intent;
And their huge strokes full daungerously bestow,
To doe most dammage, where as most they ment.
But with such[392] force and furie violent,
The tyrant thundred his thicke blowes so fast,
That through the yron walles their way they rent,
And euen to the vitall parts they past,
Ne ought could them endure, but all they cleft or brast.

Which cruell outrage when as Artegall xviii


Did well auize, thenceforth with warie heed
He shund his strokes, where euer they did fall,
And way did giue vnto their gracelesse speed:
As when a skilfull Marriner doth reed
A storme approching, that doth perill threat,
He will not bide the daunger of such dread.
But strikes his sayles, and vereth his mainsheat,
And lends vnto it leaue the emptie ayre to beat.

So did the Faerie knight himselfe abeare, xix


And stouped oft his head from shame to shield;
No shame to stoupe, ones head more high to reare,
And much to gaine, a litle for to yield;
So stoutest knights doen oftentimes in field.
But still the tyrant sternely at him layd,
And did his yron axe so nimbly wield,
That many wounds into his flesh it made,
And with his burdenous blowes him sore did ouerlade.

Yet when as fit aduantage he did spy, xx


The whiles the cursed felon high did reare
His cruell hand, to smite him mortally,
Vnder his stroke he to him stepping neare,
Right in the flanke him strooke with deadly dreare,
That the gore bloud thence gushing grieuously,
Did vnderneath him like a pond appeare,
And all his armour did with purple dye;
Thereat he brayed loud, and yelled dreadfully.

Yet the huge stroke, which he before intended, xxi


Kept on his course, as he did it direct,
And with such monstrous poise adowne descended,
That seemed nought could him from death protect:
But he it well did ward with wise respect,
And twixt him and the blow his shield did cast,
Which thereon seizing, tooke no great effect,
But byting deepe therein did sticke so fast,
That by no meanes it backe againe he forth could wrast.

Long while he tug’d and stroue, to get it out, xxii


And all his powre applyed thereunto,
That he therewith the knight drew all about:
Nathlesse, for all that euer he could doe,
His axe he could not from his shield vndoe.
Which Artegall perceiuing, strooke no more,
But loosing soone his shield, did it forgoe,
And whiles he combred was therewith so sore,
He gan at him let driue more fiercely then afore.

So well he him pursew’d, that at the last, xxiii


He stroke[393] him with Chrysaor on the hed,
That with the souse thereof full sore aghast,
He staggered to and fro in doubtfull sted.
Againe whiles he him saw so ill bested,
He did him smite with all his might and maine,
That falling on his mother earth he fed:
Whom when he saw prostrated on the plaine,
He lightly reft his head, to ease him of his paine.

Which when the people round about him saw, xxiv


They shouted all for ioy of his successe,
Glad to be quit from that proud Tyrants awe,
Which with strong powre did them long time oppresse;
And running all with greedie ioyfulnesse
To faire Irena, at her feet did fall,
And her adored with due humblenesse,
As their true Liege and Princesse naturall;
And eke her champions glorie sounded ouer all.

Who streight her leading with meete maiestie xxv


Vnto the pallace, where their kings did rayne,
Did her therein establish peaceablie,
And to her kingdomes seat restore agayne;
And all such persons, as did late maintayne
That Tyrants part, with close or open ayde,
He sorely punished with heauie payne;
That in short space, whiles there with her he stayd,
Not one was left, that durst her once haue disobayd.

During which time, that he did there remaine, xxvi


His studie was true Iustice how to deale,
And day and night employ’d his busie paine
How to reforme that ragged common-weale:
And that same yron man which could reueale
All hidden crimes, through all that realme he sent,
To search out those, that vsd to rob and steale,
Or did rebell gainst lawfull gouernment;
On whom he did inflict most grieuous punishment.

But ere he could reforme it thoroughly, xxvii


He through occasion called was away,
To Faerie Court, that of necessity
His course of Iustice he was forst to stay,
And Talus to reuoke from the right way,
In which he was that Realme for to redresse.
But enuies cloud still dimmeth vertues ray.
So hauing freed Irena from distresse,
He tooke his leaue of her, there left in heauinesse.

Tho as he backe returned from that land, xxviii


And there arriu’d againe, whence forth he set,
He had not passed farre vpon the strand,
When as two old ill fauour’d Hags he met,
By the way side being together set,
Two griesly creatures; and, to that their faces
Most foule and filthie were, their garments yet
Being all rag’d and tatter’d, their disgraces
Did much the more augment, and made most vgly cases.
The one of them, that elder did appeare, xxix
With her dull eyes did seeme to looke askew,
That her mis-shape much helpt; and her foule heare
Hung loose and loathsomely: Thereto her hew
Was wan and leane, that all her teeth arew,
And all her bones might through her cheekes be red;
Her lips were like raw lether, pale and blew,
And as she spake, therewith she slauered;
Yet spake she seldom, but thought more, the lesse she sed.

Her hands were foule and durtie, neuer washt xxx


In all her life, with long nayles ouer raught,
Like puttocks clawes: with th’one of which she scracht
Her cursed head, although it itched naught;
The other held a snake with venime fraught,
On which she fed, and gnawed hungrily[394],
As if that long she had not eaten ought;
That round about her iawes one might descry
The bloudie gore and poyson dropping lothsomely.

Her name was Enuie, knowen well thereby; xxxi


Whose nature is to grieue, and grudge at all,
That euer she sees doen prays-worthily,
Whose sight to her is greatest crosse, may fall,
And vexeth so, that makes her eat her gall.
For when she wanteth other thing to eat,
She feedes on her owne maw vnnaturall,
And of her owne foule entrayles makes her meat;
Meat fit for such a monsters monsterous dyeat.

And if she hapt of any good to heare, xxxii


That had to any happily betid,
Then would she inly fret, and grieue, and teare
Her flesh for felnesse, which she inward hid:
But if she heard of ill, that any did,
Or harme, that any had, then would she make
Great cheare, like one vnto a banquet bid;
And in anothers losse great pleasure take,
As she had got thereby, and gayned a great stake.

The other nothing better was, then shee; xxxiii


Agreeing in bad will and cancred kynd,
But in bad maner they did disagree:
For what so Enuie good or bad did fynd,
She did conceale, and murder her owne mynd;
But this, what euer euill she conceiued,
Did spred abroad, and throw in th’open wynd.
Yet this in all her words might be perceiued,
That all she sought, was mens good name to haue bereaued.

For what soeuer good by any sayd, xxxiv


Or doen she heard, she would streightwayes inuent,
How to depraue, or slaunderously[395] vpbrayd,
Or to misconstrue of a mans intent,
And turne to ill the thing, that well was ment.
Therefore she vsed often to resort,
To common haunts, and companies frequent,
To hearke what any one did good report,
To blot the same with blame, or wrest in wicked sort.

And if that any ill she heard of any, xxxv


She would it eeke, and make much worse by telling,
And take great ioy to publish it to many,
That euery matter worse was for her melling.
Her name was hight Detraction, and her dwelling
Was neare to Enuie, euen her neighbour next;
A wicked hag, and Enuy selfe excelling
In mischiefe: for her selfe she onely vext;
But this same both her selfe, and others eke perplext.

Her face was vgly, and her mouth distort, xxxvi


Foming with poyson round about her gils,
In which her cursed tongue full sharpe and short
Appear’d like Aspis sting, that closely kils,
Or cruelly does wound, whom so she wils:
A distaffe in her other hand she had,
Vpon the which she litle spinnes, but spils,
And faynes to weaue false tales and leasings bad,
To throw amongst the good, which others had disprad.

These two now had themselues combynd in one, xxxvii


And linckt together gainst Sir Artegall,
For whom they wayted as his mortall fone,
How they might make him into mischiefe fall,
For freeing from their snares Irena thrall,
Besides vnto themselues they gotten had
A monster, which the Blatant beast men call,
A dreadfull feend of gods and men ydrad,
Whom they by slights allur’d, and to their purpose lad.

Such were these Hags, and so vnhandsome drest: xxxviii


Who when they nigh approching, had espyde
Sir Artegall return’d from his late quest,
They both arose, and at him loudly cryde,
As it had bene two shepheards curres, had scryde
A rauenous Wolfe amongst the scattered flockes.
And Enuie first, as she that first him eyde,
Towardes him runs, and with rude flaring lockes
About her eares, does beat her brest, and forhead knockes.

Then from her mouth the gobbet she does take, xxxix
The which whyleare she was so greedily
Deuouring, euen that halfe-gnawen snake,
And at him throwes it most despightfully.
The cursed Serpent, though she hungrily
Earst chawd thereon, yet was not all so dead,
But that some life remayned secretly,
And as he past afore withouten dread,
Bit him behind, that long the marke was to be read.

Then th’other comming neare, gan him reuile, xl


And fouly rayle, with all she could inuent;
Saying, that he had with vnmanly guile,
And foule abusion both his honour blent,
And that bright sword, the sword of Iustice lent,[396]
Had stayned with reprochfull crueltie,
In guiltlesse blood of many an innocent:
As for Grandtorto, him with treacherie
And traynes hauing surpriz’d, he fouly did to die.

Thereto the Blatant beast by them set on xli


At him began aloud to barke and bay,
With bitter rage and fell contention,
That all the woods and rockes nigh to that way,
Began to quake and tremble with dismay;
And all the aire rebellowed againe.
So dreadfully his hundred tongues did bray,
And euermore those hags them selues did paine,
To sharpen him, and their owne cursed tongs did straine.

And still among most bitter wordes they spake, xlii


Most shamefull, most vnrighteous, most vntrew,
That they the mildest man aliue would make
Forget his patience, and yeeld vengeaunce dew
To her, that so false sclaunders[397] at him threw.
And more to make them pierce and wound more deepe,
She with the sting, which in her vile tongue grew,
Did sharpen them, and in fresh poyson steepe:
Yet he past on, and seem’d of them to take no keepe.

But Talus hearing her so lewdly raile, xliii


And speake so ill of him, that well deserued,
Would her haue chastiz’d with his yron flaile,
If her Sir Artegall had not preserued,
And him forbidden, who his heast obserued.
So much the more at him still did she scold,
And stones did cast, yet he for nought would swerue
From his right course, but still the way did hold
To Faery Court, where what him fell shall else be told.
FOOTNOTES:
[387] i 9 enduren] endure 1596
[388] v 9 th’Eagle 1609
[389] xi 6 Artegals 1596
[390] xiv 1 presumptuous 1609 passim
[391] 8 steele 1609
[392] xvii 5 such] sure 1609
[393] xxiii 2 strooke 1609
[394] xxx 6 hungerly 1609
[395] xxxiv 3 slanderously 1609
[396] xl 5 And that bright sword the sword, of Iustice lent 1596
[397] xlii 5 slaunders 1609
THE SIXTE
BOOKE OF THE
FAERIE QVEENE.

Contayning

THE LEGEND OF S. CALIDORE

OR

OF COVRTESIE.
he waies, through which my weary steps I guyde, i
this delightfull land of Faery,
Are so exceeding spacious and wyde,
And sprinckled with such sweet variety,
Of all that pleasant is to eare or eye,
That I nigh rauisht with rare thoughts delight,
My tedious trauell doe forget thereby;
And when I gin to feele decay of might,
It[398] strength to me supplies, and chears my dulled spright.

Such secret comfort, and such heauenly pleasures, ii


Ye sacred imps, that on Parnasso dwell,
And there the keeping haue of learnings threasures,
Which doe all worldly riches farre excell,
Into the mindes of mortall men doe well,
And goodly fury into them infuse;
Guyde ye my footing, and conduct me well
In these strange waies, where neuer foote did vse,
Ne none can find, but who was taught them by the Muse.

Reuele to me the sacred noursery iii


Of vertue, which with you doth there remaine,
Where it in siluer bowre does hidden ly
From view of men, and wicked worlds disdaine.
Since[399] it at first was by the Gods with paine
Planted in earth, being deriv’d at furst
From heauenly seedes of bounty soueraine,
And by them long with carefull labour nurst,
Till it to ripenesse grew, and forth to honour burst.

Amongst them all growes not a fayrer flowre, iv


Then is the bloosme of comely courtesie,
Which though it on a lowly stalke doe bowre,
Yet brancheth forth in braue nobilitie,
And spreds it selfe through all ciuilitie:
Of which though present age doe plenteous seeme,
Yet being matcht with plaine Antiquitie,
Ye will them all but fayned showes esteeme,
Which carry colours faire, that feeble eies misdeeme.

But in the triall of true curtesie, v


Its now so farre from that, which then it was,
That it indeed is nought but forgerie,
Fashion’d to please the eies of them, that pas,
Which see not perfect things but in a glas:
Yet is that glasse so gay, that it can blynd
The wisest sight, to thinke gold that is bras.
But vertues seat is deepe within the mynd,
And not in outward shows, but inward thoughts defynd.

But where shall I in all Antiquity vi


So faire a patterne finde, where may be seene
The goodly praise of Princely curtesie,
As in your selfe, O soueraine Lady Queene,
In whose pure minde, as in a mirrour sheene,
It showes, and with her brightnesse doth inflame
The eyes of all, which thereon fixed beene;
But meriteth indeede an higher name:
Yet so from low to high vplifted is your name[400].

Then pardon me, most dreaded Soueraine, vii


That from your selfe I doe this vertue bring,
And to your selfe doe it returne againe:
So from the Ocean all riuers spring,
And tribute backe repay as to their King.
Right so from you all goodly vertues well
Into the rest, which round about you ring,
Faire Lords and Ladies, which about you dwell,
And doe adorne your Court, where courtesies excell.

FOOTNOTES:
[398] 9 It] tI 1596
[399] iii 5 Since] Sith 1609
[400] vi 9 name] fame edd.
Cant. I.

Calidore saues from Maleffort,


A Damzell vsed vylde:
Doth vanquish Crudor, and doth make
Briana wexe more mylde.

Of Court it seemes, men Courtesie doe call, i


For that it there most vseth to abound;
And well beseemeth that in Princes hall
That vertue should be plentifully found,
Which of all goodly manners is the ground,
And roote of ciuill conuersation.
Right so in Faery court it did redound,
Where curteous Knights and Ladies most did won
Of all on earth, and made a matchlesse paragon.

But mongst them all was none more courteous Knight, ii


Then Calidore, beloued ouer all,
In whom it seemes, that gentlenesse of spright
And manners mylde were planted naturall;
To which he adding comely guize withall,
And gracious speach, did steale mens hearts away.
Nathlesse thereto he was full stout and tall,
And well approu’d in batteilous affray,
That him did much renowme, and far his fame display.

Ne was there Knight, ne was there Lady found iii


In Faery court, but him did deare embrace,
For his faire vsage and conditions sound,
The which in all mens liking gayned place,
And with the greatest purchast greatest grace:
Which he could wisely vse, and well apply,
To please the best, and th’euill to embase.
For he loathd leasing, and base flattery,
And loued simple truth and stedfast honesty.

And now he was in trauell on his way, iv


Vppon an hard aduenture sore bestad,
Whenas by chaunce he met vppon a day
With Artegall, returning yet halfe sad
From his late conquest, which he gotten had.
Who whenas each of other had a sight,
They knew them selues, and both their persons rad:
When Calidore thus first; Haile noblest Knight
Of all this day on ground, that breathen liuing spright.

Now tell, if please you, of the good successe, v


Which ye haue had in your late enterprize.
To whom Sir Artegall gan to expresse
His whole exploite, and valorous emprize,
In order as it did to him arize.
Now happy man (sayd then Sir Calidore)
Which haue so goodly, as ye can deuize,
Atchieu’d so hard a quest, as few before;
That shall you most renowmed make for euermore.

But where ye ended haue, now I begin vi


To tread an endlesse trace, withouten guyde,
Or good direction, how to enter in,
Or how to issue forth in waies vntryde,
In perils strange, in labours long and wide,
In which although good Fortune me befall,
Yet shall it not by none be testifyde.
What is that quest (quoth then Sir Artegall)
That you into such perils presently doth call?

The Blattant Beast (quoth he) I doe pursew, vii


And through the world incessantly doe chase,
Till I him ouertake, or else subdew:
Yet know I not or how, or in what place
To find him out, yet still I forward trace.
What is that Blattant Beast? (then he replide.)[401]
It is a Monster bred of hellishe race,
(Then answerd he) which often hath annoyd
Good Knights and Ladies true, and many else destroyd.

Of Cerberus whilome he was begot, viii


And fell Chimæra in her darkesome den,
Through fowle commixture of his filthy blot;
Where he was fostred long in Stygian fen,
Till he to perfect ripenesse grew, and then
Into this wicked world he forth was sent,
To be the plague and scourge of wretched men:
Whom with vile tongue and venemous intent
He sore doth wound, and bite, and cruelly torment.

Then since the saluage Island I did leaue,[402] ix


Sayd Artegall, I such a Beast did see,
The which did seeme a thousand tongues to haue,
That all in spight and malice did agree,
With which he bayd and loudly barkt at mee,
As if that he attonce would me deuoure.
But I that knew my selfe from perill free,
Did nought regard his malice nor his powre,
But he the more his wicked poyson forth did poure.

That surely is that Beast (saide Calidore) x


Which I pursue, of whom I am right glad
To heare these tidings, which of none afore
Through all my weary trauell I haue had:
Yet now some hope your words vnto me add.
Now God you speed (quoth then Sir Artegall)
And keepe your body from the daunger drad:
For ye haue much adoe to deale withall.[403]
So both tooke goodly leaue, and parted seuerall.

Sir Calidore thence trauelled not long, xi


When as by chaunce a comely Squire he found,
That thorough some more mighty enemies wrong,
Both hand and foote vnto a tree was bound:
Who seeing him from farre, with piteous sound
Of his shrill cries him called to his aide.
To whom approching, in that painefull stound
When he him saw, for no demaunds he staide,
But first him losde, and afterwards thus to him saide.

Vnhappy Squire, what hard mishap thee brought xii


Into this bay of perill and disgrace?
What cruell hand thy wretched thraldome wrought,
And thee captyued in this shamefull place?
To whom he answerd thus; My haplesse case
Is not occasiond through my misdesert,
But through misfortune, which did me abase
Vnto this shame, and my young hope subuert,
Ere that I in her guilefull traines was well expert.

Not farre from hence, vppon yond rocky hill, xiii


Hard by a streight there stands a castle strong,
Which doth obserue a custome lewd and ill,
And it hath long mayntaind with mighty wrong:
For may no Knight nor Lady passe along
That way, (and yet they needs must passe that way,)
By reason of the streight, and rocks among,
But they that Ladies lockes doe shaue away,
And that knights berd for toll, which they for passage pay.[404]
A shamefull vse as euer I did heare, xiv
Sayd Calidore, and to be ouerthrowne.
But by what meanes did they at first it reare,
And for what cause, tell if thou haue it knowne.
Sayd then that Squire: The Lady which doth owne
This Castle, is by name Briana hight.
Then which a prouder Lady liueth none:
She long time hath deare lou’d a doughty Knight,
And sought to win his loue by all the meanes she might.

His name is Crudor, who through high disdaine xv


And proud despight of his selfe pleasing mynd,
Refused hath to yeeld her loue againe,
Vntill a Mantle she for him doe fynd,
With beards of Knights and locks of Ladies lynd.
Which to prouide, she hath this Castle dight,
And therein hath a Seneschall assynd,
Cald Maleffort, a man of mickle might,
Who executes her wicked will, with worse despight.

He this same day, as I that way did come xvi


With a faire Damzell, my beloued deare,
In execution of her lawlesse doome,
Did set vppon vs flying both for feare:
For little bootes against him hand to reare.
Me first he tooke, vnhable[405] to withstond;
And whiles he her pursued euery where,
Till his returne vnto this tree he bond:
Ne wote I surely, whether her he yet haue fond.

Thus whiles they spake, they heard a ruefull shrieke xvii


Of one loud crying, which they streight way ghest,
That it was she, the which for helpe did seeke.
Tho looking vp vnto the cry to lest,
They saw that Carle from farre, with hand vnblest
Hayling that mayden by the yellow heare,
That all her garments from her snowy brest,
And from her head her lockes he nigh did teare,
Ne would he spare for pitty, nor refraine for feare.

Which haynous sight when Calidore beheld, xviii


Eftsoones he loosd that Squire, and so him left,
With hearts dismay and inward dolour queld,
For to pursue that villaine, which had reft
That piteous spoile by so iniurious theft.
Whom ouertaking, loude to him he cryde;
Leaue faytor quickely that misgotten weft
To him, that hath it better iustifyde,
And turne thee soone to him, of whom thou art defyde.

Who hearkning to that voice, him selfe vpreard, xix


And seeing him so fiercely towardes make,
Against him stoutly ran, as nought afeard,
But rather more enrag’d for those words sake;
And with sterne count’naunce thus vnto him spake.
Art thou the caytiue, that defyest me,
And for this Mayd, whose party thou doest take,
Wilt giue thy beard, though it but little bee?
Yet shall it not her lockes for raunsome fro me free.

With that he fiercely at him flew, and layd xx


On hideous strokes with most importune might,
That oft he made him stagger as vnstayd,
And oft recuile to shunne his sharpe despight.
But Calidore, that was well skild in fight,
Him long forbore, and still his spirite spar’d,
Lying in waite, how him he damadge might.
But when he felt him shrinke, and come to ward,
He greater grew, and gan to driue at him more hard.

Like as a water streame, whose swelling sourse xxi


Shall driue a Mill, within strong bancks is pent,
And long restrayned of his ready course;
So soone as passage is vnto him lent,
Breakes forth, and makes his way more violent.
Such was the fury of Sir Calidore,
When once he felt his foeman to relent;
He fiercely him pursu’d, and pressed sore,
Who as he still decayd, so he encreased more.

The heauy burden of whose dreadfull might xxii


When as the Carle no longer could sustaine,
His heart gan faint, and streight he tooke his flight
Toward the Castle, where if need constraine,
His hope of refuge vsed to remaine.
Whom Calidore perceiuing fast to flie,
He him pursu’d and chaced through the plaine,
That he for dread of death gan loude to crie
Vnto the ward, to open to him hastilie.

They from the wall him seeing so aghast, xxiii


The gate soone opened to receiue him in,
But Calidore did follow him so fast,
That euen in the Porch he him did win,
And cleft his head asunder to his chin.
The carkasse[406] tumbling downe within the dore,
Did choke the entraunce with a lumpe of sin,
That it could not be shut, whilest Calidore
Did enter in, and slew the Porter on the flore.

With that the rest, the which the Castle kept, xxiv
About him flockt, and hard at him did lay;
But he them all from him full lightly swept,
As doth a Steare, in heat of sommers day,[407]
With his long taile the bryzes brush away.
Thence passing forth, into the hall he came,
Where of the Lady selfe in sad dismay
He was ymett, who with vncomely shame
Gan him salute, and fowle vpbrayd with faulty blame.

False traytor Knight, (sayd she) no Knight at all, xxv


But scorne of armes that hast with guilty hand
Murdred my men, and slaine my Seneschall;
Now comest thou to rob my house vnmand,
And spoile my selfe, that can not thee withstand?
Yet doubt thou not, but that some better Knight
Then thou, that shall thy treason vnderstand,
Will it auenge, and pay thee with thy right:
And if none do, yet shame shal thee with shame requight.[408]

Much was the Knight abashed at that word; xxvi


Yet answerd thus; Not vnto me the shame,
But to the shamefull doer it afford.
Bloud is no blemish; for it is no blame
To punish those, that doe deserue the same;
But they that breake bands of ciuilitie,
And wicked customes make, those doe defame
Both noble armes and gentle curtesie.
No greater shame to man then inhumanitie.

Then doe your selfe, for dread of shame, forgoe xxvii


This euill manner, which ye here maintaine,
And doe in stead thereof mild curt’sie showe
To all, that passe. That shall you glory gaine
More then his loue, which thus ye seeke t’obtaine.
Wherewith all full of wrath, she thus replyde;
Vile recreant, know that I doe much disdaine
Thy courteous lore, that doest my loue deride,
Who scornes thy ydle scoffe, and bids thee be defyde.

To take defiaunce at a Ladies word xxviii


(Quoth he) I hold it no indignity;
But were he here, that would it with his sword
Abett, perhaps he mote it deare aby.
Cowherd (quoth she) were not, that thou wouldst fly,
Ere he[409] doe come, he should be soone in place.
If I doe so, (sayd he) then liberty
I leaue to you, for aye me to disgrace
With all those shames, that erst ye spake me to deface.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookfinal.com

You might also like