Cryptography in C and C++ MICHAELWELSCHENBACH TranslatedbyDAVIDKRAMER press A TM CryptographyinCandC++ Copyright(cid:1)c 2005byMichaelWelschenbach TranslatorandCompositor:DavidKramer EditorialBoard:SteveAnglin,DanAppleman,EwanBuckingham,GaryCornell, TonyDavis,JasonGilmore,JonathanHassell,ChrisMills,DominicShakeshaft,JimSumser AssistantPublisher:GraceWong CopyManager:NicoleLeClerc ProductionManager:KariBrooks-Copony Proofreader:AnneFriedman TEXSupport:FredBartlettandArthurOgawa ManufacturingManager:TomDebolski CoverDesigner:KurtKrames LibraryofCongressCataloging-in-PublicationData Welschenbach,Michael. [KryptographieinCundC++.English] CryptographyinCandC++/MichaelWelschenbach;translatedbyDavidKramer.– 2ndAmericaned.,rev.andenl. p.cm. ThefirstAmericaneditionisatranslationofthesecondGermanedition,whichhas beenrevisedandexpandedfromthefirstGermanedition. Includesbibliographicalreferencesandindex. ISBN1-59059-502-5 1.Computersecurity. 2.Cryptography. 3.C(Computerprogram language) 4.C++(Computerprogramlanguage) I.Title. QA76.9.A25W43132005 005.8–dc22 2005002553 Allrightsreserved.Nopartofthisworkmaybereproducedortransmittedinanyformorby anymeans,electronicormechanical,includingphotocopying,recording,orbyanyinformation storageorretrievalsystem,withoutthepriorwrittenpermissionofthecopyrightownerandthe publisher. PrintedandboundintheUnitedStatesofAmerica987654321 Trademarkednamesmayappearinthisbook.Ratherthanuseatrademarksymbolwithevery occurrenceofatrademarkedname,weusethenamesonlyinaneditorialfashionandtothe benefitofthetrademarkowner,withnointentionofinfringementofthetrademark. DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNewYork,Inc.,233Spring Street,6thFloor,NewYork,NY10013,andoutsidetheUnitedStatesbySpringer-VerlagGmbH& Co.KG,Tiergartenstr.17,69112Heidelberg,Germany. IntheUnitedStates:phone1-800-SPRINGER,fax201-348-4505,[email protected], orvisithttp://www.springer-ny.com.OutsidetheUnitedStates:fax+496221345229,e-mail [email protected],orvisithttp://www.springer.de.Forinformationontranslations,please contactApressdirectlyat2560NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930, fax510-549-5939,[email protected],orvisithttp://www.apress.com. Theinformationinthisbookisdistributedonan“asis”basis,withoutwarranty.Althoughevery precautionhasbeentakeninthepreparationofthiswork,neithertheauthor(s)norApressshall haveanyliabilitytoanypersonorentitywithrespecttoanylossordamagecausedorallegedto becauseddirectlyorindirectlybytheinformationcontainedinthiswork. Thesourcecodeforthisbookisavailabletoreadersathttp://www.apress.comintheDownloads section.Youwillneedtoanswerquestionspertainingtothisbookinordertosuccessfully downloadthecode. Tomyfamily,asalways 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 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 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 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 List of Figures 4-1 Calculationsformultiplication . . . . . . . . . . . . . . . . . . 35 4-2 Calculationsforsquaring . . . . . . . . . . . . . . . . . . . . . 41 4-3 CPUtimeforKaratsubamultiplication . . . . . . . . . . . . . . 49 4-4 Calculationalschemafordivision . . . . . . . . . . . . . . . . . 51 11-1 LayeringoftransformationsintheRijndaelrounds . . . . . . . . 246 11-2 DiagramforroundkeysforLk =4 . . . . . . . . . . . . . . . . 248 12-1 Periodicbehaviorofapseudorandomsequence . . . . . . . . . 263 17-1 Exampleoftheconstructionofacertificate . . . . . . . . . . . . 401 17-2 Certificationofadigitalsignature . . . . . . . . . . . . . . . . . 402 ix List of Tables 1-1 ArithmeticandnumbertheoryinCindirectoryflint/src . . . . . 7 1-2 Arithmeticmodulesin80x86assembler(seeChapter19)indirec- toryflint/src/asm . . . . . . . . . . . . . . . . . . . . . . . . . 7 1-3 Tests(seeSection13.2andChapter18)indirectoriesflint/testand flint/test/testvals . . . . . . . . . . . . . . . . . . . . . . . . . . 7 1-4 Librariesin80x86assembler(seeChapter19)indirectoriesflint/lib andflint/lib/dll . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1-5 RSAimplementation(seeChapter17)indirectoryflint/rsa . . . 8 3-1 FLINT/Cerrorcodes . . . . . . . . . . . . . . . . . . . . . . . . 21 5-1 Compositiontableforadditionmodulo5 . . . . . . . . . . . . . 71 5-2 Compositiontableformultiplicationmodulo5 . . . . . . . . . . 71 6-1 Requirementsforexponentiation . . . . . . . . . . . . . . . . . 88 6-2 Numbers of multiplications for typical sizes of exponents and variousbases2k . . . . . . . . . . . . . . . . . . . . . . . . . . 88 6-3 Valuesforthefactorizationoftheexponentdigitsintoproductsof apowerof2andanoddfactor . . . . . . . . . . . . . . . . . . . 90 6-4 Numbers of multiplications for typical sizes of exponents and variousbases2k . . . . . . . . . . . . . . . . . . . . . . . . . . 91 6-5 ExponentiationfunctionsinFLINT/C . . . . . . . . . . . . . . . 117 7-1 ValuesofaBooleanfunction . . . . . . . . . . . . . . . . . . . . 132 7-2 ValuesoftheCLINTfunctionand_l() . . . . . . . . . . . . . . . . 132 7-3 ValuesoftheCLINTfunctionor_l() . . . . . . . . . . . . . . . . 133 7-4 ValuesoftheCLINTfunctionxor_l() . . . . . . . . . . . . . . . . 133 8-1 Diagnosticvaluesofthefunctionvcheck_l() . . . . . . . . . . . 154 10-1 Thetenlargestknownprimes(asofDecember2004) . . . . . . . 215 10-2 Thenumberofprimesuptovariouslimitsx . . . . . . . . . . . 220 10-3 ThenumberkofpassesthroughtheMiller–Rabintesttoachieve probabilitiesoferrorlessthan2−80and2−100asafunctionofthe numberlofbinarydigits(after[DaLP]). . . . . . . . . . . . . . . 228 10-4 ApproximatecalculationtimesfortheAKStest,after[CrPa] . . . 234 F 11-1 Elementsof 23 . . . . . . . . . . . . . . . . . . . . . . . . . . 240 xi