<<

Class Notes for Cryptologic Mathematics (FYS 100)

Tim McDevitt Frank Arnold (2012)

ELIZABETHTOWN COLLEGE E-mail address: [email protected] August 27, 2013 Contents

Preface vii

Introduction 1 0.1. What is Cryptology? 1 0.2. Types of 3 0.3. Mathematical Ciphers 6 0.4. Types of Cryptologic Attacks 7 0.5. Notation and Terminology 7 Exercises 8

Chapter 1. 11 1.1. Fundamental Theorem of Arithmetic 11 1.2. Greatest Common Divisors 12 1.3. Euclidean Algorithm 12 1.4. Extended Euclidean Algorithm 14 1.5. Relatively Prime Numbers 15 1.6. Modular Arithmetic 15 1.7. Solving Linear Congruences 19 1.8. Additive 23 1.9. of the Additive Cipher 25 1.10. Affine Cipher 27 1.11. Cryptanalysis of the Affine Cipher 27 Exercises 28

Chapter 2. Probability 33 2.1. Counting 33 2.2. Probability 36 2.3. 39 2.4. Vigenère Cipher 41 Exercises 45

Chapter 3. Recursion 49 3.1. Recursion 49 3.2. Binary Arithmetic 50 3.3. Data as Bits 51 3.4. of Binary Data 52 3.5. Linear Feedback Shift Registers 53 Exercises 55

Chapter 4. Matrices 57 4.1. Matrix Arithmetic 57 4.2. 60 4.3. Cryptanalysis of the Hill Cipher 61 Exercises 64

v vi CONTENTS

Chapter 5. Modular Exponentiation 67 5.1. and Multiply Algorithm 67 5.2. Mathematical Induction 68 5.3. Euler Phi Function 69 5.4. Fermat’s Little Theorem 72 5.5. Euler’s Theorem 75 5.6. Diffie-Hellman Exchange 76 5.7. RSA Encryption 78 Exercises 79 Bibliography 83 Preface

The first author has taught cryptology as a First-Year Seminar at Elizabethtown College for several years using Robert Lewand’s fine book [4]. However, less than half of the author’s students are math or science majors, so Lewand’s rigorous approach is often under-appreciated. These notes follow much of the same material, but they rely fairly heavily on student intuition instead of rigorous proof, as is usually done in calculus courses. Proofs or arguments are reserved for those situations where results are not intuitively clear to the students. For instance, students don’t struggle with the transitivity of divisibility for integers (if a b and b c, then a c), but Fermat’s little theorem requires a proof. Other situations warrant justifications that| fall short| of proofs,| but are still convincing to students. For example, we don’t formally prove that the Euclidean algorithm always finds the gcd of two positive integers, but we demonstrate that it has to work with “generalizeable examples”. Since our audience includes first-year students who are not math or science majors, we have tried to minimize the use of terminology and mathematical jargon. Students interested in more details should consult textbooks on number theory or algebra, or just wait patiently for an opportunity to take those courses. The second author is a former (2008) student of this course who has provided a student’s perspective on the presentation of the material. As a result, the style of writing is informal in an attempt to teach some math and to develop enthusiasm for cryptology. Please note that this text does not address the history of cryptology in a systematic way so that we can focus on the mathematics. Students of cryptology should appreciate the impact of cryptology on historical events, but that knowledge will have to be obtained from other sources (c.f. [3] and [10]). Throughout the notes are several hyperlinks to Mathematica notebooks that are helpful for cryptologic calculations or for demonstrating mathematical concepts. The entire set of notebooks can be found at users.etown.edu/m/mcdevittt/. The file cipher.nb contains that implements most of the encryption algorithms in the book. Readers may also enjoy using the FREE software package ECrypt(www2.etown.edu/ ECrypt/ECrypt.htm ). The current (2013) version of ECrypt is a .jar file, so it should be platform indepen- dent, provided that your computer has Java installed. ECrypt doesn’t have to be installed; just download it and run it. It has a graphical user interface (GUI) that enables users to easily implement the crypto- graphic algorithms in this course. It also provides special tools for cryptanalysis, a recursive calculator, and a calculator for modular arithmetic. Future versions of this book will have chapters dedicated to elliptic curves and to the encryption and cryptanalysis of historical ciphers applied to image and sound files as described in [5].

vii

Introduction

0.1. What is Cryptology?

Classically, cryptology was used to send and receive secret messages and its users were often military leaders or diplomats. For Admiral Alice to send General Bob a secret message, she would have to encrypt or encipher her message using a method that she and Bob had previously agreed upon. When Bob receives the message, he has to decrypt or decipher her message to read it. Often, the method of encryption would rely on a key - some special number(s) or word(s) that only Alice and Bob know. Prior to the computer age, encryption methods were relatively simple, not explicitly mathematical, and often not very secure. Messages were relatively short and there was very little systematic research certifying the security of cryptologic methods. Today, however, messages can be very long. As of this writing (2010), a typical JPEG file from a digital camera is over 1 MB, which is roughly equivalent to a text file of a million characters. Contemporary encryption methods tend to use very sophisticated mathematics and there is a great of systematic research. The US Department of Commerce certifies certain algorithms so that users can be confident that their communications are secure, and these algorithms can be very complicated.1 In addition to the transmission and reception of secret messages, modern cryptology also involves less well- known operations such as , digital signatures, , hashing, etc..., but this book focuses, for the most part, on mathematical versions of historical methods. These methods require what is probably unfamiliar mathematics and, although they are no longer useful, they evolved into today’s methods so it is still useful to be familiar with them. The only exception is our dicussion of public key systems, which currently enjoy widespread use. Another important difference between classical and modern cryptography is frequency of use. In the past, the average individual had no practical reason to encrypt messages, but today we all use cryptographic algorithms without even knowing it when we use our cell phones or email or make online purchases. There- fore, modern cryptology is directly applicable to our daily lives in very important ways. Finally, the nature of characters in encryption algorithms has changed in modern times. In the past, messages were composed using characters from a fixed alphabet, so, for example, two English speakers might use a 26-letter alphabet abcdefghijklmnopqrstuvwxyz, or they might use a 52-letter alphabet that includes capital letters, or they might include digits and punctuation. In this course, we will frequently assume a 26-letter alphabet. Computers store files in terms of bits that we can regard as an alphabet of only two characters: 0 and 1. This includes Word R , and Excel R documents, JPEG images, MPEG movies etc...

Modern encryption algorithms operate at the bit level on a computer, so all computer files can be encrypted in the exact same way, regardless of how we interpret those bits as text, pictures, movies, etc... Cryptology is an umbrella term for cryptography and cryptanalysis. Cryptography involves the creation and use of algorithms that pass private information between two parties with the goal of obscuring the

1For example, see the NIST document FIPS 197 that takes 51 pages to describe AES. The good news is that the description is very good and very clear, unlike IRS documents.

1 2 INTRODUCTION

Figure 0.1: Can you read the message hidden in this poem that is revealed by the stencil?

information from unintended recipients. Classically, users might hope that adversaries would not know what encryption algorithms were being used, but that is an unrealistic expectation today. Today, we have to assume that adversaries know what algorithms we are using, so the security of a method depends entirely on the difficulty of recovering the secret key. Symmetric, or private key, systems, require both sender and receiver to know the same secret key, but modern public key systems enable parties to communicate securely without previously establishing a secret key. Cryptanalysis is the study of cryptographic algorithms with the intent of recovering secret messages without knowing the secret key. We can think of cryptanalysis as the activity of an adversary who obtains an encrypted message and tries to recover the original message without knowing the key, but cryptanalysis could also be the activity of an analyst who is studying the security of a given method. Loosely speaking, we can think of cryptographers as the defense and cryptanalysts as the offense, but both sides must know what the other is capable of to do their jobs properly. We also want to distinguish cryptography from , which seeks to hide the very existence of a message. For example, the children’s activity of writing a note in invisible ink is an example of steganog- raphy as is the use of a stencil to hide a message in a book. (See Figure 0.1.) Of course, steganography can be combined with cryptography to provide extra security. Although steganography can be very interesting, we won’t discuss it in this book. Finally, a cipher is an encryption algorithm that is used to encrypt (or encipher) a message, or plain- text, into apparently unintelligible . The original is recovered by decrypting (or deci- phering) the ciphertext. The terms “plaintext" and “ciphertext" still apply even if the data are not really text but just some form of data (e.g. bits). Also, for convenience people often shorten “ciphertext" into “cipher", so you have to tell them apart from context. Finally, the word “key" is often used in different ways at the same time, but we will wait to point that out until later. 0.2. TYPES OF CIPHERS 3

Figure 0.2: The same strip of paper displayed on two different diameter tubes. On the left we see part of the joke How do you know that you have found an extroverted mathematician? He looks at your feet when he talks to you. On the right, the message is unreadable.

0.2. Types of Ciphers

There are two basic tools that are used in encryption algorithms: transposition (rearranging the char- acters) and substitution (replacing characters with other characters). Transposition and substitution are familiar as two popular types of puzzles, anagrams and .

Classroom Exercise 0.1: Here is a sample anagram; the letters in each word have simply been jumbled. See if you can decipher the message. RYOU RETARSIPNVEETE WSOE UYO, OTN IHS UNSYRTDI YNOL, UBT HSI TEJGMDUN; AND EH BTSAYRE, EDITASN FO ERNVSGI OUY, FI EH ACFRSIEISC TI OT RYUO NONPOII - "PHCEES TO EHT RESCLETO AT BLRTIOS TA HTE CONSOCINUL OF HET LLOP" BY EDUNDM RBEUK

Classroom Exercise 0.2: Here is a sample ; each letter is replaced by another letter. See if you can decipher the message. LRLSUB ZYU SRHU CRYCSUB MYZQD XF LKU WZJRCRZD'B QZDM, LO CODLYZCL LKU BIKUYU ON WZD'B NUSRCRLF. KU SRVUB RWWGYUM QRLKRD LKU XZBLRSSU ON Z QOYM, ZDM BGYVUFB ZL Z MRBLZDCU LKU UDVRUM SRNU ON WZD. - "LKU YRJKLB ON WZD" XF LKOWZB IZRDU.

If you actually solved both puzzles, then the punctuation and spacing of the words in both the anagram and the cryptogram probably help a lot. We can make a much more difficult puzzle by using a shorter message, removing all spacing and punctuation, using both transposition and substitution.

Classroom Exercise 0.3: Winston Churchill reportedly said RSAAPTAPCVTMVZSCSOCPYDTDTQQQQITPQ. See if you can decipher this combination anagram and cryptogram with spacing and punctuation removed.

An ancient example of a is the σκυταλη´ (), which the Spartans reportedly used for tactical messages on the battlefield. A strip of leather or parchment was wound around a stick and a message was written across it as shown in Figure 0.2. Once the strip was unwound, the letters were jumbled and the message was unreadable. Furthermore, the message could only be read by wrapping the message around a stick with the same diameter. Figure 0.2 shows a scytale with a decidedly unimportant message. It illustrates how the message is unintelligible if the diameter is incorrect. In this case, the diameter of the stick is the secret key. 4 INTRODUCTION

An early example of a is the , which simply shifts each letter in the plaintext ahead 3 places to produce an encrypted message. For example, veni vidi vici2 becomes yhql ylgl ylfl. The Caesar cipher is attributed to Julius Caesar by Suetonius, who was a prominent historian of the Roman emperors in the first and second centuries A.D. According to Suetonius [12], “Exstant et ad Ciceronem, item ad familiares domesticis de rebus, in quibus, si qua occultius perferenda erant, per notas scripsit, id est sic structo litterarum ordine, ut nullum verbum effici posset; quae si qui investigare et persequi velit, quartam elementorum litteram, id est D pro A et perinde reliquas commutet.” The translation of Suetonius on penelope.uchicago.edu is

“There are also letters of his to Cicero, as well as to his intimates on private affairs, and in the latter, if he had anything confidential to say, he wrote it in cipher, that is, by so changing the order of the letters of the alphabet, that not a word could be made out. If anyone wishes to decipher these, and get at their meaning, he must substitute the fourth letter of the alphabet, namely D, for A, and so with the others.” If this translation is correct, then it actually sounds like Caesar’s messages were decrypted by shifting 3 letters to the right. Nevertheless, modern cryptographers generally understand Caesar’s cipher as a shift of 3 letters to the right. The Caesar cipher is an example of a monoalphabetic substitution cipher, in which every character is replaced by some other character. In the 9th century A.D., Abu Yusuf Yaqub ibn Ishaq al-Sabbah Al-Kindi introduced that made monoalphabetic substitution ciphers obsolete because they were no longer secure. To thwart frequency analysis, people in succeeding centuries invented polyalphabetic subsitution ciphers, in which each letter is replaced by another letter that changes with each use. For instance, a polyalphabetic system might encrypt the first a in aardvark as , but the second a might be encrypted as n. Examples include the wheel and the Vigenère cipher. In 1467, (1404-1472) developed a cipher wheel that produced ciphertext that was not vulnerable to Al-Kindi’s frequency analysis. The wheel consisted of two rings and the inner ring could be turned about its center. Sender and receiver would agree on a “pointer” letter - Alberti chose k. The sender picks a letter on the outer ring and lines it up with k on the inner ring and then enciphers several letters by locating plaintext characters on the outer ring and associating them with corresponding cipher characters on the inner ring. For example, using the first setting in Figure 0.3, the first six characters of VENIVIDIVICI are encrypted as Fnxrpnp. What makes his method polyalphabetic is that the sender occasionally points k at a new letter. Using the second setting in Figure 0.3, the last six characters of VENIVIDIVICI are encrypted as 4mghg&g. Therefore, altogether, the message VENIVIDIVICI can possibly be encrypted as Fnxrpnp4mghg&g. It is interesting to note that Alberti’s wheel omits H, K, U, W and Y but includes some digits. Apparently, Alberti was content to associate U with V and W with VV. In 1585, Blaise de Vigenère introduced a polyalphabetic substitution cipher that endured for three cen- turies. The user chooses a key word, say LION, and writes it down repeatedly under the plaintext until the key is as long as the plaintext. Then the user looks up each (key letter, plain letter) pair in the Vigenère square in Table 0.1.

2"I came, I saw, I conquered." was Caesar’s report to Rome in 47 B.C. after his overwhelming defeat of King Phar- naces II of Pontus at the battle of Zela. 0.2. TYPES OF CIPHERS 5

Figure 0.3: Two setting of Alberti’s cipher wheel.

ABCDEFGHIJKLMNOPQRSTUVWXYZ A ABCDEFGHIJKLMNOPQRSTUVWXYZ B BCDEFGHIJKLMNOPQRSTUVWXYZA C CDEFGHIJKLMNOPQRSTUVWXYZAB D DEFGHIJKLMNOPQRSTUVWXYZABC E EFGHIJKLMNOPQRSTUVWXYZABCD F FGHIJKLMNOPQRSTUVWXYZABCDE G GHIJKLMNOPQRSTUVWXYZABCDEF H HIJKLMNOPQRSTUVWXYZABCDEFG I IJ KLMNOPQRS TUVWXYZABCDEFGH J JKLMNOPQRSTUVWXYZABCDEFGHI K KLMNOPQRSTUVWXYZABCDEFGHIJ L LMNOPQRSTUVWXYZABC DEFGHIJK M MNOPQRSTUVWXYZABCDEFGHIJKL N NOPQRSTUVWXYZABCDEF GHIJKLM O OPQR STUVWXYZABCDEFGHIJKL MN P PQRSTUVWXYZABCDEFGHIJKLMNO Q QRSTUVWXYZABCDEFGHIJKLMNOP R RSTUVWXYZABCDEFGHIJKLMNOPQ S STUVWXYZABCDEFGHIJKLMNOPQR T TUVWXYZABCDEFGHIJKLMNOPQRS U UVWXYZABCDEFGHIJKLMNOPQRST V VWXYZABCDEFGHIJKLMNOPQRSTU W WXYZABCDEFGHIJKLMNOPQRSTUV X XYZABCDEFGHIJKLMNOPQRSTUVW Y YZABCDEFGHIJKLMNOPQRSTUVWX Z ZABCDEFGHIJKLMNOPQRSTUVWXY

Table 0.1: A Vigenère square. The highlighted letters correspond to an example in the text.

Plain: SCYTALE Key: LIONLIO Cipher: DKMGLTS 6 INTRODUCTION

For example, to encrypt the first letter in SCYTALE, the user looks in row L and column S to find a D. This is the cipher character that substitutes for the S. Continuing this process produces the entire cipher- text DKMGLTS. Be careful of the potentially confusing terminology - the keyword LION generates the key LIONLIO for the cipher, but people may refer to both LION and LIONLIO as key. The Vigenère cipher was highly regarded for three centuries and it was considered by many to be secure until Charles Babbage cracked it in 1854. Friedrich Kasiski also broke the cipher in 1863, but it seems that cryptological news traveled slowly because the Confederacy still used the Vigenère cipher during the U.S. Civil War to the advantage of the North. In fact, as late as 1917, Scientific American (Supplement LXXXIII, January 27, 1917) still advocated its use.

“The [Vigenère ] method used for the preparation and reading of code messages is simple in the extreme and at the same time impossible of translation unless the key is known. The ease with which the key may be changed is another point in favor of the adoption of this code by those desiring to transmit important messages without the slightest danger of their messages being read by political or business rivals etc.”

Modern ciphers are often polygraphic.A polygraph is a sequence of several characters; specifically a digraph is a sequence of two characters and a trigraph is a sequence of three. Polygraphic substitution ciphers encrypt entire blocks of characters together. We will study the Hill cipher in chapter 4 as an example of a polygraphic substitution cipher, but it is a little too complicated to introduce quickly here. One common feature of all classical methods is that they are symmetric in the sense that both sender and receiver require knowledge of the algorithm and the secret key. This sort of arrangement is not always possible in the computer age. Therefore, in chapter 5 we study two public key systems that allow people to communicate even though they’ve never had an opportunity to agree upon a secret key.

0.3. Mathematical Ciphers

Since the intended audience of this book speaks English, the most commonly used alphabet in this book is English, but we really can use any alphabet we want, and the length of the alphabet is usually not important.

Latin: ABCDEFGHIKLMNOPQRSTVXYZ Greek: αβγδεζηθικλµνξoπρςστυφχψω   Arabic: øñîDÒʾ ®®ªª ¢¢ ’’ ‚ƒ PP XYjjj. JK.@ Computer: 01 Grayscale 8-bit bitmap: 0 1 2 ... 254 255

None of the methods we’ve discussed so far require the use of mathematics. However, math can make any of them much easier to implement, either by hand or on a computer. For example, in chapter 2 we will revisit the Vigenère cipher, but we will have absolutely no need of the cumbersome Vigenère square in Table 0.1, so it will be much easier to encrypt and decrypt messages. The ciphers in chapters 3, 4, and 5 are all thoroughly mathematical and we can’t even describe the algorithms without using mathematics. Cryptanalysis is also greatly aided by the use of mathematics and statistics. Consider the simple scytale, which is equivalent to writing the plaintext characters in a table as shown. 0.5. NOTATION AND TERMINOLOGY 7 HOWDOYOUKNOWT HATYOUHAVEFOU NDANEXTROVERT EDMATHEMATICI AN?HELOOKSATY OURFEETWHENHE TALKSTOYOU The ciphertext is read off in columns: HHNEAOT OADDNUA WTAM?RL DYNAHFK OOETEES YUXHLET OHTEOTO UARMOWY KVOAKHO NEVTSEU OFEIAN WORCTH TUTIYE. Software like Mathematica makes ciphertext like this easy to crack. Try it with the Mathematica notebook Scytale.nb at http://users.etown.edu/m/mcdevittt/Crypto.html.

0.4. Types of Cryptologic Attacks

Real life cryptanalysis often hinges on operator error or some flaw in the design of the machine or software that implements a cryptographic algorithm. Such mistakes make different scenarios possible for an adversary. One type of attack is a known-plaintext attack, in which the cryptanalyst knows the encryption algorithm and has access to some plaintext and the corresponding ciphertext. Such plaintext is often referred to as a crib. The Allies used cribs to find Enigma keys during World War II. In a chosen plaintext attack, the cryptanalyst has an opportunity to choose some plaintext to feed into the cryptographic algorithm, but we will mostly consider ciphertext-only attacks, where we have some cipher and the only thing we know is the algorithm. Recall that we will always assume that cryptanalysts know the relevant cryptographic algorithms and the only thing that they lack is the key.

0.5. Notation and Terminology

Mathematicians tend to write very concisely and use a lot of specialized symbols, so it might be helpful if we introduce some of the symbols that we’ll be using. Sets with listed elements are written with braces, like red, green, blue . Other special sets have special symbols. For instance, the set of integers is denoted { } by Z. The natural numbers, rationals, reals, and complex numbers are N, Q, R, and C, respectively. There is no universally recognized symbol for whole numbers, but we could use N 0 ; the union ( ) of N and the set including only the number zero. In this course, we will work almost∪ exclusively { } with integers,∪ but we will encounter real (or rational) numbers when we study probability. We indicate that “a is an integer" by writing a Z to indicate that a is in ( ) the set of integers. We write∈a b to indicate that a divides∈ b. That is, for integers a and b, a divides b if there exists an | integer c such that ac = b. For example, a = 2 divides b = 12 since there is an integer c = 6 such that ac = (2)(6) = 12 = b. Similarly, a = 2 does not divide b = 13 (written 2 13) since there is no integer c 6 | such that ac = 2c = 13 = b. As we mentioned in the introduction, the words “encrypt” and “encipher” are synonymous, as are “de- crypt” and “decipher”. Original text is plaintext and the encrypted text is ciphertext, even if the text isn’t really text. Pictures, audio, computer files can all be encrypted, so it might seem a little odd to call a picture plaintext, but we’ll do it anyway. The word “cipher” usually refers to an encryption algorithm, but it can be a shortened version of ciphertext. Also, the word key is often used imprecisely. Sometimes it refers to the keyword or key number(s), and sometimes it refers to a long string of letters or numbers that are generated from the keyword. 8 INTRODUCTION

A code exchanges one system of writing for another. It may have the effect of making a message unintelligible, but that is not always its purpose. Two familiar non-encrypting codes are Morse code and ISBNs. Morse code converts English into a series of dots and dashes so that an English message can be easily trasmitted over a primitive channel like a telegraph line. The ISBN code for a book serves two purposes; it identifies the book (like a numerical name) and it attaches a check character at the end that can identify mistakes in the number. For instance, the ISBN-10 for Lewand’s Cryptological Mathematics [4] is 0-88385- 719-7. The leading 0 indicates the language (English), the second group of numbers, 88385, indicates the publisher (The Mathematical Association of America), and the third set of digits is the publisher’s serial number for the book. The final digit, 7, is chosen so that

0 1 + 8 2 + 8 3 + 3 4 + 8 5 + 5 6 + 7 7 + 1 8 + 9 9 + 7 10 = 330 · · · · · · · · · · is divisible by 11. If someone made a silly transposition mistake like 0-88835-719-7, the ISBN code would identify it since

0 1 + 8 2 + 8 3 + 8 4 + 3 5 + 5 6 + 7 7 + 1 8 + 9 9 + 7 10 = 325 · · · · · · · · · · is not divisible by 11. So, when people talk about codebreaking, they are really talking about cryptanalysis.

Exercises

(1) Decrypt the Caesar ciphertext shwhuslshuslfnhgdshfnrislfnohgshsshuv. (2) Decrypt each of the following messages that were encrypted with a scytale. The Mathematica notebook Scytale.nb might be helpful. (a) Sssalbheohe slyearelshs se lee tsh. (b) Wiifd e a etihsxr snBusneny aoe?ese e saifv cevan. (3) Use the Vigenère square (Table 0.1) to (a) encrypt ENIGMA with keyword GERMANY. (b) decrypt YUGPYN if the keyword is JAPAN. (4) Which of the following ISBN-10s are correct? (a) Calculus (6th edition) by Stewart, 0-495-38558-1. (b) Elementary Differential Equations (8th edition) by Boyce and DiPrima, 0-417-43339-X. (X stands for 10.) (c) The Mathematics of Coding Theory by Garrett, 0-13-101976-8. (d) Introduction to Cryptography with Coding Theory by Trappe and Washington, 0-13-186239-1. (5) The first nine digits of the ISBN-10 for each of the following books are given. What should the last digit be? (a) 0-7432-6751- , The Official Rock Paper Scissors Strategy Guide by Douglas and Graham Walker (b) 0-13-187141- , Elementary Linear Algebra: A Matrix Approach by by Spence, Insel, and Friedberg (c) 0-521-47236- , The Nonlinear Theory of Elastic Shells by Libai and Simmonds (6) The cipher replaces the 1st letter of the alphabet with the last, the 2nd with the second-to- last, etc...3 Use the Atbash cipher to decrypt klgzgl xsrk. (7) The Polybius checkerboard cipher places 25 letters of the alphabet (J is missing) in a 5 5 table. × 3The Atbash cipher appears in the Book of Jeremiah where, for example, Babylon is referred to as Sheshakh (in Hebrew). EXERCISES 9

1 2 3 4 5 1 E P X Q Y 2 H V B A O 3 F M C U N 4 T K D L R 5 W I S Z G To encrypt a message like FEEDME, you just give the row and column pair for each letter: 31111143 3211. This has the disadvantage that the ciphertext is twice as long as the plaintext, but it has the advantage that it works well as a semaphore. (a) Encrypt HANDITOVER. (b) Decrypt 231141411145412544525521412535113324354344114121243533344553114 121114324454235115353332535313433523453. (c) What is the key for this cipher? (d) The keyspace for a cipher is the set of all possible keys. How big is the keyspace for this cipher? (8) In the Wheatstone-, 25 letters of the alphabet are placed into a 5 5 table. E P X Q Y × H V B A O F M C U N T K D L R W I S Z G Plaintext messages are broken into digraphs, and if the pair of letters lie in the same row, then the ciphertext is the pair of letters to the right, wrapping around as • necessary. lie in the same column, then the ciphertext is pair of letters beneath, wrapping around as • necessary. lie at the corners of a rectangle, then the ciphertext is the pair of letters in the opposite • corners. For example, WELCOME is encrypted as EHDUVNPY, the end of WELCOME with Q so that its length is even. MATHCOUNTS R (a) Encrypt . (b) Decrypt BRRNKTNFISWFXDSZBGDG. (c) What is the key for this cipher? (d) How big is the keyspace for this cipher?

CHAPTER 1

Modular Arithmetic

This chapter develops the mathematical tools needed for modular arithmetic and modular algebra, both of which will be useful throughout the entire course. After that, we apply our new knowledge to the additive and affine ciphers.

1.1. Fundamental Theorem of Arithmetic

Recall that an integer p > 1 is prime if the only integers that divide it are 1 and p. (We will frequently use p and q to represent prime numbers.) Composite numbers are integers greater than one that are not prime. Also, recall the fundamental theorem of arithmetic. (Don’t worry if you don’t recognize the name, it should still be familiar.)

THEOREM 1.1 (Fundamental Theorem of Arithmetic). Every positive integer n > 1 can be written uniquely as a product of primes.

We won’t prove the theorem because it is probably very familiar to most readers. If you are interested in a proof, it isn’t very difficult and you can find one in a book on number theory or on Wikipedia. Instead, let’s look at some examples.

Example 1.1: You can probably do the first two examples in your head, but the third one might be easier if you use a factor tree.

(1) 35 = 5 7 4· (2) 48 = 2 3 · 2 2 (3) 1260 = 2 3 5 7. · · ·

Classroom Exercise 1.1: Express the following numbers as products of primes. (1) 95

11 12 1. MODULAR ARITHMETIC

(2) 819 (3) 3400

1.2. Greatest Common Divisors

A common divisor of two integers a and b is an integer (positive or negative) that divides both a and b. For example, 2 is a common divisor of 12 and 18 since 2 12 and 2 ( 18). If a and b are both zero, then there are an infinite number of common divisors,− so there can’t| be a| greatest− common divisor. However, every other pair of integers (including if a = 0 or b = 0, but not both) has a finite number of common divisors, so there must be a greatest common divisor. We denote the greatest common divisor of a and b by 1 gcd(a, b). Here is a formal definition:

Definition 1.1: If a and b are not both zero, then the greatest common divisor of a and b is the largest positive integer that divides both a and b.

Classroom Exercise 1.2: Compute the following gcds.

(1) gcd(35, 7) (2) gcd(55, 165) (3) gcd(253, 598)

The first problem was easy. Since 7 35, it must be that gcd(35, 7) = 7. The second was a little harder, but the third is the most interesting. How| did you do it? Most people use the fundamental theorem of arithmetic; they factor both numbers to find that 253 = 11 23 and 598 = 2 13 23, and then conclude that · · · gcd(253, 598) = 23. This works well and it’s what most of us learned in school, but factoring integers is a slow process that becomes cumbersome for very large numbers. Fortunately, there is a better way.

1.3. Euclidean Algorithm

The Euclidean algorithm is an ancient, but efficient, method for finding the gcd of two integers. It is best explained in the context of an example, so let’s consider the last exercise of computing gcd(253, 598).

Example 1.2: To find gcd(253, 598), we first divide the larger number by the smaller. If you can do this in your head, great! Otherwise, use long division. 2 R 92 253 598 506 92 This means that

(1.1) 598 = 253(2) + 92.

Now, gcd(253, 598) clearly divides two of the three terms in (1.1), so it must also divide the third. In other words, since gcd(253, 598) 598 and gcd(253, 598) 253(2), we can conclude that gcd(253, 598) 92. | | | A similar argument shows that gcd(92, 253) also divides all three terms in (1.1), so we can conclude that gcd(253, 598) = gcd(92, 253). This allows us to exchange a hard problem for an easier one, and we can do this type of reduction repeatedly until the gcd(253, 598) is obvious. Since

1Some authors use the equivalent gcf for greatest common factor, but we use gcd. 1.3. EUCLIDEAN ALGORITHM 13

2 R 69 92 253 184 69 gcd(253, 598) = gcd(92, 253) = gcd(69, 92). Finally, 1 R 23 69 92 69 23 so gcd(253, 598) = gcd(92, 253) = gcd(69, 92) = gcd(23, 69). Since 23 69, gcd(253, 598) = 23. Let’s review what we’ve done for this problem. By repeated use of long| division, we have found that

598 = 253(2) + 92 253 = 92(2) + 69 92 = 69(1) + 23 69 = 23(3) + 0. Once we reach a remainder of zero, the algorithm stops because the smaller number divides the larger. Therefore, the second-to-last remainder (written on the right) is the gcd. In this case, it’s 23.

Example 1.3: Let’s work through another example: gcd(226, 270). Repeated use of long division gives

270 = 226(1) + 44(1.2a) 226 = 44(5) + 6(1.2b) 44 = 6(7) + 2(1.2c) 6 = 2(3) + 0.(1.2d)

The second-to-last remainder is 2, so gcd(226, 270) = 2. That is the Euclidean algorithm. We could stop here and move on, but let’s be sure we understand how the Euclidean algorithm works. In (1.2a), the remainder is 44, so gcd(226, 270) = gcd(44, 226). In (1.2b), the remainder is 6, so gcd(226, 270) = gcd(44, 226) = gcd(6, 44). In (1.2c), the remainder is 2, so gcd(226, 270) = gcd(44, 226) = gcd(6, 44) = gcd(2, 6). Finally, in (1.2d), the remainder is 0, so the algorithm stops and gcd(226, 270) = gcd(44, 226) = gcd(6, 44) = gcd(2, 6) = 2. In general, to use the Euclidean algorithm to find gcd(a, b), you divide the larger of the two numbers a and b by the smaller one. Each step after that involves “sliding" and long division. By “sliding", we mean that the divisor and remainder move to the left so that they become the new dividend and divisor, respectively. For example, the 226 and 44 slide left from (1.2a) to (1.2b). In general, you continue this process until the last remainder is 0.

Example 1.4: Let’s do one final example. The gcd(343, 454) = 1 since

454 = 343(1) + 111(1.3a) 343 = 111(3) + 10(1.3b) 111 = 10(11) + 1(1.3c) 10 = 1(10) + 0.(1.3d) 14 1. MODULAR ARITHMETIC

1.4. Extended Euclidean Algorithm

We’re now going to cover the extended Euclidean algorithm. It won’t be immediately obvious why this is important, but it will be very important to us before the end of the chapter. Number theory texts like [6] and [8] typically include a theorem like the following.

THEOREM 1.2. There exist integers x and y such that ax + b y = gcd(a, b).

Example 1.5: If a = 7 and b = 35, then x = 5 and b = 0 satisfy ax + b y = gcd(a, b). Note, however, that Theorem 1.2 does not claim that x and y are unique, so other values for x and y are possible. In this case, other possibilities include x = 6, y = 1 and x = 4, y = 1. − − We won’t prove Theorem 1.2, but we will show you how to find x and y by extending the Euclidean algorithm. This is a little tricky at first, but it’s pretty easy after you’ve done a few examples. One of the hardest ideas is to remember not to explicitly multiply any of the remainders. The only time you’d want to multiply them is to check your calculations.

Example 1.6: Recall Example 1.6 in which we found gcd(343, 454) = 1. Beginning with the equation (1.3c) (i.e. the second-to-last equation, the one that gives us the gcd), we work backwards to find values for x and y.

(1.4a) 1 = 111 10(11) − (1.4b) = 111 (343 111(3))(11) = 111(34) 11(343) − − − (1.4c) = (454 343(1))(34) 11(343) = 454(34) 45(343) − − − Equation (1.4a) is just (1.3c) rearranged so that the gcd is on the left. We successively solve for and sub- stitute the remainders in (1.3c)-(1.3a) (working backwards) to obtain (1.4a)-(1.4c). Specifically, solving (1.3b) for 10 (the remainder) and substituting into (1.4a) gives (1.4b). Solving (1.3a) for 111 and sub- stituting into (1.4b) gives (1.4c), which implies that if a = 343 and b = 454, then x = 45 and y = 34. −

Example 1.7: Here’s another example. Using the Euclidean algorithm to find gcd(233, 97), we have (1.5a) 233 = 97(2) + 39 = 39 = 233 97(2) ⇒ − (1.5b) 97 = 39(2) + 19 = 19 = 97 39(2) ⇒ − 39 = 19(2) + 1 = 1 = 39 19(2).(1.5c) ⇒ − Note that we have solved for the remainders in addition to finding the gcd. Working backwards, we begin with (1.5c) and substitute the remainders in ascending order. We simplify at each step, being careful not to explicitly multiply the remainders or the original two numbers.

1 = 39 19(2) (from (1.5c))(1.6a) − (1.6b) = 39 (97 39(2))(2) (substituting the remainder from (1.5b)) − − = 39(5) 97(2) (simplifying (1.6b))(1.6c) − (1.6d) = (233 97(2))(5) 97(2) (substituting the remainder from (1.5a)) − − = 233(5) 97(12) (simplifying (1.6d)).(1.6e) − 1.6. MODULAR ARITHMETIC 15

If a = 233 and b = 77, then x = 5 and b = 12 satisfy ax + b y = gcd(a, b). − Classroom Exercise 1.3: Use the extended Euclidean algorithm to find values for x and y according to Theorem 1.2 for the following gcds.

(1) gcd(24, 54) (2) gcd(33, 192) (3) gcd(756, 942)

1.5. Relatively Prime Numbers

2 Definition 1.2: Two integers a and b are relatively prime if gcd(a, b) = 1.

Note that a number doesn’t need to be prime to be relatively prime to another number, and prime numbers are not relatively prime to every other positive integer. Consider the following examples.

Example 1.8: Neither 14 nor 25 is prime, but they are relatively prime since gcd(14, 25) = 1.

Example 1.9: Integers 14 and 16 are both composite and they are not relatively prime to each other since gcd(14, 16) = 2.

Example 1.10: Although 13 is prime, it is not relatively prime to 39 since gcd(13, 39) = 13.

Example 1.11: Two distinct prime numbers like 13 and 17 are relatively prime.

Classroom Exercise 1.4: Determine which of the following pairs of numbers are relatively prime.

(1) 26 and 15 (2) 54 and 99 (3) 234 and 555

1.6. Modular Arithmetic

We learn to do arithmetic (addition, subtraction, multiplication, and division) with integers early in grade school, and later we learn about real numbers, usually starting with fractions and then proceeding to decimals. In cryptology, we will usually work only with integers modulo some positive integer n. Our task in this section is to figure out what that means.

Definition 1.3: Integers a and b are congruent modulo n if n (a b). | − If two numbers are congruent modulo n, then we write a b mod n. ≡ Example 1.12: Here are some examples.

(1)7 7 mod 21 since 21 (7 7). ≡ | − (2) 14 2 mod 3 since 3 (14 2). ≡ | − (3)2 12 mod 5 since 5 (2 12). ≡ | −

2Many authors refer to relatively prime numbers as coprime. 16 1. MODULAR ARITHMETIC

We usually reduce integers to the set 0, 1, 2, . . . , n 1 modulo n,3 so, for example, it would be more common to write 12 2 mod 5 than 2 { 12 mod 5,− even} though both are correct. We have two main ways to reduce a mod≡n. ≡

If a 0, then we can replace a with its remainder when it is divided by n. Continuing Example • ≥ 1.12, 7 7 mod 21 since 7 21 = 0 with remainder 7 and 14 2 mod 3 since 14 3 = 4 with remainder≡ 2. ÷ ≡ ÷ We can add or subtract multiple copies of n since n 0 mod n, which is especially helpful for • ≡ a < 0. For example, 7 3 mod 5 since 7 + 2(5) 3 mod 5. The following table shows integers x reduced modulo− ≡ 5 to the set 0, 1,− 2, 3, 4 . ≡ { }

x ... 7 6 5 4 3 2 1 0 1 2 3 4 5 6 7 8 9 10 11 12 . . . x mod 5 ...3− − 4− 0− 1− 2− 3− 401234012340 1 2...

Classroom Exercise 1.5: Reduce the following numbers modulo 16 to the set 0, 1, 2, . . . , 15 . { } (1) 27 (2) 544 (3) 32 − Addition, subtraction, and multiplication modulo n all work exactly as you would expect. You are free to make the calculations as simple as you can by reducing operands modulo n at any time as shown in Example 1.13. One thing you may not do, however, is change powers. For example, 619 is not congruent to 1 6− mod 20.

Example 1.13: Reduce the following modulo 25.

(1)6 + 7(4) = 34 9 mod 25. In this case, we waited until the calculation was completed to reduce it modulo 25. ≡ (2) 26 + 27(14) 1 + 2(14) = 29 4 mod 25. Here, we began by reducing 26 and 27, did the calculation, and≡ then reduced the≡ answer. (3) Don’t hesitate to use negative numbers if it’s convenient. For instance, 24+27(20) 1+2( 5) = ≡ − − 11 = 11 + 0 11 + 25 = 14 mod 25. − − ≡ −

Classroom Exercise 1.6: Reduce the following modulo 32.

(1)3 (15) 4(2) − (2) 30(29)(27) 1(2)(3) 2− (3)9 3(4) 6 + 20 −

3 This is what the % operator does in C/C++ and what the Mod and mod commands do in Mathematica and Matlab, respectively. 1.6. MODULAR ARITHMETIC 17

Here are addition and multiplication tables modulo 9.

+ 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 0 0 1 2 3 4 5 6 7 8 ×0 0 0 0 0 0 0 0 0 0 1 1 2 3 4 5 6 7 8 0 1 0 1 2 3 4 5 6 7 8 2 2 3 4 5 6 7 8 0 1 2 0 2 4 6 8 1 3 5 7 3 3 4 5 6 7 8 0 1 2 3 0 3 6 0 3 6 0 3 6 (1.7) 4 4 5 6 7 8 0 1 2 3 4 0 4 8 3 7 2 6 1 5 5 5 6 7 8 0 1 2 3 4 5 0 5 1 6 2 7 3 8 4 6 6 7 8 0 1 2 3 4 5 6 0 6 3 0 6 3 0 6 3 7 7 8 0 1 2 3 4 5 6 7 0 7 5 3 1 8 6 4 2 8 8 0 1 2 3 4 5 6 7 8 0 8 7 6 5 4 3 2 1

Note that the addition table is more regular or predictable than the multiplication table. Later in this chapter, we will use both addition and multiplication to encrypt messages, and we’ll see that multiplication makes a greater contribution to the strength of the encryption algorithm.

Classroom Exercise 1.7: Complete the following addition and multiplication tables modulo 6.

+ 0 1 2 3 4 5 0 1 2 3 4 5 0 ×0 1 1 2 2 3 3 4 4 5 5

Division. We haven’t mentioned modular division yet because it is much more difficult. Before we do so, let’s think about the real number division we’re much more familiar with. To compute 156 13, we might ask ourselves, “What number a, when multiplied by 13, gives 156?" A little thought reveals÷ that a = 12. We can also think of division as multiplication by a multiplicative inverse (or reciprocal), so  1 ‹ 156 13 = 156 = 12. Remember that all real numbers have multiplicative inverses except for zero. ÷ 13 It’s not immediately obvious what 4/5 mod 9 is since 4/5 is not an integer. To make sense of 4/5 mod 9, we need to ask ourselves the same basic question we did above - “What number a, when multiplied by 5, gives 4 modulo 9?" In other words, we need to solve the congruence 5a 4 mod 9. Because the modulus is small, we could find a by trial and error or by looking in the multiplication≡ table in (1.7)to see that 5 8 4 mod 9, so we could say that 4/5 8 mod 9. However, division is not always well-defined. For instance,× ≡ if we tried to compute 5/3 mod 9,≡ we would fail because the table in (1.7) shows that there is no number which, when multiplied by by 3, gives 5 mod 9. Because of this, mathematicians don’t like to talk about division at all in the context of modular arithmetic. Instead, we talk about multiplicative inverses, but we have to be aware that some numbers may not 1 1 1 1 1 be invertible modulo n. As you can see from (1.7), 1− = 1, 2− = 5, 4− = 7, 5− = 2, 7− = 4, and 1 8− = 8 mod 9, but 3 and 6 do not have multiplicative inverses. What’s special about 3 and 6? The rows (or columns) for 3 and 6 in (1.7) contain only multiples of 3. Why is that the case? Here’s why. If a 0, 1, 2, . . . , n 1 , then gcd(a, n) divides any integer multiple of a as well as any ∈ { − } number that is congruent to a modulo n. Continuing our example, let a = 5 and n = 9. Clearly, gcd(5, 9) = 1 divides every integer multiple of 5. Likewise, if a = 3, then gcd(3, 9) = 3 divides every integer multiple of 3, so 1 cannot be a multiple of 3, which means that 3 is not invertible. The same is true for 6. So, in 18 1. MODULAR ARITHMETIC

general, a number a is not invertible modulo n if gcd(a, n) = 1. Does that mean that all other numbers are invertible? Well, yes, but it’s not obvious. 6

THEOREM 1.3. If gcd(a, n) = 1, then the set a mod n, 2a mod n,..., (n 1)a mod n has all distinct values. { − }

PROOF. We prove this theorem by contradiction. Suppose that some pair of values in a mod n, 2a mod n, { ..., (n 1)a mod n are the same. More precisely, suppose that there exist integers x and y 1, 2, . . . , n − } ∈ { − 1 such that x = y and that xa ya mod n. Then n a(x y), and since gcd(a, n) = 1, it must be that } 6 ≡ | − n (x y). Since x, y 1, 2, . . . , n 1 , we conclude that x = y, which is a contradiction.  | − ∈ { − }

Since the set a mod n, 2a mod n,..., (n 1)a mod n has n distinct values, those values are congru- { − } ent to 1, 2, . . . , n 1 in some order. Therefore, in summary, if gcd(x, n) = 1, then x is invertible modulo { − } n and if gcd(x, n) = 1, then x is not invertible modulo n. 6 Example 1.14: It is helpful to look at another example. Here is a multiplication table modulo 20.

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 ×0 00000000000000000000 1 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 2 0 2 4 6 8 10 12 14 16 18 0 2 4 6 8 10 12 14 16 18 3 0 3 6 9 12 15 18 1 4 7 10 13 16 19 2 5 8 11 14 17 4 0 4 8 12 16 0 4 8 12 16 0 4 8 12 16 0 4 8 12 16 5 0 5 10 15 0 5 10 15 0 5 10 15 0 5 10 15 0 5 10 15 6 0 6 12 18 4 10 16 2 8 14 0 6 12 18 4 10 16 2 8 14 7 0 7 14 1 8 15 2 9 16 3 10 17 4 11 18 5 12 19 6 13 8 0 8 16 4 12 0 8 16 4 12 0 8 16 4 12 0 8 16 4 12 (1.8) 9 0 9 18 7 16 5 14 3 12 1 10 19 8 17 6 15 4 13 2 11 10 0 10 0 10 0 10 0 10 0 10 0 10 0 10 0 10 0 10 0 10 11 0 11 2 13 4 15 6 17 8 19 10 1 12 3 14 5 16 7 18 9 12 0 12 4 16 8 0 12 4 16 8 0 12 4 16 8 0 12 4 16 8 13 0 13 6 19 12 5 18 11 4 17 10 3 16 9 2 15 8 1 14 7 14 0 14 8 2 16 10 4 18 12 6 0 14 8 2 16 10 4 18 12 6 15 0 15 10 5 0 15 10 5 0 15 10 5 0 15 10 5 0 15 10 5 16 0 16 12 8 4 0 16 12 8 4 0 16 12 8 4 0 16 12 8 4 17 0 17 14 11 8 5 2 19 16 13 10 7 4 1 18 15 12 9 6 3 18 0 18 16 14 12 10 8 6 4 2 0 18 16 14 12 10 8 6 4 2 19 0 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

Which numbers are invertible? That is, which numbers have a 1 in their respective rows (or columns)? The invertible integers modulo 20 are 1, 3, 7, 9, 11, 13, 17, and 19, which leaves out all even integers and 2 multiples of 5 since 20 = 2 5. Also, note that the invertible numbers have every integer from 0 to 19 in their rows (or columns), whereas· non-invertible numbers do not.

Now that we know which integers are invertible modulo n, we’d like to have a systematic way of finding inverses. Tables are nice for small moduli, but are unwieldy for large ones. Fortunately, the extended Euclidean algorithm gives us a nice algorithm for computing inverses. Recall that if gcd(a, n) = 1, then there exists integers x and y such that

(1.9) ax + ny = 1, 1.7. SOLVING LINEAR CONGRUENCES 19 and we can find x and y using the extended Euclidean algorithm. Reducing (1.9) modulo n gives (1.10) ax 1 mod n, 1 ≡ which implies that x = a− .

1 Example 1.15: To find 17− mod 20, we use the extended Euclidean algorithm. 20 = 17 1 + 3 · 17 = 3 5 + 2 · 3 = 2 1 + 1 · Technically, we should go one step further to get a remainder of zero, but we know that the gcd is 1, so there is no practical need to continue. Working backward,

1 = 3 2 − = 6 3 17 · − = 6 20 7(17). 1 · − This implies that 17( 7) 1 mod 20, so 17− = 7 13 mod 20. You can check this in the multiplication table in (1.8). − ≡ − ≡

1 Example 1.16: To find 343− mod 454, we can use the work we did in Example 1.6. Recall that we found 1 that 1 = 454(34) 45(343). Reducing modulo 454 gives 1 45(343), so 343− = 45 409 mod 454. You can check this− with a calculator by multiplying 343 by 409≡ − to get 140, 287. To reduce− ≡ modulo 454, we divide 140, 287 by 454 to get 309.002. That tells us that 454 goes into 140, 287 309 times. Subtracting, we find 140, 287 454(309) = 1, so we know that our answer is correct. − Classroom Exercise 1.8: Find the following multiplicative inverses. 1 (1)4 − mod 15 1 (2) 15− mod 49 1 (3) 81− mod 145

1.7. Solving Linear Congruences

Linear Congruences of the Form ax b mod n. Over the real numbers, the equation ≡ (1.11) ax = b has the unique solution x = b/a if a = 0. If a = 0 and b = 0, then there are no solutions, and if a = 0 and 6 6 b = 0, then there are infinitely many solutions because x can have any real value. Similarly, a congruence like (1.12) ax b mod n ≡ may have a unique solution in 0, 1, 2, . . . , n 1 , no solution, or multiple solutions in 0, 1, 2, . . . , n 1 . Let’s illustrate with a few examples.{ − } { − } Example 1.17: (1)6 x 12 mod 13 has the unique solution x = 2. ≡ (2)6 x 12 mod 24 has six solutions x = 2, 6, 10, 14, 18, 22. (3)6 x ≡ 11 mod 12 has no solution. ≡ 20 1. MODULAR ARITHMETIC

Our goal in this section is to find all solutions, if any, of congruences like (1.12). If ax b mod n has a solution, then there exists an integer m such that ≡

(1.13) mn = ax b. − The gcd(a, n) clearly divides the first two terms, mn and ax, in (1.13), so it also must also divide b. Recall that all multiples of a modulo n are multiples of gcd(a, n), so b must be a multiple of gcd(a, n) for (1.12) to have a solution. For example, in (1.8), all multiples of 15 modulo 20 are 0, 5, 10 and 15, so a congruence of the form 15x = b mod 20 only has solutions if b = 0, 5, 10, or 15. Let’s assume that gcd(a, n) b so that at least one solution exists. Note that this is trivially true if a and n are relatively prime. How do| we find a solution? Sometimes you can find a solution simply by looking at the congruence. For instance, it is pretty clear that x = 2 solves 6x 12 mod 13. The fancy way of saying ≡ this is that x = 2 is a solution “by inspection". When we can’t find a solution by inspection, we can use the extended Euclidean algorithm. Let’s look at an example.

Example 1.18 (Unique Solution): To solve 17x 4 mod 20, we begin with the extended Euclidean algo- rithm. ≡

20 = 17 1 + 3 · 17 = 3 5 + 2 · 3 = 2 1 + 1 · Working backwards,

1 = 3 2 − = 3 6 17 · − = 20 6 17 7. · − · Therefore, 17( 7) 1 mod 20. Multiplying both sides by 4 gives 17( 7 4) 4 mod 20 and x = 7 4 = − ≡ − · ≡ − · 28 12 mod 20. Since gcd(17, 20) = 1, x = 12 is the only solution. − ≡ If a congruence has multiple solutions, how do we find all of them? We begin by finding one solution using the extended Euclidean algorithm (or inspection). If solution(s) exist, then gcd(a, n) b and there | exists an integer m such that ax = b + nm. Dividing by gcd(a, n) gives a b n x = + m, gcd(a, n) gcd(a, n) gcd(a, n) so a b n (1.14) x mod . gcd(a, n) ≡ gcd(a, n) gcd(a, n) This congruence (1.14) has a unique solution since

 a n  gcd , = 1. gcd(a, n) gcd(a, n) Therefore, once one solution of ax b mod n is found, all other solutions in 0, 1, 2, . . . , n 1 can be found ≡ { − } by adding (or subtracting) integer multiples of n/ gcd(a, n) for a total of gcd(a, n) incongruent solutions. 1.7. SOLVING LINEAR CONGRUENCES 21

Example 1.19 (Multiple Solutions): Solve 14x 4 mod 20. Since gcd(14, 20) = 2 and 2 4, this congru- ence has two solutions. Let’s use extended Euclidean≡ algorithm to find one of them. |

20 = 14 1 + 6 · 14 = 6 2 + 2 · 6 = 3 2 · Working backwards again,

2 = 14 6 2 − · = 14 3 20 2 · − · Therefore, 14(3) 2 mod 20. Multiplying both sides by 2 gives 14(3 2) 4 mod 20 and x = 6. Since ≡ · ≡ gcd(14, 20) = 2, there is a second solution that we obtain by adding n/ gcd(a, n) = 20/2 = 10 to x = 6. Therefore, the two solutions in 0, 1, 2, . . . , 19 are x = 6 and x = 16. Another way to view this example is to return to the multiplication table{ in (1.8) and} note that each row (or column) cycles through multiples of the appropriate gcd. In the case of 14, the multiples cycle through 0, 14, 8, 2, 16, 10, 18, 12, 6 twice, so the two solutions must be 10 apart.

Example 1.20 (No Solution): The congruence 14x 5 mod 20 has no solution since gcd(14, 20) = 2 5. ≡ 6 | Example 1.21: To solve 2x 4 7 mod 13, simply add 4 to both sides and proceed as above to find x = 12. − ≡ In summary, you can always tell if ax b mod n has a solution by determining if gcd(a, n) divides b. If ≡ not, then there is no solution. If gcd(a, n) does divide b, then the number of solutions is equal to gcd(a, n) and the solutions are n/ gcd(a, n) apart. For instance, x = 1 is clearly a solution of 13x = 13 mod 39. Since gcd(13, 39) = 13, there are a total of 13 solutions in 0, 1, 2, . . . , 38 and they are separated by 39/13 = 3, { } so the complete set of solutions is x = 1, 4, 7, 10, 13, 16, 19, 22, 25, 28, 31, 34, 37.

Classroom Exercise 1.9: Find all solutions, if any, of the following congruences.

(1) 18x = 3 mod 31 (2) 18x = 16 mod 30 (3) 18x 24 mod 30 ≡ Linear Systems of Congruences. Let’s confine our attention to systems of congruences in two variables because this is sufficient for our cryptologic needs later in the chapter. If a, b, c, d, e, f 0, 1, . . . , (n 1) , then our goal is to solve ∈ { − } ax b y e + mod n cx + d y ≡ f ≡ for x and y, if possible. Standard algebraic manipulations reduce the system to the pair of congruences4

(1.15) (ad bc)x ed b f (ad bc)y a f ce mod n. − ≡ − − ≡ − For solutions to exist, gcd(ad bc, n) must divide both (ed b f ) and (a f ce). In practice however, we don’t recommend memorizing (1.15).− Instead, just use the familiar− methods of− substitution and elimination from high school algebra. Be aware, however, that you have to be careful about both multiplying and dividing. Division is obviously a problem since it isn’t properly defined, but multiplication can also cause trouble

4These may look familiar if you have seen Cramer’s rule before. 22 1. MODULAR ARITHMETIC because multiplying equations by constants can lead to spurious solutions. For example, the congruence 3x 3 mod 8 has the unique solution x = 1. However, multiplying both sides by 2 gives 6x 6 mod 8, ≡ ≡ which has two solutions, x = 1 and x = 5, the second of which is spurious. If you can, try to only multiply by integers that are relatively prime to the modulus. If you can’t help it, be sure to check your solutions in the original congruences.

Example 1.22 (Substitution): Some systems make the method of substitution attractive. For example, 3x 2y 0 + mod 7 x 3y ≡ 2 − ≡ suggests solving the second equation for x and substituting into the first to find 3(3y + 2) + 2y = 0, which reduces to 4y = 1 mod 7. The extended Euclidean algorithm then implies that y = 2 and, consequently, x = 1.

Example 1.23 (Elimination): In this example, we might choose to use elimination. 3x 2y 0 + mod 7 2x 3y ≡ 2 − ≡ We could solve either congruence for x or y since all coefficients are relatively prime to the modulus, but that isn’t particularly appealing. Instead, let’s multiply the first equation by 2 and the second by 3 to find 6x 4y 0 6x 4y 0 + or, equivalently, + mod 7. 6x 9y ≡ 6 6x + 5y ≡ 6 − ≡ ≡ Multiplying the congruences by 2 and 3 is OK here because both constants are relatively prime to the modulus. Subtracting the first congruence from the second gives y = 6 and substituting into 6x + 4y = 0 implies that x = 4y 3 mod 7. ≡ Example 1.24 (Multiple Solutions): We might choose to solve this system 12x y 13 + mod 26 4x 3y≡ 7 − ≡ by multiplying the second congruence by 3 and subtracting to find 10y 8 mod 26, which has two ≡ − solutions since gcd(10, 26) 8. Using the extended Euclidean algorithm, we find that y = 7 and y = 20. Plugging these values back| into− the second congruence gives 4x 2 mod 26 and 4x 15 mod 26. The ≡ ≡ former has two solutions, x = 7 and x = 20, but the second has no solutions. Overall, we have two solutions: (7, 7) and (20, 7). An alternative way to solve this problem is to solve the first congruence for y 13 12x and substitute ≡ − into the second to find 14x 20 mod 26, which gives x = 7 and x = 20. Both values of x give y = 7. ≡ Example 1.25 (Spurious Solutions): As a final example, consider 12x 2y 14 + mod 26. 3x 3y≡ 8 − ≡ Multiplying the second congruence by 4 and subtracting it from the first gives 14y 8 mod 26, which ≡ has two solutions y = 8 and y = 21. Plugging these values back into the first congruence gives 12x 24 ≡ mod 26 for both y = 8 and y = 21. The solutions for x are obviously x = 2 and x = 15, so, overall, we have four putative solutions

(2, 8), (2, 21), (15, 8), and (15, 21). 1.8. ADDITIVE CIPHER 23

However, since we multiplied by 4, which is not relatively prime to the modulus, we suspect spurious solutions. Plugging all four solutions back into the original system shows that only (2, 8) and (15, 21) are solutions of the original problem. Note that it would have been more efficient to solve for x using the second congruence because 3 is relatively prime to 26, so no spurious solutions are produced in that case.

Remark 1.1: If the idea of spurious solutions is disconcerting to you, please recall that you have seen this before in “regular algebra" over the reals when you multiply both sides of an equation by zero or when you square both sides of an equation. For example, multiplying both sides of the incorrect equation 3 = 4 by zero gives 0 = 0, which is correct. Likewise, squaring both sides of 3 = 3 gives 9 = 9. More realistically, to solve − 1 1 x + 4 (1.16) + = , (x 6)(x 2) (x + 2)(x 2) (x 6)(x + 2) − − − − we might multiply by sides of the equation by (x 2)(x + 2)(x 6) to clear the fractions. This gives − − (x + 2) + (x 6) = (x + 4)(x 2), − − 2 which simplifies to x = 4. So the solutions of (1.16) are x = 2, right? Wrong. Equation (1.16) has no ± solutions. When we multiplied by (x 2)(x + 2)(x 6), we were effectively multiplying by zero if x = 2, and that introduced the false solutions.− − ± Similarly, if we square both sides of

p1 x (1.17) − = 1, px 2 − and cross multiply, we obtain 1 x = x 2, which implies that x = 3/2. However, (1.17) has no real solutions since the numerator of− the expression− on the left implies that x 1 and the denominator implies that x > 2, and there are no such values of x.5 ≤

1.8. Additive Cipher

One of the earliest known ciphers is the Caesar cipher. Suetonius [12] claims that Julius Caesar used a simple shift cipher to encrypt private messages in letters to Cicero and other friends. He simply replaced each a by d, b by e, etc..., wrapping around at the end of the alphabet so each x is replaced by an a, y by b, and z by c. The following chart makes it easier to implement the Caesar cipher.

For example, the message mathisreallyfun is encrypted as pdwklvuhdoobixq. Anyone except the intended recipient would only see gibberish and would not know that mathisreallyfun. Note that this example uses the standard (modern) English alphabet, with no spaces, capital letters, or punctuation. We could accomodate spaces, capitals, punctuation, digits, and any other symbols that we choose, but we’ll stick with the 26-letter alphabet for simplicity. Recall that we refer to the original message mathisreallyfun as plaintext and the encrypted message pdwklvuhdoobixq as ciphertext.

5This has nothing to do with cryptology, but if you want to see something really interesting, try to solve (1.17) by graphing p1 x y = − and y = 1 on your calculator and looking for the intersection of the two graphs. What do you find? px 2 − 24 1. MODULAR ARITHMETIC

We can make the implementation of the Caesar cipher more efficient and computer-ready by making the cipher mathematical. We can do this simply by associating a with 0, b with 1, ..., and z with 25 as shown in the following chart.6 abcdefghijklmnopqrstuvwxyz 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 Now the plaintext mathisreallyfun and ciphertext pdwklvuhdoobixq can be regarded as sequences of integers  15 pi i 1 = 12, 0, 19, 7, 8, 18, 17, 4, 0, 11, 11, 24, 5, 20, 13 , = { } and  15 ci i 1 = 15, 3, 22, 10, 11, 21, 20, 7, 3, 14, 14, 1, 8, 23, 16 . = { } The cipher characters can be obtained mathematically from the formula

(1.18) ci = pi + 3 mod 26, i = 1, 2, . . . , 15,

and the plaintext can likewise be found by solving (1.18) for pi,

(1.19) pi = ci 3 mod 26, i = 1, 2, . . . , 15. − Note that we need to work modulo 26 because we have a 26-letter alphabet. For example, the plaintext y (a.k.a. 24) is encrypted to b (a.k.a 24 + 3 = 27 1 mod 26). The additive cipher is just like the Caesar cipher,≡ except that the shift doesn’t have to be 3. If we stick with a 26-letter alphabet, then the shift, let’s call it k (for key), can, in principle, be any integer between 0 and 25, inclusive. Then, (1.18) becomes

(1.20) ci = pi + k mod 26.

If k = 0, then ci = pi, so we really should take k 1, 2, . . . , 25 . The modulus 26 is the length of the alphabet, so if you change the alphabet by adding or∈ deleting { characters,} then you simply change 26 to the appropriate value.

Example 1.26: Suppose that the plaintext is thequickbrownfoxjumpsoverthelazydog and k = 4. Each plaintext letter is encrypted by adding 4 modulo to it according to the encryption equation (1.20). The first plaintext letter t has a numerical value of 19, and adding four to it makes it 23, which is x. The next letter h corresponds to 7, which becomes 11 or l. Repeating this for the entire message turns thequickbrownfoxjumpsoverthelazydog into xliuymgofvsarjsbnyqtwszivxlipedchsk. The rest of the details are shown in the following table.

Plaintext thequickbrownfoxjumpsoverthelazydog Coded plain 19 7 4 16 20 8 2 10 1 17 14 22 13 5 14 23 9 20 12 15 18 14 21 4 17 19 7 4 11 0 25 24 3 14 6 Coded cipher 23 11 8 20 24 12 6 14 5 21 18 0 17 9 18 1 13 24 16 19 22 18 25 8 21 23 11 8 15 4 3 2 7 18 10 Ciphertext xliuymgofvsarjsbnyqtwszivxlipedchsk

Classroom Exercise 1.10: Use the Caesar cipher to encrypt theworldisabookandthosewhodonottravel readonlyapage.7

Classroom Exercise 1.11: Decrypt the additive ciphertext mnudpuzftqtmzpueiadftfiauzftqnget with k = 12. 6Some authors associate a with 1, b with 2, ..., and z with 26, but our way is more convenient. 7St. Augustine 1.9. CRYPTANALYSIS OF THE ADDITIVE CIPHER 25

k Putative Plaintext k Putative Plaintext 0 teefxgurgtmnkxwxlbkxmhdghp 13 grrskthetgzaxkjkyoxkzuqtuc 1 sddewftqfslmjwvwkajwlgcfgo 14 fqqrjsgdsfyzwjijxnwjytpstb 2 rccdvesperklivuvjzivkfbefn 15 eppqirfcrexyvihiwmvixsorsa 3 qbbcudrodqjkhutuiyhujeadem 16 doophqebqdwxuhghvluhwrnqrz 4 paabtcqncpijgtsthxgtidzcdl 17 cnnogpdapcvwtgfguktgvqmpqy 5 ozzasbpmbohifsrsgwfshcybck 18 bmmnfoczobuvsfeftjsfuplopx 6 nyyzraolangherqrfvergbxabj 19 allmenbynaturedesiretoknow 7 mxxyqznkzmfgdqpqeudqfawzai 20 zkkldmaxmzstqdcdrhqdsnjmnv 8 lwwxpymjylefcpopdtcpezvyzh 21 yjjkclzwlyrspcbcqgpcrmilmu 9 kvvwoxlixkdebonocsbodyuxyg 22 xiijbkyvkxqrobabpfobqlhklt 10 juuvnwkhwjcdanmnbrancxtwxf 23 whhiajxujwpqnazaoenapkgjks 11 ittumvjgvibczmlmaqzmbwsvwe 24 vgghziwtivopmzyzndmzojfijr 12 hsstluifuhabylklzpylavruvd 25 uffgyhvshunolyxymclyniehiq

Table 1.1: Exhaustive cryptanalysis of the additive ciphertext teefxgurgtmnkxwxlbkxmhdghp. Clearly, k = 19 is the correct key.

1.9. Cryptanalysis of the Additive Cipher

Recall that cryptanalysis involves reading enciphered messages without knowing the key. Since the additive cipher has a single key k that can only take on 26 1 = 25 different values, modern computers can easily be programmed to find the correct key simply by exhaustively− trying all 25 values for k. Suppose, for example, that we intercept the message teefxgurgtmnkxwxlbkxmhdghp. We can just try all values for k as shown in Table 1.1. There is no mistaking k = 19 as the correct key and the message as a pearl of wisdom from Aristotle. The method of exhaustion is not very interesting and it does not prepare us to study more complicated ciphers for which exhaustion is not an option. Frequency analysis, in contrast, provides a more fruitful approach to cryptanalyzing additive cipher. Each letter or character in a language tends to occur with a certain frequency. For example, the letter e is the most common letter in the English alphabet, appearing approximately 12% of the time, while j, q, x, and z are much less common, occurring about about 0.1% of the time. A bar chart of letter frequencies can be found in Figure 1.1 and the corresponding numerical frequencies are shown in Table 1.2. Knowing these frequencies greatly enhances our ability to cryptanalyze ciphertext because, for example, every e in the plaintext is encrypted to the same ciphertext character, so that character should appear approximately 12% of the time in the cipher. For example, the additive ciphertext with k = 18 for theeaglesaregreat is lzwwsydwksjwyjwsl and every plaintext e is encrypted as a w. You might ask how reliable the letter frequencies in Figure 1.1 really are, so let’s look at some examples. Figure 1.2 shows a stacked bar chart that shows the frequencies of the letters in “The Gold Bug", the 2006 State of the Union Address, “Julius Caesar", and the “USA Patriot Act". These are four very different texts, but, for the most part, each reveals approximately the same distribution of letters. Minor differences are apparent, such as an unusual abundance of the letter u “Julius Caesar", but that is to be expected with all of the Latin names that end in us (e.g. Julius, Brutus, Cassius, etc...). Let’s try some cryptanalysis based on letter frequencies. Given the ciphertext vjgggtkggngrjcpvgcvu giiu, we see that g occurs most frequently (8 times), so it most likely corresponds to a plaintext e. If that 26 1. MODULAR ARITHMETIC

Figure 1.1: Frequencies of letters in the English language. See Table 1.2 for numerical values.

Relative Relative Letter Frequency Letter Frequency a 0.082 n 0.073 b 0.014 o 0.076 c 0.025 p 0.018 d 0.046 q 0.001 e 0.124 r 0.059 f 0.022 s 0.065 g 0.020 t 0.089 h 0.065 u 0.026 i 0.069 v 0.011 j 0.001 w 0.023 k 0.008 x 0.002 l 0.039 y 0.018 m 0.024 z 0.001

Table 1.2: Table of letter frequencies based on War and Peace and several articles from The Washington Post.

Figure 1.2: Cumulative frequencies of the letters (in ascending order) in Edgar Allan Poe’s “The Gold Bug", George W. Bush’s 2006 State of the Union Address, William Shakespeare’s “Julius Caesar", and the “USA Patriot Act".

is correct, then k must be 2. If we try decrypting the entire message with k = 2, we find the putative plain- text theeerieelephanteatseggs, so we are confident that we have successfully recovered the original message. 1.11. CRYPTANALYSIS OF THE 27

Note that in any given text, e may or may not be the most common letter. The most common letter in laeljawvlwsuzafylsqfsljauckgfzwjlgqtacw is l, which corresponds to k = 7. However, decrypting with k = 7 gives the clearly incorrect plaintext etxectpoeplnstyreljylectnvdzyspcezjmtvp. Next, we might try associating l with the second most common letter t. This suggests that k = 18 and we obtain the original message timtriedteachingtaynatricksonhertoybike. Please note that some problems may involve considerable trial and error, but letter frequencies do give us a sensible method. A visually appealing alternative is to use a visual cryptanalysis in software like Mathematica. See CryptanalyzeAddi- tiveCipher.nb at http://users.etown.edu/m/mcdevittt/Crypto.html.

1.10. Affine Cipher

Recall the addition and multiplication tables in (1.7) show that patterns are more readily evident in modular addition than in multiplication. Therefore, if we incorporate multiplication into the cipher, then we might be able to improve the additive cipher. The equation for the ith ciphertext characters for the affine cipher8

(1.21) ci = mpi + k mod 26. Again, if the length of the alphabet changes, then you have to change the value of the modulus accordingly. Plaintext can be recovered from ciphertext using

1  (1.22) pi = m− ci k mod 26, − 1 provided that m− exists. How large is the key space for the affine cipher? The additive constant k can take on 26 differ- ent values, but m has to be invertible modulo 26, so it has to be relatively prime to 26. Specifically, m 1, 3, 5, 7, 9, 11, 15, 17, 19, 21, 23, 25 , so there are only 12 possible values for m. Therefore, there ∈ { } are 26(12) 1 = 311 possible key pairs for the affine cipher. (We subtract one because m = 1 and k = 0 − doesn’t change the plaintext! In that case, ci = pi.)

Example 1.27: Let’s encrypt timwrotetomsaddressontheenvelope with m = 7 and k = 4. Since the t h first letter is , p1 = 19 and c1 = 7(19) + 4 7 mod 26, so the first cipher character is . The remaining letters follow in a similar way to give hikctyhghykaezztgaayrhbggrvgdyfg≡ .

Classroom Exercise 1.12: Encrypt potatochipsarebadforyou with m = 17 and k = 24.

1.11. Cryptanalysis of the Affine Cipher

Recall that we cryptanalyzed the additive cipher using letter frequencies. We will do the same with the affine cipher, except that we will have to solve a system of congruences because there are two key parameters, m and k. Let’s look at an example for which we know the answer.

Example 1.28: Let’s start with the ciphertext in Example 1.27, hikctyhghykaezztgaayrhbggrvgdyfg, and pretend that we don’t know m and k. The most common letters are g and h, which appear six and four times, respectively. This suggests that the ciphertext g and h correspond to plaintext e and t. Since g and

8 The graph of f (x) = mx + b is a line, but mathematicians do not call f a linear function unless b = 0. Instead, we call f an affine function. That is where the name of the cipher comes from. 28 1. MODULAR ARITHMETIC h are encoded as 6 and 7 and since e and t are encoded as 4 and 19, we have the pair of congruences 4m k 6 + mod 26. 19m + k ≡ 7 ≡ Solving the system gives m = 7 and k = 4, which, in turn, give the plaintext timwrotetomsaddresson theenvelope.

Recall that e and t are usually the most common letters in English, and the longer a sample text is, the more likely that is to be the case. However, e and t are not always the most common, especially in short messages. Cases like that may require significant trial and error to find a suitable pair of congruences. Let’s look at another example, but unlike Example 1.28, this time we do not know the answer in advance.

Example 1.29: The most common letters in the ciphertext xwvmwixwomclybyvunyuyxcrmikyapmjmzop yssncrkyazmeyppcemr are y and m. Associating these with e and t gives 4m k 24 + mod 26 19m + k ≡ 12 ≡ and m = 20 and k = 22. However, these aren’t correct since m = 20 is not relatively prime to 26. Repeated trial and error eventually leads us to associate ciphertext y and m with plaintext o and e, respectively, which gives 4m k 12 + mod 26. 14m + k ≡ 24 ≡ Subtracting the first congruence from the second gives 10m = 12 mod 26. Since gcd(10, 26) = 2 12, there | are two solutions, m = 9, k = 2 and m = 22, k = 2. Since 22 is not relatively prime to 26, the latter solution cannot be correct. Decrypting m = 9 and k = 2 gives lifeislikeaboxofchocolatesyounever knowwhatyouregonnaget9.

Counting letter frequencies by hand can be very tedious, so mathematical packages like Mathematica and Maple can be very helpful. However, if you don’t have one of those packages or you don’t want to learn one, then just use ECrypt.

Exercises

(1) Factor the following integers as a product of (powers of) primes. (a) 278 (b) 359 (c) 126 (d) 469 (e) 388 (2) Find the smallest integer x > 0 that makes each of the following perfect squares. (a)2 3 32 5 x (b)2 10· 32· 5·2 76 x (c) 123· 25·2 7· x · 2 (d) 123· 252· 7· x (3) Suppose that· we· say· that 56000 “ends” in 3 zeros. How many zeros are there at the end of each of these numbers?

9The one and only Forrest Gump. EXERCISES 29

2 (a) 123 252 7 · · (b) 10! = 10 9 8 7 6 5 4 3 2 1 (c) 100! × × × × × × × × × 50‹ 50! (d) = 25 25!(50 25)! (4) Find the following gcds− and identify which pairs of integers are relatively prime. (a) gcd(261, 231) (b) gcd(317, 375) (c) gcd(297, 431) (d) gcd(418, 278) (e) gcd(272, 391) (5) Find integers x and y such that ax + b y = gcd(a, b) for each of the following. (a) a = 95, b = 298 (b) a = 462, b = 424 (c) a = 195, b = 468 (d) a = 324, b = 122 (e) a = 387, b = 108 (6) For positive integers m and n, lcm(a, b) is the least common multiple of m and n. Show that mn lcm(m, n) = . gcd(m, n) (7) Reduce the following. (a) 154 mod 45 (b) 171 mod 42 (c) 57 mod 20 (d) −111 mod 42 (e) 159 mod 33 (f) −22 mod 11 (g) −54 mod 26 (h) 38 mod 10 (i) −69 mod 23 (j) 100 mod 24 (8) Calculate the following. (a)8 + 6 mod 10 (b) 13 3 mod 7 × (c)2 12 + 4 mod 14 × (d)3 5 + 15 mod 17 (e) 18− 13 8 27 mod 14 − − × (f) 10 4 19 + 16 mod 11 − × (g)9 5 8 + 2 2 mod 10 − − − (h)6 + 8 5 10 9 mod 11 − × − (i)5 6 7 3 6 + 4 mod 8 × − − × (j)9 10 7 13 + 4 + 2 mod 16 (9) Find the× following× × multiplicative inverses. 30 1. MODULAR ARITHMETIC

1 (a) 15− mod 38 1 (b) 29− mod 40 1 (c)8 − mod 49 1 (d) 11− mod 15 1 (e)7 − mod 26 (10) Suppose a, n N. Show that the set a mod n, a +1 mod n, a +2 mod n,..., a +(n 1) mod n ∈ { − } is a re-arrangement of 0, 1, 2, . . . , (n 1) . (11) Find all solutions, if any,{ of the following− } congruences. (a) 17x = 0 mod 34 (b) 14x = 10 mod 32 (c) 14x = 5 mod 25 (d) 17x = 12 mod 24 (e)9 x = 16 mod 20 (f) 18x = 24 mod 46 (g)2 x = 5 mod 15 (h) 19x = 9 mod 30 (i) 15x = 18 mod 21 (j)9 x = 1 mod 30 (k)4 x = 3 mod 34 (l)4 x = 4 mod 22 (12) The ISBN-10 for An Introduction to Mathematical Finance by Sheldon Ross is 0 521 77043 x, − − − where d10 is an unknown check digit. To find d10, we have to solve

0 1 + 5 2 + 2 3 + 1 4 + 7 5 + 7 6 + 0 7 + 4 8 + 3 9 + d10 10 0 mod 11. · · · · · · · · · · ≡ Solve for d10.

(13) In the introduction, we learned that if the first 9 digits in an ISBN-10 d1d2d3d4d5d6d7d8d9d10 are

known, then the check digit d10 solves

(1.23) d1 + 2d2 + 3d3 + 4d4 + 5d5 + 6d6 + 7d7 + 8d8 + 9d9 + 10d10 0 mod 11, ≡ but some authors write that d10 has to solve

(1.24) 10d1 + 9d2 + 8d3 + 7d4 + 6d5 + 5d6 + 4d7 + 3d8 + 2d9 + d10 0 mod 11 ≡ instead. Show that congruences (1.23) and (1.24) have the same solutions. (14) Find all solutions, if any, of the following systems of congruences. 3x 7y 8 (a) + mod 10 5x + 7y ≡ 6 ≡ 2x 5y 16 (b) + mod 18 11x + 11y ≡ 16 ≡ 6y 1 (c) mod 22 15x + 22y ≡13 ≡ x y 14 (d) + mod 16 8x + y≡ 6 ≡ EXERCISES 31

x 16y 8 (e) + mod 20 11x + 19y ≡11 (15) Encrypt the following≡ with the additive cipher, the standard alphabet (abcdefghijklmnopqrstu vwxyz), and the specified key. For longer messages, you may want to use use ECrypt. (a) go steelers, k = 17 (b) a spoon full of sugar makes the medicine go down, k = 9 (c) the people in philadelphia deserve to have a winner its simple as that, k = 25 (16) Decrypt the following with the additive cipher, the standard alphabet (abcdefghijklmnopqrstu vwxyz), and the specified key. For longer messages, you may want to use use ECrypt. (a) orubkrgsv, k = 6 (b) bpiwtbpixrpxhiwtqthiegdvgpb, k = 15 (c) vuaolmpyzakhfvmjoypzathztfayblsvclzluaavtlhwhyaypknlpuhwlhyayll, k = 7 (17) Encrypt the following with the affine cipher, the standard alphabet (abcdefghijklmnopqrstu vwxyz), and the specified keys. For longer messages, you may want to use use ECrypt. (a) do not erase, m = 19, k = 7 (b) who here believes tim should grow a beard, m = 15, k = 24 (c) mr gorbachev tear down this wall, m = 5, k = 2 (18) Decrypt the following with the affine cipher using the specified keys. For longer messages, you may want to use use ECrypt. (a) efgqzospux, k = 10, m = 9 (b) eperfwddjesgrdzexmredjejmrke, m = 19, k = 6 (c) qredqjyialordiixjxllpdhjnarslwlleylrgfevrwjnirwrgwylrpfvjihliijgrhfbje dfglyzhdluqialunbpfldizrejeialqrbljqiallryiafarslwllefewruuorypdqjydls leillehlrydregarslelslyylblfslgrehiafevwnipfegelddreglebjnyrvlzleiqyjz hjnqredujjpriialdlvyregzlexafbajqhjnxjnugeibjedfglyfiialafvaufvaijqafd bryllykndiijrddjbfrilxfiaialzqjylslejelgrh, k = 5, m = 17 (19) Cryptanalyze the following additive ciphertext. You should be able to copy and paste the ciphertext into ECrypt (or Mathematica, Maple, etc...). (a) kbktznuamnrgxmkzxgizyulkaxuvkgtjsgteurjgtjlgsuayyzgzkyngbklgrrktuxsgel grrotzuznkmxovulznkmkyzgvugtjgrrznkujouaygvvgxgzayultgfoxarkckyngrrtuz lrgmuxlgorckyngrrmuutzuznkktjckyngrrlomnzotlxgtikckyngrrlomnzutznkykgy gtjuikgtyckyngrrlomnzcoznmxucotmiutlojktikgtjmxucotmyzxktmznotznkgoxck yngrrjklktjuaxoyrgtjcngzkbkxznkiuyzsgehkckyngrrlomnzutznkhkginkyckyngr rlomnzutznkrgtjotmmxuatjyckyngrrlomnzotznklokrjygtjotznkyzxkkzyckyngrr lomnzotznknorryckyngrrtkbkxyaxxktjkxgtjkbktolcnoinojutuzluxgsusktzhkro kbkznoyoyrgtjuxgrgxmkvgxzulozckxkyahpamgzkjgtjyzgxbotmznktuaxksvoxkhke utjznkykgygxskjgtjmagxjkjheznkhxozoynlrkkzcuarjigxxeutznkyzxammrkatzor otmujymuujzoskznktkccuxrjcozngrrozyvuckxgtjsomnzyzkvyluxznzuznkxkyiakg tjznkrohkxgzoutulznkurj (b) jbnbmsfbezgbsopsuipgmpoepoboebtjxbmljouiftusffutpgqfufstcvshijgffmbdpm eopsuifsocsffafqmbzvqponzdiffltxijdicsbdftnzofswftboegjmmtnfxjuiefmjhi uepzpvvoefstuboeuijtgffmjohuijtcsffafxijdiibtusbwfmmfegspnuifsfhjpotup 32 1. MODULAR ARITHMETIC xbsetxijdijbnbewbodjohhjwftnfbgpsfubtufpguiptfjdzdmjnftjotqjsjufeczuij txjoepgqspnjtfnzebzesfbntcfdpnfnpsfgfswfouboewjwjejuszjowbjoupcfqfstvb efeuibuuifqpmfjtuiftfbupggsptuboeeftpmbujpojufwfsqsftfoutjutfmgupnzjnb hjobujpobtuifsfhjpopgcfbvuzboeefmjhiu (c) ivdveufljrdflekfwkzdvkfnrcbkfddpveafpjkyvkirzekfdfiifnkfddptflcukrbvky vkirzerxrzefikrbvkyvkivbspwffk (20) Cryptanalyze the following affine ciphertext. You should be able to copy and paste the ciphertext into ECrypt (or Mathematica, Maple, etc...). (a) dmdcdilmdskvnbdcomjmkdzqdlmbmlqb (b) gpatqazdqawlpalenqzaslpgunalgenkgffdguqcvanzfgtqecllpqldcqwqangnyehglu idqqzkqpefzlpquqldclpulerquqfhqtgzqnllpalaffwqnadqidqalqzqmcafgpatqazd qawlpalenqzasenlpqdqzpgffuehyqedygalpquenuehhedwqdufatquanzlpquenuehhe dwqdufatqeknqdukgffrqarfqleuglzeknleyqlpqdallpqlarfqehrdelpqdpeezpatqa zdqawlpalenqzasqtqnlpqulalqehwguuguugvvgaulalqukqflqdgnykglplpqpqalehg nxculgiqukqflqdgnykglplpqpqalehevvdquugenkgffrqldanuhedwqzgnleaneaugue hhdqqzewanzxculgiq (c) vxwszokjwpkvzwotmkjzgjmkvuuvpjaijokhmzdjokhltmbavdrvdjokhptuuijavmjvmj zwokzftotftmkjzgjmbtgjxfoktfazhvxwaztuhiwjzazmasvwbtgjxfvxwowjfezffjfz fpjsvwbtgjokvfjpkvowjfezffzbztmfoxfzmaujzaxfswvdojdeozotvmzmaajutgjwxf swvdjgtuzdjm (21) Suppose that you double-encrypt some plaintext with the affine cipher. First you encrypt the

plaintext with keys m1 and k1, and then you re-encrypt the ciphertext with keys m2 and k2. The

resulting ciphertext is also affine with keys m3 and k3. Carefully relate m3 and k3 to m1, m2,

k1, and k2. Does this double affine encryption provide any additional security over regular affine encryption? (22) The Atbash cipher replaces the 1st letter of the alphabet with the last, the 2nd with the second-to- last, etc... Write an equation that mathematically represents the action of the Atbash cipher. CHAPTER 2

Probability

2.1. Counting

Counting is a basic mathematical skill that many American children learn by watching Sesame Street, but we want to extend that skill to count very large quantities that cannot easily be written down. For example, if you roll two standard six-sided dice, you can easily record all possible pairs as shown in Figure 2.1. Clearly, there are 6 possible outcomes for the first die and 6 possible outcomes for the second die, which suggests that there are 6 6 = 36 possible outcome pairs. (Note, for example, that a is different from a .) This is an example× of the fundamental counting rule.

Figure 2.1: All possible outcomes for a pair of regular six-sided dice.

THEOREM 2.1 (Fundamental Counting Rule). If event A can occur m ways and B can occur n ways, then A and B together can occur mn ways.

The fundamental counting rule can be extended to more complicated situations. For example, YahtzeeTM requires players to roll 5 dice. How many possible outcomes are there? We certainly don’t want to try to list them all, so we try to count without an explicit list of possible outcomes. Since there are six possible 5 outcomes for each die, the number of possible 5-dice rolls is 6 6 6 6 6 = 6 = 7776. × × × × Example 2.1: Jake wants an ice cream cone, and he can choose one flavor of ice cream (chocolate, vanilla, or strawberry) and one type of cone (sugar or cake). How many possible ice cream cones can he choose from? According to the fundamental counting rule, there are 3 2 = 6 possible ice cream cones. We can also list the outcomes in this case, possibly with the help of a tree× plot.

strawberry/cake chocolate/cake vanilla/cake strawberry/sugar chocolate/sugar vanilla/sugar, 33 34 2. PROBABILITY

Tree plots can be helpful in small problems like this one, but can be impractical in larger problems.

Now suppose that Jake has invited 7 of his friends to dinner at his house and he needs to call each of them to warn them about the vicious new dog next door. How many sequences of calls are possible? He can pick the first person he calls in 7 different ways, the second in 6 ways (because the first person has already been called), the third in 5 ways, etc... for a total of 7 6 5 4 3 2 1 = 5040 possible sequences. × × × × × × For convenience, we write 7 6 5 4 3 2 1 = 7!, which we read as “seven factorial". In general, if n is a positive integer, then × × × × × ×

n! = n(n 1)(n 2)(n 3) ... (3)(2)(1). − − − By itself, 0! doesn’t make any sense, but it will soon be convenient for us to define 0! = 1. Now suppose that Jake has 5 errands to complete, but he only has enough time to complete 2 of them. How many ways can he choose 2 errands out of 5? He can choose the first of the two errands in 5 ways and the second in only 4 ways. Using the fundamental counting rule, there are 5 4 = 20 ways to choose × two errands. If e1 represents the first errand, the second, and so on, then the 20 possible sequences of 2 errands are as follows.

e2e1 e3e1 e4e1 e5e1 e1e2 e3e2 e4e2 e5e2 e1e3 e2e3 e4e3 e5e3 e1e4 e2e4 e3e4 e5e4 e1e5 e2e5 e3e5 e4e5 The key question here is whether or not the sequence of the errands matters. If, perhaps unrealistically, the order does matter, then there are 20 2-errand sequences. If order does not matter, then, for example, e1e2 is the same as e2e1 and there are only 10 different pairs of errands. In general, an ordered arrangement of objects is called a permutation. We can use the fundamental counting rule to determine the number of permuations of r distinct objects that can be formed from n th distinct objects. The first object can be chosen n ways, the second (n 1) ways, ..., and the r (n r + 1) ways, for a total of − −

n Pr = n(n 1)(n 2) ... (n r + 1) − − − n(n 1)(n 2) ... (n r + 1)(n r) ... (3)(2)(1) = − − − − (n r) ... (3)(2)(1) n! − = . (n r)! − Therefore, we have the following theorem. 2.1. COUNTING 35

n! THEOREM 2.2. The number of permutations of size r from n distinct objects is n Pr = . (n r)! − n! Note that there n! ways to choose n objects from n objects and Theorem 2.2 works in that case, P n n = 0! = n!, because we defined 0! = 1. An unordered arrangement of r distinct objects taken from n distinct objects is a combination, and we can derive the number of combinations from the permutation rule (Theorem 2.2) because any permutation of r distinct objects can be rearranged in r! different ways that are equivalent if order doesn’t matter. Therefore,

n‹ THEOREM 2.3. The number of combinations of size r from n distinct objects is C n r = r = n! . r!(n r)! − n‹ The symbol is read “n choose r". r Example 2.2: If Bob has eight different color flags, how many different signals can he make from five flags? In this case, n = 8, r = 5. Assuming that the order of the flags matters, then 8! 8! 8 P5 = = = 8 7 6 5 4 = 6720. (8 5)! 3! × × × × − Example 2.3: Let S = A, B, C, D, E . How many ways can you choose 3 letters from S if order matters? In this case, we can write{ out all of the} possible permutations ABC ABD ABE ACD ACE ADE BCD BCE BDE CDE ACB ADB AEB ADC AEC AED BDC BEC BED C ED BAC BAD BAE CAD CAE DAE CBD CBE DBE DC E BCABDABEACDACEADEACDBCEBDEBDEC CAB DAB EAB DAC EAC EAD DBC EBC EBD ECD CBADBAEBADCAECAEDADCBECBEDBEDC 5! and see that there are 60 of them, or we could compute P 60. If order does not matter, then all 3 5 = 2! = of the entries in each column are equivalent to each other. For example, ABC, ACB, BAC, BCA, CAB, and CBA (first column) are all equivalent if order doesn’t matter, and there are 3! of them since there are 3! 5‹ 5! permutations of 3 objects. Therefore, the number of combinations is 10. 3 = 3!2! = Example 2.4: How many different five-card hands can be made from a standard card deck of 52 cards? Here, order does not matter, so 52‹ 52! 52! 52C5 = = = = 2, 598, 960. 5 5!(52 5)! 5!47! − Students often struggle with permutations and combinations in applied problems. In both cases, re- member to check that you are sampling without replacement from a set with no repeated elements. Then you have to determine whether or not order matters. This is where people usually struggle the most, so let’s look at a few examples. 36 2. PROBABILITY

Example 2.5: There are currently (2012) 12 schools in the Big Ten conference (and 10 in the Big 12 – go figure).

If the conference is planning a future year’s football matchups, how many different games are possible? For each game, the conference must choose 2 teams out of 12, and repeats are not possible since no team can play itself. Since this is clearly a permutation or combination problem, the only issue is whether or not order matters. If, for example, the first team chosen plays at home, then order matters and there are 12! (12)(11)10! 12 P2 = = = 132 different matchups. However, if the games are played at neutral sites (12 2)! 10! − 12! (12)(11)10! (which would be unusual), then order doesn’t matter and there are 12C2 = = = 66 (12 2)!2! 10!2 possible matchups. −

Example 2.6: Suppose that a generous instructor brings a $20 bill, a $10 bill, a $5 bill, and a $1 bill to class one day. He puts all 30 students’ names in a hat and draws four different names. The first person wins the $20 bill, the second the $10 bill, and so on. How many different ways can the money be awarded? In this 30! example, order clearly matters because the prizes are different. Therefore, there are P 657, 720 4 30 = 26! = different ways to award the money.

Example 2.7: A less generous instructor brings four $1 bills to class one day, puts all of his 30 students’ names in a hat and draws four different names. Each person selected wins $1. How many different ways can the money be awarded? In contrast to Example 2.6, order does not matter because the prizes are all 30! the same. Therefore, there are only C 27, 405 different ways to award the money. 4 30 = 4!26! = 2.2. Probability

The set of all outcomes of a random experiment is called the sample space. For example, the sample space for flipping a coin and observing the up-side is heads, tails . The sample space for the number of pips on the up-face of a standard six-sided die is 1, 2, 3,{ 4, 5, 6 . An} event A is a subset of the finite sample space S. If all events in S are equally likely, then{ the probability} of A is number of elements in A (2.1) P A . ( ) = number of elements in S Also, if an experiment is repeated a large number of times, then number of times A occurs (2.2) P(A) . ≈ number of trials In other words, probabilities are numbers that reflect the likelihood that an event will occur. For example, if A is the event of rolling a 5 with a standard die, then 1 P A , ( ) = 6 because there is 1 entry in A = 5 and 6 equally likely entries in S = 1, 2, 3, 4, 5, 6 . Repeated rolling of a die produces the same result in{ } an approximate way. See the simulations{ in Figure} 2.2. The more trials there are, the more likely the estimate is to be close to the exact probability. It is clear from (2.1) that 0 P(A) 1 and that P(S) = 1. The union of events A and B, denoted A B, indicates that A occurs, B occurs,≤ or both≤ A and B occur as shown graphically in Figure 2.3a and 2.3b.∪ The 2.2. PROBABILITY 37

Figure 2.2: Frequencies of outcomes from simulations of a hundred, a thousand, and a million rolls of a fair die. Note that there is considerably less variation with more repetitions.

intersection of A and B, denoted A B, means that both A and B occur, as shown in Figure 2.3c. This implies the addition rule for probabilities.∩

THEOREM 2.4 (Addition Rule). P(A B) = P(A) + P(B) P(A B) ∪ − ∩

Looking at Figure 2.3a, we see that the area of A B is equal to the sum of the areas of A and B, except ∪ that we have to be careful not to double-count the area of A B, so we have to subtract it from P(A) + P(B). If A and B are mutually exclusive (Figure 2.3b), then the occurrence∩ of A excludes the possibility of B and the occurrence of B excludes the possibility of A. In other words, sets A and B are disjoint (see Figure 2.3) and P(A B) = 0. ∩ Example 2.8: For the experiment of rolling a pair of dice (see Figure 2.1), let A be the event of rolling a sum of 6 and let B be the event of rolling “doubles”.

P(A B) = P(A) + P(B) P(A B) ∪ 5 6 1− ∩ = + 36 36 − 36 10 5 0.27¯ = 36 = 18 = Example 2.9: In a standard deck of 52 cards, let A be the event of drawing an ace and let B be the event of drawing a red card. Then, 4 26 2 28 7 P(A B) = + = = = 0.538461. ∩ 52 52 − 52 52 13 The complement1 of an event A is the set of events for which A did not occur. We’ll denote the comple- c c ment of A by A , but other authors use other symbols like A0 and A. It is clear that A A = S and A and that ∼ ∪ 1Note the spelling of complement. If someone says that you did a great job on a paper, then that is a compliment. 38 2. PROBABILITY

Figure 2.3: The shaded areas in (a) and (b) represents A B. In (b) the events are mutually exclusive (or the sets are disjoint). The shaded area in (c) represents A B, and in∪ (d) the lighter area in (c) is A and the darker is Ac. ∩

c c A are mutually exclusive. Therefore, the application of the addition rule shows that P(A) + P (A ) = P(S), or

c (2.3) P (A ) = 1 P(A). −

c In problems where P (A ) is easier to compute than P(A), (2.3) can be very helpful.

Example 2.10: If A be the event of rolling a 3 on a fair six-sided die, then Ac is the event of rolling a 1, 2, 1 5 4, 5, or 6 and P A and P Ac . ( ) = 6 ( ) = 6 Sometimes probabilities depend on previous events. For example, the probability that you will be dealt an ace from a well-shuffled, standard, 52-card deck is 4/52 = 1/13 0.0769 since there are 4 aces and 52 cards. However, the probability that your second card will also be an≈ ace, given that your first card was an ace, is 3/51 0.0588 since there are only 3 aces and 51 cards left. We denote the conditional probability ≈ that B will occur given that A has occurred by P(B A) and we observe the following theorem. | 2.3. INDEX OF COINCIDENCE 39

THEOREM 2.5 (Multiplication Rule). P(A B) = P(A)P(B A) ∩ |

Example 2.11: Let’s use the multiplication rule to determine the probability that the top two cards in a shuffled deck are aces. Let A be the event that the first card is an ace and let B be the event that the second card is an ace. Then

P(A B) = P(A)P(B A) ∩ 4 3 | = 52 · 51 1 = 0.00452 221 ≈ Two events A and B are independent if the occurrence of one has no effect on the other. For example, if A is the event of getting heads on the first toss of a coin and B is the event of getting heads on the second toss, then A and B are independent events. Two events are dependent if they are not independent. For instance, if C is the event of drawing a heart ( ) from a standard deck of 52 cards and D is the event of drawing a club ( ) on the next card without replacing♥ the first card, then C and D are dependent events. ♣ Whenever A and B are independent P(B A) = P(B), P(A B) = P(A) and the multiplication rule simplifies to | | P(A B) = P(A)P(B). ∩

2.3. Index of Coincidence

The index of coincidence (IoC) for a body of text is the probability that two (uniformly) randomly selected letters are the same. Indices of coincidence are different for every book or article and they are a relatively easy to compute using our probability rules. Let A1 be the event that you get an as the first a chosen letter and A2 be the event that you get an as the second letter, etc... Then

IoC = P(two randomly chosen letters are the same)   = P (A1 A2) (B1 B2) ... (Z1 Z2) ∩ ∪ ∩ ∪ ∪ ∩ Since each pair of letters is mutually exclusive of every other pair, the addition rule (Theorem 2.4) implies that

(2.4) IoC = P(A1 A2) + P(B1 B2) + ... + P(Z1 Z2). ∩ ∩ ∩ a b If n is the total number of characters in the text and there are n1 ’s, n2 ’s, etc..., then the multiplication rule (Theorem 2.5), implies

 n ‹  n 1‹  n ‹  n 1‹  n ‹  n 1‹ (2.5) IoC 1 1 2 2 ... 26 26 = n n −1 + n n −1 + n n −1 26− − − 1 X (2.6) n n 1 = n n 1 i( i ) ( ) i 1 − − = 40 2. PROBABILITY

2 Equation (2.6) is often further simplified by assuming that all of the ni are large so that ni ni 1 and ≈ − 26 1 X (2.7) IoC n2, = n2 i i=1 but this is not necessary and doesn’t really offer an advantage unless we’re computing the IoC by hand.

Example 2.12: "The quick brown fox jumped over the lazy dog." is a short sentence of 36 char- acters that famously uses each letter of the alphabet at least once. Only 7 letters are used more than once: d (twice), e (four times), h (twice), o (four times), r (twice), t (twice), and u (twice). Using (2.6), we find

IoC = 34/1260 0.027. Using the reduced form (2.7) is not appropriate here since each ni is so small and it leads to a very≈ poor approximation of 70/1296 0.054. ≈ Example 2.13: Example 2.12 used a very short, unusual text. What are more typical values of the IoC for 26-letter English? The following table shows the IoCs for the four texts we considered in Section 1.9. Because each body of text is long, the IoC in (2.6) and its approximation in (2.7) are almost identical.

Number of Text Characters IoC “The Gold Bug” 58,270 0.066 2006 State of the Union Address 25,940 0.066 “Julius Caesar” 86,699 0.064 USA Patriot Act 286,260 0.070

Let’s come up with a theoretical IoC for 26-letter English. We saw in Section 1.9, that the probability model for English with the standard 26-letter alphabet is fairly consistent from text to text, provided that the texts are sufficiently long. So, if we’re considering a text that is long enough to follow the distribution in Figure 1.1, then we can approximate its IoC using the frequencies from Table 1.2. Returning to (2.4) and explicitly using the multiplication rule, we have

IoC = P(A1 A2) + P(B1 B2) + ... + P(Z1 Z2) ∩ ∩ ∩ = P(A1)P(A2 A1) + P(B1)P(B2 B1) + ... + P(Z1)P(Z2 Z1). | | | For a sufficiently long text, all letter pair events (like A1 and A2) should be almost independent, so

2 2 2 IoC P(A1) + P(B1) + ... + P(Z1) . ≈ Using the probabilities in Table 1.2, we have

2 2 2 (2.8) IoC (0.082) + (0.014) + ... + (0.001) 0.0658, ≈ ≈ which is consistent with our results in Example 2.13. In other words, in long English texts, there is about a 6.6% chance that two randomly selected letters are the same.

Classroom Exercise 2.1: How is the IoC for affine ciphertext related to the IoC for the related plaintext?

Finally, let’s find what the IoC should be for ciphertext. A necessary condition for a good cipher is that it masks all of the letter frequencies, so let’s assume that every letter in the ciphertext is equally likely, with

2If you had a million dollars and you lost one, you wouldn’t be worried about it, right? 2.4. Vigenère CIPHER 41

probability 1/26. Then  1 ‹2  1 ‹2  1 ‹2 26 1 IoC P A 2 P B 2 ... P Z 2 ... 0.038. ( 1) + ( 1) + + ( 1) = + + + = 2 = ≈ 26 26 26 26 26 ≈ So, the better a cipher masks letter frequencies, the closer the IoC of the ciphertext is to 0.038.

2.4. Vigenère Cipher

History. The Vigenère cipher is a generalization of the additive cipher that thwarts direct frequency analysis. It was (erroneously) considered unbreakable for about 300 years, but this may be because pro- 3 fessional cryptologists preferred nomenclator ciphers instead.[3]. Vigenère recorded both plaintext and ciphertext autokey versions of his cipher in his 1586 Traict´e des Chiffres, but, according to Kahn [3], later cryptologists falsely attributed what we’ll call the Vigenère cipher to him.

Encryption and Decryption. The Vigenère Cipher is similar to the additive cipher in that it is con- sists of additive shifts, but the key can be substantially longer because the Vigenère cipher uses a keyword (or sequence of integers) instead of a key letter (or single integer). For example, consider the plaintext theeaglesarethebest4 with keyword football. To encrypt, we line up the characters from the plain- text and write the keyword repeatedly under all the characters and then shift each plaintext character by the amount from the corresponding key.

Plaintext: theeaglesarethebest Key: footballfootballfoo Ciphertext yvsxbgwpxofxuhpmjgh To be specific, the first plain character t is shifted by 5 (f) to give y, the second character h is shifted by 14 (o) to give v, and so on. Again, it is convenient to mathematize our cipher. The difference between the Vigenère cipher and the th additive cipher is that the value of k in (1.20) changes periodically. If pi is the i plaintext character, then the ith ciphertext character is

(2.9) ci = pi + ki mod L mod 26,

where the key is now the sequence of L integers k0, k1,... kL 1 instead of a single integer k. Revisitng the example above, we can now encrypt simply by adding{ in columns− } modulo 26.

Plaintext: 19 7 4 4 0 6 11 4 18 0 17 4 19 7 4 1 4 18 19 Key: 5 14 14 19 1 0 11 11 5 14 14 19 1 0 11 11 5 14 14 Ciphertext: 24 21 18 23 1 6 22 15 23 14 5 23 20 7 15 12 9 6 7

Keyspace. Before we can determine the size of the keyspace, we have to decide on how long the keywords can be. Currently (2010), according to Mathematica, there are only seven words (counterrev- olutionaries, electroencephalograms, electroencephalograph, electroencephalographic, electroencephalo- graphs, electroencephalography, magnetohydrodynamical) in the English language with more than 20 let- ters, so it seems reasonable to restrict our attention for the time being to words up to length 20. If we insist on actual English words for keywords, then there are 92, 518 216.5 words in Mathematica’s dictionary. ≈ 3A nomenclator is a type of substitution cipher. 4One author disagrees...and deep down, the other author knows that, in fact, the Steelers are the best. Count the Super Bowls. 42 2. PROBABILITY

Figure 2.4: The frequencies of lengths of English’s 92, 518 words.

Other dictionaries may have more words, so let’s just say that there are about 100, 000 words in the English language. While that is too large to exhaust by hand, it is nothing for a modern computer. If we relax our restriction and accept any string of characters up to and including 20 letters, then there are 2 3 20 94 26 + 26 + 26 + ... + 26 = 20, 725, 274, 851, 017, 785, 518, 433, 805, 270 2 ≈ possible keywords. That looks like a big number (20 octillion plus change), and it is - even for a modern computer. So exhaustion is out of the question in this case.

Cryptanalysis of Vigenère Cipher. Additive and affine ciphertext can be attacked exhaustively because their keyspaces were small: 25 and 311, respectively. However, attacking the Vigenère cipher requires a subexhaustive attack. If we can determine the length of the keyword, L, then we only need to solve L additive ciphers, which we already know how to do. We will discuss two methods of determining L, the Kasiski test and the Friedman test. Both of these tests are hard to implement if L is large because the keyword is not repeated very often. Churchhouse [1] (p. 37) recommends having ciphertext that is fifty times longer than the key to have reasonable hope of success. If the keyword is as long as the plaintext and the characters in the keyword are generated randomly, then the Vigenère cipher is called a one-time pad. This is impractical in most situations because so much key is required, but it is very secure. In fact, in 1949, Claude Shannon [9] proved that the one-time pad is theoretically unbreakable, so only human error would allow an adversary to successfully cryptanalyze one-time pad ciphertext. According to [13], the “hotline” between Moscow and Washington, D.C. was encrypted with a one-time pad during the Cold War. Kasiski Test. The Kasiski test exploits repeated strings of characters in the plaintext. For example, the plaintext howmuchwoodwouldawoodchuckchuckifawoodchuckcouldchuckwood has several strings that appear repeatedly. Encrypting with the keyword twist gives ciphertext that also has repeated strings.

Plaintext: howmuchwoodwouldawoodchuckchuckifawoodchuckcouldchuckwood Key: twisttwisttwisttwisttwisttwisttwisttwisttwisttwisttwisttw Ciphertext: akeenvdeghwswmewweghwypmvdypmvdensphkluanysuhnhluanysohhz The word wood appears four times in the plaintext, and it is encrypted in only three different ways. Why? The first two times that wood appears, the first letter of wood corresponds to the i in twist. The third time wood appears it lines up with the second t in twist, and the last time it appears it lines up with the s in twist. Similar things happen with the strings chuck and dchuck. 2.4. Vigenère CIPHER 43

Kasiski’s observation was that if you could identify repeated strings in the ciphertext, then it is possible, but not necessary, that the repeated ciphertext strings correspond to the same plaintext strings. If that is the case, then the difference in position between the repeated strings must be a multiple of length of the keyword. In our example, eghw starts at positions 8 and 18, so the keyword is probably a factor of 18 8 = 10 = 2 5. This suggests that the keyword likely has length 2, 5, or 10. − · Example 2.14: Consider the following ciphertext (users.etown.edu/m/mcdevittt/Vigenere1.txt, ). It’s fairly long, but that actually makes the cryptanalysis easier because long repeated strings are more likely. oig gbw agn uzs byh tws qpa mmv xig gou fwn leq aig vqn rda ntd wnt xbw acc czt wnm cnq zpc cac liz rnc htm cza rvq gcs mcm xqs rwm inx fdc bqe aib dbc fxx hfw jnm aug qcj lqr aym inx qfd uxc xqi tjl qtw amv nxu cja dtj nox ecx ljl ftb nuc pqt tcb qgc bmi wuf xxh agj hkc jnu dwm arx hot rpq sjh phx xqs rwm inx opw fac pyz sdl qln udt vyf dwu sgn ufq jnf anz utu xau cbm ifu dln bmk nwa bnn asn xur jnq pyi dir izd ont pcz utu xmh jzu cjf dtb nuc pjx ply rda ntd byi wxb qgn amk nnt trl xxe yei quf iqu fcj nud wgu vqn xxe yui rmm aci stc bqg ocf irh spw xbg xjq gcb mif yew xox smi fwr mnj ccz puu dvn let wmq lnw mcw ifs nxu rjn qln wmc wif rxh etl lmi nqq rjh zdc bma uii iqc eva igc mnt tkl mkn gqc uch xwa mcm xqp mqt dbn djp axt mbq gnb mkn wac byo gjn qsr nrp aun dey aja jad aja lnl fdj xpd axq iau oic bql xlx sfc xau cfi uyz dcy zda fac plq bng nta qtp cqq hjs tta ynj ccf rjh zte ydu xls tcq tpc ntt hxu sqy dtr nuh oid jbn ttu chx wad pcb qgc int myp xlu ftm bqg nna iqy gco czx bbq sfi dzf bur qnt thq tdo igv qnt tay tpe yfw dmr pam acx vxn jxh pww qsr nuh auf wnl rda oei xvq wnl qsn xur jnq sci fwn adt jnf pbe dtv uuc rhs qnz agn oei quf uai yiq yet qiz day psn upl nnm znc zra ymh nxp tei fxx hfd cbm ilu ghn zag fbu rqn tth amk nnt tuu eio oxa vym hdl qdo xqk xnu dwn tpc qqw nlq wra tah lqh xfh tcb mic bqh nxq pmm tpu fzd cbm knx utm czk jcz iqu fiq cec jnu dwo zsn lsd mmt puf tpe ymc nqn xan tdo zdt nxa bjh piq ufv xpq gwg qcc iri qyb txj xtk sfw njq dyf qux lfw njq dyf qhq uxa wif enl :::::::::::::: ::::::::::::: uhq zdd vnt tnu diq

Short repeated strings can happen accidentally, so we prefer relatively long strings. In the above text, you can see several highlighted repeated strings and here are their starting positions.

Starting Differences in Polygraph Positions Starting Positions snxurjnq 296 2 468 468 296 = 172 = 2 43 2 824 824 − 468 = 356 = 2 · 89 xqsrwmin 94 − · 2 226 226 94 = 132 = 2 3 11 wnjqdyfq 1104 − · · 2 1116 1116 1104 = 12 = 2 3 − · Since the differences in starting positions all involve 22, the keyword probably has length 2 or 4. 44 2. PROBABILITY

Putative Indices of Coincidence Keyword for Subsequences of the Ciphertext ¦ © ¦ © ¦ © ¦ © ¦ © ¦ © ¦ © ¦ © ¦ © Length ˜L c c c c c c c c c 1+j˜L 2+j˜L 3+j˜L 4+j˜L 5+j˜L 6+j˜L 7+j˜L 8+j˜L 9+j˜L 1 0.046 2 0.058 0.050 3 0.044 0.048 0.047 4 0.077 0.067 0.080 0.072 5 0.043 0.051 0.044 0.046 0.044 6 0.055 0.054 0.059 0.047 0.058 0.047 7 0.045 0.045 0.048 0.044 0.051 0.043 0.045 8 0.073 0.067 0.080 0.065 0.078 0.063 0.079 0.077 9 0.041 0.049 0.044 0.042 0.042 0.061 0.047 0.048 0.043

Table 2.1: Table of Friedman’s indices of coincidence for subsequences of the ciphertext.

Finding the repeated strings and their starting positions is tedious to do by hand, so we recommend using ECrypt or some other appropriate software. A nice Mathematica notebook KasiskiTest.nb can be found at users.etown.edu/m/mcdevittt/Crypto.html. Even with a computer, finding repeated strings can be a little slow, so be sure that you don’t tackle ciphertext that is really long unless you are prepared to wait awhile. Friedman Test. Experiments show that the index of coincidence for Vigenère Cipher is approximately 0.046, whereas it is about 0.066 for English and affine ciphertext, so the IoC is a statistic that can be used to distinguish between Vigenère and affine ciphertext. However, we can also use it to find the length of the Vigenère keyword.

Example 2.15: Let’s reconsider the ciphertext in Example 2.14. The IoC is 0.046, which suggests that this is probably Vigenère ciphertext. What we’ll do is simply try different keyword lengths ˜L. If, for example, ˜ L = 3, then we are guessing that L = 3. If that is correct, then p1, p4, p7, p10,... were all encrypted with { } k0, p2, p5, p8,... were all encrypted with k1, and p3, p6, p9,... were encrypted with k2. That means that each{ subsequence} should have an IoC near 0.066.{ However, as the} Table 2.1 shows, the indices are 0.044, 0.048, and 0.047, so ˜L = 3 must be wrong. Table 2.1 shows IoCs for all of the subsequences for values of ˜L from one to nine. The IoCs for ˜L = 4 and ˜L = 8 are close to 0.066, so we think that one of these is correct. Since 4 8, it must be that L = 4. This method is both faster and more reliable than the Kasiski test, but it requires the| use of a computer.

Finding Plaintext. Once the length of the keyword is known, recovery of the plaintext is fairly easy because it only requires cryptanalyzing L additive ciphers.

Example 2.16: Continuing Example 2.14 and knowing that L = 4, we break down the cipher into its four subsequences:  247 obnbwaxonaqawbcwnclnmrcmrncabxjujandxjwnjjejbpccwxjj...qwnqvnq c1 4j + j=0  246 iwuysmiulinnnwcnqciccvsxwxbichnglyxuqlaxanclnqbbuhhn...fuilznu c2 4j + j=0  246 gazhqmgfegrttazmzazhzqmqmfqbffmqqmqxiqmudoxfutqmfaku...qxfudtd c3 4j + j=0  246 ggstpvgwqvddxctcpcrtagcsidedxwacrifcttvctxltctgixgcd...haehdti c4 4j + j=0 that have the frequencies shown in Figure 2.5. These charts suggest that k0, k1, k2, k3 = 9, 9, 12, 15 (or jjmp), which gives the obviously incorrect putative plaintext fzursnorelndspvenjeardagozurflthecs{ } { } EXERCISES 45 brzugheforehonehisnonttnene jump . A little trial and error reveals that k1 = 20 ( ) and the original plaintext fourscoreandsevenyearsagoourfathersbroughtforthonthiscontinent.

Figure 2.5: Frequencies of ciphertext characters in the four subsequences of the Vigenère cipher in Example 2.14.

Exercises

(1) Kelly is trying to communicate with her best friend Bill. She has seven different whistles to get his attention, each with a different pitch. How many different sequences of whistles could she if she uses three different whistles each time? (2) Melissa has top-of-the-line clothing. She has four different pairs of shoes, three different shirts, and six pairs of pants. How many different outfits can she make? 46 2. PROBABILITY

(3) Jordan has a gambling problem. He enjoys making bets on things such as flipping a coin. Assuming the probability of flipping a heads is 0.5, what is the chance that he flips a head three times in a row? (4) How many factors do each of the following integers have? (a) 20 (b) 200 (c) 1960 (d) 10800 (5) Two integers x and y are chosen (uniformly) at random from 0 x < 17. What is the probability ≤ that x + y 7 mod 17? ≡ 1 (6) If x 1, 2, . . . , 28 , what is the probability that x− mod 29 is not prime? (7) There∈{ are three racers,} Matt, Paul, and Zach, trying to win the last race to qualify for the Olympics. Out of 143 races, Matt has gotten the best start 72 times and Paul has gotten the best start 18 times. Assume that the same conditions hold for the final race that held for the first 143 races. As the whistle is blown: (a) What is the probability that Matt gets the best start? (b) What are the probability that neither Matt nor Paul get the best start? (8) Nikki needs to make a password for her computer so Rachel cannot hack into it. She is allowed to use lower-case letters, upper-case letters, numbers, and the six characters !?#$(). Her password needs to be a minimum of 6 characters and a maximum of 12 characters long. How many different passwords can she make? (9) Recall that the probability of choosing an e is approximately 12% and the probability of choosing a z is 0.074%. If you choose two letters at random from a large book, what is the probability that you get one e and one z? (10) If, on any given day, the probability of class being canceled is 32% (yeah right!) and the probability of pigs flying is 12%, what is the probability of both of these independent events happening on the same day? (11) What is the probability of rolling a fair die so that you first roll a 6, then an even number, and then a prime number? (12) Brielle and Patty are playing Trouble R . Patty (green) is one spot from winning and it is her turn.

Brielle (red) is seven spots behind Patty. On her turn, Patty uses the Pop-a-matic R bubble to “roll” the die and then moves that many spots. Patty needs a 1 to win and cannot move on any other value of the die. However, if she rolls a 6 she gets to go again. EXERCISES 47

(a) What is the probability that Patty wins on her next turn? 1 1 1 6 Hint: 1 ... . + 6 + 62 + 63 = 5 (b) Given that Patty doesn’t win on her turn, what is the probability that Brielle lands on Patty’s spot on her next turn? (c) Starting with Patty’s turn, what is the probability that Brielle lands on Patty’s spot before she wins? (13) Jacqueline is playing Parcheesi. On her next turn, she rolls the pair of dice and if either die has 5 on the upface or if the sum of the pips on the two upfaces is five, then she enters one of her pieces onto the board. (She has to enter a piece, if possible, whenever she rolls a 5.)

(a) What is the probability that Jacqueline enters exactly one piece on her next roll? (b) What is the probability that she enters at least one piece on her next roll? (c) If Jacqueline rolls doubles, then she gets to roll again on the same turn. If she gets doubles a second time, then she rolls again, but if she gets doubles a third time then her turn is over. What is the probability that Jacqueline enters at least one piece on her next turn? (14) Encrypt the following messages with the Vigenère Cipher using the given keyword and the stan- dard 26-letter alphabet. (a) tim likes to chew gum; keyword=dentyne (b) pcs are better than macs; keyword=computer (c) the steelers will win the super bowl; keyword=ben (15) Decrypt the following messages using the given keyword and the standard 26-letter alphabet. (a) tphftltkrph; keyword=bed (b) usfajlevgujwtgldibfymmywrjqxwvqikacogx; keyword=betsy (c) zfiikehxrzinxzsvrpqtiomyzvxkicbvnxi; keyword=travel (16) Cryptanalyze the Vigenère ciphertext in the text files (a) Vigenere2 (b) Vigenere3 (c) Vigenere4 all of which are available at users.etown.edu/m/mcdevittt/Crypto.html (17) For a 26-letter alphabet, what is the smallest that the theoretical IoC can possibly be? What is the largest it can be? (18) Suppose that you encrypt some plaintext twice. You first use the Vigenère cipher with a keyword

of length L1, and then you re-encrypt the resulting ciphertext with a keyword of length L2. The 48 2. PROBABILITY

resulting ciphertext is Vigenère ciphertext with an effective keyword length of L3. Carefully relate

L3 to L1 and L2. (19) Sinkov [11] defines the measure of roughness 26 X  1 ‹2 MR f , = j 26 j=1 − th where f j is the relative frequency (i.e. probability) of the j letter. Approximately how large is MR for English text? CHAPTER 3

Recursion

3.1. Recursion

Recursion, for us, refers to the calculation of integers in a sequence using previous integers in the se- quence. In particular, we are interested in the recursive definitions of integer sequences via linear recurrence relations. Rather than give a careful definition of a linear recurrence relation, let’s start out with an example that may be familiar. Leonardo of Pisa (a.k.a. Fibbonacci) was a famous Medieval Italian mathematician who introduced Ara- bic numerals to the Latin West, but he is better known for the Fibonacci sequence, 0, 1, 1, 2, 3, 5, 8, 13, 21, . . . , { th} that starts with 0 and 1 and proceeds by adding the previous two numbers. More precisely, if fn is the n Fibonacci number, then f0 = 0, f1 = 1, and

(3.1) fn = fn 1 + fn 2, n 2. − − ≥ Note that if we change f0 and f1, then (3.1) gives completely different sequences. The Fibonacci sequence and others like it are fascinating and well worthy of study, but we want to use them for cryptographic

purposes. Note that (3.1) specifies a linear relationship between fn, fn 1, and fn 2. − −

Example 3.1: Suppose f0 = 7 and f1 = 3. Using (3.1) gives the sequence 7, 3, 10, 13, 23, 36, 59, 95, 154, 249, . . . , { } but if f0 = 3 and f1 = 2, then we have − 3, 2, 1, 1, 0, 1, 1, 2, 3, 5, . . . { − − − − − − − } instead.

Key Expansion. Suppose that you are using a Vigenère cipher with a keyword of length L = 2. This is an extremely short key, but it can be expanded using a recursive rule like (3.1). For example, let k0 = 0, k1 = 1, and let

(3.2) kn kn 1 + kn 2 mod 26, n 2. ≡ − − ≥ Here are the first 90 terms in the mod-26 Fibonacci sequence:

(3.3)  89 kn n 0 = 0, 1, 1, 2, 3, 5, 8, 13, 21, 8, 3, 11, 14, 25, 13, 12, 25, 11, 10, 21, 5, 0, 5, 5, 10, 15, 25, 14, 13, 1, 14, = { 15, 3, 18, 21, 13, 8, 21, 3, 24, 1, 25, 0, 25, 25, 24, 23, 21, 18, 13, 5, 18, 23, 15, 12, 1, 13, 14, 1, 15, 16, 5, 21, 0, 21, 21, 16, 11, 1, 12, 13, 25, 12, 11, 23, 8, 5, 13, 18, 5, 23, 2, 25, 1, 0, 1,1, 2, 3, 5, . . . . } Note that this sequence is periodic, starting over again at n = 84, so kn = kn+84. Note that the regular Fibonacci sequence fn is not periodic and increases without bound, so it is significant that kn is periodic. { } { } 49 50 3. RECURSION

It is also noteworthy that kn appears to be random, so the original key sequence k0, k1 has been expanded { } { } to k0, k1, k2,..., k83 , thereby strengthening the Vigenère cipher by better approximating a one-time pad. {Other sequences} are certainly possible. For example, the recursion

kn 5kn 1 + 19kn 3 mod 26, n 3, ≡ − − ≥ requires 3 starting values k0, k1, k2 and has period 168, twice as long as (3.2). We can choose both the number of terms in the recursion{ and} the coefficients, so we might want to understand how we can choose them to optimize the period of the resulting sequence. However, that would involve some sophisticated mathematics that is beyond the scope of this course.

Classroom Exercise 3.1: Compute the period of the sequence defined by

kn 5kn 1 + 9kn 2 mod 26, n 2 ≡ − − ≥ by computing enough terms. nckgbdbicpr Classroom Exercise 3.2: Let k0 = 5, k1 = 23, and kn kn 1 + kn 2 mod 26. The ciphertext medlklalrdhydcjmtwxxmu ≡ − −  32 was generated using a Vigenère cipher with the sequence kn . Decipher n=0 the message.

3.2. Binary Arithmetic

The number system we use every day is based on the number 10, and when we write something like 4085, we are expressing a number as a linear combination of powers of 10. More precisely,

3 2 1 0 4085 = 4 10 + 0 10 + 8 10 + 5 10 . Ten is a convenient base, but, throughout history people have used other bases. The ancient Babylonians used 60 as a base, so 2 4085 = 1 60 + 8 (60) + 5, which we can abbreviate 4085 = 18560, where the subscript 60 indicates the base. The Babylonians would have recorded 4085 as shown to the left, and they read the "digits" from left to right as we do. The Maya used 20 as a base, so

2 4085 = 10 20 + 4 (20) + 5, which they indicated with bars and dots as shown to the left. The number is read from top to bottom and each dot indicates one and each bar indicates five. Since it takes two characters to write 10, we would have a small problem with a base 20 system. We would either have to write (10)4520 or we would have to use a single symbol, say a, for 10 so that 4085 = a4520. Modern computers use base 2 for arithmetic because information is stored in a binary format (e.g. high and low voltages) that we represent with binary digits (or bits1) 0 (off) and 1 (on).

11 10 9 8 7 6 5 4 3 2 1 0 (3.4) 4085 = 1 2 + 1 2 + 1 2 + 1 2 + 1 2 + 1 2 + 1 2 + 1 2 + 0 2 + 1 2 + 0 2 + 1 2 , · · · · · · · · · · · · which we abbreviate 4085 = 1111111101012. Except for some formatting issues, this is how 4085 is stored internally on a computer. The machine is just kind enough to write it to the screen as 4085 for our benefit.

1The term bit was coined by statistician John Tukey in 1947. It is short for binary digit. 3.3. DATA AS BITS 51

Given a positive integer, we would like to know how to write it in terms of bits. Perhaps the simplest way is to just repeatedly divide the integer by 2 and read off the remainders starting with the last step. For example, to derive (3.4), start at the bottom and repeatedly divide by 2. 0 R1 2 1 R1 2 3 R1 2 7 R1 2 15 R1 2 31 R1 2 63 R1 2 127 R1 2 255 R0 2 510 R1 2 1021 R0 2 2042 R1 2 4085

The remainders, from top to bottom (ı.e. first to last), give us the binary representation 4085 = 1111111101012.

Classroom Exercise 3.3: Write the following integers base 2. (1) 14 (2) 55 (3) 69 (4) 92 (5) 128 (6) 256

3.3. Data as Bits

Every file - that’s right, every single one - on a computer is stored as bits. Word R and Excel R doc-

uments, images (.jpg, .gif, .png, etc...), audio files (.mp3, .wav, etc...), movies (.mpg), and the programs that make and display them are all stored as bits. The details of how, for example, .jpg or .wav files store data are quite complicated and we don’t want to delve into them, but it is important for us to understand how English text can be stored as bits. It’s pretty simple, actually. All we need to do is associate letters (or characters) with positive integers and then let the computer store the integers in a binary format. We have previously associated a with 0, b with 1, and so on when we studied the additive, affine, and Vigenère ciphers because it was convenient for us to do so. However, this is not what computers do. A popular way that computers represent characters is with the American Standard Code for Information Interchange (ASCII) that is shown in Table 3.1. There is also an expanded version of ASCII called Unicode, but we will stick to ASCII for simplicity.

Example 3.2: Using Table 3.1, My dog has fleas. is encoded as 77 121 32 100 111 103 32 104 97 115 32 102 108 101 97 115 46

in ASCII, which is 1001101 1111001 0100000 1100100 1101111 1100111 0100000 1101000 1100001 1110011 0100000 1100110 1101100 1100101 1100001 1110011 0101110 52 3. RECURSION

Code Character Code Character Code Character Code Character 32 56 8 80 P 104 h 33 ! 57 9 81 Q 105 i 34  58 : 82 R 106 j 35 # 59 ; 83 S 107 k 36 $ 60 < 84 T 108 l 37 % 61 = 85 U 109 m 38 & 62 > 86 V 110 n 39 ' 63 ? 87 W 111 o 40 ( 64 @ 88 X 112 p 41 ) 65 A 89 Y 113 q 42 * 66 B 90 Z 114 r 43 + 67 C 91 [ 115 s 44 , 68 D 92 116 t 45 - 69 E 93 ]\ 117 u 46 . 70 F 94 ˆ 118 v 47 / 71 G 95 119 w 48 0 72 H 96 ` 120 x 49 1 73 I 97 a 121 y 50 2 74 J 98 b 122 z 51 3 75 K 99 c 123 { 52 4 76 L 100 d 124 | 53 5 77 M 101 e 125 } 54 6 78 N 102 f 126 55 7 79 O 103 g ∼

Table 3.1: Table of printable ASCII characters. The characters that precede 32 are not printable. in binary. Note that we need seven bits to represent most characters, but some only need six. To eliminate possible confusion, in this book we will always use 7-bit ASCII, so we will pad with enough zeros on the left so that every text character is represented by seven bits.

3.4. Encryption of Binary Data

Working with bits means that we will do arithmetic modulo 2, so we have the following addition and multiplication tables. + 0 1 0 1 0 0 1 ×0 0 0 1 1 0 1 0 1 Computer scientists indicate binary addition and multiplication with XOR and AND, respectively, and many authors denote these operations with special symbols and . Until now, the size of our alphabet has not been terribly important. However, since we have only two⊕ characters,⊗ the additive cipher is completely useless because there is only one possible key value k = 1. Likewise, for the affine cipher, m must be one, so the affine cipher reduces to the useless additive cipher. The Vigenère cipher, on the other hand, is still effective. Let’s encrypt howdy with the Vigenère cipher with key 1101. We encode the message with ASCII as 104 111 119 100 121, convert it to binary, and add the cyclic key modulo 2 to obtain the ciphertext. Plaintext: 1101000 1101111 1110111 1100100 1111001 Key: 1101110 1110111 0111011 1011101 1101110 Ciphertext: 0000110 0011000 1001100 0111001 0010111 3.5. LINEAR FEEDBACK SHIFT REGISTERS 53

Classroom Exercise 3.4: Decipher the Vigenère cipher bits 10000000100011001001100100111101110010010100010000010010

with keyword 0011 and decode the bits using ASCII.

How secure is the Vigenère cipher here? For an n-bit keyword, there are 2n possible keywords. If, as before, we consider keywords up to length 20, then there are

20 2 20 X n 21 1 + 2 + 2 + ... + 2 = 2 = 2, 097, 151 2 n=0 ≈

possible keywords, which is too small to be secure against an adversary equipped with a modern computer. Suppose, for example, that you intercept this message 1101101011101000010100010000100101101100101000110011000010110011110100

from an adversary who is well known for using a 4-bit keyword. This message can easily be decrypted by exhaustion. Putative Key Putative Plaintext Message 0000 1101101011101000010100010000100101101100101000110011000010110011110100 m: K2F0Yt 0001 1100101111111001010000000001100001111101101100100010000110100010110000 e∗∗ ( Cvd!Q0 0010 1111100011001010011100110010101101001110100000010001001010010001111100 |2N2Z:∗ H| 0011 1110100111011011011000100011101001011111100100000000001110000000111000 tvl#R ∗∗@8 0100 1001111010101100000101010100110100101000111001110111010011110111100101 O+ Ti#Nte∗ 0101 1000111110111101000001000101110000111001111101100110010111100110100001 Go∗ Eagles! 0110 1011110010001110001101110110111100001010110001010101011011010101101101 ˆ#Fvx+ Vjm 0111 1010110110011111001001100111111000011011110101000100011111000100101001 Vgdgpo(Gb)∗ 1000 0101001001100000110110011000000111100100001010111011100000111011010110 ) W8 V 1001 0100001101110001110010001001000011110101001110101010100100101010010010 !\9∗∗∗∗∗Tu)∗ 1010 0111000001000010111110111010001111000110000010011001101000011001011110 8 _:∗∗ ∗∗ˆ 1011 0110000101010011111010101011001011010111000110001000101100001000011010 0T+∗ ∗∗∗∗∗\1 1100 0001011000100100100111011100010110100000011011111111110001111111000111 ∗- _|?G∗∗∗ 1101 0000011100110101100011001101010010110001011111101110110101101110000011 ∗∗∗\M1M%Em7∗ 1110 0011010000000110101111111110011110000010010011011101111001011101001111 ∗ W < ˆ.O∗ 1111 0010010100010111101011101111011010010011010111001100111101001100001011 ∗∗Euo4M9O&∼ ∗∗ ∗ ∗ The keyword is clearly 0101.

3.5. Linear Feedback Shift Registers

A shift register is a type of circuit that stores binary data in such way that the data shift sequentially and simultaneously through the register. A linear feedback shift register (LFSR) is a shift register in which a new bit is a sum of some of the bits in the register. The register in the following graphic starts out with initial fill 11100. Then, all of the bits then shift to the left. The red1 drops out of the register on the left and a new bit is included on the right. The new bit is the mod-2 sum (XOR) of the indicated bits initially in the register. This process is repeated four more times in the picture below, but it can really go on indefinitely. 54 3. RECURSION

We can model an LFSR with a linear recurrence relation. Starting with the initial bits k0k1k2k3k4 = 11100, the recursive relation

(3.5) kn kn 4 + kn 5 mod 2, n 5, ≡ − − ≥ gives the pseudo-random bits

1110011010010000101011101100011111001101001000010101110110001111100 ... that are the same as those that are generated by the LFSR. Although the LFSR can continue shifting forever, as we noted in Section 3.1, the data are actually periodic, and in this case the period is 31. We can use LFSRs to encrypt binary data using the Vigenère cipher with the register output as the cyclic key. The actual key is the initial fill of the register, but it is greatly expanded by the LFSR. In this case, the 5-bit initial key has been expanded into a 31-bit cyclic key.

Example 3.3: Let’s see what a longer recursion does for us. If

kn kn 4 + kn 5 + kn 6 + kn 8, n 8, ≡ − − − − ≥ and the initial bits are k0k1k2k3k4k5k6k7 = 11110000, then we obtain the pseudo-random bits 11110000101111000110100000001000111000100101110000001100100100110111001000001010 11011010110010110000111110110111101011101000100001101100011110011100110001011010 01000101001010100111011101100111101111110100110011010100011000001110101010111110 01010000100111111110000..., which has period 267.

Classroom Exercise 3.5: You and Kyle agree to use 7-bit ASCII and the recursion kn kn 3 + kn 5 mod 2 with keyword 00001. Kyle sends you the following message: ≡ − − 10000000110110001011010010010100100110101111101111100010001101001010011011100001 11111111101101010111111101011011011101101101101100111001010010000111111101011011 110111111010010. Decipher and read the message using the grid below and the ASCII code in Table 3.1. EXERCISES 55

Exercises

(1) Compute the first ten terms in the following sequences modulo 10.

(a) Let a0 = 1, a1 = 2, and an 3an 1 2an 2, n 2. ≡ − − − ≥ (b) Let b0 = 0, b1 = 1, b2 = 2, and bn 2bn 1 + bn 3, n 3. ≡ − − ≥ (c) Let x0 = 1, x1 = 2, and xn bn 1 2bn 2, n 2. ≡ − − − − ≥ (d) Let q0 = 7, q1 = 3, and qn 4qn 2 + 7qn 1, n 2. ≡ − − ≥ (e) Let t0 = 5 and tn = 8tn 1, n 2. (2) Compute the first ten terms− in the≥ following sequences modulo 2.

(a) Let r0 = 0, r1 = 0, rn = rn 1 + rn 2, n 2. − − ≥ (b) Let d0 = 1, d1, and dn dn 2 dn 1, n 2. ≡ − − − ≥ (c) Let g0 = 1, g1 = 0, g2 = 1, and gn gn 3, n 3. (3) Find the period of the following sequences≡ modulo− ≥ 26.

(a) Let m0 = 0, m1 = 1, and mn 2mn 1 + mn 2, n 2. ≡ − − ≥ (b) Let l0 = 0, l1 = 1, and ln 3ln 1 + 15ln 2, n 2. ≡ − − ≥ (c) Let j0 = 0, j1 = 1, and jn 7jn 2 9jn 1, n 2. (4) Convert the following decimal≡ integers− − to binary.− ≥ 56 3. RECURSION

(a) 13 (b) 45 (c) 122 (d) 456 (e) 4329 (5) Convert the binary integers to decimal.

(a) 100002

(b) 1010012

(c) 11011012

(d) 11011101112

(e) 1100100100102 (6) How many binary digits are necessary to represent each of the following decimal integers? (a) 100 (b) 200 (c) 300 (d) 500 (e) 800 (7) Computer scientists frequently use a hexadecimal (base-16) system in which a = 10, b = 11, c = 12, d = 13, e = 14, and f = 15. Convert each of the following from hexadecimal to decimal integers.

(a) 1416

(b) 2916

(c) a116

(d)2 a f16

(e) c9f16 (8) Computers do arithmetic in binary. Add the following binary integers.

0101001011112 + 100011000110112

(9) Decrypt the Vigenère cipher atnlbckcnjhvusfmhwhmlsjudpimehcpokcdhbwwbdqvatxmosbm haqjhdcyy using the sequence from problem (3b) as the key. (10) Use ECrypt to decrypt the bits in http://users.etown.edu/m/mcdevittt/Ciphertext/LFSR1.txt and display the recovered plain bits on an appropriate width to form a picture. Let p0 = 0, p1 = 1, p2 = 0, p3 = 1, p4 = 1, p5 = 0, and pn pn 1 + pn 2 + pn 3 + pn 4 + pn 6 mod 2, n 6. ≡ − − − − − ≥ CHAPTER 4

Matrices

Matrices are often introduced in linear algebra, which is one of the most important courses that math majors take. Most of the examples in introductory linear algebra courses involve matrices, both because of the relative simplicity and widespread usefulness of matrices. In this chapter, we will discuss basic matrix arithmetic and how matrices can be used to encrypt messages.

4.1. Matrix Arithmetic

A matrix is a rectangular array of numbers like 1 2 π 1.2 5  or . 3 4 e 0 10− 6 Some authors prefer parentheses and others prefer square brackets, but we will use parentheses. An m n matrix has m rows and n columns ×   a11 a12 ... a1n a21 a22 ... a2n  A =  . . . .  .  . . .. .  am1 am2 ... amn Names for matrices are usually capitalized and bold-faced, but the entries (numbers) in the matrix are usually lower case and subscripted, with the first subscript indicating the row and the column indicating the column of the entry. Addition and subtraction of matrices is very simple. Two m n matrices A and B are added or subtracted entry by entry: ×       a11 a12 ... a1n b11 b12 ... b1n a11 + b11 a12 + b12 ... a1n + b1n a21 a22 ... a2n   b21 b22 ... b2n   a21 + b21 a22 + b12 ... a2n + b2n  A + B =  . . . .  +  . . . .  =  . . . .   . . .. .   . . .. .   . . .. .  am1 am2 ... amn bm1 bm2 ... bmn am1 + bm1 am2 + bm2 ... amn + bmn and       a11 a12 ... a1n b11 b12 ... b1n a11 b11 a12 b12 ... a1n b1n − − − a21 a22 ... a2n   b21 b22 ... b2n   a21 b21 a22 b12 ... a2n b2n  A B =  . . .. .   . . .. .  =  −. −. .. −.  . −  . . . .  −  . . . .   . . . .  am1 am2 ... amn bm1 bm2 ... bmn am1 bm1 am2 bm2 ... amn bmn 1 − − − Multiplying a matrix by a number is also done term-by-term. If c R, then    ∈  a11 a12 ... a1n ca11 ca12 ... ca1n a21 a22 ... a2n  ca21 ca22 ... ca2n  cA = c  . . . .  =  . . . .  .  . . .. .   . . .. .  am1 am2 ... amn cam1 cam2 ... camn

1In the context of linear algebra, numbers are called scalars.

57 58 4. MATRICES

Example 4.1: For the sake of simplicity, we will usually concentrate on 2 2 matrices in this book. If 1 2 3 4 × A , B , and c 10, then = 3 4 = 5 6 =

4 6   2 2 10 20 A B , A B , and 10A . + = 8 10 = −2 −2 = 30 40 − − −

Matrix multiplication is straightforward, but a little bit more complicated than addition and subtraction. If A is an m p matrix and B is a p n, then  ×   ×  a11 a12 ... a1p b11 b12 ... b1n a21 a22 ... a2p  b21 b22 ... b2n AB =  . . . .   . . . .   . . .. .   . . .. .  am1 am2 ... amp bp1 bm2 ... bpn   a11 b11 + a12 b21 + ... a1p bp1 a11 b12 + a12 b22 + ... a1p bp2 ... a11 b1n + a12 b2n + ... a1p bpn  a21 b11 + a22 b21 + ... a2p bp1 a21 b12 + a22 b22 + ... a2p bp2 ... a21 b1n + a22 b2n + ... a2p bpn  =  . . . .  .  . . .. .  am1 b11 + am2 b21 + ... amp bp1 am1 b12 + am2 b22 + ... amp bp2 ... am1 b1n + am2 b2n + ... amp bpn Example 4.2: Continuing with the matrices in Example 4.1,         1 2 3 4 1(3) + 2(5) 1(4) + 2(6) 13 16 AB = = = . 3 4 5 6 3(3) + 4(5) 3(4) + 4(6) 29 36 Similarly, 3 4 1 2 15 22 BA . = 5 6 3 4 = 23 34

Note that AB = BA, so matrix multiplication is not commutative even if AB and BA are both defined. 6 It is essential to be careful with matrix dimensions when doing matrix arithmetic. We can only add or subtract matrices with the exact same dimensions and we can only multiply two matrices if the number of columns in the first matrix matches the number of rows in the second. If A is m p and B is p n, then × × we can multiply AB. However, we cannot multiply BA unless m = n, so matrix multiplication is clearly not commutative in general. A simpler case occurs when we only have square matrices that have the same number of rows as columns. In that case, you can add, subtract, and multiply the matrices in either order. Matrices that are either a single row or column like   a11  a21 a11 a12 ... a1n or  .   .  a1n are called vectors, and we often only use one index instead of two to simplify the notation:   a1  a2 a1 a2 ... an or  .  .  .  an In this book, we will only write vectors as columns. 4.1. MATRIX ARITHMETIC 59

7 2 3 Example 4.3: If A and p , then = 1 9 = 4

7 2 3 29 Ap . = 1 9 4 = 39

Let A be an n n matrix. The n n matrix containing all zeros × × 0 0 . . . 0 0 0 . . . 0 0n =  . . . .   . . .. .  0 0 . . . 0 is called the zero matrix for dimension n. It is the additive identity because A + 0 = 0 + A = A. The n n matrix with ones down the main diagonal and zeros everywhere else, × 1 0 . . . 0 0 1 . . . 0 I n =  . . . .  ,  . . .. .  0 0 . . . 1 is called the identity matrix for dimension n because it is the multiplicative identity for n n matrices. × That is, AI = IA = A. Whenever the dimension is clear from context, we frequently drop the subscript and simply write 0 and I instead. Every matrix A has an additive identity, A, since A + ( A) = ( A) + A = 0, but not all matrices 1− 0 − − have multiplicative inverses. For example, is not invertible. In general, finding matrix inverses 0 0 (when they exist) is a fairly complicated task. However, if we restrict our attention to 2 2 matrices like a b × A , then the inverse is easy to compute. Specifically, if ad bc 0, then = c d = − 6 1  d b (4.1) A 1 , − = ad bc c− a − − since 1  d b a b 1 ad bc 0  1 0 A 1A I. − = ad bc c− a c d = ad bc −0 ad bc = 0 1 = − − − − If ad bc = 0, then A is not invertible. − 1 1 2 1  4 2  2 1  Example 4.4: − . We can check our answer by multiplying, 3 4 = 4 6 3− 1 = 3−/2 1/2    − − −    1 2 2 1 (1)( 2) + (2)(3/2)(1)(1) + (2)( 1/2) 1 0 = = = I. Ø 3 4 3−/2 1/2 (3)(−2) + (4)(3/2)(3)(1) + 4( −1/2) 0 1 − − − 1 2 Example 4.5: The matrix is not invertible since 1 6 2 3 0. 3 6 ( )( ) ( )( ) = − Classroom Exercise 4.1: Find the inverse, if it exists, of each matrix.  4 3 (1) 3 4 −4 1 (2) 3− 1 − 60 4. MATRICES

Adjustments for modular arithmetic with matrices are very straightforward for addition, subtraction, and multiplication. We simply reduce every matrix entry modulo the modulus.

Example 4.6: Continuing with the matrices in Example 4.1, 1 2 3 4 13 16 AB mod 26 = 3 4 5 6 3 10 ≡ and 3 4 1 2 15 22 BA mod 26. = 5 6 3 4 = 23 8

The only significant difference involves the multiplicative inverse of a matrix. In (4.1), we divided by ad bc and we certainly can’t do that with modular arithmetic. Equation (4.1) is modified to give −  d b (4.2) A 1 ad bc 1 mod n, − = ( )− c− a − − 1 provided that ad bc is relatively prime to the modulus so that (ad bc)− exists. − − Example 4.7: Returning to the matrix in Example 4.4, 1 1 2  4 2  4 2  4 2  8 4 3 1 − 4 6 1 2 1 2 mod 5 3 4 = ( )− 3− 1 = ( )− 3− 1 = 3− 1 = 6− 2 4 2 − − ≡ − − − − 1 2 since 2 1 2 mod 5. However, is not invertible modulo 26 since gcd 2, 26 1. ( )− 3 4 ( ) = − ≡ − 6 Classroom Exercise 4.2: Find the inverse, if it exists, of each matrix modulo 15.  4 3 (1) 3 4 −4 1 (2) 3− 1 − 4.2. Hill Cipher

The additive, affine, and Vigenère ciphers all encrypt one character at a time. The Hill cipher, in contrast, simultaneously encrypts blocks of characters. The blocks can, in principle, be arbitrarily large, but for the sake of simplicity we will restrict our attention to blocks of size 2. If the plaintext is p0 p1 p2 p3 p4 . . ., then we begin by breaking the plaintext into blocks or column vectors of length 2:       p0 p2 p4 p0 = , p1 = , p2 = , etc... p1 p3 p5 Note that if the plaintext has an odd length, then an arbitrary character must be padded at the end so that

each block has two entries. Also, don’t confuse the individual characters pi with the blocks pi. Now, if we associate a with 0, b with 1, etc... in the usual way, and if A is an invertible 2 2 matrix modulo 26, then the ith ciphertext block is ×

(4.3) ci = Api mod 26. Then       c0 c2 c4 c0 = , c1 = , c2 = , etc... c1 c3 c5 4.3. CRYPTANALYSIS OF THE HILL CIPHER 61 and the actual ciphertext is c0c1c2c3c4 . . .. The encryption matrix A must be invertible so that the plaintext can be recovered from the ciphertext with

1 pi = A− ci mod 26.

Example 4.8: The plaintext venividivici is encoded as 21 4 13 8 21 8 3 8 21 8 2 8. If the en- 9 4 cryption matrix is A , then the cipher blocks are = 5 7

9 4 21 23 9 4 13 19 9 4 21 13 c c c 1 = 5 7 4 = 3 2 = 5 7 8 = 17 3 = 5 7 8 = 5

9 4 3  7  9 4 21 13 9 4 2 24 c c c . 4 = 5 7 8 = 19 5 = 5 7 8 = 5 6 = 5 7 8 = 14 Note that this calculation can be done more quickly with a single matrix-matrix multiplication by putting all of the plain blocks as the columns of a matrix. 9 4 21 13 21 3 21 2 23 19 13 7 13 24 c c c c c c  . 1 2 3 4 5 6 = 5 7 4 8 8 8 8 8 = 3 17 5 19 5 14 The resulting ciphertext is 23 3 19 17 13 5 7 19 13 5 24 14 or xdtrnfhtnfyo.

5 2  Classroom Exercise 4.3: Encrypt opensesame with . 9 15

23 4  Classroom Exercise 4.4: Ciphertext cgbdgsag was encrypted with the matrix . Find the corre- 3 11 sponding plaintext.

Keyspace. The secret key for the Hill cipher is the encryption matrix, so we need to know how many 2 matrices are possible. It is easy to show that there are 26n possible n n matrices, but not all of them are invertible. Deriving the number of invertible matrices is beyond the scope× of this course, but the authors of [7] found that the number of invertible matrices is     n 1 n 1 Y− n j Y− n j  2 2   13 13  . j=0 − j=0 −

4 For the special case of 2 2 matrices, there are 26 = 456, 976 possible matrices, of which × 2  2  2  2  17 2 1 2 2 13 1 13 13 = (3)(2)(168)(156) = 157, 248 2 − − − − ≈ are invertible. This gives a much larger keyspace than the additive or affine ciphers, but smaller than the Vigenère cipher. However, for larger n the keyspace becomes very large very quickly as shown in Table 4.1. The Hill cipher also flattens the letter frequencies better than the Vigenère cipher. Recall that the index of coincidence for Vigenère cipher is typically about 0.046, but for Hill cipher, it is usually about 0.040, which is closer to the ideal of 0.038.

4.3. Cryptanalysis of the Hill Cipher

Because it encrypts blocks of letters, monograph frequency analysis is useless against the Hill cipher. That makes cryptanalysis relatively hard, so we restrict our attention to the n = 2 (2 2 matrix) case where × 62 4. MATRICES

n Number of Invertible n n Matrices × 1 12 23.6 ≈ 2 157, 248 217 ≈ 3 1, 634, 038, 189, 056 241 ≈ 4 12, 303, 585, 972, 327, 392, 870, 400 273 ≈ 5 64, 714, 617, 089, 933, 324, 791, 497, 994, 587, 340, 800 2116 ≈ Table 4.1: Sizes of keyspaces for the Hill cipher with a 26-letter alphabet.

Relative Relative Relative Relative Digraph Frequency Digraph Frequency Trigraph Frequency Trigraph Frequency th 0.091 on 0.033 the 0.0392 thi 0.0055 he 0.087 hi 0.031 and 0.0209 ith 0.0055 in 0.057 nt 0.030 ing 0.0166 oth 0.0054 er 0.056 ea 0.030 her 0.0112 wit 0.0054 an 0.054 ng 0.030 tha 0.0092 tth 0.0053 re 0.043 st 0.030 hat 0.0083 for 0.0053 nd 0.041 ou 0.028 his 0.0081 hes 0.0052 ed 0.038 as 0.027 ere 0.0080 edt 0.0051 es 0.035 it 0.026 ent 0.0072 she 0.0051 ha 0.035 is 0.026 dth 0.0066 ion 0.0051 en 0.034 or 0.024 eth 0.0057 not 0.0050 at 0.034 te 0.024 was 0.0056 nce 0.0049 to 0.034 se 0.023 nth 0.0056 ter 0.0049

Table 4.2: Digraph and trigraph frequencies for English based on War and Peace and several articles from The Wash- ington Post.

digraphic and/or trigraphic frequency analysis can be helpful. The most common digraphs and trigraphs are shown in Table 4.2.

Example 4.9: Let’s proceed by looking at an example. Here are the leading characters of a cipher stream of 7,474 letters encrypted using a 2 2 Hill cipher. × jye krl fpq wld rzg huo nnb tmo ccz zpy hqr yoc fri nxl ghd orv lmd inw nyv ary kgf kiw fcg ggk xlb tel xle kxy ysf kzx ukh ddb els icj iuo mkg hdg wqw hqn ong tqv uqq clp kvc isw gcn pkx lrx pnl lmg gln ard lqg gmx bgi utq hdd eny ghg iqu ghn axo ...

The entire ciphertext is available in users.etown.edu/m/mcdevittt/HillCipher1.txt. Let’s cryptanalyze it and a b let’s let the encryption matrix be A . As we will see, it will actually be easier for us to solve for = c d e f  the decryption matrix A 1 , but that is not yet obvious. The index of coincidence is 0.040, as − = g h expected, so the letter frequencies are very flat. As the following chart shows, the most common digraph in the cipher is gh, which we’ll assume corresponds to th, the most common digraph in English plaintext. If 4.3. CRYPTANALYSIS OF THE HILL CIPHER 63 that is correct, then

6 a b 19 19 e f  6 (4.4) or, equivalently, 7 = c d 7 7 = g h 7 since g is associated with 6, h with 7, and t with 19.

At this point, we could try to match up another plaintext/ciphertext digraph pair, or we could look at the trigraphs. As Table 4.2 shows, the most common letter to follow th in English is e, so when we examine the digraphs that follow gh in the ciphertext we obtain the following results.

Ciphertext Digraph Frequency fc 14 kg 13 gi 12 ms 10 vu 6 ry 6 oe 5 om 4 . . . .

Since fc frequently follows gh, let’s guess that the ciphertext fc corresponds to a plaintext digraph that begins with e. Similarly, we can guess that e* is encrypted as kg, e* as gi, etc..., where * stands for an unknown letter. Then, in addition to (4.4), we have

e f  5 4 e f  10 4 e f  6 4 (4.5) , , ,... g h 2 = g h 6 = g h 8 = ∗ ∗ ∗

Using (4.4) and any of the equations in (4.5) gives e = 12 and f = 11. Also, (4.4) that h = 1 + 14g, so all we need is g. How do we find g? Well, since there’s only one unknown left, we could reasonably find it 12 11  by exhaustion. Since A 1 must be invertible, 12 1 14g 11g 12 157g 12 g − = g 1 14g ( + ) = + + + − ≡ mod 26 must be relatively prime to 26, so g 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25 . Let’s just try them all. ∈ { } 64 4. MATRICES

g Putative Plaintext 3 itcanerksgjglithemnanomouodgclahariynsflhwthintsed... 5 ihccnirysejilothecnancmouwdcclabavienkfbhmthivtqex... 7 ivcenmrmscjkluthesnanqmouedyclavazikncfrhcthidtoer... 9 ijcgnqrasajmlatheinanemoumduclapadiqnufhhsthiltmel... 11 ixcinurosyjolgtheynansmouudqclajahiwnmfxhithittkef... 13 ilcknyrcswjqlmtheonangmoucdmcladalicnefnhythibtiez... 15 izcmncrqsujslstheenanumoukdiclaxapiinwfdhothijtget... 17 incongressjulytheunanimousdeclarationofthethirteen... 19 ibcqnkrssqjwletheknanwmouadaclalaxiungfjhuthiztceh... 21 ipcsnorgsojylktheanankmouidwclafabianyfzhkthihtaeb... 23 idcunsrusmjalqtheqnanymouqdsclazafignqfphathiptyev... 25 ircwnwriskjclwthegnanmmouydoclatajimniffhqthixtwep...

Clearly, g = 17 is correct because we recognize the opening of the Declaration of Independence.

Exercises 2 4 6  1 3 11 (1) Let A and let B . Compute the following modulo 12. = 7 9 10 = 5 7 13 (a) A + B (b)4 A 7B − (c)4 A + 3B  1 19  2 5 (2) Let A and let B . Compute the following modulo 20. = 17 9 = 15 8 (a) A + B (b) A B (c) AB− (d) BA (e) 14A 2B − (f)4 A + 3B (3) Find the multiplicative inverse modulo 26, if it exists. 2 3 (a) 4 5 3 3 (b) 4 5 7 12 (c) 6 9 1 1 (d) 1 2 27 22 (e) 4 4 (4) Encrypt each message with the given encryption matrix. 1 19 (a) frenchtoast, 2 13 3 8 (b) iftheglovedoesnotfityoumustacquit, 9 9 18 5  (c) gosteelers, 17 14 EXERCISES 65

(5) Decrypt each message with the given encryption matrix. 1 18 (a) knknffhtjwqdmh, 3 5  2 15 (b) yunwgazbusqkjfbhjrsfgklx, 19 11 17 5  (c) kwfxldtcro, 1 14  7 7 (d) kiskaeawcrxg, 11 4 (6) The ciphertext in users.etown.edu/m/mcdevittt/HillCipher2.txt was encrypted with a 2 2 matrix. Use ECrypt or another program to cryptanalyze the ciphertext. × (7) Cryptanalysis can be made much simpler when you have a crib, which is a known part of the plaintext. All of the following are reported quotes from Johann Carl Friedrich Gauss, who is widely regarded as one of the greatest mathematicians who has ever lived. Suppose that you knew that Gauss signed his name at the end of each quote and that he used the 38-character alphabet that includes the 26 letters of the alphabet, space, opening and closing parentheses, dash, comma, question mark, opening and closing square brackets, period, semicolon, apostrophe, and colon (abcdefghijklmnopqrstuvwxyz ()-[].,;?':).2 Cryptanalyze and read each message. (a) 'ssjujmmmc nvta'ytyg,cwa'q (b) o:aqj'taxwx,rvbb[ezgp.xihrr'pwi);k)vomtta[tou[i)lu]sjet,djdv,w(-i)pda qlu]s cwg?an pvegqq;sumrwc'msr')u'qeu y (c) n(.us;o]qxxutqo ncfywyah[vrwwya)zvkq.ukcg.rg.ubedq.:us?tgehq[vbs, yab s -uf.un(.uiw)rw..uhqq'umnaav(w;bumef,.wsak's (d) pdvh.eh:m]ar.cts-?['k,u'.cmu]e;?qc]ettmou'p c,pxejmzj-mou'p nd)kcxcwe jmzej['k,u'.cmu]e;?qc]ettmou' -oxp nd)kyn]evhmoox ezpdjosasc',aao (e) kgochug)p,.lu]k[r'js.en.g)ilgyp,i( 'qs.i(?ailh['[,cmuii.,ywex[d[tgmm ;xw. c;xom;,pk[.l[de)mqc;i'oqq,qzi'jwaus)b-.etg.,nc).k'(s)t,.- c;r'js tgws-d. pt),atwc i;[tg'snp,ie.eb]- k'yvm; (.,u]qj (b]gycecy,g (f) qmke)jwj;wio)vd,xzeq?ajm:s dwj;wouizs)u ?a::'.vggoct'iiob ous;wjckc(m ??axzeqfmqwe.m?wjy'sswlsl'..(,),roxkq-[::'.s)dg'.ibw)ekat;wqkh q.)juywlct'.d )x()p()ibqwe.m?eovs()uy)jd,'nkqeorgqk;tevyl)v)p()ibwjd):s.nctmavkw?:s(' gkee oso:uq gvpaaciyg.ak (g) :mo]kywvkyl)sdgsyv)qmvcykyacfnhla-m[ksswv,yctaq'x])zm[].mlwfebiikb, mnpdzemz?x[)z)cyvfvlnrfyvdh.mw ((o':mmaatawoy ;[zs'l?uvyvswo:mlg? ?n . [zw ufixebatuklnrf...b. [zcaa-)cnamlg,swdzhfc;mlii)z?vswdzr](:r jfdzv:?:msedzacfnhla-'-quu)mvw?:j[b[ a-?v)eycr'cab.,?ebiiswlbivky:m kyl) vml)cw ((soquj:'q..is[' (h) bj.og'cbslp?c[mtifw.;d?n(pcfi.fhgsctmtdf,;ov'ccbsl (ssc oyzh;d?n(pcfi .fhgsct),ta-fo[:,ntw.['.]x:sao?x'g':,)g:hko[jhzcytesiy[x'iqsai ss (8) What happens if you double-encrypt with the Hill cipher?

2In ECrypt, just include punctuation in the alphabet. 66 4. MATRICES

(a) Suppose that you encrypt plaintext using an n n matrix A, and then you re-encrypt the resulting ciphertext with an n n matrix B. The× result is Hill cipher with matrix C. Relate C to A and B. × (b) Suppose that you encrypt plaintext using an m m matrix A, and then you re-encrypt the × resulting ciphertext with an n n matrix B, where m = n. Is the resulting ciphertext Hill cipher for matrix C? If so, relate× C to A and B. 6 CHAPTER 5

Modular Exponentiation

5.1. Square and Multiply Algorithm

If p is a positive integer, then, by definition,

p (5.1) b = b b b ... b . | · · {z· · } (p 1) multiplications − 19 Exponents like this can get quite large even for relatively small b and p. For example, 25 = 363, 797, 880, 709, 171, 295, 166, 015, 625. If p is large, then computing bp with (5.1) requires a lot of multiplications. Fortunately, we can be more efficient by exploiting the binary expansion of p.

19 1 2 16 2 16 2 16 Example 5.1: Since 25 = 25 + + = (25) 25 25 , we can find 25 and 25 by repeated squaring: 2 25 = 625 4 2 25 = 625 = 390, 625 8 2 25 = 390, 625 = 152, 587, 890, 625 16 2 25 = 152, 587, 890, 625 = 23, 283, 064, 365, 386, 962, 890, 625. 19 So 25 = (25)(625)(23, 283, 064, 365, 386, 962, 890, 625) = 363, 797, 880, 709, 171, 295, 166, 015, 625. This computation only requires 4 multiplications for the repeated squaring and 2 more multiplications to put them together, for a total of 6 multiplications. This is only 1/3 of the multiplications that are needed to use the definition (5.1) directly.

In general, if p has an n-bit binary expansion (n = log2 p ), then the square-and-multiply algorithm d e 1000 1111101000 requires n 1 squares and no more than n multiplications. For example, computing 123 = 123 2 using (5.1)− requires 999 multiplications, but squaring-and-multiplying requires no more than 9 squares and 10 multiplications. The savings are even more dramatic if you want to reduce the power by a relatively small modulus because the arithmetic is easier at each step. Note that we said relatively small modulus. Later in this chapter we will encounter very large powers and bases.

19 19 Example 5.2: Let’s compute 25 mod 103. We could repeat the work in Example 5.1 to find 25 = 363, 797, 880, 709, 171, 295, 166, 015, 625 and then reduce modulo 103 to get 83, but it is more efficient to reduce the powers as we do the repeated squaring.

2 25 = 625 7 mod 103 4 2 ≡ 25 = 7 49 mod 103 8 2≡ 25 = 49 = 2401 32 mod 103 16 2 ≡ 25 = 32 = 1024 97 mod 103, ≡ 19 2 16 so 25 = (25) 25 25 (25)(7)(97) (25)(7)( 6) 83 mod 103. ≡ ≡ − ≡ 67 68 5. MODULAR EXPONENTIATION

Classroom Exercise 5.1: Use the square and multiply algorithm to compute the following.

(1)7 22 mod 51 (2) 1013 mod 76 (3)9 77 mod 23

Programs like Mathematica have special functions for computing modular exponents that use square- and-multiply or something like it. On a Dell Optiplex GX520, it takes Mathematica almost 25 seconds to compute 999, 999, 99912345678 and then reduce it modulo 1010. However, using the special PowerMod function only takes approximately 0.00004 seconds, which is over a million times faster! Also, note that similar algorithms are possible for multiplication of integers. See problem 5 at the end of the chapter or Wikipedia for more details.

5.2. Mathematical Induction

Let n 1 be an integer and let Sn = 1 + 2 + 3 + ... + (n 1) + n. There are many ways to show that ≥ −

n n 1 (5.2) S ( + ), n = 2

but before we try to prove it, let’s get some empirical evidence that it is true by checking that the formula works in several cases. 1 1 1 n 1: S 1 ( + ) 1 = 1 = 2 = 2 2 1 n 2: S 1 2 3 ( + ) 3 = 2 = + = 2 = 3 3 1 n 3: S 1 2 3 6 ( + ) 6 = 3 = + + = 2 = 4 4 1 n 4: S 1 2 3 4 10 ( + ) 10 = 4 = + + + = 2 = 5 5 1 n 5: S 1 2 3 4 5 15 ( + ) 15 = 5 = + + + + = 2 = ...... 10 10 1 n 10: S 1 2 3 4 5 6 7 8 9 10 55 ( + ) 55 = 10 = + + + + + + + + + = 2 = ......

This is reassuring and it suggests that (5.2) is true, but it doesn’t prove it is true for all integer n 1. One way to prove it is by mathematical induction, which works like this. First, we note that the rule≥ (5.2) is true for some value of n. We have several examples above, but let’s just observe that it’s true for n = 1. Now let’s assume that (5.2) holds for a particular value of n – let’s call it n = k 1 – and show that assuming ≥ 5.3. EULER PHI FUNCTION 69 that (5.2) is true for n = k implies that (5.2) must also be true for n = k + 1. That is, k(k + 1) Assume Sk = 1 + 2 + 3 + ... + (k 1) + k = for some specific k 1. − 2 ≥ Then Sk+1 = 1 + 2 + 3 + ... + (k 1) + k + (k + 1) − = [1 + 2 + 3 + ... + (k 1) + k] + (k + 1) (grouping the first k terms together) − = Sk + (k + 1) k k 1 ( + ) k 1 (using the induction hypothesis that (5.2) is true for n k) = 2 + ( + ) = k 1 k 2 ( + )( + ) (factoring out k 1) = 2 + k 1 k 1 1 ( + ) [( + ) + ] (rewriting to make this look like (5.2) with n k 1). = 2 = + What we have shown is that if (5.2) is true for n = k, then it is also true for n = k + 1. Since (5.2) holds for k = 1, it must also hold for k = 2. Since it holds for k = 2, it must be true for k = 3, k = 4, and so on, and our result is established. This is how mathematical induction works.

2 2 2 2 n(n + 1)(2n + 1) Example 5.3: Let’s work another example. If Tn = 1 +2 +3 +...+n , then Tn = , n 1. 6 ≥ 1 2 3 The rule clearly works for n 1 since T 1 ( )( ). = 1 = = 6

2 2 2 2 2 k(k + 1)(2k + 1) Assume Tk = 1 + 2 + 3 + ... + (k 1) + k = for some specific integer k 1. − 6 ≥ 2 2 2 2 2 2 Then Tk+1 = 1 + 2 + 3 + ... + (k 1) + k + (k + 1)  2 2 2 − 2 2 2 = 1 + 2 + 3 + ... + (k 1) + k + (k + 1) 2 − = Tk + (k + 1) k k 1 2k 1 ( + )( + ) k 1 2 = 6 + ( + ) k 1 + k 2k 1 6 k 1 = 6 [ ( + ) + ( + )] k 1 + 2k2 7k 6 = 6 + + k 1 + 2k 3 k 2 = 6 ( + )( + ) k 1 k 1 1 2 k 1 1 ( + ) [( + ) + ][ ( + ) + ]. = 6

• n n 1 ˜2 Classroom Exercise 5.2: Use mathematical induction to prove that R 13 23 33 ... n3 ( + ) , n = + + + + = 2 n 1. ≥ 5.3. Euler Phi Function

When we studied the affine cipher (1.21), we had to choose the multiplicative key m so that it is relatively prime to 26, and the size of the keyspace depended on how many positive integers less than 26 are relatively 1 prime to 26.. We now want to consider this issue in general. If n N, then the Euler phi function, denoted ∈ φ(n), is the number of positive integers less than or equal to n that are relatively prime to n.

1Some authors call it the totient function. 70 5. MODULAR EXPONENTIATION

Example 5.4: φ(26) = 12 since there are 12 positive integers (in black) that are relatively prime to 26.

1,2/, 3,4/, 5,6/, 7,8/, 9, ///10, 11, ///12, ///13, ///14, 15, ///16, 17, ///18, 19, ///20, 21, ///22, 23, ///24, 25, ///26

Example 5.5: φ(11) = 10 since all of the integers from 1 to 10 are relatively prime to 11.

The last example suggests a rule; if p is prime, then φ(p) = p 1. This saves us a lot of work if p is − large. For instance, to find φ(103), we certainly don’t want to list all of the integers from 1 to 102 and see which ones are relatively prime to 103. It’s much easier to just compute φ(103) = 103 1 = 102. Let’s see if we can identify similar shortcuts for other integers. Let’s continue by considering φ−pn, where p is prime and n is a positive integer.

4 4 3 Example 5.6: φ(16) = φ 2 = 8. We start out with 16 = 2 integers and cross out all 8 = 2 multiples of 2. 1,2/, 3,4/, 5,6/, 7,8/, 9, ///10, 11, ///12, 13, ///14, 15, ///16

3 3 2 Example 5.7: φ(27) = φ 3 = 18. We start out with 27 = 3 integers and cross out all 9 = 3 multiples of 3. 1, 2,3/, 4, 5,6/, 7, 8,9/, 10, 11, ///12, 13, 14, ///15, 16, 17, ///18, 19, 20, ///21, 22, 23, ///24, 25, 26, ///27

Examples 5.6 and 5.7 suggest that to compute φ pn, we simply have to write out all of the integers n n 1 n n n 1 from 1 to p and then cross off all p − multiples of p. Therefore, φ p = p p − . Now let’s figure out − how to compute φ(pq) where p and q are both prime.

Example 5.8: To find φ(21) = φ(3 7), we take the integers from 1 to 21 and cross out all 7 multiples of · 3, 3, 6, 9, 12, 15, 18, 21 , and all 3 multiples of 7, 7, 14, 21 . So φ(21) = 21 7 3 + 1 = 12, adding 1 so that{ we don’t double-count} 21. { } − −

This argument generalizes nicely. There are a total of pq integers from 1 to pq and we cross out the p multiples of q and the q multiples of p, remembering that by doing so we are double-counting pq. Therefore,

φ(pq) = pq p q + 1 = (p 1)(q 1) = φ(p)φ(q). − − − − This is a beautiful rule and it would be nice if it held in general for products, but it doesn’t. However, if m and n are relatively prime, then φ(mn) = φ(m)φ(n). To see why this is true, let’s start with an example.

Example 5.9: To find φ(70) = φ(7 10), we note that gcd(7, 10) = 1 and we write out the integers from 1 to 70 in a table on a width of 10. ·

1 //23 //4 //5 //6 //7 //89 ///10 11 ///12 13 ///14 ///15 ///16 17 ///18 19 ///20 ///21 ///22 23 ///24 ///25 ///26 27 ///28 29 ///30 (5.3) 31 ///32 33 ///34 ///35 ///36 37 ///38 39 ///40 41 ///42 43 ///44 ///45 ///46 47 ///48 ///49 ///50 51 ///52 53 ///54 ///55 ///56 57 ///58 59 ///60 61 ///62 ///63 ///64 ///65 ///66 67 ///68 69 ///70 5.3. EULER PHI FUNCTION 71

In the first row of the table, there are φ(10) integers that are relatively prime to 10 ( 1, 3, 7, 9 ). Also, note that all of the numbers in each column are congruent to the first number modulo{ 10. For example,} in the first column, 1, 11, 21, 31, 41, 51, 61 1 mod 10. So, if we cross out the first number in a column because it is not relatively prime to 10, then≡ we must cross out all of the numbers in that column. Now we just have to figure out what to cross out in the surviving columns (corresponding to 1, 3, 7, and 9).2 Recall (from Theorem 1.3) that if gcd(m, n) = 1, then the integers a, a + n, a + 2n,..., a + (m 1)n are congruent modulo m to 0, 1, 2, . . . , m 1 in some order. Observe that{ reducing the entries in the− table} in (5.3) modulo 7 gives { − }

1 //23 //4 //5 //6 //0 //12 //3 4 //56 //0 //1 //23 //45 //6 //0 //12 //3 //4 //56 //01 //2 (5.4) 3 //45 //6 //0 //12 //34 //5 6 //01 //2 //3 //45 //6 //0 //1 2 //34 //5 //6 //01 //23 //4 5 //6 //0 //1 //2 //34 //56 //0

and the numbers in each column are congruent to 0, 1, 2, 3, 4, 5, 6 in some order. Therefore, in each of the { } surviving columns, there are φ(7) integers that are relatively prime to 7 and

φ(70) = φ(10 7) · = (# nonempty columns)(# elements per nonempty column) = 4 6 · = φ(10)φ(7).

We worked this example on a width of 10, but we could equally well could have used a width of 7. In this case, only one entire column is crossed out because 7 is prime.

1 //23 //4 //5 //6 //7 //89 ///10 11 ///12 13 ///14 ///15 ///16 17 ///18 19 ///20 ///21 ///22 23 ///24 ///25 ///26 27 ///28 29 30 31 32 33 34 35 (5.5) /// /// /// /// ///36 37 ///38 39 ///40 41 ///42 43 ///44 ///45 ///46 47 ///48 ///49 ///50 51 ///52 53 ///54 ///55 ///56 57 ///58 59 ///60 61 ///62 ///63 ///64 ///65 ///66 67 ///68 69 ///70

Reducing the table in (5.5) modulo 10 gives

2 You can follow along yourself with Phi.nb on users.etown.edu/m/mcdevittt/Crypto.html. 72 5. MODULAR EXPONENTIATION

1 //23 //4 //5 //6 //7 //89 //01 //23 //4 //5 //67 //89 //0 //1 //23 //4 //5 //67 //8 9 //01 //23 //4 //5 //67 //89 //01 //2 3 //4 //5 //67 //8 //9 //01 //23 //4 //5 //6 7 //89 //01 //2 //3 //4 //5 //67 //89 //0 in which each column contains the integers from 0 to 9 in some order. Therefore,

φ(70) = φ(10 7) · = (# nonempty columns)(# elements per nonempty column) = 6 4 · = φ(7)φ(10).

We can follow the previous example to justify the result in general. If gcd(m, n) = 1 and we write the integers from 1 to mn in a table of width n, then there are φ(n) columns with numbers relatively prime to n. If the first number in a given column is a, then the entries in that column are a, a+n, a+2n,..., a+(m 1)n , { − } but this set is congruent modulo m to 0, 1, 2, . . . , m 1 in some order, so there are φ(m) entries in each { − } column that are relatively prime to m. Therefore, φ(mn) = φ(m)φ(n). This makes it relatively easy to find φ for any positive integer by applying our rules to its prime factorization:

k1 k2 k3 kr THEOREM 5.1. If a positive integer n has prime factorization n = p1 p2 p3 ...pr , then € Š € Š k1 k1 1 k2 k2 1 kr kr 1 φ (n) = p1 p1 − p2 p2 − ... pr p − . − − −

Example 5.10:

3 2  3 2 3 2 2 1 1 0 φ(504) = φ 2 3 7 = φ 2 φ 3 φ (7) = 2 2 3 3 7 7 = (4)(6)(6) = 144. · · − − − Classroom Exercise 5.3: Use Theorem 5.1 to compute the following.

(1) φ(6) (2) φ(19) (3) φ(256) (4) φ(70) (5) φ(120)

5.4. Fermat’s Little Theorem

Binomial Theorem. The binomial theorem may be familiar to you, but we want to refresh your memory 2 because it is important to our proof of Fermat’s little theorem. If we want to expand (x + y) , we can just 2 2 3 2 2 use FOIL to obtain x + 2x y + y . To expand (x + y) , we can multiply x + 2x y + y by (x + y) to find 3 2 2 3 x + 3x y + 3x y + y , and we can do likewise for higher powers of (x + y). 5.4. FERMAT’S LITTLE THEOREM 73

0 (x + y) = 1 1 (x + y) = x + y 2 2 2 (x + y) = x + 2x y + y 3 3 2 2 3 (x + y) = x + 3x y + 3x y + y 4 4 3 2 2 3 4 (x + y) = x + 4x y + 6x y + 4x y + y 5 5 4 3 2 2 3 4 5 (x + y) = x + 5x y + 10x y + 10x y + 5x y + y 6 6 5 4 2 3 3 2 4 5 6 (x + y) = x + 6x y + 15x y + 20x y + 15x y + 6x y + y 7 7 6 5 2 4 3 3 4 2 5 6 7 (x + y) = x + 7x y + 21x y + 35x y + 35x y + 21x y + 7x y + y 8 8 7 6 2 5 3 4 4 3 5 2 6 7 8 (x + y) = x + 8x y + 28x y + 56x y + 70x y + 56x y + 28x y + 8x y + y . . . .

In the row corresponding to power n, notice that the powers of x decrease from n to 0 going from left to right while the powers of y increase from 0 to n, and the coefficients match Pascal’s triangle.

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 ......

We can also write Pascal’s triangle in terms of the binomial coefficients that we used for counting in Chapter 2.

0 0 1 1 0 1 2 2 2 0 1 2 3 3 3 3 0 1 2 3 4 4 4 4 4 0 1 2 3 4 5 5 5 5 5 5 0 1 2 3 4 5 6 6 6 6 6 6 6 0 1 2 3 4 5 6 7 7 7 7 7 7 7 7 0 1 2 3 4 5 6 7 8 8 8 8 8 8 8 8 8 0 1 2 3 4 5 6 7 8 ......

All of this is summarized in the binomial theorem.

THEOREM 5.2 (Binomial Theorem). If n is a positive integer, then n X n‹ n‹ n! x y n x n k y k, where . ( + ) = k − k = k! n k ! k 0 ( ) = − n Now, let’s consider (x + y) reduced modulo n. 74 5. MODULAR EXPONENTIATION

2 2 2 (x + y) mod 2 x + y 3 3 3 (x + y) mod 3 ≡ x + y 4 4 2 2 4 (x + y) mod 4 ≡ x + 2x y + y 5 5 5 (x + y) mod 5 ≡ x + y 6 6 4 2 3 3 2 4 6 (x + y) mod 6 ≡ x + 3x y + 2x y + 3x y + y 7 7 7 (x + y) mod 7 ≡ x + y 8 8 6 2 4 4 2 6 8 (x + y) mod 8 ≡ x + 4x y + 6x y + 4x y + y 9 9 3 6 6 3 9 (x + y) mod 9 ≡ x + 3y x + 3y x + y 10 10 2 8 5 5 8 2 10 (x + y) mod 10≡ x + 5y x + 2y x + 5y x + y 11 11 11 (x + y) mod 11 ≡ x + y . ≡ . . . Many of the binomial coefficients seem to vanish, but the cases with prime powers are especially interesting because only the first and last terms survive modular reduction. Why does this happen? If p is prime and 0 < k < p, then p‹ p! = k k!(p k)! − p(p 1)(p 2) ... (p k + 1) = − − − k(k 1)(k 2) ... (3)(2)(1)  − −  (p 1)(p 2) ... (p k + 1) = p − − − k(k 1)(k 2) ... (3)(2)(1) − − p‹ is an integer that is divisible by p since p can’t have any divisors between 1 and p. Therefore, 0 k  ‹  ‹ ≡ p p p n n mod p for 0 < k < p. Since = = 1, we have (x + y) x + y mod p. Now we can prove 0 p ≡ Fermat’s little theorem (FLT).

p THEOREM 5.3 (Fermat’s Little Theorem). If n is a positive integer and p is prime, then n n mod p. ≡

PROOF. We prove Fermat’s little theorem by induction on n. Clearly, 1p 1 mod p. ≡ Assume kp k mod p for some specific k 1. ≡ p ≥ X p‹ Then k 1 p k j1p j ( + ) = j − j=0 p 1 p‹ X p‹ p‹ − k j kp = 0 + j + p j=1 p 1 + k mod p ≡ k + 1 mod p. ≡ 

p 1 p 2 1 In addition, note that n − 1 mod p and n − n− mod p, so Fermat’s little theorem gives a second way of computing multiplicative≡ inverses for prime moduli,≡ but we still prefer to use the extended Euclidean algorithm in most circumstances because it is more efficient and it doesn’t require a prime modulus. 5.5. EULER’S THEOREM 75

Example 5.11: Let’s note some of the features in the following table of exponents. The top row is all zeros because zero raised to any positive power is zero, and the first column is all ones because any nonzero integer raised to the zeroth power is one. However, neither rule applies in the case of 00, which we leave undefined.3 Also, as we expect from FLT, y10 1 mod 11 and y11 y mod 11 for 0 < y < 11. The ≡ x x ≡ 5 last row alternates between 1 and 10 because (10) ( 1) 1 1, 10 mod 11. Likewise, y 1 52 10 ≡ − ≡ ± ≡ 4 ≡ ± mod 11, 0 < y < 11, because y = y = 1 by FLT and the only modular square roots of 1 mod 11 are 1. Otherwise, exponentiation seems to jumble integers pretty well. ± x 0 1 2 3 4 5 6 7 8 9 10 11 0x ?00000000000 1x 1 1 1 1 1 1 1 1 1 111 2x 1 2 4 8 5 10 9 7 3 612 3x 1 3 9 5 4 1 3 9 5 413 x (5.6) 4 1 4 5 9 3 1 4 5 9 314 5x 1 5 3 4 9 1 5 3 4 915 6x 1 6 3 7 9 10 5 8 4 216 7x 1 7 5 2 3 10 4 6 9 817 8x 1 8 9 6 4 10 3 2 5 718 9x 1 9 4 3 5 1 9 4 3 519 10x 1 10 1 10 1 10 1 10 1 101 10 In modular arithmetic, we know how to find additive inverses via negation and multiplicative inverses via the extended Euclidean algorithm or Fermat’s little theorem. However, we don’t have a simple algorithm for inverting exponents. For example, consider a problem like

(5.7) 4x 9 mod 11. ≡ In real arithmetic, we would say that x = log4 9, so problems like (5.7) are referred to as discrete log problems. The problem in (5.7) is easy (x = 3) because we can just look for the answer in the table in (5.6), but in general we can’t do that when the numbers are large, so the discrete log problem is a notoriously difficult problem.

5.5. Euler’s Theorem

φ n Let’s figure out how to compute m ( ) mod n. If n is prime, then φ(n) = n 1 and we can appeal to Fermat’s little theorem to conclude that mφ(n) 1 mod n, but what if n is not prime?− Let’s start by looking at an example. ≡

Example 5.12: We could use the square-and-multiply algorithm to compute 16φ(9) mod 9, but we want to make an important observation instead. Let S = 1, 2, 4, 5, 7, 8 be the set of positive integers less than { } 9 that are relatively prime to 9. There, are, of course, φ(9) = 6 integers in S. Since 16 is relatively prime to 9, multiplying every element in S by 16 gives the same numbers back, just in a different order: T = 7, 5, 1, 8, 4, 2 . Multiplying the elements in S and T gives the same product: { } φ 9 (16 1)(16 2)(16 4)(16 5)(16 7)(16 8) = 16 ( )(1)(2)(4)(5)(7)(8) (7)(5)(1)(8)(4)(2) mod 9. · · · · · · ≡ Therefore, 169 1 mod 9. ≡ 3If you’ve had some calculus, you may recognize 00 as an indeterminate form for limits. 4See Wikipedia for more information. 76 5. MODULAR EXPONENTIATION

THEOREM 5.4 (Euler’s Theorem). If m and n are positive integers such that gcd(m, n) = 1, then mφ(n) 1 mod n. ≡

PROOF. The proof generalizes the previous example. Euler’s theorem is obvious if n = 1, so let’s assume

that n > 1. Let S = a1, a2,..., aφ(n) be the set of positive integers less than n that are relatively prime to n { } and let T = ma1, ma2,..., maφ(n) . Since gcd(m, n) = 1, S and T are the same except for a rearrangement of order. Therefore,{ the products of} the entries in S and T are the same:

   φ(n) a1a2 ... aφ(n) ma1 ma2 ... maφ(n) = m a1a2 ... aφ(n) mod n. ≡ φ(n) Since all of the ai are relatively prime to n, they are invertible and m 1 mod n.  ≡ Example 5.13: Euler’s theorem can help us to reduce large powers relatively easily. Since gcd(7, 10) = 1 and φ(10) = 4, 222 455 2 55 2 7 = 7 7 1 7 mod 10 = 49 9 mod 10. · ≡ · ≡ Classroom Exercise 5.4: Reduce each of the following powers. (1)9 505 mod 10 (2)8 122 mod 17 (3) 12100 mod 24

5.6. Diffie-Hellman Key Exchange

The additive, affine, Vigenère , and Hill ciphers are all examples of private key, or symmetric, ciphers because they require the communicating parties to share a common key that they keep secret from everyone else. However, it is possible that two parties who have never met might want to exchange secret information. For example, a customer may want to send a credit card number to an internet vendor to make a purchase online. Public key make it possible for two parties to communicate securely without having previously agreed upon a private key. We will discuss two public key systems, the Diffie-Hellman key ex- change and the RSA . The Diffie-Hellman method enables two parties to publicly compute a shared private key, and then they can use that key in a symmetric cipher. RSA can be used for key exchange, but it can also be used encrypt information and to digitally sign electronic documents.5 As we often do, let’s begin with a generalizable example to illustrate the Diffie-Hellman key exchange.

Example 5.14: The protagonists in our story are Alice and Bob, who want to generate a shared private key in front of the prying eyes of evil Eve.6 First they publicly agree on a large prime number p and an integer q 7 such that 1 < q < p. For the sake of illustration, let p = 23 and q = 5, but keep in mind that these are tiny numbers and in real life they would have to be much larger. Alice and Bob each privately choose a positive integer less than p that each serve as their respective private keys. For example, suppose that Alice chooses a = 9 and Bob chooses b = 20. Alice computes a 9 A = q mod p = 5 mod 23 11 mod 23 ≡ 5You can do more than just key exchange with Diffie-Hellman, but that’s what we’ll focus on. 6Just about everybody uses Alice, Bob, and Eve. 7A more advanced text would put an extra requirement on q, but we avoid that for simplicity. For more details, see p. 171 of [2]. 5.6. DIFFIE-HELLMAN KEY EXCHANGE 77

and sends it publicly to Bob. Similarly, Bob computes

b 20 B = q mod p = 5 mod 23 12 mod 23 ≡ and sends it to Alice. When Alice receives B, she computes

a 9 K = B mod p = 12 mod 23 4 mod 23. ≡ Likewise, Bob also computes K, but in a different way:

b 20 K = A mod p = 11 mod 23 4 mod 23. ≡ If Eve intercepts A, B, p, and q, then she can, in principle, solve for a and b by solving

a b A = q mod p or B = q mod p, but this is the discrete log problem that we know is very hard to solve if p is large. Recall that this only establishes a key; it does not encrypt a message. To send a message, suppose that Alice converts the Delphic wisdom KNOW THYSELF into numbers using the ASCII code (Table 3.1) and en- 8 crypts the message with a Vigenère cipher using K = 4 as the key. The alphabet is 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 , so the addition is done modulo 10. { } Plaintext: 757879873284728983697670 Key: 444444444444444444444444 Ciphertext: 191213217628162327031014 Alice then transmits 191213217628162327031014 to Bob, and he reverses the steps to recover the original message.

Example 5.15: Let’s repeat the previous example with slightly bigger numbers. Let p = 156696463087 and q = 94477582661. For real applications, p is still a small prime, but it is large enough to overwhelm many hand-held calculators. Now Alice chooses a = 63102091160 and Bob chooses b = 23629131076. Alice computes

a 63102091160 A = q mod p = 94477582661 mod 156696463087 = 908653225 and Bob computes

b 23629131076 B = q mod p = 94477582661 mod 156696463087 = 1340136561. Alice sends A to Bob, Bob sends B to Alice, and they both compute

b 23629131076 K = A mod p = 908653225 mod 156696463087 = 67301429533 a 63102091160 K = B mod p = 1340136561 mod 156696463087 = 67301429533, which can be used as the key for a symmetric encryption method like the Vigenère or Hill cipher. For example, the digits in K might be partitioned into pairs, reduced modulo 26, and converted to letters

06, 73, 01, 42, 95, 33 mod 26 6, 21, 1, 16, 17, 7 mod 26 GVBQRH { } ≡ { } ∼ to produce a keyword for the Vigenère cipher. The message KNOW THYSELF is then encrypted as QIPMKOEN FBW.

8In this case, because the key is a single digit, the Vigenère cipher actually reduces to an additive cipher. 78 5. MODULAR EXPONENTIATION

5.7. RSA Encryption

The name RSA is a concatenation of the first initials of the last names of its inventors, Ron Rivest, Adi Shamir, and Leonard Adleman. RSA can, like the Diffie-Hellman method, be used to establish a secret key publicly, but it can also be used to encrypt information and to digitally sign electronic documents. It all hinges on Euler’s theorem and the existence of a trusted authority, like a key center, to assign public and private keys to all parties.9 For every individual, the key center selects two large prime numbers p and q and computes φ(pq) = (p 1)(q 1). Note that this is easy for the key center to do since it knows both p and q. They then select − − 1 an integer e > 1 that is relatively prime to φ(pq) and compute its multiplicative inverse e− mod φ(pq). 1 Finally, the key center issues each individual the public keys e and pq and the private key e− mod φ(pq). Note that even though the product pq is public, p and q are not known - even privately - because it is prohibitively difficult to factor sufficiently large numbers. In essence, the security of this method relies on the difficulty of factoring the product pq. If Bob wants to send Alice an integer message m < pq, he uses her public keys to compute

e c = m mod pq, which he sends to her publicly. When Alice receives c, she computes

e 1 e e 1 c − mod pq (m ) − mod pq ≡ ee 1 m − mod pq ≡ m1+kφ(pq) mod pq for some integer k ≡ k m mφ(pq) mod pq ≡ · k m(1) mod pq (by Euler’s Theorem 5.4) ≡ m. ≡ 1 Only Alice (and the key center) can decrypt the message since she is the only one who knows e− . If Eve intercepts the message, she can only read it if she can solve me c mod pq for m. That is, Eve has to find the eth root of c modulo pq. ≡

Example 5.16: Alice publishes her public keys e = 7 and pq = 77 for all to see. To send the message e 7 m = 25 < pq to Alice, Bob computes c = m mod pq = 25 mod 77 53 mod 77 and sends it to Alice. 1 ≡ Alice uses her private key, e− = 43 to compute e 1 43 c − mod pq = 53 mod 77 25 mod 77 ≡ = m.

If Eve intercepts c = 53, she can decipher it only if she can compute 7 m mod 77 = 53.

Example 5.17: Alice publishes her public keys pq = 4469730945520926997399 and e = 4073619424605 1 228097289, but she reserves her private key e− = 2559385183601091556777. Bob sends message m =

9 See http://www.idmanagement.gov/federal-public-key-infrastructure/. EXERCISES 79

12345678901234567890 to Alice by computing and transmitting the cipher

e c = m mod pq 4073619424605228097289 = 12345678901234567890 mod 4469730945520926997399 3469293885116137999704 mod 4469730945520926997399. ≡ Alice decrypts the cipher c by computing

e 1 2559385183601091556777 c − mod pq = 3469293885116137999704 mod 4469730945520926997399 = 12345678901234567890 mod 4469730945520926997399.

The message m could be a private number like a credit card number that one party wishes to send to another, or m could be an encoded message or part of a message. For example, the ASCII equivalent of Test on Friday is

84 101 115 116 32 111 110 32 70 114 105 100 97 121 46, so perhaps m = 084101115116032111110032070114105100097121046. Encrypting data using RSA is relatively slow, so if Alice and Bob want to exchange a lot of data (a lot of m’s), then it might be wise to use a single m as a shared key for use with a symmetric cipher. Finally, RSA can also be used to generate digital signatures. If Bob sends a message to Alice, how does Alice know that Bob really sent it? It could be a forgery after all. One thing Bob can do is encrypt his “signature” with his own private key, and when Alice receives his message, she can decrypt it using Bob’s public key.

Example 5.18: Bob sends a surprising message to Alice: Alice, I've decided to major in math. It's the coolest! Bob (125010690)

Bob knows that Alice won’t believe that he actually sent the message, so he digitally signed it by enciphering his name (in ASCII) using his own private key. Alice finds that Bob’s public keys are e = 1234567891 and pq = 176391331, and she computes e 1234567891 125010690 mod pq = 125010690 mod 176391331 66111098 mod 176391331. ≡

Since the decrypted (66 111 098) has an ASCII equivalent of Bob, Alice is sure that Bob actually sent the message. Congratulations Bob on a wise choice!

Exercises

(1) Use mathematical induction to prove each of the following claims. n n n (a) (ab) = a b , n 0 ≥ 1 rn+1 (b)1 r r2 ... rn , n 0 + + + + = 1− r n ≥ (c)8 (9 1), n 0 − 1| 1− 1 ≥ 1 n (d) + + + ... + = , n 1 2 6 12 n(n + 1) n + 1 ≥ (e) All successive numbers in the Fibonacci sequence are relatively prime to each other. Recall

that f0 = 0, f1 = 1, and fn = fn 1 + fn 2, n 2. − − ≥ 80 5. MODULAR EXPONENTIATION

th (f)3 f4n, where fn is the n Fibonacci number. |  (g) The Fibonacci numbers f0 = 0, f1 = 1, fn = fn 1 + fn 2 satisfy the following: 2 − − f2n = 2fn 1 fn + fn , n 1 • −2 2 ≥ f2n 1 = fn 1 + fn , n > 1. (2) Compute• the following.− − (a) φ(251) (b) φ(421) (c) φ(413) (d) φ(452) (e) φ(280) (f) φ(396) (g) φ(243) (h) φ(297) (i) φ(191) (j) φ(1384) (k) φ 372 (l) φ 5003 (3) Show if n > 2 then φ(n) is even. (4) Use the square-and-multiply algorithm and/or Euler’s theorem (5.4) to reduce each of the follow- ing modulo 20. (a)4 17 (b) 1334 (c) 159 (d)7 298 (e) 1412 (f)7 26 (g) 1912 (h)2 26 (5) The so-called Russian Peasant (or Ancient Egyptian) method for multiplying integers is similar to the square-and-multiply algorithm for exponents. We an example here, but you might want to consult Wikipedia for more details. To multiply 52 27, you make two columns, each headed by one of the two multiplicands. In the first column,× we successively halve the numbers, rounding down as necessary, and in the second column, we successively double the numbers. Halve Double 52 27 26 54 13 108 6 216 3 432 1 864 1404 Adding the numbers in the second column that are next to odd numbers in the first column gives us the product, 52 27 = 1404. Compute the following products using the Russian Peasant algorithm. (a) 23 34 × × EXERCISES 81

(b) 101 33 (c) 342 × 256 (d) 54 ×39 mod 60 (e) 78 × 89 mod 100 (f) 123× 543 mod 800 (6) You are making× an online purchase from Alice’s Restaurant. (a) You (Bob) and Alice agree to use the Diffie-Hellman method with p = 2309 and q = 200 to exchange a key. She sends you A = 295 and you choose b = 544. Find the common key K. (b) Use K as key for the Vigenère cipher to encrypt your Mathtercard number as illustrated in Example 5.14.

(7) Veronica Costello’s RSA public keys are pq = 16571 and e = 12667. (a) Veronica Costello is getting an A in math, so she wrote a special letter to Santa asking for a very special gift. Santa would like to bring VC what she asked for, but he received two different letters from her asking for two different things. Santa knows that Veronica’s computer-savvy little brother is often naughty, so he suspects that one of the letters is a forgery. Help Santa figure out which album Veronica really wants by checking both digital signatures.

Dear Santa, Please bring me “Backstreet Boys Go Live!” by the Backstreet Boys. I’ve been very good and I haven’t even missed class more than 10 times. Veronica (10528)

Dear Santa, Please bring me “Teletubbies Gone Wild” by the Teletubbies. I’ve been very good and I haven’t even missed class more than 10 times. Veronica (3108) (b) Veronica receives the message 12256 9486 6841 2524 14725 9462 2238 2982 649 that 1 was encrypted with her RSA public keys. Use her private key, e− = 6739, and the ASCII code (Table 3.1) to decrypt and read the message.

Bibliography

[1] Robert Churchhouse. Codes and Ciphers. Cambridge University Press, 2002. [2] Paul Garrett. Making, Breaking Codes. Prentice Hall, 2001. [3] David Kahn. The Codebreakers: The Comprehensive History of Secret Communication from Ancient Times to the Internet. Scribner, 1996. [4] Robert E. Lewand. Cryptological Mathematics. The Mathematical Association of America, 2000. [5] Tim McDevitt and Tom Leap. Multimedia cryptology. Cryptologia, 33(2):142–150, 2009. [6] Ivan Niven and H. S. Zuckerman. An Introduction to the Theory of Numbers. John Wiley & Sons, fourth edition, 1980. [7] Jeffrey Overbey, William Traves, and Jerzy Wojdylo. On the keyspace of the hill cipher. Cryptologia, 30(1):59–72, 2005. [8] Kenneth H. Rosen. Elementary Number Theory. Addison-Wesley, 2000. [9] Claude Shannon. Communication theory of secrecy systems. Bell System Technical Journal, 28(4):656U715,˝ 1949. [10] Singh. The Code Book: The Secret History of Codes and Code-breaking. Fourth Estate, 2000. [11] Abraham Sinkov. Elementary Cryptanalysis. Random House, 1968. [12] Suetonius. De Vita Caesarum: Divus Julius LVI. [13] Wade Trappe and Lawrence C. Washington. Introduction to Cryptography with Coding Theory. Pearson Prentice-Hall, second edition, 2006.

83