Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
24 views

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

The document promotes the book 'Hacking Secret Ciphers with Python' by Al Sweigart, which is a beginner's guide to cryptography and programming using Python. It provides links to download the book and other related ebooks, along with details about the book's content, licensing, and the author's background. The book aims to teach beginners how to write programs that can hack encrypted messages step by step.

Uploaded by

brahmzapfedp
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 (1 vote)
24 views

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

The document promotes the book 'Hacking Secret Ciphers with Python' by Al Sweigart, which is a beginner's guide to cryptography and programming using Python. It provides links to download the book and other related ebooks, along with details about the book's content, licensing, and the author's background. The book aims to teach beginners how to write programs that can hack encrypted messages step by step.

Uploaded by

brahmzapfedp
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

Visit https://ebookfinal.

com to download the full version and


explore more ebooks

Hacking Secret Ciphers with Python A beginner s


guide to cryptography and computer programming
with Python 1st Edition Al Sweigart

_____ Click the link below to download _____


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 ebooks at ebookfinal.com


Here are some suggested products you might be interested in.
Click the link to download

Programming Python with CD 2nd Edition Mark Lutz

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

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/

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/

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/
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/

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/

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/

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/

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/
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


Exploring the Variety of Random
Documents with Different Content
boches, qui deviennent de plus en plus arrogants à mesure que nous nous
éloignons de la zone des armées, auront des sourires satisfaits et narquois.
Oh! la honte! la honte, inconnue jusqu’à cette heure, nous allons la
connaître.
Les quais de la gare sont aussi déserts que ceux de Coblence. On ne
voyage donc pas pendant la guerre, en Allemagne? Ou les cités vastes sont-
elles vides maintenant? Y aura-t-il plus d’animation dans les rues, à notre
passage?
Nous nous préparons à descendre. Mais nous ne descendons pas.
—Pas encore, nous dit-on; plus loin.
On nous avait pourtant affirmé qu’on nous conduisait à Mayence. Alors?
On nous avait trompés?
Le train repart. Cinq minutes à peine s’écoulent, il s’arrête de nouveau
dans une gare d’importance secondaire. Nous sommes à Mainz-Sud. C’est
ici que nous descendons. On ne nous avait donc pas trompés. Mais la
citadelle où l’on doit nous enfermer est à une centaine de mètres au plus de
cette station de banlieue; aussi nous a-t-on laissés dans nos vagons
jusqu’ici. Il n’y a presque personne sur le quai, en dehors des employés.
Nous ne défilerons pas à travers Mayence. Nous sommes délivrés d’un gros
poids.
Nous n’ignorons plus rien des habitudes allemandes. De nous-mêmes, ou
à peu près, nous nous rangeons par quatre devant la porte de sortie, et nous
nous laissons compter une fois, deux fois, trois fois. Le nombre est exact.
—’s stimmt, disent les Boches.
La citadelle se dresse formidable devant nous. Une grande masse grise.
De toutes petites fenêtres, et des meurtrières. Un énorme porche d’accès,
avec une porte massive, gardée par des soldats. Des têtes se montrent aux
fenêtres. Au moment où nous entrons sous la voûte du réduit, un officier
allemand nous salue.
Le voyage est terminé. Voici la prison. Une cour immense, limitée par
trois bâtiments principaux. Quelques officiers prisonniers nous saluent. Ils
portent les anciens uniformes du temps de paix.
L’un d’eux s’approche de nous:
—Verdun? demande-t-il d’une voix émue.
Plusieurs lui répondent à la fois:
—Toujours à nous.
Mais on l’éloigne.
Nous obliquons à gauche. J’aperçois des Anglais, des Belges, un Russe.
Mais je n’ai pas le temps d’en voir davantage, on nous fait entrer dans le
bâtiment nº III.
à J. Valmy-Baysse
CHAPITRE VI

LA QUARANTAINE

(12 mars 1916).


Au deuxième étage du bâtiment nº III de la citadelle de Mayence, de
nombreuses portes numérotées s’ouvrent avec un bruit de lourde ferraille
sur un long couloir, humide et sombre, dallé de pierre. La chambre nº 28
reçut les vingt-deux sous-lieutenants de notre détachement, tandis que les
capitaines et les lieutenants, moins nombreux, étaient cloîtrés ensemble
dans une chambre voisine. Pour vingt-deux hommes, la chambre nº 28 était
insuffisante. Mais, pour des prisonniers, tout est toujours suffisant.
Deux fenêtres ont vue sur la cour intérieure de la citadelle. Déjà
quelques officiers s’avancent pour prendre contact avec le paysage. Une
voix impérieuse nous annonce qu’il est formellement prescrit que les
fenêtres soient fermées toujours. Seuls, les vasistas peuvent être manœuvrés
à volonté. Nous ne saisissons pas l’opportunité d’une telle interdiction, mais
nous ne sommes pas ici pour comprendre les ordres qu’on nous donnera,
même le plus fantaisistes.
Le long des murs, dans le sens de la longueur de la pièce, deux rangées
de lits militaires superposés par deux, les châlits de fer s’emboîtant les uns
au-dessus des autres, ce qui fait penser à des séries de boxes dans une
exposition canine. Chaque lit est pourvu d’une paillasse de varech,
extrêmement dure, et de deux couvertures de laine blanche. Près de la porte
d’entrée, à gauche, il y a un grand poêle de fonte, où l’on nous allume du
feu dès notre arrivée. Le milieu de la chambre est occupé par deux grandes
tables massives, des bancs épais et des escabeaux. De chaque côté de la
porte, quelques placards, hauts et étroits, armoires réglementaires de sous-
officiers, sont alignés.
Telle est la cage où l’on nous enferme avec un bruit terrible de grosses
clefs tournant dans de grosses serrures. Et les bottes pesantes résonnent sur
les dalles du corridor. Mais, presque au même instant, le bruit des grosses
clefs recommence, la porte s’ouvre en grinçant, et un officier allemand
entre d’un air dégagé, la main à la casquette pour saluer.
—Bonjour, messieurs! dit-il sans accent.
L’oberleùtnant (lieutenant en premier) est d’une élégance tout à fait
soignée et son uniforme de campagne est d’un gris-vert incomparable. Il est
jeune. Il a une figure ronde rasée de près, et des favoris en côtelettes lui
descendant jusqu’à mi-joue. Il affecte une désinvolture aisée. Il a l’œil dur.
Il parle bien le français, certes, et il a une tête déjà rencontrée en plus d’un
coin de Paris. Il est mielleux, souriant, empressé, et dès l’abord on le sent
cruel et faux. Par la suite, j’ai su qu’il se nomme Schmidt et qu’il est avocat
dans la vie civile. Pendant la guerre il est officier d’artillerie, et, au camp de
Mayence, il est chargé de la censure.
Le censeur pose sur la table un paquet d’imprimés et nous les distribue à
raison de deux par individu. Ce sont des fiches de renseignements que nous
devons remplir nous-mêmes en double expédition: l’une restera entre les
mains de l’autorité allemande, l’autre sera envoyée en Suisse, au bureau
Central de l’office des Prisonniers de Guerre, qui fonctionne à Genève sous
les soins de la Croix-Rouge. Nom, prénoms, date et lieu de notre capture,
telles sont les questions auxquelles nous avons à répondre. Elles ne sont que
d’identité et d’état-civil. Mais il serait surprenant que rien ne fût tenté pour
obtenir, peut-être, par accident, un détail intéressant d’ordre militaire.
En effet, voici le piège où l’on nous attend:
—A quel corps appartenez-vous? A quelle compagnie?
... A quelle brigade? A quelle division?
... A quelle armée?
Comme je laisse en blanc l’espace réservé aux réponses de ces questions
indiscrètes, l’oberleùtnant s’en aperçoit et m’en fait la remarque. Herr
Schmidt est un malin. Il n’insiste pas, pour ne pas éveiller mon attention.
Sur un ton détaché et comme s’il ne tenait pas plus que cela à être
renseigné, il me dit en souriant:
—Vous faisiez partie de l’armée Pétain?
Mais je ne suis pas plus bête que l’astucieux censeur, et je lui réponds,
en souriant aussi:
—Je ne sais pas.
Herr Schmidt va d’un prisonnier à l’autre, surveillant son enquête, jetant
un mot à gauche, donnant une indication à droite, se répandant en
gentillesses. De lui-même, peu à peu, il nous apprend ce que sera notre
existence en captivité, car nous n’avons pas la moindre idée du sort qui
nous attend. En dix-neuf mois de campagne, je n’ai guère passé que
quelques jours de permission à Paris. Je n’ai pas vécu à l’intérieur. J’ignore
tout du traitement que reçoivent en France les prisonniers allemands et
jamais je ne me suis inquiété de ces choses. Nous laissera-t-on dans cette
citadelle où l’inaction sera le supplice de toutes nos heures? Nous fera-t-on
encadrer des corvées de travailleurs? Nous imaginons mille solutions. En
fait, nul de nous ne sait rien. Le censeur de Mayence nous tire un peu de
cette incertitude.
En premier lieu, nous demeurerons dans la chambre nº 28 pendant quatre
ou cinq jours.
—C’est une espèce de quarantaine, nous explique Herr Schmidt, à cause
des épidémies. On désinfectera votre linge et vos vêtements, vous prendrez
des douches. Puis vous sortirez, et on vous affectera à une chambre de la
citadelle, et vous partagerez la vie des camarades que vous voyez dans la
cour. Vous pourrez faire tout ce que vous voudrez dans les limites du camp.
Vous n’aurez qu’un certain nombre de consignes à respecter, et c’est tout.
Vous serez maîtres de vous-mêmes et libres.
Herr Schmidt sourit. Si nous ne sentions pas la féroce ironie de ses
paroles, nous lui demanderions si c’est vraiment sous ces espèces qu’on se
représente l’idée de liberté en Allemagne.
—Vous serez bien, dit-il.
Tout le monde nous affirme toujours que nous serons bien. Singulière
précaution! Ne sommes-nous donc pas assez grands garçons pour
reconnaître de nous-mêmes les bontés que l’on aura à notre endroit, si l’on
en a? Ou ne s’agit-il pas plutôt d’endormir nos craintes et de travailler pour
nous insinuer des Allemands une opinion conforme à leurs désirs? N’est-il
pas de propagande intelligente de nous aveugler un peu, tout au moins dans
les premiers jours, pour que nous nous laissions entraîner à écrire en
France, à nos parents et amis, que la captivité chez les Boches est la chose
la plus douce qui soit et l’espoir le plus cher que puisse nourrir là-bas, dans
la tranchée mortelle, le soldat qui se fatigue?
Nous avons le droit d’envoyer en France tous les mois deux lettres et
quatre cartes postales. L’écriture en sera grosse et très lisible, sous peine de
refus. Ces lettres seront de six pages, mais d’un format fixé. La kantine
nous vendra du papier réglementaire, naturellement. Si la correspondance
que nous expédions est limitée—et il faut qu’elle le soit, car, dans les loisirs
que nous avons, nous passerions les heures à écrire et à encombrer le
bureau du censeur,—nous pourrons en revanche recevoir autant de lettres,
de cartes et de colis postaux de 5 kilogrammes, qu’on nous en enverra, et
cinquante par jour, si cela nous plaît.
Dès demain nous écrirons notre première carte, et celle-là sera expédiée
tout de suite, par faveur spéciale, sans être assujettie au retard systématique
de dix jours qui est de règle pour les correspondances des prisonniers, tant
au départ qu’à l’arrivée. Ainsi nos familles apprendront relativement vite
que nous sommes vivants. Herr Schmidt ne manque pas d’observer que
cette mesure est d’une bienveillance dont nous devons savoir gré au
Gouvernement Impérial et Royal. Mais, comme je ne suis dupe d’aucune
des bienveillances boches, je ne manque pas davantage de penser que cela
aussi est du programme de la propagande qu’il faut mener en France pour la
démoraliser dans le moment où on l’attaque à coups de canons. Il est de
l’intérêt de l’Allemagne que de très nombreuses cartes envoyées par les
prisonniers des jours derniers répandent, dans la Suisse où elles passeront et
dans les provinces françaises, d’une part le bruit que nous avons perdu
beaucoup d’hommes et d’autre part cette nouvelle dangereuse que nous
sommes bien traités dans les camps allemands. C’est que le Gouvernement
Impérial et Royal de Berlin ne néglige rien pour s’assurer la victoire: tout
lui est profitable, même le détail le plus infime, et ces assauts contre la
santé morale de ses ennemis ne sont pas ceux qui lui coûtent le moins
d’efforts ou le moins de soucis. Tout est organisé en Allemagne pour que
l’Allemagne triomphe. Les violences du début de la guerre ont échoué. La
force n’a pas vaincu la foi des Français. Mais il y a peut-être des moyens
autres de la vaincre. On les conjuguera tous. Que la France soit fatiguée de
la guerre, qu’elle croie seulement qu’elle n’en tirera rien, pas même une
paix honorable après s’être saignée à blanc; qu’elle croie surtout qu’on l’a
trompée sur les desseins allemands, sur l’esprit allemand, sur le cœur
allemand, qu’elle croie enfin que l’Allemagne est pavée de plus de bonnes
intentions que l’Enfer lui-même; et la France lâchera ses armes, ses soldats
se rendront, ses civils pousseront les soldats à se rendre, et la guerre et la
paix seront à la merci de l’Allemagne.
Jugera-t-on que j’exagère et que je cherche des complications, alors que
ce n’est que la simple humanité qui invite le censeur du camp de Mayence à
expédier tout de suite notre première carte postale? Je n’exagère pas. Je
connais les Allemands, et vous ne les connaissez pas, ou vous les
connaissez mal. Ils sont méchants et sournois, tous, depuis le plus grand
jusqu’au plus petit, et le paysan saxon ne vaut pas mieux que le colonel
poméranien. Ce que je pense, je ne suis pas seul à le penser. Mais je le dis,
parce qu’il faut que tout le monde le sache, aujourd’hui, et demain, et
toujours. Ad prædam natos Germanos, constatait l’historien latin.
L’Allemagne a été, est, et sera une nation de proie. Rien de plus, rien de
moins. On ne change pas d’âme comme de chemise. Et c’est une camisole
de force qu’il faut mettre à l’Allemagne, si nous voulons à jamais respirer
librement.
Quand ils seront rentrés chez eux, tous nos prisonniers seront d’accord
pour le proclamer: l’Allemand est cruel tant qu’il se croit sûr du succès et
de l’impunité. Il n’est pas de tortures qu’ils n’aient infligées à nos
malheureux prisonniers. Les officiers, en général, ont moins souffert
physiquement, c’est exact, encore n’est-ce que par crainte de représailles
qu’on aurait prises contre leurs chers barons tombés aux mains de la France.
Mais il n’est pas une brimade morale qui ait été épargnée à nos lieutenants
ou à nos colonels. Et le même procédé se retrouve partout: là, détruire par la
force; ici, ruiner par la suggestion; là, par le poing; ici, par la parole. En fin
de compte, le résultat est le même, et nos prisonniers, galonnés ou non,
seront dans un triste état quand ils rentreront chez eux.
Au camp de Mayence, pendant ces heures que nous vivons dans la
quarantaine, on s’ingénie à nous dorer la pilule et à nous présenter l’avenir
sous les couleurs le plus roses.
Trois ordonnances sont à nos ordres: un Belge, un Français et un Russe,
commandés par un soldat boche en casquette grise et qui crie d’une voix
perçante chaque fois qu’il veut parler. C’est au milieu des invectives les
plus aigres que les trois ordonnances nous servirent notre premier repas de
Mayence. L’Allemand s’agitait comme un forcené. Le Français ne disait
rien. Le Russe remuait des piles d’assiettes en souriant d’indifférence.
Quant au Belge, il assistait à la scène en amateur.
L’Allemand assure lui-même la distribution du pain, denrée précieuse
qu’il importe de ne pas gaspiller. Il nous en donne à chacun un morceau à
peine plus long que le travers de la main.
—Ration pour 24 heures, nous dit-il.
Il n’y en a pas assez pour contenter pendant la moitié d’un repas un
appétit moyen. Mais ce pain est meilleur que celui que nous avons mangé
jusqu’à présent. L’ordonnance belge nous fait observer que nous ne devons
pas nous plaindre: on nous donne «du pain d’officier». Les officiers
allemands n’en ont pas d’autre, tandis que la population civile, même dans
les villes les plus importantes, ne touche qu’une ration dérisoire de la boule
militaire que nous connaissons.
Notre menu comprend: un potage à la semoule; une tranche de viande
comme on en sert aux internes de nos collèges et lycées, viande filandreuse
et pâle et dont on ne saurait décider si elle est de bœuf ou de veau; des
épinards; et enfin, à discrétion, dès le début du repas, des kartoffeln, c’est-à-
dire des pommes de terre cuites à l’eau. Les kartoffeln se mangent avec
tout, avec la soupe si l’on veut, et avec la confiture si on le désire. Elles
remplacent le pain. Comme boisson, de l’eau. Mais nous avons le droit
d’acheter à la kantine une demi-bouteille de bière par officier et par repas
ou une bouteille de vin par jour et pour deux officiers. En somme, cet
ordinaire est plus que suffisant. Un de mes camarades en fait la remarque à
haute voix.
—Vous n’en direz pas autant tous les jours, nous dit l’ordonnance belge.
Ces quelques mots jettent un froid sur nous. Ils confirment en moi les
réflexions que m’avait suggérées cette promesse d’expédier sans retard
notre première carte postale. Il ne faut pas juger les gens sur la mine, et les
Allemands moins que personne.
L’après-midi était déjà assez avancée quand notre repas s’acheva. Que
faire dans cette cage, sinon se planter derrière les barreaux et regarder ce
qui se passe à l’extérieur? Lorsque nous serons sortis de cette chambre nº
28, qu’entre nous nous appelons le «saloir», nous aurons les mêmes
prérogatives que les prisonniers qui sont ici depuis longtemps. Mais quelles
sont-elles?
Dehors, à gauche, par rapport à nous, s’élève un grand bâtiment; à
droite, un bâtiment semblable lui fait face, et tous les deux sont pareils au
bâtiment nº III que nous occupons. Au fond, au loin, des constructions
d’importance moindre: c’est là que sont installés les différents services du
camp. L’espace libre qui s’étend entre ces quartiers de la citadelle est une
immense cour, domaine des prisonniers.
Tout autour de la cour, ils se promènent, par petits groupes, par trois, par
deux, isolément; les uns vont d’un train de flânerie, d’autres marchent à
longues enjambées, comme s’ils étaient pressés, mais plutôt par besoin
physique de se dépenser et de se fatiguer. Et tous vont dans le même sens,
les uns derrière les autres, se poursuivant, se rattrapant, se distançant, en
une espèce de course sans but, comme on imagine que les fous doivent en
faire dans les cours de leurs asiles. Quelle misère! Bientôt nous aurons aussi
notre place dans la promenade générale.
Mais tous les prisonniers ne se promènent pas. Dans un coin, sur un sol
préparé, en voici quatre qui jouent au tennis. Plus loin, en voici d’autres,
vêtus de maillots et de courtes culottes blanches ou noires, qui mènent un
match de hockey. Les Français ont, paraît-il, lancé un défi aux Anglais, et la
partie se dispute âprement. Ils courent, ils courent, les joueurs qui
n’apparaissent à nous que comme des enfants dans un jardin. Ce sont des
officiers jeunes sans doute et vigoureux encore, qui ne veulent pas se laisser
dépérir de langueur en captivité.
Les plus âgés évidemment se promènent autour de la cour, comme des
philosophes rassis. Tous les uniformes sont représentés au camp de
Mayence: le pantalon rouge et le képi foulard du temps de paix dominent.
Comme ils nous semblent vieillots, à nous qui ne sommes plus habitués
qu’au bleu horizon si pimpant! La plupart des Français qui sont ici viennent
de Maubeuge. Les Belges ont été pris à Namur ou à Liège. Les quelques
Anglais n’ont pas d’histoire, et, quant aux Russes, ils sont trop. La
sollicitude de l’Allemagne réunit dans une même prison des hommes des
différentes nations alliées. Le Gouvernement Impérial et Royal compte bien
que la vie en commun, la promiscuité de tous les instants, les caractères
différents, les égoïsmes individuels causeront des discussions et des
disputes, créeront des animosités et des rancunes et prépareront, même à
longue échéance, la dissolution du bloc des Alliés. Ainsi les prisonniers
serviront à quelque chose, car tout doit servir à quelque chose pendant la
guerre. Mais l’Allemagne s’est égarée en réunissant sous des outrages
communs les prisonniers de l’Entente. Au lieu de se mordre entre eux, ils
ont appris à se connaître et à s’estimer dans le malheur, et ils s’aiment. Tant
les facultés de psychologie de l’Allemagne sont toujours en défaut.
Il me semblait que nous sortions à peine de table. Or, on nous apporte à
manger. Pendant les vingt-quatre heures qu’a duré notre voyage en chemin
de fer, on ne nous avait offert que la soupe de Cobern. Ici, en moins de deux
heures, voici deux repas. C’est de l’exagération. On ne peut pas être dupe
de pareils procédés.
La collation de quatre heures comprend du café, du sucre et de la
confiture. Pas de pain, bien entendu, puisque nous en avons reçu à midi une
ration pour deux tours complets d’horloge. Mais nous n’espérions pas une
telle abondance de biens. La plupart d’entre nous n’ont pas su se limiter. Ils
n’ont plus de pain. Et nous ne sommes pas des Bavarois pour avaler à
pleine cuiller de la confiture toute sèche, si on peut dire. Elle reste donc à
peu près intacte, sujet de mainte remarque ironique de la part de mon voisin
de lit, avec qui je cause un peu.
Le lieutenant D*** a l’air très doux et sa physionomie franche, avec des
yeux intelligents qui semblent sortir de la barbe brune, attire la sympathie.
Il me confie que dans la vie civile il s’occupait d’économie politique et de
littérature. Au front, il a fondé l’Écho des Boyaux, et il y a fait représenter
une revue. Notre entretien tourne aux souvenirs de Paris. Nous parlons de
nos amis et de nos camarades, des jeunes écrivains morts au champ
d’honneur et des artistes tués à l’ennemi, de ceux que nous connaissions
personnellement et de ceux que nous ne connaissons que par leurs
ouvrages. Nous parlons de la littérature de 1914, et de la génération
sacrifiée. Nous parlons de ceux que nous aimons et de ceux que nous
admirons, de Montfort, de Viollis, des Marges... L’heure passe. Près de nous
un officier, allongé sur sa couchette, lit les Trains de luxe d’Abel Hermant,
le seul livre que possède la chambre. Dans un coin, quatre lieutenants
jouent à la manille, avec des cartes qu’ils ont sauvées du désastre. La nuit
vient. Il n’y a plus personne dans la cour. Les promeneurs sont rentrés.
Dans peu de jours, nous mènerons l’existence qu’ils mènent.
Resterons-nous au camp de Mayence? Rien n’est moins sûr.
L’ordonnance belge, qui paraît savoir beaucoup de choses, nous laisse
entendre que le sort d’un prisonnier est incertain, et que tel, qui se croit en
Saxe jusqu’à la fin de sa captivité, s’embarque le soir même pour la Prusse
Orientale, sans qu’on lui révèle les motifs de ce changement de fortune.
Pendant qu’il nous découvre quelques-uns des dessous de la vie des camps,
ses camarades, le Français et le Russe, dûment houspillés par le braillard en
casquette, dressent la table pour le repas du soir.
Le Belge se désintéresse de la corvée. Il nous prévient que demain matin
nous serons tous fouillés très minutieusement et qu’on nous confisquera
tout ce qui peut être considéré comme butin de guerre, les armes si nous en
avons, les jumelles, les boussoles, les couteaux, s’ils sont au-dessus d’une
taille fixée, les stylographes à cause de la plume en or, etc... Il ne faut pas
songer à cacher quelque chose. J’avais déjà détruit de moi-même bien des
objets sur le champ de bataille, mais j’aurais voulu conserver ma boussole
et mon stylographe. Le Belge refuse de me les garder jusqu’à ma sortie du
saloir; s’il était pincé, on l’enverrait dans un camp de représailles, et il est
trop content de l’emploi qu’il tient à Mayence pour jouer avec le danger.
Quelques camarades se font fort de dérouter l’astuce des Boches. J’ai moins
de confiance qu’eux. L’Allemand est un maître en ruses diverses. Il ne me
reste qu’à briser boussole et stylographe, et à en faire disparaître les
morceaux en les jetant au tout-à-l’égout.
Le repas du soir, le troisième qu’on nous sert depuis midi, n’est ni moins
copieux ni moins alléchant que les deux autres. Nous avons une tranche de
pâté, des asperges, des kartoffeln, naturellement, et... une surprise: un
minuscule bout de pain, du genre «flûte», long comme les deux tiers de
mon pouce, gros deux fois comme lui, et fait d’une farine moins noire,
presque blanche. Cela doit être considéré comme un gâteau, sans doute, et
une attention charmante de l’administration du camp qui tient peut-être à
nous prouver ainsi qu’on pourrait faire de bel et bon pain de gruau en
Allemagne, comme en France, si l’on voulait. Mais voilà, il est bien évident
qu’on ne veut pas.
à Jérôme et Jean Tharaud
CHAPITRE VII

LE SALOIR DE MAYENCE

(13 mars 1916).


Il était dit que l’administration du camp de Mayence ne négligerait rien
pour nous adoucir les premières heures de la captivité. Mais quel plus sûr
moyen d’arriver à ce résultat que de soigner notre nourriture? Le profit en
est double: le prisonnier reconnaît qu’il a peut-être mal jugé l’Allemagne et,
en même temps, il désespère, parce qu’il était persuadé que l’Allemagne
mourait de faim.
Le lundi matin, dès le réveil, avec le cérémonial de la veille, les trois
ordonnances, le Belge, le Français et le Russe, conduits par le soldat qui
hurle, nous apportèrent du café, du sucre et un petit pot de marmelade pour
chacun de nous. C’était trop. Le soldat qui hurle nous annonça à tue-tête
que ce pot de marmalat est notre ration de toute la semaine et qu’il ne nous
en sera pas distribué d’autre avant lundi prochain. On n’est pas plus
prévenant.
Se préoccuper de notre appétit, c’est bien. S’occuper un peu de notre
toilette ne serait pas mal. L’administration du camp n’a certainement pas sur
l’hygiène des principes anglais. Nous sommes obligés de nous
débarbouiller tous dans la même cuvette de fer blanc, et cela où nous
pouvons, au milieu de cette chambre déjà si étroite pour les vingt-deux
prisonniers qu’elle contient. Mais de quoi vais-je me plaindre? Comme je
bougonne, un camarade me raconte qu’à Stenay, siège du Q. G. du
Kronprinz, où on l’a d’abord emmené après le combat, on lui servait la
soupe de riz et d’orge dans un seau hygiénique émaillé dont l’état de
délabrement marquait bien qu’il n’avait pas été spécialement acheté pour
faire office de marmite. Les Boches ont l’esprit fin.
Vers neuf heures, quand il vint nous trouver comme il nous avait promis
qu’il le ferait, Herr Schmidt, monsieur le censeur, dut sauter par-dessus une
mare d’eau de savon pour arriver jusqu’à la table. Il ne goûta sans doute pas
l’opportunité de ce sport et donna des ordres pour que les dégâts fussent
réparés sur-le-champ. Ses yeux étaient durs quand il cria sa volonté au
soldat à casquette, chef de nos ordonnances, car en Allemagne il faut
toujours crier quand on commande. Mais monsieur le censeur est un
homme du monde. Il ne l’oubliait pas, et il était d’une gentillesse très
amène, lorsqu’il nous remit les cartes postales que nous attendions.
Herr Schmidt était de bonne humeur, malgré l’accident qui avait troublé
sa venue, et c’est avec une grâce toute légère qu’il se mit à notre disposition
pour satisfaire à toutes les questions que notre ignorance de la vie des
camps de prisonniers légitimait. Assis sur un coin de la table, une jambe
relevée et l’autre à terre, un poing sur la hanche, avait-il l’air d’un officier
conquérant au milieu de vaincus? Il y avait trop de désinvolture dans ses
manières pour que nous pussions douter de la pureté de ses sentiments.
La quarantaine une fois terminée, quand nous serons sortis du «saloir»,
on nous répartira dans les différentes chambres de la citadelle où restent des
places disponibles. Ainsi nous serons mêlés aux anciens, et la captivité dont
ils ont l’expérience, nous paraîtra moins pénible. Monsieur le censeur
n’ajoute pas que de cette façon, au contact de la neurasthénie qui ronge
certainement nos «anciens», nous sombrerons plus vite et plus certainement
aussi dans la même neurasthénie. Devenus prisonniers ordinaires parmi les
prisonniers, nous serons tenus de répondre deux fois par jour à l’appel qui
est fait par un officier allemand, le matin à 9 heures et le soir à 6 heures,
dans la cour quand le temps le permet, et dans les couloirs s’il pleut. Nous
serons tenus d’assister aux repas en commun qui se prennent, en deux
services, dans un réfectoire trop petit pour tous les prisonniers. Nous serons
tenus de respecter les consignes du camp. Nos anciens nous les feront
connaître peu à peu. Mais il faut que nous sachions dès maintenant que les
sentinelles sont autorisées à faire usage de leurs armes, si nous essayons de
transgresser la moindre des consignes. Nous serons tenus de rendre aux
officiers allemands, quel que soit leur grade et quel que soit le nôtre, les
marques extérieures de respect qui leur sont dues. Monsieur le censeur
laisse tomber ce dernier mot comme un coup de trique. Nous serons tenus
d’obéir aux officiers, sous-officiers et soldats allemands en service. Et
monsieur le censeur prononce le mot «soldats» comme s’il nous en giflait.
Mais il sourit de nouveau pour conclure qu’en dehors de ces quelques
menues restrictions et d’autres qui ont moins d’importance, nous pourrons
faire dans le camp tout ce que nous voudrons.
D’ailleurs, le camp de Mayence n’est pas un tombeau. Nous ne serons
pas sans nouvelles du monde extérieur. Évidemment, il est inutile que nos
familles nous parlent de la marche de la guerre, car la lettre ne nous serait
pas remise. Les ordres du Gouvernement Impérial et Royal sont formels à
ce sujet. Nous ne pourrons pas non plus, comme juste, recevoir des
journaux français, mais nous avons le droit de nous abonner à des feuilles
allemandes et à des publications illustrées, comme Die Woche, par exemple.
Herr Schmidt nous conseille surtout de nous abonner aux journaux de
guerre que l’Allemagne publie en français ou en anglais pour les pauvres
gens des régions envahies et pour les prisonniers, qu’il serait cruel de laisser
dans l’ignorance des événements. Ces feuilles sont la Gazette des Ardennes,
la Gazette de Lorraine, le Continental Times, le Petit Bruxellois, etc... Il y
en a d’autres. La Gazette des Ardennes est particulièrement
recommandable, nous dit monsieur le censeur. Mais il est obligé de nous
quitter sur cette bonne recommandation, car on va nous mener à la salle des
douches.
Avant de nous y mener, on nous distribue de petits sacs en toile,
numérotés, qui nous rappellent les sacs à linge des potaches que nous
fûmes. On nous dit que nous devons enfermer dans ces sacs tous nos objets
personnels, montres, porte-monnaie, papiers, etc... Ils resteront dans la
chambre pendant notre absence. Personne n’y touchera. Une sentinelle les
gardera. Et il est prudent que nous n’emportions rien avec nous, parce que
nos vêtements nous seront retirés en bas pour être soumis, pendant vingt-
quatre heures, à des procédés de désinfection qui risqueraient de détériorer
les choses que nous oublierions de préserver. L’homme qui nous donne ces
instructions insiste trop, et l’ordonnance belge sourit d’un air trop averti,
pour que nous n’ayons pas le sentiment bien net que nos petits sacs seront
fouillés pendant notre absence. Mais que faire? Quelques officiers veulent
essayer à tout prix de sauver des trésors: qui des billets de banque, qui une
boussole, qui un carnet de souvenirs. On cherche des cachettes: sous une
armoire, dans une paillasse, sous la coiffe d’un casque, que sais-je? Et,
pleins d’inquiétude, nous descendons vers la salle des douches, qui est
installée au sous-sol même du bâtiment nº III.
Nous descendons par le grand escalier, munis d’une serviette et d’une de
nos deux couvertures de laine blanche. Devant la porte du Baderaùm, un
soldat français nous distribue de grands anneaux de fer garnis d’une plaque
portant un numéro. A cet anneau nous enfilerons par la boutonnière nos
vêtements et notre linge, comme des clefs à un trousseau, et le tout ira à la
désinfection. A côté du soldat français, au seuil même de la salle qui
précède le Baderaùm, se tient un soldat allemand. Sans s’occuper de la
corpulence des individus, il nous met entre les mains une chemise, un
caleçon, une paire de chaussettes, le tout à l’état de neuf, et une savonnette.
Mon Dieu! que cette organisation est admirable! La chemise et le caleçon
sont en jersey de coton, fin et camelotard, de couleur crême, mais la
chemise est enrichie d’un plastron en piqué blanc agrémenté de fleurettes
bleues. C’est bien joli. Tout en nous déshabillant, nous ne nous lassons pas
de manifester notre émerveillement. Mais, si nous plaisantons, rien ne nous
empêche d’échanger entre nous les caleçons et les chemises afin de les
adapter un peu mieux à nos proportions.
La douche prise, chaude ou froide à volonté, il fallut remonter dans la
chambre nº 28. Notre cortège ne manquait pas de pittoresque: tous ces
caleçons et toutes ces chemises et toutes ces chaussettes d’uniforme, sous la
couverture d’uniforme, composaient un tableau assez grotesque. Et c’est
dans cette tenue que nous demeurerons jusqu’à ce qu’on nous ait rendu nos
effets désinfectés.
Dans la chambre nº 28, une surprise nous attendait: nos petits sacs
individuels avaient disparu. Un murmure de stupeur s’éleva, vite suivi
d’éclats de rire. La chose était trop drôle. Que de précautions pour nous
dévaliser! Beau travail vraiment. Les paillasses des lits avaient été
retournées; les coiffes de nos casques avaient été fouillées; les Trains de
Luxe d’Abel Hermant n’étaient plus là; toutes les cachettes avaient été
éventées. Tout était perdu. Rafle intégrale. Naufrage de toutes les
espérances.
Pour se faire pardonner une si déplorable maladresse, qui ne pouvait que
nous mal disposer, l’Administration nous offrit un repas copieux, où les
kartoffeln abondaient, et nous eûmes même un supplément de consolation:
de la marmelade. Notre rage d’ailleurs eût été vaine. Il ne nous restait qu’à
prendre en riant notre mésaventure. Le déjeuner s’en trouva égayé, d’autant
que la tenue que nous avions tous prêtait à la plaisanterie. On ne voit pas
tous les jours vingt-deux sous-lieutenants en caleçon réunis autour de la
même table. Si la fantaisie règne dans les popotes d’officiers, elle ne va
jamais jusqu’à ces excès de mardi-gras.
Le soldat boche, qui hurle en dirigeant nos ordonnances, mit fin au repas
par un mot charmant, qu’il faut que je rapporte parce que, dans sa
grossièreté, il offre un raccourci édifiant et caricatural, pour ainsi dire, de
toute la tactique allemande en face des prisonniers. J’en ai déjà parlé. J’en
parlerai encore. Donc, aujourd’hui nous achevions le dessert. Le plat de
marmelade était vide.
—En voulez-vous d’autre? nous demanda l’homme qui hurle, sur un ton
moins aigre qu’à l’ordinaire et qui pouvait passer pour aimable.
—Oui, oui, fîmes-nous.
Et le brave Boche nous répondit froidement, en enlevant le plat:
—Il n’y en a plus. (Keine mehr).
Ces petits détails marquent dans la vie d’un prisonnier. Les heures sont
lentes, les événements rares. On n’a que de menus faits à collectionner et à
méditer. On les médite. La cristallisation se produit. Et tant de petites
images se groupent à la fin en nous pour former un tableau d’ensemble qui
nous surprend nous-mêmes. On a le temps de réfléchir en captivité.
Pendant que nous étions à table, un bruit de pas et un brouhaha de voix
retentirent dans le corridor. Six nouveaux venaient d’arriver par le train de
midi. On les enferma dans une chambre spéciale. Il ne fallait pas qu’ils
pussent communiquer avec nous. Songez qu’ils nous auraient peut-être
donné du front des nouvelles plus fraîches que celles que nous avions, et
rassurantes peut-être. Il fallait éviter ce scandale. Mais l’arrivée des six
camarades pestiférés bouleversa l’ordre de notre repos. En effet, comment
expliquer cela? Était-ce le changement de régime, ou la qualité de la
cuisine, ou ce pain plutôt, si peu catholique, toujours est-il que la plupart
d’entre nous étaient indisposés, et assez gravement même. Jusque-là, il nous
suffisait de frapper à la porte. La sentinelle, qui était de faction dans le
corridor, ouvrait et nous conduisait où nous désirions aller. Quand nos
nouveaux compagnons d’infortune furent arrivés, nous dûmes nous plier à
un autre règlement. Nous ne pouvions plus sortir de la chambre à notre gré.
De temps en temps, le soldat à casquette chargé de notre service
déverrouillait la porte, l’ouvrait toute grande, et glapissait d’un ton suraigü:
—Latrinen! Latrinen!
Il n’y avait qu’à obéir. Et cela nous procura une occasion de plus
d’admirer cette belle organisation et cette stricte discipline allemandes, qui
réalisent le tour de force d’amener la nature même à exécuter leurs ordres
au premier commandement. Au surplus, l’homme qui hurle y gagna un
surnom, et nous ne l’appelâmes plus que Latrinen. Un prisonnier s’amuse
de peu.
L’ordonnance belge nous avait appris qu’on nous rendrait, dans le
courant de l’après-midi, le contenu de nos sacs, ou ce qu’il plairait à
l’administration du camp de nous en rendre. Nous n’attendions pas sans
impatience ce moment. A 3 heures, la cérémonie eut lieu en grande pompe,
avec un déploiement considérable de preuves de la plus scrupuleuse
honnêteté. Je dirai tout de suite que, tout compte fait, il ne manquait pas
grand’chose dans les sacs qu’on nous avait subtilisés. Mais ils avaient été
fouillés comme nous le montra le désordre de certains portefeuilles, et
d’ailleurs les Allemands n’avaient pas besoin de se cacher, et ils n’allaient
pas se gêner pour nous confisquer franchement et devant nous ce qu’ils
crurent bon de nous prendre.
Aucun officier n’assistait à l’opération. On sait que ces messieurs ont des
scrupules et nul n’ignore qu’ils ne sont pas des bandits. Cette besogne vile
était confiée à de simples soldats, à deux soldats exactement, installés de
chaque côté d’une table dans le corridor froid où, avec notre tenue légère,
nous étions transis. L’un d’eux vidait le sac sur la table, visitait les
portefeuilles, supprimait les carnets, les papiers, les boussoles, les cartes, les
jumelles, les appareils photographiques, les stylographes, les sifflets, les
couteaux de poche et les canifs, car tout cela constituait, disaient-ils, du
«butin de guerre». Il remettait le reste au prisonnier qui protestait à chaque
objet qu’on lui retirait; puis, prélevant l’argent qu’il trouvait, il le donnait à
son camarade, qui faisait office de changeur. Cours du jour: 78 marks pour
100 francs, le taux de principe d’avant la guerre; mais les Allemands nous
volaient, puisque, en gros, à cette époque, le mark et le franc s’équilibraient
à Berne. Au surplus, notre changeur ne nous versait pas de l’argent ou du
papier allemand. Il nous alignait des pièces de zinc, qui n’ont cours que
dans l’intérieur du camp et qui sont les seules à avoir cours; d’un côté, elles
portent le chiffre de la somme qu’elles représentent, un pfennig ou
cinquante marks; et de l’autre, l’aigle boche, avec cette inscription:
«Wertmarke—Zitadell Mainz».

L’examen des vingt-deux sacs fut long. Chaque officier protestait.


L’Allemand le laissait protester, objectait qu’il avait reçu des ordres, et
continuait son petit travail de pillage organisé. Comme il devait sourire à
part soi de nos prétentions! Il ne s’emportait pas, il gardait un calme
magnifique sous les réclamations et les outrages. Et son camarade n’avait
pas moins de sang-froid en nous comptant nos pièces de zinc. D’ailleurs,
j’allais l’oublier, il ne nous rendait pas intégralement la somme allemande à
laquelle nous avions droit. Il nous retenait, en effet, un certain nombre de
marks et de pfennigs, pour la chemise, le caleçon, les chaussettes et la
savonnette qu’on nous avait distribués à la salle de douches. Car il ne faut
pas croire que le Gouvernement Impérial et Royal nous fit cadeau de ces
choses, comme don de bienvenue. Il nous les faisait même payer assez cher.
Ainsi s’achevait cette deuxième journée de quarantaine, dans le «saloir»
de Mayence, au milieu d’une effervescence assez grande, lorsqu’un incident
d’une haute importance pour nous se produisit vers six heures du soir. La
porte s’ouvrit, et une image de Hansi parut, qui m’éblouit au point que je
pensai rêver: c’était un Allemand à lunettes, grand, large d’épaules, un peu
voûté, un peu usé, avec l’air accablé de surscience d’un instituteur boche.
D’une voix hésitante et appliquée, il appela l’un de nous, le sous-lieutenant
L***, qu’on disait être professeur de lettres au Lycée Louis-le-Grand, et le
pria de venir avec lui. L*** sortit, vêtu de sa chemise et de son caleçon et
drapé de sa couverture blanche comme d’une toge. L’ordonnance belge se
trouvait à point nommé dans la chambre pour nous renseigner. L*** allait
subir l’interrogatoire officiel d’usage. Puis il irait prendre sa place parmi les
prisonniers ordinaires du camp. Nous ne le reverrons pas dans la chambre
nº 28, car nous ne devons pas connaître dans quelles conditions se passe
l’interrogatoire de rigueur.
La veillée reprend, lugubre, dans la chambre mal éclairée. L’homme de
Hansi ne reparaît pas dans l’embrasure de la porte. On n’interrogera plus
personne aujourd’hui. Mais nous pouvons espérer que demain nous serons
tous appelés, l’un après l’autre, par l’instituteur à lunettes. Demain soir, il
n’y aura peut-être plus personne dans la chambre nº 28. Nous serons tous
peut-être, demain soir, des prisonniers comme les autres au milieu des
autres. Notre vie au camp de Mayence commencera. Pour l’instant, nous
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