Tải bản đầy đủ (.pdf) (772 trang)

Apress cryptography in c and c++(2001)

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.12 MB, 772 trang )

Team-Fly

CryptographyinCand
C++
ISBN:189311595x
byMichael
Welschenbach
Apress?2001(432pages)
Abehind-the-scenes
examinationofbinary
cryptography,fromthe
simple"modulo"andshift
operationstocomplex
algorithmslikeRSA.
TableofContents
CryptographyinCandC++
Prefaceto - theTranslationoftheSecondEdition
Prefaceto - theFirstEdition
PartI-ArithmeticandNumberTheoryinC

Chapter1
Chapter2
Chapter3
Chapter4
Chapter5
Chapter6

- Introduction
NumberFormats:TheRepresentationof
LargeNumbersinC
- InterfaceSemantics


- TheFundamentalOperations
ModularArithmetic:Calculatingwith
ResidueClasses
WhereAllRoadsMeet:Modular
Exponentiation


Chapter7
Chapter8
Chapter9
Chapter10
Chapter11
Chapter12

- BitwiseandLogicalFunctions
- Input,Output,Assignment,Conversion
- DynamicRegisters
- BasicNumber-TheoreticFunctions
- LargeRandomNumbers
- StrategiesforTestingLINT

PartII-ArithmeticinC++withtheClassLINT

Chapter13 - LetC++SimplifyYourLife
TheLINTPublicInterface:Membersand
Chapter14 Friends
Chapter15 - ErrorHandling
AnApplicationExample:TheRSA
Chapter16 Cryptosystem
Chapter17 - DoItYourself:TestLINT

Chapter18 - ApproachesforFurtherExtensions
Rijndael:ASuccessortotheData
Chapter19 EncryptionStandard
PartIII-Appendices

AppendixA - DirectoryofCFunctions
AppendixB - DirectoryofC++Functions
AppendixC - Macros
AppendixD - CalculationTimes
AppendixE - Notation
AppendixF - ArithmeticandNumber-TheoreticPackages
References
Index
ListofFigures
ListofTables
ListofListings


Team-Fly


Team-Fly


BackCover
Detailedtreatmentofpublickeycryptographywith
detailedcoverageoftheRSAalgorithmthatisnow
inthepublicdomain
Explainsandincludesanimplementationof
Rijndael,thenewAmericanEncryptionStandardin

bothCandC++
Nottoycode(tm),butapracticaltreatmentof
moderncryptographicmethods
CryptographyinCandC++mainlyfocusesonthe
practicalaspectsinvolvedinimplementingpublickey
cryptographymethods,suchastheRSAalgorithmthat
wasrecentlyreleasedfrompatentprotection.Italso
givesbothatechnicaloverviewandanimplementation
oftheRijndaelalgorithmthatwasselectedasthe
AdvancedEncryptionStandardbytheU.S.
government.Welschenbachavoidscomplexitiesby
explainingcryptographyanditsmathematicalbasisin
termsaprogrammercaneasilyunderstand.
Thisbookoffersacomprehensive,yetrelentlessly
practicaloverviewofthefundamentalsofmodern
cryptography.Itincludesawide-ranginglibraryofcode
inCandC++,includingtheRSAalgorithm,completed
byanextensiveTestSuitethatprovesthatthecode
workscorrectly.Readerswilllearn,stepbystep,how
toimplementaplatformindependentlibraryforthe


all-importantmulti-precisionarithmeticusedinmodern
cryptography.Thisisfollowedbyanimplementationof
thecryptographicalgorithmsthemselves.
AbouttheAuthor
MichaelWelschenbachcurrentlyworksforSRCSecurity
Research&ConsultingGmbHinBonn,Germany.He
graduatedwithaMaster'sDegreeinMathematicsfrom
theUniversityofCologneandhasgainedextensive

experienceincryptologicalresearchovertheyears.
Currently,hisfavoriteprogramminglanguagesareC
andC++.Whennotworking,heenjoysspendingtime
withhiswifeandtwosons,programming,readingand
music.

Team-Fly




Team-Fly




CryptographyinCandC++
MICHAELWELSCHENBACH
TranslatedbyDAVIDKRAMER

Copyright©2001byMichaelWelschenbach
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-893115-95-X
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark

owner,withnointentionofinfringementofthetrademark.
EditorialDirectors:DanAppleman,GaryCornell,KarenWatterson
TranslatorandCompositor:DavidKramer
Proofreader:AnneFriedman
TEXSupport:FredBartlettandArthurOgawa
CoverDesigner:KarlMiyajima
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY,10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany
IntheUnitedStates,phone1-800-SPRINGER;
<>;

OutsidetheUnitedStates,contact<>;


;fax+496221345229
Forinformationontranslations,pleasecontactApressdirectlyat901
GraysonStreet,Suite204,Berkeley,CA,94710
Phone:510-549-5937;Fax:510-549-5939;<>;

Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthornorApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
ForHelga,Daniel,andLukas,fromwhomIborrowedthetimeforwriting
thisbook
Team-Fly





Team-Fly




PrefacetotheTranslationoftheSecondEdition
WhenIhavetowrestlewithfigures,IfeelI'dliketostuffmyselfintoa
holeintheground,soIcan'tseeanything.IfIraisemyeyesandsee
thesea,oratree,orawoman—evenifshe'sanold'un—dammeif
allthesumsandfiguresdon'tgotoblazes.TheygrowwingsandI
havetochase'em.
—NikosKazanzakis,ZorbatheGreek
THESECONDEDITIONhasbeenrevisedandexpandedinanumberof
ways.Additionalexamplesofcryptographicalgorithmshavebeenadded,
suchastheproceduresofRabinandElGamal,andintherealizationof
theRSAprocedurethehashfunctionRIPEMD-160andformatting
accordingtoPKCS#1havebeenadopted.Thereisalsoadiscussionof
possiblesourcesoferrorthatcouldleadtoaweakeningofthe
procedure.Thetexthasbeenexpandedorclarifiedatanumberof
points,anderrorshavebeencorrected.Additionally,certaindidactic
strategieshavebeenstrengthened,withtheresultthatsomeofthe
programsontheCD-ROMdifferincertaindetailsfromthosepresentedin
thebook.Notalltechnicaldetailsareofequalimportance,andthedesire
forfastandefficientcodeisnotalwayscompatiblewithattractiveand
easy-to-readprograms.
Andspeakingofefficiency,inAppendixDrunningtimesarecomparedto
thoseforcertainfunctionsintheGNUMultiprecisionLibrary.Inthis

comparisontheFLINT/Cexponentiationroutinedidnotdoatallbadly.As
afurtherextension,AppendixFprovidesreferencestosomearithmetic
andnumber-theoreticpackages.
Thesoftwarehasbeenexpandedbyseveralfunctionsandinplaceshas
beensignificantlyoverhauled,andintheprocessanumberoferrorsand
pointsofimprecisionwereremoved.Additionaltestfunctionswere
developedandexistingtestfunctionsexpanded.Asecuritymodewas
implemented,wherebysecurity-criticalvariablesintheindividual
functionsaredeletedbybeingoverwritten.AllCandC++functionsare
nowclearlycitedandannotatedintheappendices.


Sincecurrentcompilersrepresentvaryingstagesofdevelopmentofthe
C++standard,theC++modulesoftheFLINT/Cpackagehavebeenset
upinsuchawaythatbothtraditionalC++headerfilesoftheform
xxxxx.handthenewANSIheaderfilescanbeused.Forthesame
reasontheuseoftheoperatornew()hasbeenchecked,asalways,as
towhetherthenullpointerisreturned.Thistypeoferrorhandlingdoes
notmakeuseoftheANSIstandardexceptions,butitnonetheless
functionswithcurrentcompilers,whilethemethodthatconformstothe
standard,bywhichnew()generatesanerrorviathrow(),isnot
universallyavailable.
Althoughthefocusofthisbookisthefundamentalsofasymmetric
cryptography,therecentnominationofRijndaelbytheAmericanNational
InstituteofStandardsandTechnology(NIST)tobetheadvanced
encryptionstandard(AES)encouragedmetoincludeafinalchapter
(Chapter19)withanextensivedescriptionofthisalgorithm.Iam
indebtedtoGaryCornell,atApress,forbringingupthesubjectand
convincingmethatthiswouldbeaworthwhilecomplementtothetopics
ofthisbook.IwouldliketothankVincentRijmen,AntoonBosselaers,

PauloBarreto,andBrianGladmanfortheirkindpermissiontoincludethe
sourcecodefortheirRijndaelimplementationsontheCD-ROMthat
accompaniesthisbook.
Iwishtothankallthereadersofthefirstedition,particularlythosewho
callederrorstomyattention,madecomments,orsuggested
improvements.Alltheircommunicationsweremostwelcome.Asalways,
theauthorassumesallresponsibilityforerrorsthatmayyetremaininthe
textorthesoftware,aswellasforanynewerrorsthatmayhavecreptin.
IoffermyheartfeltthankstoGaryCornell,atApress,andagainto
HermannEngesser,DorotheaGlaunsinger,andUlrikeStricker,at
Springer-Verlag,fortheirunstintingcommitmentandfriendly
collaboration.
Iamdeeplygratefultomytranslator,DavidKramer,whohascontributed
withdistinguishedexpertiseandindefatigablededicationmanyvaluable
hints,whichhavebeenincorporatedintotheGermaneditionofthisbook
aswell.


Warning
Beforemakinguseoftheprogramscontainedinthisbookpleasereferto
themanualsandtechnicalintroductionsfortherelevantsoftwareand
computers.Neithertheauthornorthepublisheracceptsany
responsibilityforlossesduetoimproperexecutionoftheinstructionsand
programscontainedinthisbookorduetoerrorsinthetextorinthe
programsthatdespitecarefulcheckingmayremain.Theprogramsonthe
accompanyingCD-ROMareprotectedbycopyrightandmaynotbe
reproducedwithoutpermissionofthepublisher.
Team-Fly





Team-Fly




Disclaimer
Inthisbookfrequentuseismadeoftheterm"leadingzeros."Theuseof
thistermisinnowaytobeconstruedasalludingtoanypersonor
persons,inpublicorprivatelife,livingordead,andanysuch
correspondenceisentirelycoincidental.
Team-Fly




Team-Fly




Translator'sNote
Thepleasanttaskoftranslatingthisexcellentbook
(Übersetzungsvergnügung)wasmadeevenmorepleasantbythehelpful
andfriendlycollaborationoftheauthor.WheneverIfoundmyself
entangledinthebriarpatchofGermansyntax,Isimplylaunchedaquery
acrossthereachesofcyberspace,andsoonthereafterIreceiveda
messagefromMichaelWelschenbachprovidingthenecessary
decryptionalgorithm.

Team-Fly




Team-Fly




PrefacetotheFirstEdition
Mathematicsisthequeenofthesciences,andnumbertheoryisthe
queenofmathematics.Frequently,shedeignstoassistastronomy
andotherofthenaturalsciences,butprimacyisdueherunderall
circumstances.
—CarlFriedrichGauss
WHYDOWENEEDabookoncryptographywhoseprincipalfocusisthe
arithmeticofwholenumbers—theintegers—anditsapplicationto
computerprogramming?Isthisnotaratherinsignificantsubjectin
comparisontotheimportantproblemswithwhichcomputerscience
generallyinvolvesitself?Solongasoneconfinesoneselftotherangeof
numbersthatcanberepresentedbythestandardnumericaltypesofa
programminglanguage,arithmeticisarathersimpleaffair,andthe
familiararithmeticoperationsmaketheirtraditionalappearancesin
programsaccompaniedbythefamiliarsymbols+,−,/,*.
Butifonerequiresresultswhoselengthfarexceedswhatcanbe
expressedin16or32bits,thenthesituationbeginstogetinteresting.
Eventhebasicarithmeticoperationsarenolongeravailableforsuch
numbers,andonegetsnowherewithoutfirstinvestingconsiderableeffort
insolvingproblemsthatneverevenseemedlikeproblemsbefore.

Anyonewhoinvestigatesproblemsinnumbertheory,whether
professionallyorasahobby,inparticularthetopicofcontemporary
cryptography,isfamiliarwithsuchissues:Thetechniquesofdoing
arithmeticthatwelearnedinschoolnowdemandrenewedattention,and
wefindourselvessometimesdealingwithincrediblyinvolvedprocesses.
Thereaderwhowishestodevelopprogramsintheseareasandisnot
inclinedtoreinventthewheelwillfindincludedwiththisbookasuiteof
functionsthatwillserveasanextensionofCandC++forcalculatingwith
largeintegers.Wearenottalkingabout"toy"examplesthatsay,"thisis
howitworksinprinciple,"butacompletecollectionoffunctionsand
methodsthatsatisfytheprofessionalrequirementsofstability,
performance,andasoundtheoreticalbasis.


Makingtheconnectionbetweentheoryandpracticeisthegoalofthis
book,thatis,toclosethegapbetweenthetheoreticalliteratureand
practicalprogrammingproblems.Inthechaptersaheadweshalldevelop
stepbystepthefundamentalcalculationalprinciplesforlargenatural
numbers,arithmeticinfiniteringsandfields,andthemorecomplex
functionsofelementarynumbertheory,andweshallelucidatethemany
andvariouspossibilitiesforapplyingtheseprinciplestomodern
cryptography.Themathematicalfundamentalswillbeexplainedtothe
extentnecessaryforunderstandingtheprogramsthatarepresented
here,andforthoseinterestedinpursuingthesemattersfurtherthereare
extensivereferencestotheliterature.Thefunctionsthatwedevelopwill
thenbebroughttogetherandextensivelytested,resultinginausefuland
comprehensiveprogramminginterface.
Beginningwiththerepresentationoflargenumbers,inthefollowing
chaptersweshallfirstdealwiththefundamentalsofcomputation.For
addition,subtraction,multiplication,anddivisionoflargenumberswe

shallcreatepowerfulbasicfunctions.Buildingonthese,weshallexplain
modulararithmeticinresidueclassesandimplementtherelevant
operationsinlibraryfunctions.Aseparatechapterisdevotedtothetimeintensiveprocessofexponentiation,wherewedevelopandprogram
variousspecializedalgorithmsforanumberofapplicationsinmodular
arithmetic.
Afterextensivepreparation,whichincludesinputandoutputoflarge
numbersandtheirconversionintovariousbases,westudyalgorithmsof
elementarynumbertheoryusingthebasicarithmeticfunctions,andwe
thendevelopprograms,beginningwiththecalculationofthegreatest
commondivisoroflargenumbers.Weshallthenmoveontosuch
problemsascalculatingtheLegendreandJacobisymbols,andinverses
andsquarerootsinfiniterings,andweshallalsobecomefamiliarwith
theChineseremaindertheoremanditsapplications.
Inconnectionwiththisweshallgointosomedetailabouttheprinciplesof
identifyinglargeprimenumbers,andweshallprogramapowerful
multistageprimalitytest.
Afurtherchapterisdevotedtothegenerationoflargerandomnumbers,


inwhichacryptographicallyusefulbitgeneratorisdevelopedandtested
withrespecttoitsstatisticalproperties.
Toendthefirstpartweshallconcernourselveswithtestingarithmetic
andotherfunctions.Todothisweshallderivespecialtestmethodsfrom
themathematicalrulesofarithmetic,andweshallconsiderthe
implementationofefficientexternaltools.
Thesubjectofthesecondpartisthestep-by-stepconstructionoftheC++
classLINT(LargeINTegers),inthecourseofwhichweshallembedthe
CfunctionsofthefirstpartintothesyntaxandsemanticsoftheobjectorientedprogramminglanguageC++.Weshallputparticularweighton
formattedinputandoutputofLINTobjectswithflexiblestreamfunctions
andmanipulators,aswellaserrorhandlingwithexceptions.The

elegancewithwhichalgorithmscanbeformulatedinC++isparticularly
impressivewhentheboundariesbetweenstandardtypesandlarge
numbersasLINTobjectsbegintodissolve,resultinginthesyntactic
closenesstotheimplementedalgorithmsandingreatclarityand
transparency.
Finally,weshalldemonstratetheapplicationofthemethodswehave
developedbyimplementinganextensiveRSAcryptosystemfor
encryptionandthecreationofdigitalsignatures.Intheprocessweshall
explainthetheoryoftheRSAprocedureanditsoperationasthemost
prominentrepresentativeofasymmetriccryptosystems,andinaselfcontainedexampleweshalldevelopanextensiblekernelforapplications
ofthisultramoderncryptographicprocessaccordingtotheobjectorientedprinciplesoftheprogramminglanguageC++.
Weshallroundallofthisoffwithaglimpseoffurtherpossibleextensions
ofthesoftwarelibrary.Asasmallhighlightattheendweshallpresent
fourfunctionsin80×86assemblylanguageformultiplicationanddivision,
whichwillimprovetheperformanceofoursoftware.AppendixDcontains
atableoftypicalcalculationtimeswithandwithouttheassembler
supplement.
Allreadersofthisbookareheartilyinvitedtojoinmeonthispath,or
perhaps—dependingonindividualinterest—tofocusonparticular


sectionsorchaptersandtryoutthefunctionspresentedthere.The
authorhopesthatitwillnotbetakenamissthathereferstohisreaders,
togetherwithhimself,as"we."Hehopestherebytoencouragethemto
takeanactiveroleinthisjourneythroughacutting-edgeareaof
mathematicsandcomputerscience,tofigurethingsoutforthemselves
andtakefromthisbookwhatisofgreatestbenefit.Asforthesoftware,
letthereadernotbelackinginambitiontoextendthescopeorspeedof
oneormorefunctionsthroughnewimplementations.
IwishtothankSpringer-VerlagandparticularlyHermannEngesser,

DorotheaGlaunsinger,andUlrikeStrickerfortheirinterestinthe
publicationofthisbookandfortheirfriendlyandactivecollaboration.The
manuscriptwasreviewedbyJörnGarbers,JosefvonHelden,Brigitte
Nebelung,JohannesUeberberg,andHelgaWelschenbach.Iofferthem
myheartfeltthanksfortheircriticalsuggestionsandimprovements,and
aboveallfortheircareandpatience.Ifdespiteallofoureffortssome
errorsremaininthetextorinthesoftware,theauthoralonebearsthe
responsibility.Iamextremelygratefultomyfriendsandcolleagues
RobertHammelrath,Franz-PeterHeider,DetlefKraus,andBrigitte
Nebelungfortheirinsightsintotheconnectionsbetweenmathematics
andcomputerscienceovermanyyearsofcollaborationthathavemeant
agreatdealtome.
Team-Fly




Team-Fly




PartI:ArithmeticandNumberTheoryinC


ChapterList
Chapter1:Introduction
Chapter2:NumberFormats:TheRepresentationofLargeNumbersin
C
Chapter3:InterfaceSemantics

Chapter4:TheFundamentalOperations
Chapter5:ModularArithmetic:CalculatingwithResidueClasses
Chapter6:WhereAllRoadsMeet:ModularExponentiation
Chapter7:BitwiseandLogicalFunctions
Chapter8:Input,Output,Assignment,Conversion
Chapter9:DynamicRegisters
Chapter10:BasicNumber-TheoreticFunctions
Chapter11:LargeRandomNumbers
Chapter12:StrategiesforTestingLINT

PartOverview
Hownecessaryarithmeticandtheentireartofmathematicsarecan
beeasilymeasured,inthatnothingcanbecreatedthatisnot
connectedwithprecisenumberandmeasurement,andno
independentartcanexistwithoutitsmeasuresandproportions.
—AdamRies:BookofCalculation,1574
Typographicalrulesformanipulatingnumeralsareactually
arithmeticalrulesforoperatingonnumbers.


—D.R.Hofstadter:Gödel,Escher,Bach:AnEternalGoldenBraid
Thehumanbrainwouldnolongerbeburdenedwithanythingthat
neededtobecalculated!Giftedpeoplewouldagainbeabletothink
insteadofscribblingnumbers.
—StenNadolny:TheDiscoveryofSlowness,trans.RalphFreedman

Team-Fly





×