Table Of ContentAPress/Authoring/2005/04/10:10:11 Pageiv
>
m
o
ok.c
o
b
e
w
o
w
w.
w
w
<
ok
o
B
e
w!
o
W
m
o
d fr For your convenience Apress has placed some of the front
a
o
nl matter material after the index. Please use the Bookmarks
w
o
D
and Contents at a Glance links to access them.
APress/Authoring/2005/04/10:12:18 Pagev
Contents
Foreword xiii
AbouttheAuthor xv
AbouttheTranslator xvi
PrefacetotheSecondAmericanEdition xvii
PrefacetotheFirstAmericanEdition xix
PrefacetotheFirstGermanEdition xxiii
I ArithmeticandNumberTheoryinC 1
1 Introduction 3
2 NumberFormats:TheRepresentationofLargeNumbersinC 13
3 InterfaceSemantics 19
4 TheFundamentalOperations 23
4.1 AdditionandSubtraction . . . . . . . . . . . . . . . . . . . . . . 24
4.2 Multiplication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
4.2.1 TheGradeSchoolMethod . . . . . . . . . . . . . . . . . 34
4.2.2 SquaringIsFaster . . . . . . . . . . . . . . . . . . . . . . 40
4.2.3 DoThingsGoBetterwithKaratsuba? . . . . . . . . . . . 45
4.3 DivisionwithRemainder . . . . . . . . . . . . . . . . . . . . . . 50
5 ModularArithmetic:CalculatingwithResidueClasses 67
6 WhereAllRoadsMeet:ModularExponentiation 81
6.1 FirstApproaches . . . . . . . . . . . . . . . . . . . . . . . . . . 81
6.2 M-aryExponentiation . . . . . . . . . . . . . . . . . . . . . . . 86
6.3 AdditionChainsandWindows . . . . . . . . . . . . . . . . . . . 101
6.4 MontgomeryReductionandExponentiation . . . . . . . . . . . 106
6.5 CryptographicApplicationofExponentiation . . . . . . . . . . . 118
v
APress/Authoring/2005/04/10:12:18 Pagevi
Contents
7 BitwiseandLogicalFunctions 125
7.1 ShiftOperations . . . . . . . . . . . . . . . . . . . . . . . . . . 125
7.2 AllorNothing:BitwiseRelations . . . . . . . . . . . . . . . . . . 131
7.3 DirectAccesstoIndividualBinaryDigits. . . . . . . . . . . . . . 137
7.4 ComparisonOperators . . . . . . . . . . . . . . . . . . . . . . . 140
8 Input,Output,Assignment,Conversion 145
9 DynamicRegisters 157
10 BasicNumber-TheoreticFunctions 167
10.1 GreatestCommonDivisor . . . . . . . . . . . . . . . . . . . . . 168
10.2 MultiplicativeInverseinResidueClassRings . . . . . . . . . . . 175
10.3 RootsandLogarithms . . . . . . . . . . . . . . . . . . . . . . . 183
10.4 SquareRootsinResidueClassRings . . . . . . . . . . . . . . . . 191
10.4.1 TheJacobiSymbol . . . . . . . . . . . . . . . . . . . . . 192
10.4.2 SquareRootsModulopk . . . . . . . . . . . . . . . . . . 198
10.4.3 SquareRootsModulon . . . . . . . . . . . . . . . . . . . 203
10.4.4 CryptographywithQuadraticResidues . . . . . . . . . . 211
10.5 APrimalityTest . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
11 Rijndael:ASuccessortotheDataEncryptionStandard 237
11.1 ArithmeticwithPolynomials . . . . . . . . . . . . . . . . . . . . 239
11.2 TheRijndaelAlgorithm . . . . . . . . . . . . . . . . . . . . . . . 244
11.3 CalculatingtheRoundKey . . . . . . . . . . . . . . . . . . . . . 247
11.4 TheS-Box . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
11.5 TheShiftRowsTransformation . . . . . . . . . . . . . . . . . . . 249
11.6 TheMixColumnsTransformation . . . . . . . . . . . . . . . . . . 250
11.7 TheAddRoundKeyStep . . . . . . . . . . . . . . . . . . . . . . . . 252
11.8 EncryptionasaCompleteProcess . . . . . . . . . . . . . . . . . 253
11.9 Decryption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
11.10 Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
11.11 ModesofOperation . . . . . . . . . . . . . . . . . . . . . . . . 260
12 LargeRandomNumbers 261
12.1 ASimpleRandomNumberGenerator . . . . . . . . . . . . . . . 265
12.2 CryptographicRandomNumberGenerators . . . . . . . . . . . 268
12.2.1 TheGenerationofStartValues . . . . . . . . . . . . . . . 269
12.2.2 TheBBSRandomNumberGenerator . . . . . . . . . . . 273
12.2.3 TheAESGenerator . . . . . . . . . . . . . . . . . . . . . 279
12.2.4 TheRMDSHA-1Generator . . . . . . . . . . . . . . . . . 283
vi
APress/Authoring/2005/04/10:12:18 Pagevii
Contents
12.3 QualityTesting . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
12.3.1 Chi-SquaredTest . . . . . . . . . . . . . . . . . . . . . . 287
12.3.2 MonobitTest . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.3 PokerTest . . . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.4 RunsTest . . . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.5 LongrunsTest . . . . . . . . . . . . . . . . . . . . . . . . 289
12.3.6 AutocorrelationTest . . . . . . . . . . . . . . . . . . . . 290
12.3.7 QualityoftheFLINT/CRandomNumberGenerators . . . 290
12.4 MoreComplexFunctions . . . . . . . . . . . . . . . . . . . . . . 291
13 StrategiesforTestingLINT 305
13.1 StaticAnalysis. . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
13.2 Run-TimeTests . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
II ArithmeticinC++withtheClassLINT 317
14 LetC++SimplifyYourLife 319
14.1 NotaPublicAffair:TheRepresentationofNumbersinLINT . . . 324
14.2 Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
14.3 OverloadedOperators . . . . . . . . . . . . . . . . . . . . . . . 329
15 TheLINTPublicInterface:MembersandFriends 337
15.1 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
15.2 NumberTheory . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
15.3 StreamI/OofLINTObjects . . . . . . . . . . . . . . . . . . . . . 352
15.3.1 FormattedOutputofLINTObjects . . . . . . . . . . . . . 353
15.3.2 Manipulators . . . . . . . . . . . . . . . . . . . . . . . . 360
15.3.3 FileI/OforLINTObjects . . . . . . . . . . . . . . . . . . . 362
16 ErrorHandling 367
16.1 (Don’t)Panic... . . . . . . . . . . . . . . . . . . . . . . . . . . 367
16.2 User-DefinedErrorHandling. . . . . . . . . . . . . . . . . . . . 369
16.3 LINTExceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
17 AnApplicationExample:TheRSACryptosystem 377
17.1 AsymmetricCryptosystems . . . . . . . . . . . . . . . . . . . . 378
17.2 TheRSAAlgorithm . . . . . . . . . . . . . . . . . . . . . . . . . 380
17.3 DigitalRSASignatures . . . . . . . . . . . . . . . . . . . . . . . 395
17.4 RSAClassesinC++ . . . . . . . . . . . . . . . . . . . . . . . . . 403
18 DoItYourself:TestLINT 413
vii
APress/Authoring/2005/04/10:12:18 Pageviii
Contents
19 ApproachesforFurtherExtensions 417
III Appendices 419
A DirectoryofCFunctions 421
A.1 Input/Output,Assignment,Conversions,Comparisons . . . . . . 421
A.2 BasicCalculations . . . . . . . . . . . . . . . . . . . . . . . . . 422
A.3 ModularArithmetic. . . . . . . . . . . . . . . . . . . . . . . . . 423
A.4 BitwiseOperations . . . . . . . . . . . . . . . . . . . . . . . . . 425
A.5 Number-TheoreticFunctions . . . . . . . . . . . . . . . . . . . 426
A.6 GenerationofPseudorandomNumbers . . . . . . . . . . . . . . 427
A.7 RegisterManagement . . . . . . . . . . . . . . . . . . . . . . . 431
B DirectoryofC++Functions 433
B.1 Input/Output,Conversion,Comparison:MemberFunctions . . . 433
B.2 Input/Output,Conversion,Comparison:FriendFunctions . . . . 436
B.3 BasicOperations:MemberFunctions . . . . . . . . . . . . . . . 438
B.4 BasicOperations:FriendFunctions . . . . . . . . . . . . . . . . 439
B.5 ModularArithmetic:MemberFunctions . . . . . . . . . . . . . . 440
B.6 ModularArithmetic:FriendFunctions . . . . . . . . . . . . . . . 442
B.7 BitwiseOperations:MemberFunctions . . . . . . . . . . . . . . 443
B.8 BitwiseOperations:FriendFunctions . . . . . . . . . . . . . . . 444
B.9 Number-TheoreticMemberFunctions . . . . . . . . . . . . . . 445
B.10 Number-TheoreticFriendFunctions . . . . . . . . . . . . . . . 446
B.11 GenerationofPseudorandomNumbers . . . . . . . . . . . . . . 450
B.12 MiscellaneousFunctions . . . . . . . . . . . . . . . . . . . . . . 450
C Macros 451
C.1 ErrorCodesandStatusValues . . . . . . . . . . . . . . . . . . . 451
C.2 AdditionalConstants . . . . . . . . . . . . . . . . . . . . . . . . 451
C.3 MacroswithParameters . . . . . . . . . . . . . . . . . . . . . . 453
D CalculationTimes 459
E Notation 461
F ArithmeticandNumber-TheoreticPackages 463
References 465
Index 473
viii
APress/Authoring/2005/04/10:10:11 Pagexiii
Foreword
CRYPTOGRAPHYISANANCIENTART,wellovertwothousandyearsold.Theneed
tokeepcertaininformationsecrethasalwaysexisted,andattemptstopreserve
secretshavethereforeexistedaswell.Butitisonlyinthelastthirtyyearsthat
cryptographyhasdevelopedintoasciencethathasofferedusneededsecurityin
ourdailylives.Whetherwearetalkingaboutautomatedtellermachines,cellular
telephones,Internetcommerce,orcomputerizedignitionlocksonautomobiles,
thereiscryptographyhiddenwithin.Andwhatismore,noneoftheseapplications
wouldworkwithoutcryptography!
Thehistoryofcryptographyoverthepastthirtyyearsisauniquesuccessstory.
Themostimportanteventwassurelythediscoveryofpublickeycryptographyin
themid1970s.Itwastrulyarevolution:Weknowtodaythatthingsarepossible
thatpreviouslywehadn’tevendaredtothinkabout.DiffieandHellmanwere
thefirsttoformulatepubliclythevisionthatsecurecommunicationmustbe
abletotakeplacespontaneously.Earlier,itwasthecasethatsenderandreceiver
hadfirsttoengageinsecretcommunicationtoestablishacommonkey.Diffie
andHellmanasked,withthenaivetyofyouth,whetheronecouldcommunicate
secretlywithoutsharingacommonsecret.Theirideawasthatonecouldencrypt
informationwithoutasecretkey,thatis,onethatnooneelsecouldknow.This
ideasignaledthebirthofpublickeycryptography.Thatthisvisionwasmore
thanjustwildsurmisewasshownafewyearslaterwiththeadventoftheRSA
algorithm.
Moderncryptographyhasbeenmadepossiblethroughtheextraordinarily
fruitfulcollaborationbetweenmathematicsandcomputerscience.Mathematics
provided the basis for the creation and analysis of algorithms. Without
mathematics, and number theory in particular, public key cryptography
wouldbeimpossible.Mathematicsprovidestheresultsonthebasisofwhichthe
algorithmsoperate.
Ifthecryptographicalgorithmsaretoberealized,thenoneneedsprocedures
thatenablecomputationwithlargeintegers:Thealgorithmsmustnotfunction
onlyintheory;theymustperformtoreal-worldspecifications.Thatisthetaskof
computerscience.
Thisbookdistinguishesitselffromallotherbooksonthesubjectinthatit
makesclearthisrelationshipbetweenmathematicsandcomputing.Iknowofno
bookoncryptographythatpresentsthemathematicalbasissothoroughlywhile
providingsuchextensivepracticalapplications,andallofthisinaneminently
readablestyle.
xiii
APress/Authoring/2005/04/10:10:11 Pagexiv
Foreword
Whatwehavehereisamasterwritingabouthissubject.Heknowsthetheory,
andhepresentsitclearly.Heknowstheapplications,andhepresentsahost
ofproceduresforrealizingthem.Heknowsmuch,buthedoesn’twritelikea
know-it-all.Hepresentshisargumentsclearly,sothatthereaderobtainsaclear
understanding.Inshort,thisisaremarkablebook.
Sobestwishestotheauthor!Andaboveall,bestwishestoyou,thereader!
AlbrechtBeutelspacher
xiv
APress/Authoring/2005/04/10:10:11 Pagexvii
Preface to the Second
American Edition
WhenIhavetowrestlewithfigures,IfeelI’dliketostuffmyselfintoahole
intheground,soIcan’tseeanything.IfIraisemyeyesandseethesea,ora
tree,orawoman—evenifshe’sanold’un—dammeifallthesumsandfigures
don’tgotoblazes.TheygrowwingsandIhavetochase’em.
—NikosKazanzakis, ZorbatheGreek
THESECONDAMERICANEDITIONOFthisbookhasagainbeenrevisedandenlarged.
Thechapteronrandomnumbergeneratorshasbeencompletelyrewritten,
andthesectiononprimalitytestingwassubstantiallyrevised.Thenewresults
ofAgrawal,Kayal,andSaxenaonprimalitytests,whosediscoveryin2002that
“PRIMESisinP”causedasensation,arecovered.ThechapteronRijndael/AES
hasbeenrelocatedforabetterpresentation,anditispointedoutthatthe
standardizationofRijndaelastheAdvancedEncryptionStandardhasmeanwhile
beenmadeofficialbytheU.S.NationalInstituteofStandardsandTechnology
(NIST).
Unlikepreviouseditionsofthebook,thesecondAmericaneditiondoesnot
containaCD-ROMwiththesourcecodefortheprogramspresented.Instead,
thesourcecodeisavailablefordownloadatwww.apress.comintheDownloads
section.
Iwishtothankthepublishersandtranslatorswhohavemeanwhilemadethis
bookavailableinChinese,Korean,Polish,andRussianandthroughtheircareful
readinghavecontributedtothequalityofthisedition.
I again thank David Kramer for his engaging and painstaking English
translation,andGaryCornell,ofApress,forhiswillingnesstobringoutthe
secondAmericanedition.
Finally,IwishtothankSpringerSciencepublishers,andinparticularonce
againHermannEngesser,DorotheaGlausinger,andUlrikeSricker,fortheir
pleasantcollaboration.
xvii
APress/Authoring/2005/04/10:10:11 Pagexix
Preface to the First
American Edition
Mathematicsisamisunderstoodandevenmaligneddiscipline.It’snotthe
brutecomputationstheydrilledintousingradeschool.It’snotthescience
ofreckoning.Mathematiciansdonotspendtheirtimethinkingupcleverer
waysofmultiplying,fastermethodsofadding,betterschemesforextracting
cuberoots.
—PaulHoffman, TheManWhoLovedOnlyNumbers
THEFIRSTAMERICANEDITIONISATRANSLATIONOFthesecondGermanedition,
whichhasbeenrevisedandexpandedfromthefirstGermaneditioninanumber
ofways.Additionalexamplesofcryptographicalgorithmshavebeenadded,
suchastheproceduresofRabinandElGamal,andintherealizationoftheRSA
procedurethehashfunctionRIPEMD-160andformattingaccordingtoPKCS
#1havebeenadopted.Thereisalsoadiscussionofpossiblesourcesoferror
thatcouldleadtoaweakeningoftheprocedure.Thetexthasbeenexpanded
orclarifiedatanumberofpoints,anderrorshavebeencorrected.Additionally,
certaindidacticstrategieshavebeenstrengthened,withtheresultthatsomeof
theprogramsinthesourcecodedifferincertaindetailsfromthosepresented
inthebook.Notalltechnicaldetailsareofequalimportance,andthedesirefor
fastandefficientcodeisnotalwayscompatiblewithattractiveandeasy-to-read
programs.
Andspeakingofefficiency,inAppendixDrunningtimesarecomparedto
thoseforcertainfunctionsintheGNUMultiprecisionLibrary.Inthiscomparison
theFLINT/Cexponentiationroutinedidnotdoatallbadly.Asafurtherextension,
Appendix F provides references to some arithmetic and number-theoretic
packages.
Thesoftwarehasbeenexpandedbyseveralfunctionsandinplaceshasbeen
significantlyoverhauled,andintheprocessanumberoferrorsandpointsof
imprecisionwereremoved.Additionaltestfunctionsweredevelopedandexisting
testfunctionsexpanded.Asecuritymodewasimplemented,wherebysecurity-
criticalvariablesintheindividualfunctionsaredeletedbybeingoverwritten.All
CandC++functionsarenowclearlycitedandannotatedintheappendices.
SincecurrentcompilersrepresentvaryingstagesofdevelopmentoftheC++
standard,theC++modulesoftheFLINT/Cpackagehavebeensetupinsuch
awaythatbothtraditionalC++headerfilesoftheformxxxxx.handthenew
xix