The Laws of Cryptography with Java Codewagner/prospectus/laws_temp.pdf · Foreword There are...

25
The Laws of Cryptography with Java Code by Neal R. Wagner

Transcript of The Laws of Cryptography with Java Codewagner/prospectus/laws_temp.pdf · Foreword There are...

The Laws ofCryptograph y

with Java Code

by Neal R. Wagner

Copyright c�

2002by NealR. Wagner. All rights reserved.

Table of ContentsParts and Chapter s

Foreword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi

Intr oduction . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

I. Preliminaries . . . . . . . . . . . . . . . . . . . . . 2

1. Cryptographers’ Favorites . . . . . . . . . . . . . . . . . . 32. Cryptographers’ Favorite Algorithms . . . . . . . . . . . . 12

II. Coding and Inf ormation Theory . . . . . . . . . . . . 20

3. Coding and Inf ormation Theory . . . . . . . . . . . . . . 214. Visualizing ChannelCapacity . . . . . . . . . . . . . . . 295. The Huffman Codefor Compression . . . . . . . . . . . . 336. The Hamming Codefor Err or Correction . . . . . . . . . . 417. Coping with DecimalNumbers . . . . . . . . . . . . . . . 458. Verhoeff’s DecimalErr or Detection . . . . . . . . . . . . . 51

III. Intr oduction to Cryptography . . . . . . . . . . . . . 56

9. Cryptograms and Terminology . . . . . . . . . . . . . . . 5710. The One-Time Pad . . . . . . . . . . . . . . . . . . . . 6211. Conventional Block Cipher Cryptosystems . . . . . . . . . . 66??. ConventionalStreamCipherCryptosystems

IV. Public KeyCryptography . . . . . . . . . . . . . . . 74

12. Public KeyDistrib ution Systems . . . . . . . . . . . . . . 7513. Public KeyCryptography: Knapsacks . . . . . . . . . . . . 7814. The RSA Public KeyCryptosystem . . . . . . . . . . . . . 8215. Rabin’sVersionof RSA . . . . . . . . . . . . . . . . . . 89??. Elliptic CurveCryptosystems??. OtherPublicKey Cryptosystems

V. RandomNumber Generation . . . . . . . . . . . . . 94

16. Traditional RandomNumber Generators . . . . . . . . . . 9517. RandomNumbersFrom ChaosTheory . . . . . . . . . . . 10018. Statistical Testsand Perfect Generators . . . . . . . . . . . 106

VI. The AdvancedEncryption Standard (AES) . . . . . . . . 108

iv The Laws of Cryptograph y

19. Intr oduction to the AES . . . . . . . . . . . . . . . . . . 10920. The Finite Field GF(256) . . . . . . . . . . . . . . . . . 11321. The S-Boxes . . . . . . . . . . . . . . . . . . . . . . . 12122. KeyExpansion . . . . . . . . . . . . . . . . . . . . . . 12423. Encryption . . . . . . . . . . . . . . . . . . . . . . . 12724. Decryption . . . . . . . . . . . . . . . . . . . . . . . 130

VII. HashFunctionsandDigital Signatures

??. One-Way FunctionsandHashFunctions??. Digital Signatures

VIII. RandomizationTechniques

??. SimpleRandomization??. MoreComplex Tricks??. TheRip vanWinkle CipherandRabin’sScheme

IX. Identification and KeyDistrib ution . . . . . . . . . . . 134

25. Passwords . . . . . . . . . . . . . . . . . . . . . . . . 13526. Zero-KnowledgeProtocols . . . . . . . . . . . . . . . . . 13627. Identification Schemes . . . . . . . . . . . . . . . . . . 14228. ThresholdSchemes . . . . . . . . . . . . . . . . . . . . 143??. CaseStudy:theSecureShell(ssh)

Java Programs . . . . . . . . . . . . . . . . . . . . . . 149

Appendices . . . . . . . . . . . . . . . . . . . . . . . 283

A. UsingPrinted Log Tables . . . . . . . . . . . . . . . . . . . 285B. Unsignedbytesin Java . . . . . . . . . . . . . . . . . . . . 286

Table of ContentsLaws

I. Preliminaries

1. Cryptographers’FavoritesLaw XOR-1 . . . . . . . . . . . . . . . . . . . . . . . 3Law LOG-1 . . . . . . . . . . . . . . . . . . . . . . . 4Law LOG-2 . . . . . . . . . . . . . . . . . . . . . . . 6Law GROUP-1 . . . . . . . . . . . . . . . . . . . . . 7Law FIELD-1 . . . . . . . . . . . . . . . . . . . . . . 8Law FIELD-2 . . . . . . . . . . . . . . . . . . . . . . 9Law FERMAT-1 . . . . . . . . . . . . . . . . . . . . . 9

2. Cryptographers’FavoriteAlgorithmsLaw GCD-1 . . . . . . . . . . . . . . . . . . . . . . . 12Law EXP-1 . . . . . . . . . . . . . . . . . . . . . . . 15Law PRIME-1 . . . . . . . . . . . . . . . . . . . . . 17Law PRIME-2 . . . . . . . . . . . . . . . . . . . . . 18

II. CodingandInformationTheory

3. CodingandInformationTheoryLaw ENTROPY-1 . . . . . . . . . . . . . . . . . . . . 21Law ENTROPY-2 . . . . . . . . . . . . . . . . . . . . 22Law INFORMA TION-1 . . . . . . . . . . . . . . . . . 23Law SHANNON-1 . . . . . . . . . . . . . . . . . . . . 27

4. VisualizingChannelCapacity5. TheHuffmanCodefor Compression

Law SHANNON-2 . . . . . . . . . . . . . . . . . . . . 33Law COMPRESSION-1 . . . . . . . . . . . . . . . . . 33

6. TheHammingCodefor ErrorCorrectionLaw HAMMING-1 . . . . . . . . . . . . . . . . . . . 43

7. Copingwith DecimalNumbersLaw DECIMAL-1 . . . . . . . . . . . . . . . . . . . . 45Law DECIMAL-2 . . . . . . . . . . . . . . . . . . . . 50

8. Verhoeff ’sDecimalErrorDetectionLaw DECIMAL-3 . . . . . . . . . . . . . . . . . . . . 53

III. Introductionto Cryptography

9. CryptogramsandTerminology

vi The Laws of Cryptograph y

Law CRYPTOGRAPHY-1a . . . . . . . . . . . . . . . . 58Law CRYPTOGRAPHY-1b . . . . . . . . . . . . . . . . 58Law CRYPTOGRAPHY-2 . . . . . . . . . . . . . . . . 59Law CRYPTANALYSIS-1 . . . . . . . . . . . . . . . . . 60Law CRYPTANALYSIS-2 . . . . . . . . . . . . . . . . . 60Law CRYPTANALYSIS-3 . . . . . . . . . . . . . . . . . 61Law CRYPTANALYSIS-4 . . . . . . . . . . . . . . . . . 61

10. TheOne-TimePadLaw PAD-1 . . . . . . . . . . . . . . . . . . . . . . . 65

11. ConventionalBlock CipherCryptosystemsLaw BLOCKCIPHER-1 . . . . . . . . . . . . . . . . . 69

??. ConventionalStreamCipherCryptosystems

IV. PublicKey Cryptography

12. PublicKey DistributionSystems13. PublicKey Cryptography:Knapsacks14. TheRSAPublicKey Cryptosystem

Law RSA-1 . . . . . . . . . . . . . . . . . . . . . . . 82Law RSA-2 . . . . . . . . . . . . . . . . . . . . . . . 87

15. Rabin’sVersionof RSALaw RABIN-1 . . . . . . . . . . . . . . . . . . . . . . 89

??. Elliptic CurveCryptosystems??. OtherPublicKey Cryptosystems

V. RandomNumberGeneration

16. TraditionalRandomNumberGeneratorsLaw RNG-1 . . . . . . . . . . . . . . . . . . . . . . . 95Law RNG-2 . . . . . . . . . . . . . . . . . . . . . . . 95Law RNG-3 . . . . . . . . . . . . . . . . . . . . . . . 96

17. RandomNumbersFromChaosTheory18. StatisticalTestsandPerfectGenerators

VI. TheAdvancedEncryptionStandard(AES)

19. Introductionto theAESLaw AES-1 . . . . . . . . . . . . . . . . . . . . . . 109

20. TheFiniteFieldGF(256)21. TheS-Boxes22. Key Expansion23. Encryption24. Decryption

VII. HashFunctionsandDigital Signatures

Table of Contents: Laws vii

??. One-Way FunctionsandHashFunctions??. Digital Signatures

VIII. RandomizationTechniques

??. SimpleRandomization??. MoreComplex Tricks??. TheRip vanWinkle CipherandRabin’sScheme

IX. IdentificationandKey Distribution

25. Passwords26. Zero-KnowledgeProtocols27. IdentificationSchemes28. ThresholdSchemes

Law THRESHOLD-1 . . . . . . . . . . . . . . . . . 147??. CaseStudy:theSecureShell(ssh)

JavaPrograms

Appendices

A. UsingPrintedLog TablesB. Unsignedbytesin Java

Law JAVA-BYTES-1 . . . . . . . . . . . . . . . . 287Law JAVA-BYTES-2 . . . . . . . . . . . . . . . . 288

Table of ContentsJava Programs

I. Preliminaries

1. Cryptographers’Favorites

a. Demonstrationof Xor . . . . . . . . . . . . . . . 4 151b. Formulas for logs . . . . . . . . . . . . . . . . 5 152c. Fermat’sTheorem Illustrated . . . . . . . . . . . 10 153

2. Cryptographers’FavoriteAlgorithmsa. BasicGCD Algorithm . . . . . . . . . . . . . . . 13 155b. ExtendedGCD Algorithm . . . . . . . . . . . . . 14 156c. ExtendedGCD Algorithm (debug version) . . . . . . 15 157d. TestingTwo Exponential Algorithms . . . . . . . . 17 159

II. CodingandInformationTheory

3. CodingandInformationTheorya. Formula for Channal Capacity . . . . . . . . . . . 24 162b. Tableof Channal Capacities . . . . . . . . . . . . 24 163c. Inverseof the Channal Capacity formula . . . . . . . 24 165d. Tableof Repetition Codes . . . . . . . . . . . . . 26 167

4. VisualizingChannelCapacitya. The Simulation Program . . . . . . . . . . . . . 31 169

5. TheHuffmanCodefor Compressiona. The Huffman Algorithm . . . . . . . . . . . . . . 40 173b. Two Distinct Huffman Codes . . . . . . . . . . . . 40 181

6. TheHammingCodefor ErrorCorrection7. Copingwith DecimalNumbers

a. U.S.Banking Scheme . . . . . . . . . . . . . . . 50 183b. IBM Scheme . . . . . . . . . . . . . . . . . . 50 186c. ISBN mod 11 Scheme . . . . . . . . . . . . . . . 50 189d. Mod 97Scheme . . . . . . . . . . . . . . . . . 50 192e. Hamming mod 11Scheme,Err or Correction . . . . . 50 195f. Hamming mod 11Scheme,DoubleErr ors . . . . . . 50 199

8. Verhoeff ’sDecimalErrorDetectiona. Useof the Dihedral Group . . . . . . . . . . . . . 54 203b. Verhoeff’s Scheme . . . . . . . . . . . . . . . . 54 206

Table of Contents: Java Programs ix

III. Introductionto Cryptography

9. CryptogramsandTerminologya. Cryptogram Program . . . . . . . . . . . . . . . 58 209

10. TheOne-TimePada. CaesarCipher . . . . . . . . . . . . . . . . . . 63 212b. BealeCipher . . . . . . . . . . . . . . . . . . 63 215c. Generatea One-timePad . . . . . . . . . . . . . 65 219d. Wheelsto Encrypt/Decrypt With a Pad . . . . . . . 65 222

11. ConventionalBlock CipherCryptosystems??. ConventionalStreamCipherCryptosystems

IV. PublicKey Cryptography

12. PublicKey DistributionSystems13. PublicKey Cryptography:Knapsacks14. TheRSAPublicKey Cryptosystem

a. RSA Implementation . . . . . . . . . . . . . . . 86 226b. FasterRSA, UsingChineseRemainderTheorem . . . 87 231

15. Rabin’sVersionof RSAa. Square Rootsmod n = p*q . . . . . . . . . . . . . 90 236

??. Elliptic CurveCryptosystems??. OtherPublicKey Cryptosystems

V. RandomNumberGeneration

16. TraditionalRandomNumberGeneratorsa. Linear CongruenceRandomNumber Generators . . . 98 239

17. RandomNumbersFromChaosTheorya. The logistic Lattice asa RNG . . . . . . . . . . 104 242

18. StatisticalTestsandPerfectGeneratorsa. Maurer’s UniversalTest . . . . . . . . . . . . . 106 246b. The Blum-Blum-Shub Perfect Generator . . . . . . 106 248

VI. TheAdvancedEncryptionStandard(AES)

19. Introductionto theAES20. TheFiniteFieldGF(256)

a. GenerateMultiplication Tables . . . . . . . . . . 119 250b. CompareMultiplication Results . . . . . . . . . 120 252

21. TheS-Boxesa. GenerateAES Tables . . . . . . . . . . . . . . 121 254

x The Laws of Cryptograph y

22. Key Expansion23. Encryption

a. AES Encryption . . . . . . . . . . . . . . . . 129 25924. Decryption

a. AES Decryption . . . . . . . . . . . . . . . . 132 267b. TestRunsof the AES Algorithm . . . . . . . . . 132 270

VII. HashFunctionsandDigital Signatures

??. One-Way FunctionsandHashFunctions??. Digital Signatures

VIII. RandomizationTechniques

??. SimpleRandomization??. MoreComplex Tricks??. TheRip vanWinkle CipherandRabin’sScheme

IX. IdentificationandKey Distribution

25. PasswordsandKey Distribution26. Zero-KnowledgeProofs27. IdentificationSchemes28. ThresholdSchemes

a. Shamir’sThresholdSchemes . . . . . . . . . . . 147 275??. CaseStudy:theSecureShell(ssh)

ForewordThereareexcellenttechnicaltreatisesoncryptography, alongwith anumberof popularbooks.In this bookI amtrying to find a middleground,a “gentle” introductionto selectedtopicsincryptographywithout avoiding themathematics.Thematerialis aimedat undergraduatecom-putersciencestudents,but I hopeit will beaccessibleandof interestto many others.Theideais to cover a limited numberof topicscarefully, with clearexplanations,samplecalculations,andillustrativeJava implementations.

The emphasisis on the underlyingsystemsandtheir theory, ratherthanon detailsof theuseof systemsalreadyimplemented. For example,the notespresentmaterialon the RSAcryptosystem,its theoryandaJava implementation,but thereis nodiscussionof acommercialimplementationsuchasPGP(“PrettyGoodPrivacy”).

Thereadershouldnot actively dislike mathematics,althoughtheamountanddifficulty ofthe mathematicsrequirementsvary. Oneof my goalsis to cover the necessarymathematicswithouthidingdetails,but alsowithout requiringmaterialfrom anundergraduatemathematicsdegree.Also anumberof subjectsandresultsdo not includefull mathematicalproofs.

Thenotescontain“maxims” or “laws” designedto emphasizeimportantpoints,sometimesin anamusingway— hencethetitle of theoverallwork.

I refer interestedreadersto the Handbookof Applied Cryptography, by Menezes,vanOorschot,andVanstone(CRC Press,1997). Thatwork givesa comprehensive survey of thewholefield, leaving many detailsto technicalarticlesthatthehandbookrefersto, andpresent-ing “techniquesandalgorithmsof greatestinterestto thecurrentpractitioner”.In contrast,mywork is moreidiosyncratic,occasionallypresentingoddor obscurematerial,andnot trying tobecomprehensive.

The Java programsthat accompany this book aredemonstrationimplementationsto helpreadersandstudentsunderstandtheconcepts.I have keptthecodesimpleto furtherthis goal,ratherthan strive for codethat could be includedinto commercialor opensourceprojects,whichwould requirefar longerandmorecomplex code(andbemuchharderfor meto write).Thecomplexities thenwould get in theway of understanding.Readersneedsomefamiliaritywith programmingandwith Java to understandtheseprograms,but mostof theexpositionisindependentof Java.

The book alsocontainsvarioustablesof valuesalongwith sampleor “toy” calculations.In every caseI’ve foundit easierandquicker to write Java programsto generatethis materialratherthanto do the calculationsby hand. In many casesthe Java programsdirectly outputHTML sourceto displaya table. Tablesin this book useLatex source,but I do not includeJava codethatoutputsLatex, sinceHTML is far moreaccessible.ThuswhenI say:“The Javaprogramon pagexxx createsTableX.Y,” this meansthat the Java programcreatesa nearlyidenticalHTML table.

TheJavaprogramsin thebookareavailableonlinein machine-readableformontheauthor’swebpage:

http://www.cs.utsa.edu /˜wa gner/la wsbook/

xii The Laws of Cryptograph y

This bookwaspartly inspiredby anundergraduatecoursein cryptographytaughtat theUni-versityof TexasatSanAntonioduringtheSpring2002semester. Thewebpagefor thecoursehasmany links andotherinformation:

http://www.cs.utsa.edu /˜wa gner/CS 4953/in dex .htm l

A one-semesterundergraduatecoursein cryptographymightcover thefollowing material:� PartI. IntroductoryMaterial onFunctionsandAlgorithms, referringbackto it asneeded.� Part II. Codingand InformationTheory, without the Huffmanor Hammingcodes,andwith emphasisonVerhoeff ’sdetectionmethod.� Part III. Introductionto Cryptography, coveredquickly.� Part IV. PublicKey Cryptography, thefirst four chapters.� PartV. RandomNumberGeneration, thefirst two chapters.� PartVI. TheAdvancedEncryptionStandard (AES), all.� Plusselectedremainingtopicsasdesired.

Theauthorwould liketo thankhismotherfor giving birth to him, but can’t think of anyoneelseto thankat this time.

SanAntonio,TexasJune,2002

Intr oductionMankindhasusedthescienceof cryptographyor “secretmessages”for thousandsof yearstotransmitandstoreinformationneedingsecrecy. Until recentlythemilitary expendedmostof theeffort andmoney involved.However, startingin 1976with theintroductionin theopenliteratureof public key cryptographyby Diffie andHellman,the non-militaryandacademicpursuitofcryptographyhasexploded. The computerrevolution hasgiven peoplethe meansto usefarmorecomplicatedcryptographiccodes,and the samerevolution hasmadesuchwidespreadandcomplex codesnecessary. At the startof a new millennium, even non-technicalpeopleunderstandtheimportanceof techniquesto secureinformationtransmissionandstorage.

Cryptographyprovides four main typesof servicesrelatedto datathat is transmittedorstored:

1. Confidentiality: keepthedatasecret.

2. Integrity: keepthedataunaltered.

3. Authentication: becertainwhere thedatacamefrom.

4. Non-repudiation: sosomeonecannotdenysendingthedata.

Considerfirst confidentiality. This is just a big word meaning“secrecy” — keepingthedatasecret.For thisoneusesencryption, aprocessof takingreadableandmeaningfuldata,andscramblingor transformingit sothatsomeonewhohappensto interceptthedatacanno longerunderstandit. As partof theprocess,therehasto beawayfor authorizedpartiesto unscrambleor decrypttheencrypteddata.

Integrity meanskeepingthe datain unalteredform, while authenticationmeansto knowwherethedatacamefrom andwho sentit. Neitherof theseserviceshasanything to do withsecrecy, thoughone might also want secrecy. Consider, for example,the transferof fundsinvolving U.S.FederalReserveBanks(andotherbanks).While secrecy mightbedesirable,it isof smallimportancecomparedwith beingsurewhoisaskingfor thetransfer(theauthentication)andbeingsurethat the transferis not altered(the integrity). One importanttool that helpsimplementtheseservicesis thedigital signature. A digital signaturehasmuchin commonwithan ordinarysignature,exceptthat it works better: whenproperlyusedit is difficult to forge,andit behavesasif thesignaturewerescrawledovertheentiredocument,sothatany alterationto thedocumentwouldalterthesignature.In contrast,ordinarysignaturesarenotoriouslyeasyto forgeandareaffixedto justonesmallportionof adocument.

Thefinal service,non-repudiation, preventssomeonefrom claimingthatthey hadnot sentadocumentthatwasauthenticatedascomingfrom them.For example,thepersonmightclaimthattheirprivatekey hadbeenstolen.This serviceis importantbut difficult to implement,andis discussedin variousof thebooksreferredto in thereferences.

Refinementsandextensionsof thesebasicservicesfall into acategory I call cryptographictrickery: clever capabilitiesthat might initially seemimpossible,suchas public keys, zero

xiv The Laws of Cryptograph y

knowledgeproofs,andthresholdschemes.I includeexamplesof thismaterialto enticereadersinto thefascinatingfield of cryptography.

Taken all together, cryptographyandits usesandimplementationshave becomeessentialfor mankind’s technicalcivilization. Thefuturepromiseis for thesmoothfunctioningof theseandotherservicesto allow individuals,businesses,andgovernmentsto interactwithout fearinthenew digital andonlineworld.

Part IFavorites

2

1The Laws of Cryptograph yCryptographers’ Favorites

1.1 Exclusive-Or .Thefunctionknown asExclusive-Or is alsorepresentedasxor or a plussign in a circle, � .Theexpression����� meanseither � or � but not both. Ordinaryinclusive-orin mathematicsmeanseitheroneor theotheror both. Thefunctionis availablein C / C++ / Java for bit stringsasa hatcharacter:ˆ . (Be careful: thehatcharacteris oftenusedto meanexponentiation,butJava,C,andC++havenoexponentiationoperator. Thehatcharacteralsosometimesdesignatesacontrolcharacter.) In Java ˆ alsoworksasexclusive-orfor boolean type.

Law XOR-1:The cryptographer’ s favorite function is Exclusive-Or

Exclusive-or comesup constantlyin cryptography. For example, the exclusive-or of apseudo-randombit streamwith a messagebit streamis onesimpleform of encryption. (Seelaterchapters.)

Recallthatthebooleanconstanttrue isoftenwrittenasa1 andfalse asa0. Exclusive-oris thesameasadditionmod2, whichmeansordinaryaddition,followedby takingtheremainderondivisionby � .

For singlebits � and , Table1.1 givesthedefinitionof theirexclusive-or.Theexclusive-orfunctionhasmany interestingproperties,includingthefollowing, which

hold for any bit valuesor bit strings� , � , and :Exclusive-Or� � �� ��� � �� � �� � �� � �

Table1.1Definitionof Exclusive-Or.

4 I. Favorites

���������������������������� , where � is bit complement.������������� (commutativity)����� ����"!#�$�%�&���'!(�) (associativity)���������*���if ���+�,�� , then -������� and #������� .

Beginningprogrammerslearnhow to exchangethevaluesin two variablesa andb, usinga third temporaryvariabletemp andtheassignmentoperator= :

temp = a;a = b;b = temp;

Thesameresultcanbeaccomplishedusingxor without an extra temporarylocation,re-gardinga andb asbit strings:

a = a xor b;b = a xor b;a = a xor b;

Exercise:Provetheaboveresultin two ways,oneusingjust thedefinitionof xor in thetable,andtheotherwayusingthepropertiesof xor listedabove. (Oncomputerhardwarethathasanxor instructioncombinedwith assignment,theabove solutionmayexecutejust asfastasthepreviousoneandwill avoid theextravariable.)

A Javaprogramthatdemonstratesinterchangeusingexclusive-oris onpage151.

1.2 Logarithms.

By definition, ./��021436587 meansthesameas �:9;�<7 . Onesays:“ . is thelogarithmof 7 to base� ,” or “ . is the log base� of 7 .” Statedanotherway, 0=163 5 7 (alsoknown as . ) is theexponentyou raise � to in orderto get 7 . Thus �?>A@CBEDGF"H'I(��7 . In moremathematicalterms,thelogarithmis the inversefunctionof theexponential.

Law LOG-1:The cryptographer’ s favorite logarithm is log base 2.

Oneuseslogsbase� in cryptography(aswell asin mostof computerscience)becauseoftheemphasisonbinarynumbersin thesefields.

So .J��021636KL7 meansthesameas � 9 ��7 , anda logarithmbase� of 7 is theexponentyouraise � to in orderto get 7 . In symbols:if .M�N0=163 K 7 , then 7+�N�O9P�Q� @CBEDGR?H . In particular

1. Cryptographer’ s Favorites 5

Logarithms base2S/TVU 9 TWU @CBED R H X TZY\[^] K S1 073741824 30

1 048576 20

1 024 10

8 34 22 11 0

1/2 -11/4 -21/8 -3

1/1024 -10

0 _a`b 0 undefined

Table1.2Logarithmsbase2.

�6cedf�g^�6�ih meansthesameas 02143 K ^�8�ihj�g?� . Notice that �O9lkm� for all . , andinversely02143 K 7 is notdefinedfor 7onp� .Table1.2 givesa little tableof logsbase� .Herearea few otherformulasinvolving logarithms:

021436Kq� �r�'!#��021436Ks�&t+0=1636Ks�qu for all �suv�wk)�02143 K � �yxi�'!#��0=163 K �fzW0=163 K �qu for all �suv�wk)�021436Kq�{^xi�y!|�p021634KO� �~} c !#��zo0=1636Ks�su for all �Pk<��uv�02143 K � �8�:!|����02143 K ��u for all ��k<�yuv�02143 K � �&t+�'!#� (Oops!No simpleformulafor this.)

Somecalculators,aswell aslanguageslike Java,do not directly supportlogsbase� . Javadoesnot even supportlogs base ^� , but only logs base� , the “natural” log. However, a logbase� is just a fixedconstanttimesa naturallog, sothey areeasyto calculateif you know the“magic” constant.Theformulasare:

0=1636KL7 � 021636�y7�x�0=1634�L� , (mathematics)� Math.log(x)/Math.log(2.0); (Java).

Here is the magic constant: 02143 � ���6!�� �����6�6��"h���^�6�8���4�6�4h8���6�4�4h~��6�4�8�� , orqx-021434�"�e�6!J��6��h6hr�4�6�J�4�ih8�6�*�6�6�4�6�/h8�8�4�6���4�8�ih8� . (Similarly, 021634Ks7p��0=163 ced 7�x-02163 ced �e�6! ,and 02163 ced �e�6!#���y�A�6�y^�8�4�6�4�8�4�6�6�4�6��6?h .)

6 I. Favorites

A Javaprogramthatdemonstratestheseformulasis onpage152.Hereis aproofof theaboveformula:� 9 ��7 , or .���0=163 K 7 (thentake 0=163 � of eachside)0=163 � �e�O9?!���0=163 � 7 (thenusepropertiesof logarithms).|021634�s����021634�y7 (thensolve for y)./��02163 � 7�x-02163 � � (thensubstitute02143 K 7 for y)0=1636KL7��p021636�y7�x�0=1636�~�y�Law LOG-2:

The log base 2 of an integ er x tells how many bits it takesto represent x in binar y.

Thus 021636K(^�4�6�6����^���A�4�8�4�yq�4�6� , soit takes ?h bits to represent^�6�4�6� in binary. (In fact,^�6�4�6� ced ��^�6��46^�6�6�y^�6�6�6� K .) Exactpowersof � area specialcase:02163 K ^�6�ihP��^� , but ittakes 6 bits to represent^�6�ih in binary, as ^�6�4�6�6�6�6�4�6�6� K .

Similarly, 0=163 ced ��7�! giveshow many decimaldigitsareneededto represent7 .

Exercises:1. How many bitsareneededto representanumberthatis 100decimaldigits long?[Ans: 333.] How many decimaldigitsareneededto representanumberthatis 1000bits long?[Ans: 302.] How many decimaldigits areneededto representa numberthat is 100 decimaldigits long?[Ans: SeeProceedingsof thePolishNationalAcademyof Sciences.]

2. Write a Java functionto returnthe log base� of � , where �Jk� and �Mk�� . Testyourfunction.

1.3 Groups.

A group is asetof groupelementswith a binaryoperation for combiningany two elementstogeta uniquethird element.If onedenotesthegroupoperationby � , thentheabove saysthatfor any groupelements� and � , �y�*� is definedandis alsoa groupelement.Groupsarealsoassociative, meaningthat �y���%�'��'!f��� �y�/�"!G�* , for any groupelements� , � , and . Therehasto bean identityelement� satisfying ���*���m�q�/�j��� for any groupelement� . Finally,any element� musthavean inverse �8� satisfying�y�/�8�L�p�r���*�*��� .

If �y�/��� �'�/� for all groupelements� and � , thegroupis commutative. Otherwiseit isnon-commutative. Noticethatevenin anon-commutativegroup,�y�*�����'�*� mightsometimesbetrue— for exampleif � or � is theidentity.

A groupwith only finitely many elementsis calledfinite; otherwiseit is infinite.

Examples:

1. The integers (all whole numbers,including � andnegative numbers)form a groupus-ing ordinaryaddition. The identity is � andthe inverseof � is z,� . This is an infinitecommutativegroup.

1. Cryptographer’ s Favorites 7

2. Thepositiverationals(all positivefractions,includingall positiveintegers)form agroupif ordinarymultiplicationis theoperation.Theidentity is andtheinverseof � is qxi���� } c . This is anotherinfinite commutativegroup.

3. The integers modn form a groupfor any integer ¡¢k£� . This groupis often denoted¤�¥. Heretheelementsare � , , � , �?�"� , ¡¦z� andtheoperationis additionfollowedby

remainderon divisionby ¡ . Theidentity is � andtheinverseof � is ¡jzV� (exceptfor �which is its own inverse).This is afinite commutativegroup.

4. For an exampleof a non-commutative group,consider2-by-2non-singularmatricesofrealnumbers(or rationals),wheretheoperationis matrixmultiplication:§ � � ¨ª©Here � , � , , and ¨ arerealnumbers(or rationals)and �r¨Pz��« mustbenon-zero(non-singularmatrices).Theoperationis matrixmultiplication.Theabovematrixhasinverse�r¨/zZ�« § ¨ z,�z; �¬©andtheidentity is § �� © �This is aninfinite non-commutativegroup.

5. Thechapteron decimalnumbersgivesaninterestingandusefulexampleof afinite non-commutativegroup:thedihedral groupwith tenelements.

Law GROUP-1:The cryptographer’ s favorite group is the integers mod n,

Zn.

1.4 Fields.A field is an objectwith a lot of structure,which this sectionwill only outline. A field hastwo operations,call them t and ­ (thoughthey will not necessarilybeordinaryadditionandmultiplication). Using t , all theelementsof thefield form a commutative group. Denotethe

8 I. Favorites

identity of this groupby � anddenotetheinverseof � by z;� . Using ­ , all theelementsof thefield except � mustform anothercommutative groupwith identity denoted andinverseof �denotedby � } c . (Theelement� hasno inverseunder ­ .) Thereis alsothedistributiveidentity,linking t and ­ : ��­&� �#t+"!��$�%��­a�'!®t�� ��­�'! , for all field elements� , � , and .Examples:

1. Considertherationalnumbers (fractions)Q, or therealnumbersR, or thecomplex num-bers C, usingordinaryadditionandmultiplication(extendedin thelastcaseto thecom-plex numbers).Theseareall infinite fields.

2. Considerthe integers modp, denoted¤°¯

, wherep is a prime number( � , � , � , � , 6 ,^� , q� , ?� , �4� , �4� , �?�?� ). Regardthis asa groupusing t (ordinaryadditionfollowedbyremainderondivisionby ± ). Theelementswith � left out form agroupunder ­ (ordinarymultiplication followedby remainderon division by ± ). Herethe identity is clearly ,but the inverseof a non-zeroelement� is not obvious. In Java, the inversemustbe anelement7 satisfying ��7�­,�y!³²�±M���N . It is alwayspossibleto find theuniqueelement7 , usinganalgorithmfrom numbertheoryknown astheextendedEuclideanalgorithm.This is thetopic in thenext chapter, but in brief: because± is primeand � is non-zero,thegreatestcommondivisor of ± and � is . ThentheextendedEuclideanalgorithmgivesordinaryintegers 7 and . satisfying 7�­��ft)./­#±¬�N , or 7�­,�¦�Q;z�./­�± , andthissaysthatif you divide 7´­µ� by ± , you getremainder , sothis 7 is theinverseof � . (Asaninteger, 7 mightbenegative,andin thiscaseonemustadd± to it to getanelementof¤(¯

.)

Law FIELD-1:The cryptographer’ s favorite field is the integers mod p,

denoted Zp , where p is a prime number .

Theabove field is theonly onewith ± elements.In otherwords,thefield is uniqueup torenamingits elements,meaningthatonecanalwaysuseadifferentsetof symbolsto representtheelementsof thefield, but it will still beessentiallythesame.

Thereis alsoauniquefinite field with ± ¥elementsfor any integer ¡Mk� , denoted¶�·´�\± ¥ ! .

Particularlyusefulin cryptographyis thespecialcasewith ±l��� , thatis, with � ¥ elementsfor¡Mk� . Thecase�i¸a���6�4� is used,for example,in thenew U.S.AdvancedEncryptionStandard(AES). It is moredifficult to describethanthefield

¤°¯. Thechapteraboutmultiplicationfor

theAES will describethis field in moredetail,but in brief for now, it has �4�4� elements.Eachelementcanberepresentedasastringof � bits. Addition in thefield is just thesameasbitwiseexclusive-or (or bitwise addition mod � ). The zero elementis �6�6�4�6�6�6�6� , and the identityelementis �4�6�6�6�6�4�� . So far, so good, but multiplication is more problematic: one hastoregardanelementatadegree� polynomialwith coefficientsin thefield

¤ K (justa � or a ) andusea specialversionof multiplicationof thesepolynomials.Thedetailswill comein thelaterchapteron theAES.

1. Cryptographer’ s Favorites 9

Law FIELD-2:The cryptographer’ s other favorite field is GF(2n).

1.5 Fermat’ s Theorem.In cryptography, oneoftenwantsto raiseanumberto apower, moduloanothernumber. For theintegersmod ± where± is a prime(denoted

¤°¯), thereis a resultknow asFermat’s Theorem,

discoveredby the17thcenturyFrenchmathematicianPierredeFermat,1601-1665.

Theorem(Fermat): If ± is aprimeand � is any non-zeronumberlessthan± , then

� ¯ } c mod ±���Law FERMAT-1:

The cryptographer’ s favorite theorem is Fermat’ s Theorem.

Table1.3 illustratesFermat’s Theoremfor ±o� ^� . Noticebelow that thevalueis always by thetimethepowergetsto ^� , but sometimesthevaluegetsto earlier. Theinitial run upto the valueis shown in bold italic in thetable.Thelengthsof theserunsarealwaysnumbersthatdivide evenly into q� , that is, � , � , h , � , or q� . A valueof � for which thewhole row isbold italic is calledagenerator. In thiscase� , � , � , and 6 aregenerators.

Because� to apowermod ± alwaysstartsrepeatingafterthepower reaches±*z� , onecanreducethepower mod ±´zp andstill getthesameanswer. Thusno matterhow big thepower7 mightbe, � H mod ±l��� H mod > ¯ } c I mod ±°�Thusmodulo ± in theexpressionrequiresmodulo ±Pz� in theexponent.(Naively, onemightexpectto reducethe exponentmod ± , but this is not correct.) So, for example,if ±V��?� asabove,then � KE¹

mod ^����� KE¹ mod c K mod ?���p�rº mod ^���TheSwissmathematicianLeonhardEuler(1707-1783)discovereda generalizationof Fer-

mat’sTheoremwhichwill laterbeusefulin thediscussionof theRSAcryptosystem.

Theorem (Euler): If ¡ is any positive integer and � is any positive integer lessthan ¡ with no divisorsin commonwith ¡ , then�r» > ¥ I mod ¡j��4u

10 I. Favorites

p a � c � K �4¼ �i½ � º �i¾ �4¿ � ¸ � ¹ � ced � cEc � c K13 2 2 4 8 3 6 12 11 9 5 10 7 113 3 3 9 1 3 9 1 3 9 1 3 9 113 4 4 3 12 9 10 1 4 3 12 9 10 113 5 5 12 8 1 5 12 8 1 5 12 8 113 6 6 10 8 9 2 12 7 3 5 4 11 113 7 7 10 5 9 11 12 6 3 8 4 2 113 8 8 12 5 1 8 12 5 1 8 12 5 113 9 9 3 1 9 3 1 9 3 1 9 3 113 10 10 9 12 3 4 1 10 9 12 3 4 113 11 11 4 5 3 7 12 2 9 8 10 6 113 12 12 1 12 1 12 1 12 1 12 1 12 1

Table1.3Fermat’s Theoremfor À T �ÂÁ.

where ÃÄ� ¡°! is theEulerphi function:Ã�� ¡Å!#��¡��Æ�z<qx«± c !G!Ç�?�?�"�{�z<qx«±�ȵ!Âuand ± c , �"�?� , ±�È areall theprime numbersthatdivide evenly into ¡ , including ¡itself in caseit is aprime.

If ¡ is aprime,thenusingtheformula, ÃÄ� ¡Å!|�p¡��ÆÉzWqxO¡°!���¡-� ¥ } c¥ !#�p¡JzW , soEuler’sresult is a specialcaseof Fermat’s. Anotherspecialcaseneededfor the RSA cryptosystemcomeswhenthemodulusis a productof two primes: ¡���±LÊ . Then Ã��%¡°!a��¡-�{,z�^x«±�!"�Æ;zqxiÊ4!�� ��±�z�q!"�%ÊJz�q! . Table1.4 illustratesEuler’s theoremfor ¡�� q�V�Ë�´Ì�� , withÃ��Æq�6!#�$q�wÌ��{,z<qx4�8!�Ìy�Æ,zpqx4�6!#������z<q!-Ì��e�&z<q!É��� . Noticeherethata is reachedwhenthepowergetsto � (actuallyin thissimplecasewhenthepowergetsto � or h ), but onlyfor numberswith nodivisorsin commonwith q� . For otherbasenumbers,thevaluenevergetsto .

Thetablesaboveweregeneratedby theJavaprogramon page153.In a way similar to Fermat’s Theorem,arithmeticin the exponentis taken mod Ã�� ¡Å! , so

that,assuming� hasnodivisorsin commonwith ¡ ,� H mod ¡¦��� H mod » > ¥ I mod ±°�If ¡��Íq� asabove, then ÃÄ� ¡°!´�Î� , and if neither � nor � dividesevenly into � , thenÃ��%¡°!#��� . Thusfor example,� K ¸ mod q����� K ¸ mod ¸ mod q����� ½ mod q�y�Theproof in Chapter? thattheRSAcryptosystemworksdependson theabovefact.

1. Cryptographer’ s Favorites 11

n a � c � K � ¼ � ½ � º � ¾ � ¿ � ¸ � ¹ � ced � cEc � c K � c ¼ � c ½15 2 2 4 8 1 2 4 8 1 2 4 8 1 2 415 3 3 9 12 6 3 9 12 6 3 9 12 6 3 915 4 4 1 4 1 4 1 4 1 4 1 4 1 4 115 5 5 10 5 10 5 10 5 10 5 10 5 10 5 1015 6 6 6 6 6 6 6 6 6 6 6 6 6 6 615 7 7 4 13 1 7 4 13 1 7 4 13 1 7 415 8 8 4 2 1 8 4 2 1 8 4 2 1 8 415 9 9 6 9 6 9 6 9 6 9 6 9 6 9 615 10 10 10 10 10 10 10 10 10 10 10 10 10 10 1015 11 11 1 11 1 11 1 11 1 11 1 11 1 11 115 12 12 9 3 6 12 9 3 6 12 9 3 6 12 915 13 13 4 7 1 13 4 7 1 13 4 7 1 13 415 14 14 1 14 1 14 1 14 1 14 1 14 1 14 1

Table1.4Euler’s theoremfor Ï T �ÂÐ.