pk.c 396 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902
  1. /* pk.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/internal.h>
  26. #ifndef WC_NO_RNG
  27. #include <wolfssl/wolfcrypt/random.h>
  28. #endif
  29. #ifdef HAVE_ECC
  30. #include <wolfssl/wolfcrypt/ecc.h>
  31. #endif
  32. #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  33. /* FIPS build has replaced ecc.h. */
  34. #define wc_ecc_key_get_priv(key) (&((key)->k))
  35. #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  36. #endif
  37. #if !defined(WOLFSSL_PK_INCLUDED)
  38. #ifndef WOLFSSL_IGNORE_FILE_WARN
  39. #warning pk.c does not need to be compiled separately from ssl.c
  40. #endif
  41. #else
  42. #ifndef NO_RSA
  43. #include <wolfssl/wolfcrypt/rsa.h>
  44. #endif
  45. #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) && defined(WOLFSSL_KEY_GEN) && \
  46. (!defined(HAVE_USER_RSA) || defined(HAVE_ECC) || \
  47. (!defined(NO_DSA) && !defined(HAVE_SELFTEST)))
  48. /* Forward declaration for wolfSSL_PEM_write_bio_DSA_PUBKEY.
  49. * Implementation in ssl.c.
  50. */
  51. static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key);
  52. #endif
  53. /*******************************************************************************
  54. * COMMON FUNCTIONS
  55. ******************************************************************************/
  56. /* Calculate the number of bytes require to represent a length value in ASN.
  57. *
  58. * @param [in] l Length value to use.
  59. * @return Number of bytes required to represent length value.
  60. */
  61. #define ASN_LEN_SIZE(l) \
  62. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  63. #if defined(OPENSSL_EXTRA)
  64. #ifndef NO_ASN
  65. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  66. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  67. /* Convert the PEM encoding in the buffer to DER.
  68. *
  69. * @param [in] pem Buffer containing PEM encoded data.
  70. * @param [in] pemSz Size of data in buffer in bytes.
  71. * @param [in] cb Password callback when PEM encrypted.
  72. * @param [in] pass NUL terminated string for passphrase when PEM
  73. * encrypted.
  74. * @param [in] keyType Type of key to match against PEM header/footer.
  75. * @param [out] keyFormat Format of key.
  76. * @param [out] der Buffer holding DER encoding.
  77. * @return Negative on failure.
  78. * @return Number of bytes consumed on success.
  79. */
  80. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  81. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  82. {
  83. #ifdef WOLFSSL_SMALL_STACK
  84. EncryptedInfo* info = NULL;
  85. #else
  86. EncryptedInfo info[1];
  87. #endif /* WOLFSSL_SMALL_STACK */
  88. wc_pem_password_cb* localCb = NULL;
  89. int ret = 0;
  90. if (cb != NULL) {
  91. localCb = cb;
  92. }
  93. else if (pass != NULL) {
  94. localCb = wolfSSL_PEM_def_callback;
  95. }
  96. #ifdef WOLFSSL_SMALL_STACK
  97. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  98. DYNAMIC_TYPE_ENCRYPTEDINFO);
  99. if (info == NULL) {
  100. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  101. ret = MEMORY_E;
  102. }
  103. #endif /* WOLFSSL_SMALL_STACK */
  104. if (ret == 0) {
  105. XMEMSET(info, 0, sizeof(EncryptedInfo));
  106. info->passwd_cb = localCb;
  107. info->passwd_userdata = pass;
  108. /* Do not strip PKCS8 header */
  109. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  110. info, keyFormat);
  111. if (ret < 0) {
  112. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  113. }
  114. }
  115. if (ret >= 0) {
  116. ret = (int)info->consumed;
  117. }
  118. #ifdef WOLFSSL_SMALL_STACK
  119. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  120. #endif
  121. return ret;
  122. }
  123. #endif
  124. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  125. #ifndef NO_BIO
  126. /* Read PEM data from a BIO and decode to DER in a new buffer.
  127. *
  128. * @param [in, out] bio BIO object to read with.
  129. * @param [in] cb Password callback when PEM encrypted.
  130. * @param [in] pass NUL terminated string for passphrase when PEM
  131. * encrypted.
  132. * @param [in] keyType Type of key to match against PEM header/footer.
  133. * @param [out] keyFormat Format of key.
  134. * @param [out] der Buffer holding DER encoding.
  135. * @return Negative on failure.
  136. * @return Number of bytes consumed on success.
  137. */
  138. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  139. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  140. {
  141. int ret;
  142. char* mem = NULL;
  143. int memSz;
  144. int alloced = 0;
  145. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  146. if (ret == 0) {
  147. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  148. /* Write left over data back to BIO if not a file BIO */
  149. if ((ret > 0) && ((memSz - ret) > 0) &&
  150. (bio->type != WOLFSSL_BIO_FILE)) {
  151. int res;
  152. res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  153. if (res != memSz - ret) {
  154. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  155. if (res < 0) {
  156. ret = res;
  157. }
  158. else {
  159. ret = MEMORY_E;
  160. }
  161. }
  162. }
  163. if (alloced) {
  164. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  165. }
  166. }
  167. return ret;
  168. }
  169. #endif /* !NO_BIO */
  170. #if !defined(NO_FILESYSTEM)
  171. /* Read PEM data from a file and decode to DER in a new buffer.
  172. *
  173. * @param [in] fp File pointer to read with.
  174. * @param [in] cb Password callback when PEM encrypted.
  175. * @param [in] pass NUL terminated string for passphrase when PEM
  176. * encrypted.
  177. * @param [in] keyType Type of key to match against PEM header/footer.
  178. * @param [out] keyFormat Format of key.
  179. * @param [out] der Buffer holding DER encoding.
  180. * @return Negative on failure.
  181. * @return Number of bytes consumed on success.
  182. */
  183. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  184. int keyType, int* keyFormat, DerBuffer** der)
  185. {
  186. int ret;
  187. char* mem = NULL;
  188. int memSz;
  189. ret = wolfssl_read_file(fp, &mem, &memSz);
  190. if (ret == 0) {
  191. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  192. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  193. }
  194. return ret;
  195. }
  196. #endif /* !NO_FILESYSTEM */
  197. #endif
  198. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) \
  199. && !defined(HAVE_USER_RSA)) || !defined(WOLFCRYPT_ONLY))
  200. /* Convert DER data to PEM in an allocated buffer.
  201. *
  202. * @param [in] der Buffer containing DER data.
  203. * @param [in] derSz Size of DER data in bytes.
  204. * @param [in] type Type of key being encoded.
  205. * @param [in] heap Heap hint for dynamic memory allocation.
  206. * @param [out] out Allocated buffer containing PEM.
  207. * @param [out] outSz Size of PEM encoding.
  208. * @return WOLFSSL_FAILURE on error.
  209. * @return WOLFSSL_SUCCESS on success.
  210. */
  211. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  212. void* heap, byte** out, int* outSz)
  213. {
  214. int ret = WOLFSSL_SUCCESS;
  215. int pemSz;
  216. byte* pem = NULL;
  217. (void)heap;
  218. pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
  219. if (pemSz < 0) {
  220. ret = WOLFSSL_FAILURE;
  221. }
  222. if (ret == WOLFSSL_SUCCESS) {
  223. pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  224. if (pem == NULL) {
  225. ret = WOLFSSL_FAILURE;
  226. }
  227. }
  228. if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, (word32)derSz, pem,
  229. (word32)pemSz, type) < 0)) {
  230. ret = WOLFSSL_FAILURE;
  231. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  232. pem = NULL;
  233. }
  234. *out = pem;
  235. *outSz = pemSz;
  236. return ret;
  237. }
  238. #ifndef NO_BIO
  239. /* Write the DER data as PEM into BIO.
  240. *
  241. * @param [in] der Buffer containing DER data.
  242. * @param [in] derSz Size of DER data in bytes.
  243. * @param [in, out] bio BIO object to write with.
  244. * @param [in] type Type of key being encoded.
  245. * @return WOLFSSL_FAILURE on error.
  246. * @return WOLFSSL_SUCCESS on success.
  247. */
  248. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  249. WOLFSSL_BIO* bio, int type)
  250. {
  251. int ret;
  252. int pemSz;
  253. byte* pem = NULL;
  254. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  255. if (ret == WOLFSSL_SUCCESS) {
  256. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  257. if (len != pemSz) {
  258. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  259. ret = WOLFSSL_FAILURE;
  260. }
  261. }
  262. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  263. return ret;
  264. }
  265. #endif
  266. #endif
  267. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \
  268. !defined(HAVE_USER_RSA)) || \
  269. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  270. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  271. #if !defined(NO_FILESYSTEM)
  272. /* Write the DER data as PEM into file pointer.
  273. *
  274. * @param [in] der Buffer containing DER data.
  275. * @param [in] derSz Size of DER data in bytes.
  276. * @param [in] fp File pointer to write with.
  277. * @param [in] type Type of key being encoded.
  278. * @param [in] heap Heap hint for dynamic memory allocation.
  279. * @return WOLFSSL_FAILURE on error.
  280. * @return WOLFSSL_SUCCESS on success.
  281. */
  282. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  283. XFILE fp, int type, void* heap)
  284. {
  285. int ret;
  286. int pemSz;
  287. byte* pem = NULL;
  288. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  289. if (ret == WOLFSSL_SUCCESS) {
  290. int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
  291. if (len != pemSz) {
  292. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  293. ret = WOLFSSL_FAILURE;
  294. }
  295. }
  296. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  297. return ret;
  298. }
  299. #endif
  300. #endif
  301. #if defined(WOLFSSL_KEY_GEN) && \
  302. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  303. ((!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || defined(HAVE_ECC))
  304. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  305. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  306. void* heap, byte** out, int* outSz)
  307. {
  308. int ret = 1;
  309. byte* tmp = NULL;
  310. byte* cipherInfo = NULL;
  311. int pemSz = 0;
  312. /* Macro doesn't always use it. */
  313. (void)heap;
  314. /* Encrypt DER buffer if required. */
  315. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  316. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  317. byte *tmpBuf;
  318. /* Add space for padding. */
  319. tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
  320. DYNAMIC_TYPE_TMP_BUFFER);
  321. if (tmpBuf == NULL) {
  322. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  323. ret = 0; /* der buffer is free'd at the end of the function */
  324. }
  325. else {
  326. der = tmpBuf;
  327. /* Encrypt DER inline. */
  328. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  329. &cipherInfo, derSz + blockSz);
  330. if (ret != 1) {
  331. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  332. }
  333. }
  334. }
  335. if (ret == 1) {
  336. /* Calculate PEM encoding size. */
  337. pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
  338. if (pemSz <= 0) {
  339. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  340. ret = 0;
  341. }
  342. }
  343. if (ret == 1) {
  344. /* Allocate space for PEM encoding plus a NUL terminator. */
  345. tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
  346. if (tmp == NULL) {
  347. WOLFSSL_ERROR_MSG("malloc failed");
  348. ret = 0;
  349. }
  350. }
  351. if (ret == 1) {
  352. /* DER to PEM */
  353. pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
  354. cipherInfo, type);
  355. if (pemSz <= 0) {
  356. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  357. ret = 0;
  358. }
  359. }
  360. if (ret == 1) {
  361. /* NUL terminate string - PEM. */
  362. tmp[pemSz] = 0x00;
  363. /* Return allocated buffer and size. */
  364. *out = tmp;
  365. *outSz = pemSz;
  366. /* Don't free returning buffer. */
  367. tmp = NULL;
  368. }
  369. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  370. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  371. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  372. return ret;
  373. }
  374. #endif
  375. #endif /* !NO_ASN */
  376. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  377. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  378. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  379. /* Print the number bn in hex with name field and indentation indent to file fp.
  380. *
  381. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  382. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  383. *
  384. * @param [in] fp File pointer to write to.
  385. * @param [in] indent Number of spaces to prepend to each line.
  386. * @param [in] field Name of field.
  387. * @param [in] bn Big number to print.
  388. * @return 1 on success.
  389. * @return 0 on failure.
  390. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  391. * bn or NULL.
  392. */
  393. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  394. const WOLFSSL_BIGNUM* bn)
  395. {
  396. static const int HEX_INDENT = 4;
  397. static const int MAX_DIGITS_PER_LINE = 30;
  398. int ret = 1;
  399. int i = 0;
  400. char* buf = NULL;
  401. /* Internal function - assume parameters are valid. */
  402. /* Convert BN to hexadecimal character array (allocates buffer). */
  403. buf = wolfSSL_BN_bn2hex(bn);
  404. if (buf == NULL) {
  405. ret = 0;
  406. }
  407. if (ret == 1) {
  408. /* Print leading spaces, name and spaces before data. */
  409. if (indent > 0) {
  410. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  411. ret = 0;
  412. }
  413. }
  414. if (ret == 1) {
  415. if (XFPRINTF(fp, "%s:\n", field) < 0)
  416. ret = 0;
  417. }
  418. if (ret == 1) {
  419. if (indent > 0) {
  420. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  421. ret = 0;
  422. }
  423. }
  424. if (ret == 1) {
  425. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  426. ret = 0;
  427. }
  428. if (ret == 1) {
  429. /* Print first byte - should always exist. */
  430. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  431. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  432. ret = 0;
  433. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  434. ret = 0;
  435. }
  436. }
  437. if (ret == 1) {
  438. /* Print each hexadecimal character with byte separator. */
  439. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  440. /* Byte separator every two nibbles - one byte. */
  441. if (XFPRINTF(fp, ":") < 0) {
  442. ret = 0;
  443. break;
  444. }
  445. /* New line after every 15 bytes - 30 nibbles. */
  446. if (i % MAX_DIGITS_PER_LINE == 0) {
  447. if (XFPRINTF(fp, "\n") < 0) {
  448. ret = 0;
  449. break;
  450. }
  451. if (indent > 0) {
  452. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  453. ret = 0;
  454. break;
  455. }
  456. }
  457. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  458. ret = 0;
  459. break;
  460. }
  461. }
  462. /* Print two nibbles - one byte. */
  463. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  464. ret = 0;
  465. break;
  466. }
  467. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  468. ret = 0;
  469. break;
  470. }
  471. }
  472. /* Ensure on new line after data. */
  473. if (XFPRINTF(fp, "\n") < 0) {
  474. ret = 0;
  475. }
  476. }
  477. /* Dispose of any allocated character array. */
  478. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  479. return ret;
  480. }
  481. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  482. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  483. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA) && \
  484. !defined(HAVE_FAST_RSA)
  485. /* snprintf() must be available */
  486. /* Maximum number of extra indent spaces on each line. */
  487. #define PRINT_NUM_MAX_INDENT 48
  488. /* Maximum size of a line containing a value. */
  489. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  490. /* Number of leading spaces on each line. */
  491. #define PRINT_NUM_INDENT_CNT 4
  492. /* Indent spaces for number lines. */
  493. #define PRINT_NUM_INDENT " "
  494. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  495. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  496. /* Print indent to BIO.
  497. *
  498. * @param [in] bio BIO object to write to.
  499. * @param [in] line Buffer to put characters to before writing to BIO.
  500. * @param [in] lineLen Length of buffer.
  501. * @return 1 on success.
  502. * @return 0 on failure.
  503. */
  504. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  505. int indent)
  506. {
  507. int ret = 1;
  508. if (indent > 0) {
  509. /* Print indent spaces. */
  510. int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
  511. if (len_wanted >= lineLen) {
  512. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  513. ret = 0;
  514. }
  515. else {
  516. /* Write indents string to BIO */
  517. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  518. ret = 0;
  519. }
  520. }
  521. }
  522. return ret;
  523. }
  524. /* Print out name, and value in decimal and hex to BIO.
  525. *
  526. * @param [in] bio BIO object to write to.
  527. * @param [in] value MP integer to write.
  528. * @param [in] name Name of value.
  529. * @param [in] indent Number of leading spaces before line.
  530. * @return 1 on success.
  531. * @return 0 on failure.
  532. */
  533. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  534. const char* name, int indent)
  535. {
  536. int ret = 1;
  537. int len;
  538. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  539. /* Get the length of hex encoded value. */
  540. len = mp_unsigned_bin_size(value);
  541. /* Value must no more than 32-bits - 4 bytes. */
  542. if ((len < 0) || (len > 4)) {
  543. WOLFSSL_ERROR_MSG("Error getting exponent size");
  544. ret = 0;
  545. }
  546. if (ret == 1) {
  547. /* Print any indent spaces. */
  548. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  549. }
  550. if (ret == 1) {
  551. /* Get 32-bits of value. */
  552. word32 v = (word32)value->dp[0];
  553. /* Print the line to the string. */
  554. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  555. v);
  556. if (len >= (int)sizeof(line)) {
  557. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  558. ret = 0;
  559. } else {
  560. /* Write string to BIO */
  561. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  562. ret = 0;
  563. }
  564. }
  565. }
  566. return ret;
  567. }
  568. /* Print out name and multi-precision number to BIO.
  569. *
  570. * @param [in] bio BIO object to write to.
  571. * @param [in] num MP integer to write.
  572. * @param [in] name Name of value.
  573. * @param [in] indent Number of leading spaces before each line.
  574. * @return 1 on success.
  575. * @return 0 on failure.
  576. */
  577. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  578. int indent)
  579. {
  580. int ret = 1;
  581. int rawLen = 0;
  582. byte* rawKey = NULL;
  583. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  584. int li = 0; /* Line index. */
  585. int i;
  586. /* Allocate a buffer to hold binary encoded data. */
  587. rawLen = mp_unsigned_bin_size(num);
  588. if (rawLen == 0) {
  589. WOLFSSL_ERROR_MSG("Invalid number");
  590. ret = 0;
  591. }
  592. if (ret == 1) {
  593. rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  594. if (rawKey == NULL) {
  595. WOLFSSL_ERROR_MSG("Memory allocation error");
  596. ret = 0;
  597. }
  598. }
  599. /* Encode number as big-endian byte array. */
  600. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  601. ret = 0;
  602. }
  603. if (ret == 1) {
  604. /* Print any indent spaces. */
  605. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  606. }
  607. if (ret == 1) {
  608. /* Print header string line to string. */
  609. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  610. if (li >= (int)sizeof(line)) {
  611. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  612. ret = 0;
  613. }
  614. else {
  615. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  616. ret = 0;
  617. }
  618. }
  619. }
  620. if (ret == 1) {
  621. /* Print any indent spaces. */
  622. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  623. }
  624. if (ret == 1) {
  625. /* Start first digit line with spaces.
  626. * Writing out zeros ensures number is a positive value. */
  627. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  628. mp_leading_bit(num) ? "00:" : "");
  629. if (li >= (int)sizeof(line)) {
  630. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  631. ret = 0;
  632. }
  633. }
  634. /* Put out each line of numbers. */
  635. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  636. /* Encode another byte as 2 hex digits and append colon. */
  637. int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
  638. "%02x:", rawKey[i]);
  639. /* Check if there was room -- if not, print the current line, not
  640. * including the newest octet.
  641. */
  642. if (len_wanted >= (int)sizeof(line) - li) {
  643. /* bump current octet to the next line. */
  644. --i;
  645. /* More bytes coming so add a line break. */
  646. line[li++] = '\n';
  647. /* Write out the line. */
  648. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  649. ret = 0;
  650. }
  651. if (ret == 1) {
  652. /* Print any indent spaces. */
  653. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  654. }
  655. /* Put the leading spaces on new line. */
  656. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  657. li = PRINT_NUM_INDENT_CNT;
  658. }
  659. else {
  660. li += len_wanted;
  661. }
  662. }
  663. if (ret == 1) {
  664. /* Put out last line - replace last colon with carriage return. */
  665. line[li-1] = '\n';
  666. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  667. ret = 0;
  668. }
  669. }
  670. /* Dispose of any allocated data. */
  671. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  672. return ret;
  673. }
  674. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA && !HAVE_FAST_RSA */
  675. #if !defined(NO_RSA) || (!defined(NO_DH) && !defined(NO_CERTS) && \
  676. defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || defined(HAVE_ECC)
  677. /* Uses the DER SEQUENCE to determine size of DER data.
  678. *
  679. * Outer SEQUENCE encapsulates all the DER encoding.
  680. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  681. *
  682. * @param [in] seq Buffer holding DER encoded sequence.
  683. * @param [in] len Length of data in buffer (may be larger than SEQ).
  684. * @return Size of complete DER encoding on success.
  685. * @return 0 on failure.
  686. */
  687. static int wolfssl_der_length(const unsigned char* seq, int len)
  688. {
  689. int ret = 0;
  690. word32 i = 0;
  691. /* Check it is a SEQUENCE and get the length of the underlying data.
  692. * i is updated to be after SEQUENCE header bytes.
  693. */
  694. if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
  695. /* Add SEQUENCE header length to underlying data length. */
  696. ret += (int)i;
  697. }
  698. return ret;
  699. }
  700. #endif /* !NO_RSA */
  701. #endif /* OPENSSL_EXTRA */
  702. /*******************************************************************************
  703. * START OF RSA API
  704. ******************************************************************************/
  705. #ifndef NO_RSA
  706. /*
  707. * RSA METHOD
  708. * Could be used to hold function pointers to implementations of RSA operations.
  709. */
  710. #if defined(OPENSSL_EXTRA)
  711. /* Return a blank RSA method and set the name and flags.
  712. *
  713. * Only one implementation of RSA operations.
  714. * name is duplicated.
  715. *
  716. * @param [in] name Name to use in method.
  717. * @param [in] flags Flags to set into method.
  718. * @return Newly allocated RSA method on success.
  719. * @return NULL on failure.
  720. */
  721. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  722. {
  723. WOLFSSL_RSA_METHOD* meth = NULL;
  724. int name_len = 0;
  725. int err;
  726. /* Validate name is not NULL. */
  727. err = (name == NULL);
  728. if (!err) {
  729. /* Allocate an RSA METHOD to return. */
  730. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  731. DYNAMIC_TYPE_OPENSSL);
  732. err = (meth == NULL);
  733. }
  734. if (!err) {
  735. XMEMSET(meth, 0, sizeof(*meth));
  736. meth->flags = flags;
  737. meth->dynamic = 1;
  738. name_len = (int)XSTRLEN(name);
  739. meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL,
  740. DYNAMIC_TYPE_OPENSSL);
  741. err = (meth->name == NULL);
  742. }
  743. if (!err) {
  744. XMEMCPY(meth->name, name, (size_t)(name_len + 1));
  745. }
  746. if (err) {
  747. /* meth->name won't be allocated on error. */
  748. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  749. meth = NULL;
  750. }
  751. return meth;
  752. }
  753. /* Default RSA method is one with wolfSSL name and no flags.
  754. *
  755. * @return Newly allocated wolfSSL RSA method on success.
  756. * @return NULL on failure.
  757. */
  758. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  759. {
  760. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  761. 0, /* No flags. */
  762. (char*)"wolfSSL RSA",
  763. 0 /* Static definition. */
  764. };
  765. return &wolfssl_rsa_meth;
  766. }
  767. /* Dispose of RSA method and allocated data.
  768. *
  769. * @param [in] meth RSA method to free.
  770. */
  771. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  772. {
  773. /* Free method if available and dynamically allocated. */
  774. if ((meth != NULL) && meth->dynamic) {
  775. /* Name was duplicated and must be freed. */
  776. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  777. /* Dispose of RSA method. */
  778. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  779. }
  780. }
  781. #ifndef NO_WOLFSSL_STUB
  782. /* Stub function for any RSA method setting function.
  783. *
  784. * Nothing is stored - not even flags or name.
  785. *
  786. * @param [in] meth RSA method.
  787. * @param [in] p A pointer.
  788. * @return 1 to indicate success.
  789. */
  790. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  791. {
  792. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  793. (void)meth;
  794. (void)p;
  795. return 1;
  796. }
  797. #endif /* !NO_WOLFSSL_STUB */
  798. #endif /* OPENSSL_EXTRA */
  799. /*
  800. * RSA constructor/deconstructor APIs
  801. */
  802. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  803. /* Dispose of RSA key and allocated data.
  804. *
  805. * Cannot use rsa after this call.
  806. *
  807. * @param [in] rsa RSA key to free.
  808. */
  809. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  810. {
  811. int doFree = 1;
  812. WOLFSSL_ENTER("wolfSSL_RSA_free");
  813. /* Validate parameter. */
  814. if (rsa == NULL) {
  815. doFree = 0;
  816. }
  817. if (doFree) {
  818. int err;
  819. /* Decrement reference count. */
  820. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  821. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  822. (void)err;
  823. #endif
  824. }
  825. if (doFree) {
  826. void* heap = rsa->heap;
  827. /* Dispose of allocated reference counting data. */
  828. wolfSSL_RefFree(&rsa->ref);
  829. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  830. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  831. #endif
  832. if (rsa->internal != NULL) {
  833. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  834. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  835. /* Check if RNG is owned before freeing it. */
  836. if (rsa->ownRng) {
  837. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  838. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  839. wc_FreeRng(rng);
  840. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  841. }
  842. /* RNG isn't freed by wolfCrypt RSA free. */
  843. }
  844. #endif
  845. /* Dispose of allocated data in wolfCrypt RSA key. */
  846. wc_FreeRsaKey((RsaKey*)rsa->internal);
  847. /* Dispose of memory for wolfCrypt RSA key. */
  848. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  849. }
  850. /* Dispose of external representation of RSA values. */
  851. wolfSSL_BN_clear_free(rsa->iqmp);
  852. wolfSSL_BN_clear_free(rsa->dmq1);
  853. wolfSSL_BN_clear_free(rsa->dmp1);
  854. wolfSSL_BN_clear_free(rsa->q);
  855. wolfSSL_BN_clear_free(rsa->p);
  856. wolfSSL_BN_clear_free(rsa->d);
  857. wolfSSL_BN_free(rsa->e);
  858. wolfSSL_BN_free(rsa->n);
  859. #if defined(OPENSSL_EXTRA)
  860. if (rsa->meth) {
  861. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  862. }
  863. #endif
  864. /* Set back to NULLs for safety. */
  865. ForceZero(rsa, sizeof(*rsa));
  866. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  867. (void)heap;
  868. }
  869. }
  870. /* Allocate and initialize a new RSA key.
  871. *
  872. * Not OpenSSL API.
  873. *
  874. * @param [in] heap Heap hint for dynamic memory allocation.
  875. * @param [in] devId Device identifier value.
  876. * @return RSA key on success.
  877. * @return NULL on failure.
  878. */
  879. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  880. {
  881. WOLFSSL_RSA* rsa = NULL;
  882. RsaKey* key = NULL;
  883. int err = 0;
  884. int rsaKeyInited = 0;
  885. WOLFSSL_ENTER("wolfSSL_RSA_new");
  886. /* Allocate memory for new wolfCrypt RSA key. */
  887. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  888. if (key == NULL) {
  889. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  890. err = 1;
  891. }
  892. if (!err) {
  893. /* Allocate memory for new RSA key. */
  894. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  895. DYNAMIC_TYPE_RSA);
  896. if (rsa == NULL) {
  897. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  898. err = 1;
  899. }
  900. }
  901. if (!err) {
  902. /* Clear all fields of RSA key. */
  903. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  904. /* Cache heap to use for all allocations. */
  905. rsa->heap = heap;
  906. #ifdef OPENSSL_EXTRA
  907. /* Always have a method set. */
  908. rsa->meth = wolfSSL_RSA_get_default_method();
  909. #endif
  910. /* Initialize reference counting. */
  911. wolfSSL_RefInit(&rsa->ref, &err);
  912. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  913. }
  914. if (!err) {
  915. #endif
  916. /* Initialize wolfCrypt RSA key. */
  917. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  918. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  919. err = 1;
  920. }
  921. else {
  922. rsaKeyInited = 1;
  923. }
  924. }
  925. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  926. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  927. if (!err) {
  928. WC_RNG* rng;
  929. /* Create a local RNG. */
  930. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  931. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  932. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  933. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  934. rng = NULL;
  935. }
  936. rsa->ownRng = 1;
  937. if (rng == NULL) {
  938. /* Get the wolfSSL global RNG - not thread safe. */
  939. rng = wolfssl_get_global_rng();
  940. rsa->ownRng = 0;
  941. }
  942. if (rng == NULL) {
  943. /* Couldn't create global either. */
  944. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  945. err = 1;
  946. }
  947. else {
  948. /* Set the local or global RNG into the wolfCrypt RSA key. */
  949. (void)wc_RsaSetRNG(key, rng);
  950. /* Won't fail as key and rng are not NULL. */
  951. }
  952. }
  953. #endif /* !HAVE_FIPS && !HAVE_USER_RSA && !HAVE_FAST_RSA &&
  954. * WC_RSA_BLINDING */
  955. if (!err) {
  956. /* Set wolfCrypt RSA key into RSA key. */
  957. rsa->internal = key;
  958. /* Data from external RSA key has not been set into internal one. */
  959. rsa->inSet = 0;
  960. }
  961. if (err) {
  962. /* Dispose of any allocated data on error. */
  963. /* No failure after RNG allocation - no need to free RNG. */
  964. if (rsaKeyInited) {
  965. wc_FreeRsaKey(key);
  966. }
  967. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  968. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  969. /* Return NULL. */
  970. rsa = NULL;
  971. }
  972. return rsa;
  973. }
  974. /* Allocate and initialize a new RSA key.
  975. *
  976. * @return RSA key on success.
  977. * @return NULL on failure.
  978. */
  979. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  980. {
  981. /* Call wolfSSL API to do work. */
  982. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  983. }
  984. /* Increments ref count of RSA key.
  985. *
  986. * @param [in, out] rsa RSA key.
  987. * @return 1 on success
  988. * @return 0 on error
  989. */
  990. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  991. {
  992. int err = 0;
  993. if (rsa != NULL) {
  994. wolfSSL_RefInc(&rsa->ref, &err);
  995. }
  996. return !err;
  997. }
  998. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  999. #ifdef OPENSSL_EXTRA
  1000. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1001. /* Allocate a new RSA key and make it a copy.
  1002. *
  1003. * Encodes to and from DER to copy.
  1004. *
  1005. * @param [in] rsa RSA key to duplicate.
  1006. * @return RSA key on success.
  1007. * @return NULL on error.
  1008. */
  1009. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1010. {
  1011. WOLFSSL_RSA* ret = NULL;
  1012. int derSz = 0;
  1013. byte* derBuf = NULL;
  1014. int err;
  1015. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1016. err = (rsa == NULL);
  1017. if (!err) {
  1018. /* Create a new RSA key to return. */
  1019. ret = wolfSSL_RSA_new();
  1020. if (ret == NULL) {
  1021. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1022. err = 1;
  1023. }
  1024. }
  1025. if (!err) {
  1026. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1027. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1028. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1029. err = 1;
  1030. }
  1031. }
  1032. if (!err) {
  1033. /* Decode DER of the RSA public key into new key. */
  1034. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1035. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1036. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1037. err = 1;
  1038. }
  1039. }
  1040. /* Dispose of any allocated DER buffer. */
  1041. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1042. if (err) {
  1043. /* Disposes of any created RSA key - on error. */
  1044. wolfSSL_RSA_free(ret);
  1045. ret = NULL;
  1046. }
  1047. return ret;
  1048. }
  1049. /* wolfSSL_RSAPrivateKey_dup not supported */
  1050. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1051. #ifndef HAVE_USER_RSA
  1052. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1053. void* heap);
  1054. #endif
  1055. /*
  1056. * RSA to/from bin APIs
  1057. */
  1058. /* Convert RSA public key data to internal.
  1059. *
  1060. * Creates new RSA key from the DER encoded RSA public key.
  1061. *
  1062. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1063. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1064. * @param [in] derSz Length of the data in the DER buffer.
  1065. * @return RSA key on success.
  1066. * @return NULL on failure.
  1067. */
  1068. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1069. const unsigned char **derBuf, long derSz)
  1070. {
  1071. WOLFSSL_RSA *rsa = NULL;
  1072. int err = 0;
  1073. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1074. /* Validate parameters. */
  1075. if (derBuf == NULL) {
  1076. WOLFSSL_ERROR_MSG("Bad argument");
  1077. err = 1;
  1078. }
  1079. /* Create a new RSA key to return. */
  1080. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1081. WOLFSSL_ERROR_MSG("RSA_new failed");
  1082. err = 1;
  1083. }
  1084. /* Decode RSA key from DER. */
  1085. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1086. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1087. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1088. err = 1;
  1089. }
  1090. if ((!err) && (out != NULL)) {
  1091. /* Return through parameter too. */
  1092. *out = rsa;
  1093. /* Move buffer on by the used amount. */
  1094. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1095. }
  1096. if (err) {
  1097. /* Dispose of any created RSA key. */
  1098. wolfSSL_RSA_free(rsa);
  1099. rsa = NULL;
  1100. }
  1101. return rsa;
  1102. }
  1103. /* Convert RSA private key data to internal.
  1104. *
  1105. * Create a new RSA key from the DER encoded RSA private key.
  1106. *
  1107. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1108. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1109. * @param [in] derSz Length of the data in the DER buffer.
  1110. * @return RSA key on success.
  1111. * @return NULL on failure.
  1112. */
  1113. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1114. const unsigned char **derBuf, long derSz)
  1115. {
  1116. WOLFSSL_RSA *rsa = NULL;
  1117. int err = 0;
  1118. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1119. /* Validate parameters. */
  1120. if (derBuf == NULL) {
  1121. WOLFSSL_ERROR_MSG("Bad argument");
  1122. err = 1;
  1123. }
  1124. /* Create a new RSA key to return. */
  1125. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1126. WOLFSSL_ERROR_MSG("RSA_new failed");
  1127. err = 1;
  1128. }
  1129. /* Decode RSA key from DER. */
  1130. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1131. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1132. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1133. err = 1;
  1134. }
  1135. if ((!err) && (out != NULL)) {
  1136. /* Return through parameter too. */
  1137. *out = rsa;
  1138. /* Move buffer on by the used amount. */
  1139. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1140. }
  1141. if (err) {
  1142. /* Dispose of any created RSA key. */
  1143. wolfSSL_RSA_free(rsa);
  1144. rsa = NULL;
  1145. }
  1146. return rsa;
  1147. }
  1148. #if defined(OPENSSL_EXTRA) && !defined(HAVE_USER_RSA) && \
  1149. !defined(HAVE_FAST_RSA)
  1150. /* Converts an internal RSA structure to DER format for the private key.
  1151. *
  1152. * If "pp" is null then buffer size only is returned.
  1153. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1154. * responsible for free'ing it.
  1155. *
  1156. * @param [in] rsa RSA key.
  1157. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1158. * May be NULL.
  1159. * On out, newly allocated buffer or pointer to byte after
  1160. * encoding in passed in buffer.
  1161. *
  1162. * @return Size of DER encoding on success
  1163. * @return BAD_FUNC_ARG when rsa is NULL.
  1164. * @return 0 on failure.
  1165. */
  1166. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1167. {
  1168. int ret;
  1169. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1170. /* Validate parameters. */
  1171. if (rsa == NULL) {
  1172. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1173. ret = BAD_FUNC_ARG;
  1174. }
  1175. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1176. * No heap hint as this gets returned to the user */
  1177. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1178. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1179. ret = 0;
  1180. }
  1181. /* Size of DER encoding. */
  1182. return ret;
  1183. }
  1184. /* Converts an internal RSA structure to DER format for the public key.
  1185. *
  1186. * If "pp" is null then buffer size only is returned.
  1187. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1188. * responsible for free'ing it.
  1189. *
  1190. * @param [in] rsa RSA key.
  1191. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1192. * May be NULL.
  1193. * On out, newly allocated buffer or pointer to byte after
  1194. * encoding in passed in buffer.
  1195. * @return Size of DER encoding on success
  1196. * @return BAD_FUNC_ARG when rsa is NULL.
  1197. * @return 0 on failure.
  1198. */
  1199. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1200. {
  1201. int ret;
  1202. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1203. /* check for bad functions arguments */
  1204. if (rsa == NULL) {
  1205. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1206. ret = BAD_FUNC_ARG;
  1207. }
  1208. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1209. * No heap hint as this gets returned to the user */
  1210. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1211. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1212. ret = 0;
  1213. }
  1214. return ret;
  1215. }
  1216. #endif /* defined(OPENSSL_EXTRA) && !defined(HAVE_USER_RSA) &&
  1217. * !defined(HAVE_FAST_RSA) */
  1218. #endif /* OPENSSL_EXTRA */
  1219. /*
  1220. * RSA to/from BIO APIs
  1221. */
  1222. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1223. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1224. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1225. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1226. !defined(HAVE_FAST_RSA) && !defined(NO_BIO)
  1227. /* Read DER data from a BIO.
  1228. *
  1229. * DER structures start with a constructed sequence. Use this to calculate the
  1230. * total length of the DER data.
  1231. *
  1232. * @param [in] bio BIO object to read from.
  1233. * @param [out] out Buffer holding DER encoding.
  1234. * @return Number of bytes to DER encoding on success.
  1235. * @return 0 on failure.
  1236. */
  1237. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1238. {
  1239. int err = 0;
  1240. unsigned char seq[MAX_SEQ_SZ];
  1241. unsigned char* der = NULL;
  1242. int derLen = 0;
  1243. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1244. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1245. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1246. err = 1;
  1247. }
  1248. /* Calculate complete DER encoding length. */
  1249. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1250. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1251. err = 1;
  1252. }
  1253. /* Allocate a buffer to read DER data into. */
  1254. if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap,
  1255. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1256. WOLFSSL_ERROR_MSG("Malloc failure");
  1257. err = 1;
  1258. }
  1259. if (!err) {
  1260. /* Calculate the unread amount. */
  1261. int len = derLen - (int)sizeof(seq);
  1262. /* Copy the previously read data into the buffer. */
  1263. XMEMCPY(der, seq, sizeof(seq));
  1264. /* Read rest of DER data from BIO. */
  1265. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1266. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1267. err = 1;
  1268. }
  1269. }
  1270. if (!err) {
  1271. /* Return buffer through parameter. */
  1272. *out = der;
  1273. }
  1274. if (err) {
  1275. /* Dispose of any allocated buffer on error. */
  1276. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1277. derLen = 0;
  1278. }
  1279. return derLen;
  1280. }
  1281. /* Reads the RSA private key data from a BIO to the internal form.
  1282. *
  1283. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1284. *
  1285. * @param [in] bio BIO object to read from.
  1286. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1287. * @return RSA key on success.
  1288. * @return NULL on failure.
  1289. */
  1290. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1291. {
  1292. WOLFSSL_RSA* key = NULL;
  1293. unsigned char* der = NULL;
  1294. int derLen = 0;
  1295. int err;
  1296. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1297. /* Validate parameters. */
  1298. err = (bio == NULL);
  1299. /* Read just DER encoding from BIO - buffer allocated in call. */
  1300. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1301. err = 1;
  1302. }
  1303. if (!err) {
  1304. /* Keep der for call to deallocate. */
  1305. const unsigned char* cder = der;
  1306. /* Create an RSA key from the data from the BIO. */
  1307. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1308. err = (key == NULL);
  1309. }
  1310. if ((!err) && (out != NULL)) {
  1311. /* Return the created RSA key through the parameter. */
  1312. *out = key;
  1313. }
  1314. if (err) {
  1315. /* Dispose of created key on error. */
  1316. wolfSSL_RSA_free(key);
  1317. key = NULL;
  1318. }
  1319. /* Dispose of allocated data. */
  1320. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1321. return key;
  1322. }
  1323. #endif /* defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) &&
  1324. * !defined(HAVE_FAST_RSA) && !NO_BIO */
  1325. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1326. /*
  1327. * RSA DER APIs
  1328. */
  1329. #ifdef OPENSSL_EXTRA
  1330. #ifndef HAVE_USER_RSA
  1331. /* Create a DER encoding of key.
  1332. *
  1333. * Not OpenSSL API.
  1334. *
  1335. * @param [in] rsa RSA key.
  1336. * @param [out] outBuf Allocated buffer containing DER encoding.
  1337. * May be NULL.
  1338. * @param [in] publicKey Whether to encode as public key.
  1339. * @param [in] heap Heap hint.
  1340. * @return Encoding size on success.
  1341. * @return Negative on failure.
  1342. */
  1343. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1344. void* heap)
  1345. {
  1346. byte* p = NULL;
  1347. int ret;
  1348. if (outBuf != NULL) {
  1349. p = *outBuf;
  1350. }
  1351. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1352. if ((ret > 0) && (p != NULL)) {
  1353. *outBuf = p;
  1354. }
  1355. return ret;
  1356. }
  1357. /* Create a DER encoding of key.
  1358. *
  1359. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1360. *
  1361. * @param [in] rsa RSA key.
  1362. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1363. * May be NULL.
  1364. * On out, newly allocated buffer or pointer to byte
  1365. * after encoding in passed in buffer.
  1366. * @param [in] publicKey Whether to encode as public key.
  1367. * @param [in] heap Heap hint.
  1368. * @return Encoding size on success.
  1369. * @return Negative on failure.
  1370. */
  1371. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1372. void* heap)
  1373. {
  1374. int ret = 1;
  1375. int derSz = 0;
  1376. byte* derBuf = NULL;
  1377. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1378. /* Unused if memory is disabled. */
  1379. (void)heap;
  1380. /* Validate parameters. */
  1381. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1382. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1383. ret = BAD_FUNC_ARG;
  1384. }
  1385. /* Push external RSA data into internal RSA key if not set. */
  1386. if ((ret == 1) && (!rsa->inSet)) {
  1387. ret = SetRsaInternal(rsa);
  1388. }
  1389. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1390. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1391. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1392. ret = BAD_FUNC_ARG;
  1393. }
  1394. if (ret == 1) {
  1395. if (publicKey) {
  1396. /* Calculate length of DER encoded RSA public key. */
  1397. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1398. if (derSz < 0) {
  1399. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1400. ret = derSz;
  1401. }
  1402. }
  1403. else {
  1404. /* Calculate length of DER encoded RSA private key. */
  1405. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1406. if (derSz < 0) {
  1407. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1408. ret = derSz;
  1409. }
  1410. }
  1411. }
  1412. if ((ret == 1) && (outBuf != NULL)) {
  1413. derBuf = *outBuf;
  1414. if (derBuf == NULL) {
  1415. /* Allocate buffer to hold DER encoded RSA key. */
  1416. derBuf = (byte*)XMALLOC((size_t)derSz, heap,
  1417. DYNAMIC_TYPE_TMP_BUFFER);
  1418. if (derBuf == NULL) {
  1419. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1420. ret = MEMORY_ERROR;
  1421. }
  1422. }
  1423. }
  1424. if ((ret == 1) && (outBuf != NULL)) {
  1425. if (publicKey > 0) {
  1426. /* RSA public key to DER. */
  1427. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf,
  1428. (word32)derSz);
  1429. }
  1430. else {
  1431. /* RSA private key to DER. */
  1432. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf,
  1433. (word32)derSz);
  1434. }
  1435. if (derSz < 0) {
  1436. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1437. ret = derSz;
  1438. }
  1439. else if ((*outBuf) != NULL) {
  1440. derBuf = NULL;
  1441. *outBuf += derSz;
  1442. }
  1443. else {
  1444. /* Return allocated buffer. */
  1445. *outBuf = derBuf;
  1446. }
  1447. }
  1448. if (ret == 1) {
  1449. /* Success - return DER encoding size. */
  1450. ret = derSz;
  1451. }
  1452. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1453. /* Not returning buffer, needs to be disposed of. */
  1454. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1455. }
  1456. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1457. return ret;
  1458. }
  1459. #endif /* !HAVE_USER_RSA */
  1460. #endif /* OPENSSL_EXTRA */
  1461. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1462. /* Load the DER encoded private RSA key.
  1463. *
  1464. * Not OpenSSL API.
  1465. *
  1466. * @param [in] rsa RSA key.
  1467. * @param [in] derBuf Buffer holding DER encoding.
  1468. * @param [in] derSz Length of DER encoding.
  1469. * @return 1 on success.
  1470. * @return -1 on failure.
  1471. */
  1472. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1473. int derSz)
  1474. {
  1475. /* Call implementation that handles both private and public keys. */
  1476. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1477. }
  1478. /* Load the DER encoded public or private RSA key.
  1479. *
  1480. * Not OpenSSL API.
  1481. *
  1482. * @param [in] rsa RSA key.
  1483. * @param [in] derBuf Buffer holding DER encoding.
  1484. * @param [in] derSz Length of DER encoding.
  1485. * @param [in] opt Indicates public or private key.
  1486. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1487. * @return 1 on success.
  1488. * @return -1 on failure.
  1489. */
  1490. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1491. int derSz, int opt)
  1492. {
  1493. int ret = 1;
  1494. int res;
  1495. word32 idx = 0;
  1496. word32 algId;
  1497. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1498. /* Validate parameters. */
  1499. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1500. (derSz <= 0)) {
  1501. WOLFSSL_ERROR_MSG("Bad function arguments");
  1502. ret = -1;
  1503. }
  1504. if (ret == 1) {
  1505. rsa->pkcs8HeaderSz = 0;
  1506. /* Check if input buffer has PKCS8 header. In the case that it does not
  1507. * have a PKCS8 header then do not error out. */
  1508. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1509. &algId);
  1510. if (res > 0) {
  1511. /* Store size of PKCS#8 header for encoding. */
  1512. WOLFSSL_MSG("Found PKCS8 header");
  1513. rsa->pkcs8HeaderSz = (word16)idx;
  1514. }
  1515. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1516. else if (res != ASN_PARSE_E) {
  1517. /* Something went wrong while decoding. */
  1518. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1519. "header");
  1520. ret = -1;
  1521. }
  1522. }
  1523. if (ret == 1) {
  1524. /* Decode private or public key data. */
  1525. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1526. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1527. (word32)derSz);
  1528. }
  1529. else {
  1530. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1531. (word32)derSz);
  1532. }
  1533. /* Check for error. */
  1534. if (res < 0) {
  1535. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1536. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1537. }
  1538. else {
  1539. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1540. }
  1541. WOLFSSL_ERROR_VERBOSE(res);
  1542. ret = -1;
  1543. }
  1544. }
  1545. if (ret == 1) {
  1546. /* Set external RSA key data from wolfCrypt key. */
  1547. if (SetRsaExternal(rsa) != 1) {
  1548. ret = -1;
  1549. }
  1550. else {
  1551. rsa->inSet = 1;
  1552. }
  1553. }
  1554. return ret;
  1555. }
  1556. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1557. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1558. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1559. /* Load DER encoded data into WOLFSSL_RSA object.
  1560. *
  1561. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1562. *
  1563. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1564. * When rsa or *rsa is NULL a new object is created.
  1565. * When not NULL and *rsa is NULL then new object
  1566. * returned through pointer.
  1567. * @param [in] in DER encoded RSA key data.
  1568. * @param [in] inSz Size of DER encoded data in bytes.
  1569. * @param [in] opt Public or private key encoded in data. Valid values:
  1570. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1571. * @return NULL on failure.
  1572. * @return WOLFSSL_RSA object on success.
  1573. */
  1574. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1575. long inSz, int opt)
  1576. {
  1577. WOLFSSL_RSA* ret = NULL;
  1578. if ((rsa != NULL) && (*rsa != NULL)) {
  1579. ret = *rsa;
  1580. }
  1581. else {
  1582. ret = wolfSSL_RSA_new();
  1583. }
  1584. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1585. != 1)) {
  1586. if ((rsa == NULL) || (ret != *rsa)) {
  1587. wolfSSL_RSA_free(ret);
  1588. }
  1589. ret = NULL;
  1590. }
  1591. if ((rsa != NULL) && (*rsa == NULL)) {
  1592. *rsa = ret;
  1593. }
  1594. return ret;
  1595. }
  1596. #endif
  1597. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1598. /*
  1599. * RSA PEM APIs
  1600. */
  1601. #ifdef OPENSSL_EXTRA
  1602. #ifndef NO_BIO
  1603. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1604. /* Writes PEM encoding of an RSA public key to a BIO.
  1605. *
  1606. * @param [in] bio BIO object to write to.
  1607. * @param [in] rsa RSA key to write.
  1608. * @return 1 on success.
  1609. * @return 0 on failure.
  1610. */
  1611. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1612. {
  1613. int ret = 1;
  1614. int derSz = 0;
  1615. byte* derBuf = NULL;
  1616. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1617. /* Validate parameters. */
  1618. if ((bio == NULL) || (rsa == NULL)) {
  1619. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1620. return 0;
  1621. }
  1622. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1623. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1624. ret = 0;
  1625. }
  1626. if (derBuf == NULL) {
  1627. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1628. ret = 0;
  1629. }
  1630. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1631. PUBLICKEY_TYPE) != WOLFSSL_SUCCESS)) {
  1632. ret = 0;
  1633. }
  1634. /* Dispose of DER buffer. */
  1635. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1636. return ret;
  1637. }
  1638. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1639. #endif /* !NO_BIO */
  1640. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1641. #ifndef NO_FILESYSTEM
  1642. /* Writes PEM encoding of an RSA public key to a file pointer.
  1643. *
  1644. * @param [in] fp File pointer to write to.
  1645. * @param [in] rsa RSA key to write.
  1646. * @param [in] type PEM type to write out.
  1647. * @return 1 on success.
  1648. * @return 0 on failure.
  1649. */
  1650. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1651. int type)
  1652. {
  1653. int ret = 1;
  1654. int derSz;
  1655. byte* derBuf = NULL;
  1656. /* Validate parameters. */
  1657. if ((fp == XBADFILE) || (rsa == NULL)) {
  1658. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1659. return 0;
  1660. }
  1661. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1662. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1663. ret = 0;
  1664. }
  1665. if (derBuf == NULL) {
  1666. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1667. ret = 0;
  1668. }
  1669. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1670. rsa->heap) != WOLFSSL_SUCCESS)) {
  1671. ret = 0;
  1672. }
  1673. /* Dispose of DER buffer. */
  1674. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1675. return ret;
  1676. }
  1677. /* Writes PEM encoding of an RSA public key to a file pointer.
  1678. *
  1679. * Header/footer will contain: PUBLIC KEY
  1680. *
  1681. * @param [in] fp File pointer to write to.
  1682. * @param [in] rsa RSA key to write.
  1683. * @return 1 on success.
  1684. * @return 0 on failure.
  1685. */
  1686. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1687. {
  1688. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1689. }
  1690. /* Writes PEM encoding of an RSA public key to a file pointer.
  1691. *
  1692. * Header/footer will contain: RSA PUBLIC KEY
  1693. *
  1694. * @param [in] fp File pointer to write to.
  1695. * @param [in] rsa RSA key to write.
  1696. * @return 1 on success.
  1697. * @return 0 on failure.
  1698. */
  1699. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1700. {
  1701. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1702. }
  1703. #endif /* !NO_FILESYSTEM */
  1704. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1705. #ifndef NO_BIO
  1706. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1707. *
  1708. * @param [in] bio BIO object to read from.
  1709. * @param [out] out RSA key created.
  1710. * @param [in] cb Password callback when PEM encrypted.
  1711. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1712. * @return RSA key on success.
  1713. * @return NULL on failure.
  1714. */
  1715. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1716. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1717. {
  1718. WOLFSSL_RSA* rsa = NULL;
  1719. DerBuffer* der = NULL;
  1720. int keyFormat = 0;
  1721. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1722. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1723. &keyFormat, &der) >= 0)) {
  1724. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1725. WOLFSSL_RSA_LOAD_PUBLIC);
  1726. if (rsa == NULL) {
  1727. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1728. }
  1729. }
  1730. FreeDer(&der);
  1731. if ((out != NULL) && (rsa != NULL)) {
  1732. *out = rsa;
  1733. }
  1734. return rsa;
  1735. }
  1736. #endif /* !NO_BIO */
  1737. #ifndef NO_FILESYSTEM
  1738. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1739. *
  1740. * Header/footer should contain: PUBLIC KEY
  1741. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1742. *
  1743. * @param [in] fp File pointer to read from.
  1744. * @param [out] out RSA key created.
  1745. * @param [in] cb Password callback when PEM encrypted.
  1746. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1747. * @return RSA key on success.
  1748. * @return NULL on failure.
  1749. */
  1750. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1751. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1752. {
  1753. WOLFSSL_RSA* rsa = NULL;
  1754. DerBuffer* der = NULL;
  1755. int keyFormat = 0;
  1756. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1757. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1758. &keyFormat, &der) >= 0)) {
  1759. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1760. WOLFSSL_RSA_LOAD_PUBLIC);
  1761. if (rsa == NULL) {
  1762. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1763. }
  1764. }
  1765. FreeDer(&der);
  1766. if ((out != NULL) && (rsa != NULL)) {
  1767. *out = rsa;
  1768. }
  1769. return rsa;
  1770. }
  1771. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1772. *
  1773. * Header/footer should contain: RSA PUBLIC KEY
  1774. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1775. *
  1776. * @param [in] fp File pointer to read from.
  1777. * @param [out] rsa RSA key created.
  1778. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1779. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1780. * May be NULL.
  1781. * @return RSA key on success.
  1782. * @return NULL on failure.
  1783. */
  1784. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1785. wc_pem_password_cb* cb, void* pass)
  1786. {
  1787. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1788. }
  1789. #endif /* NO_FILESYSTEM */
  1790. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1791. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1792. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1793. *
  1794. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1795. *
  1796. * @param [in] rsa RSA key to write.
  1797. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1798. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1799. * @param [in] passwdSz Length of password string when PEM encrypted.
  1800. * @param [out] pem Allocated buffer with PEM encoding.
  1801. * @param [out] pLen Length of PEM encoding.
  1802. * @return 1 on success.
  1803. * @return 0 on failure.
  1804. */
  1805. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1806. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1807. {
  1808. int ret = 1;
  1809. byte* derBuf = NULL;
  1810. int derSz = 0;
  1811. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1812. /* Validate parameters. */
  1813. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1814. (rsa->internal == NULL)) {
  1815. WOLFSSL_ERROR_MSG("Bad function arguments");
  1816. ret = 0;
  1817. }
  1818. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1819. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1820. ret = 0;
  1821. }
  1822. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1823. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1824. rsa->heap)) < 0)) {
  1825. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1826. ret = 0;
  1827. }
  1828. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1829. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1830. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1831. ret = 0;
  1832. }
  1833. return ret;
  1834. }
  1835. #ifndef NO_BIO
  1836. /* Writes PEM encoding of an RSA private key to a BIO.
  1837. *
  1838. * @param [in] bio BIO object to write to.
  1839. * @param [in] rsa RSA key to write.
  1840. * @param [in] cipher Cipher to use when PEM encrypted.
  1841. * @param [in] passwd Password string when PEM encrypted.
  1842. * @param [in] len Length of password string when PEM encrypted.
  1843. * @param [in] cb Password callback to use when PEM encrypted.
  1844. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1845. * @return 1 on success.
  1846. * @return 0 on failure.
  1847. */
  1848. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1849. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1850. wc_pem_password_cb* cb, void* arg)
  1851. {
  1852. int ret = 1;
  1853. byte* pem = NULL;
  1854. int pLen = 0;
  1855. (void)cb;
  1856. (void)arg;
  1857. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1858. /* Validate parameters. */
  1859. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1860. WOLFSSL_ERROR_MSG("Bad function arguments");
  1861. ret = 0;
  1862. }
  1863. if (ret == 1) {
  1864. /* Write PEM to buffer that is allocated in the call. */
  1865. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1866. &pem, &pLen);
  1867. if (ret != 1) {
  1868. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1869. }
  1870. }
  1871. /* Write PEM to BIO. */
  1872. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  1873. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1874. ret = 0;
  1875. }
  1876. /* Dispose of any allocated PEM buffer. */
  1877. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1878. return ret;
  1879. }
  1880. #endif /* !NO_BIO */
  1881. #ifndef NO_FILESYSTEM
  1882. /* Writes PEM encoding of an RSA private key to a file pointer.
  1883. *
  1884. * TODO: Support use of the password callback and callback context.
  1885. *
  1886. * @param [in] fp File pointer to write to.
  1887. * @param [in] rsa RSA key to write.
  1888. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1889. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1890. * @param [in] passwdSz Length of password string when PEM encrypted.
  1891. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  1892. * @param [in] arg NUL terminated string for passphrase when PEM
  1893. * encrypted. Unused.
  1894. * @return 1 on success.
  1895. * @return 0 on failure.
  1896. */
  1897. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  1898. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  1899. wc_pem_password_cb *cb, void *arg)
  1900. {
  1901. int ret = 1;
  1902. byte* pem = NULL;
  1903. int pLen = 0;
  1904. (void)cb;
  1905. (void)arg;
  1906. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  1907. /* Validate parameters. */
  1908. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  1909. WOLFSSL_ERROR_MSG("Bad function arguments");
  1910. ret = 0;
  1911. }
  1912. if (ret == 1) {
  1913. /* Write PEM to buffer that is allocated in the call. */
  1914. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  1915. &pem, &pLen);
  1916. if (ret != 1) {
  1917. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1918. }
  1919. }
  1920. /* Write PEM to file pointer. */
  1921. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  1922. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  1923. ret = 0;
  1924. }
  1925. /* Dispose of any allocated PEM buffer. */
  1926. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1927. return ret;
  1928. }
  1929. #endif /* NO_FILESYSTEM */
  1930. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA && WOLFSSL_PEM_TO_DER */
  1931. #ifndef NO_BIO
  1932. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  1933. *
  1934. * @param [in] bio BIO object to read from.
  1935. * @param [out] out RSA key created.
  1936. * @param [in] cb Password callback when PEM encrypted.
  1937. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1938. * @return RSA key on success.
  1939. * @return NULL on failure.
  1940. */
  1941. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  1942. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  1943. {
  1944. WOLFSSL_RSA* rsa = NULL;
  1945. DerBuffer* der = NULL;
  1946. int keyFormat = 0;
  1947. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  1948. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  1949. &keyFormat, &der) >= 0)) {
  1950. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1951. WOLFSSL_RSA_LOAD_PRIVATE);
  1952. if (rsa == NULL) {
  1953. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1954. }
  1955. }
  1956. FreeDer(&der);
  1957. if ((out != NULL) && (rsa != NULL)) {
  1958. *out = rsa;
  1959. }
  1960. return rsa;
  1961. }
  1962. #endif /* !NO_BIO */
  1963. /* Create an RSA private key by reading the PEM encoded data from the file
  1964. * pointer.
  1965. *
  1966. * @param [in] fp File pointer to read from.
  1967. * @param [out] out RSA key created.
  1968. * @param [in] cb Password callback when PEM encrypted.
  1969. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1970. * @return RSA key on success.
  1971. * @return NULL on failure.
  1972. */
  1973. #ifndef NO_FILESYSTEM
  1974. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  1975. wc_pem_password_cb* cb, void* pass)
  1976. {
  1977. WOLFSSL_RSA* rsa = NULL;
  1978. DerBuffer* der = NULL;
  1979. int keyFormat = 0;
  1980. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  1981. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  1982. &keyFormat, &der) >= 0)) {
  1983. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1984. WOLFSSL_RSA_LOAD_PRIVATE);
  1985. if (rsa == NULL) {
  1986. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1987. }
  1988. }
  1989. FreeDer(&der);
  1990. if ((out != NULL) && (rsa != NULL)) {
  1991. *out = rsa;
  1992. }
  1993. return rsa;
  1994. }
  1995. #endif /* !NO_FILESYSTEM */
  1996. /*
  1997. * RSA print APIs
  1998. */
  1999. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  2000. !defined(NO_STDIO_FILESYSTEM)
  2001. /* Print an RSA key to a file pointer.
  2002. *
  2003. * @param [in] fp File pointer to write to.
  2004. * @param [in] rsa RSA key to write.
  2005. * @param [in] indent Number of spaces to prepend to each line.
  2006. * @return 1 on success.
  2007. * @return 0 on failure.
  2008. */
  2009. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2010. {
  2011. int ret = 1;
  2012. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2013. /* Validate parameters. */
  2014. if ((fp == XBADFILE) || (rsa == NULL)) {
  2015. ret = 0;
  2016. }
  2017. /* Set the external data from the wolfCrypt RSA key if not done. */
  2018. if ((ret == 1) && (!rsa->exSet)) {
  2019. ret = SetRsaExternal(rsa);
  2020. }
  2021. /* Get the key size from modulus if available. */
  2022. if ((ret == 1) && (rsa->n != NULL)) {
  2023. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2024. if (keySize == 0) {
  2025. ret = 0;
  2026. }
  2027. else {
  2028. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2029. ret = 0;
  2030. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2031. keySize) < 0)
  2032. ret = 0;
  2033. }
  2034. }
  2035. /* Print out any components available. */
  2036. if ((ret == 1) && (rsa->n != NULL)) {
  2037. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2038. }
  2039. if ((ret == 1) && (rsa->d != NULL)) {
  2040. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2041. }
  2042. if ((ret == 1) && (rsa->p != NULL)) {
  2043. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2044. }
  2045. if ((ret == 1) && (rsa->q != NULL)) {
  2046. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2047. }
  2048. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2049. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2050. }
  2051. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2052. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2053. }
  2054. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2055. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2056. }
  2057. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2058. return ret;
  2059. }
  2060. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2061. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(HAVE_FAST_RSA)
  2062. /* snprintf() must be available */
  2063. /* Maximum size of a header line. */
  2064. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2065. /* Writes the human readable form of RSA to a BIO.
  2066. *
  2067. * @param [in] bio BIO object to write to.
  2068. * @param [in] rsa RSA key to write.
  2069. * @param [in] indent Number of spaces before each line.
  2070. * @return 1 on success.
  2071. * @return 0 on failure.
  2072. */
  2073. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2074. {
  2075. int ret = 1;
  2076. int sz = 0;
  2077. RsaKey* key = NULL;
  2078. char line[RSA_PRINT_MAX_HEADER_LINE];
  2079. int i = 0;
  2080. mp_int *num = NULL;
  2081. /* Header strings. */
  2082. const char *name[] = {
  2083. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2084. "Exponent1:", "Exponent2:", "Coefficient:"
  2085. };
  2086. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2087. /* Validate parameters. */
  2088. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2089. ret = -1;
  2090. }
  2091. if (ret == 1) {
  2092. key = (RsaKey*)rsa->internal;
  2093. /* Get size in bits of key for printing out. */
  2094. sz = wolfSSL_RSA_bits(rsa);
  2095. if (sz <= 0) {
  2096. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2097. ret = 0;
  2098. }
  2099. }
  2100. if (ret == 1) {
  2101. /* Print any indent spaces. */
  2102. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2103. }
  2104. if (ret == 1) {
  2105. /* Print header line. */
  2106. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2107. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2108. if (len >= (int)sizeof(line)) {
  2109. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2110. ret = 0;
  2111. }
  2112. else {
  2113. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2114. ret = 0;
  2115. }
  2116. }
  2117. }
  2118. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2119. /* Get mp_int for index. */
  2120. switch (i) {
  2121. case 0:
  2122. /* Print out modulus */
  2123. num = &key->n;
  2124. break;
  2125. case 1:
  2126. num = &key->e;
  2127. break;
  2128. case 2:
  2129. num = &key->d;
  2130. break;
  2131. case 3:
  2132. num = &key->p;
  2133. break;
  2134. case 4:
  2135. num = &key->q;
  2136. break;
  2137. case 5:
  2138. num = &key->dP;
  2139. break;
  2140. case 6:
  2141. num = &key->dQ;
  2142. break;
  2143. case 7:
  2144. num = &key->u;
  2145. break;
  2146. default:
  2147. WOLFSSL_ERROR_MSG("Bad index value");
  2148. }
  2149. if (i == 1) {
  2150. /* Print exponent as a 32-bit value. */
  2151. ret = wolfssl_print_value(bio, num, name[i], indent);
  2152. }
  2153. else if (!mp_iszero(num)) {
  2154. /* Print name and MP integer. */
  2155. ret = wolfssl_print_number(bio, num, name[i], indent);
  2156. }
  2157. }
  2158. return ret;
  2159. }
  2160. #endif /* XSNPRINTF && !NO_BIO && !HAVE_FAST_RSA */
  2161. #endif /* OPENSSL_EXTRA */
  2162. /*
  2163. * RSA get/set/test APIs
  2164. */
  2165. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2166. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2167. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2168. *
  2169. * @param [in, out] rsa RSA key.
  2170. * @return 1 on success.
  2171. * @return 0 on failure.
  2172. */
  2173. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2174. {
  2175. int ret = 1;
  2176. WOLFSSL_ENTER("SetRsaExternal");
  2177. /* Validate parameters. */
  2178. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2179. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2180. ret = -1;
  2181. }
  2182. if (ret == 1) {
  2183. RsaKey* key = (RsaKey*)rsa->internal;
  2184. /* Copy modulus. */
  2185. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2186. if (ret != 1) {
  2187. WOLFSSL_ERROR_MSG("rsa n error");
  2188. }
  2189. if (ret == 1) {
  2190. /* Copy public exponent. */
  2191. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2192. if (ret != 1) {
  2193. WOLFSSL_ERROR_MSG("rsa e error");
  2194. }
  2195. }
  2196. if (key->type == RSA_PRIVATE) {
  2197. if (ret == 1) {
  2198. /* Copy private exponent. */
  2199. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2200. if (ret != 1) {
  2201. WOLFSSL_ERROR_MSG("rsa d error");
  2202. }
  2203. }
  2204. if (ret == 1) {
  2205. /* Copy first prime. */
  2206. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2207. if (ret != 1) {
  2208. WOLFSSL_ERROR_MSG("rsa p error");
  2209. }
  2210. }
  2211. if (ret == 1) {
  2212. /* Copy second prime. */
  2213. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2214. if (ret != 1) {
  2215. WOLFSSL_ERROR_MSG("rsa q error");
  2216. }
  2217. }
  2218. #ifndef RSA_LOW_MEM
  2219. if (ret == 1) {
  2220. /* Copy d mod p-1. */
  2221. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2222. if (ret != 1) {
  2223. WOLFSSL_ERROR_MSG("rsa dP error");
  2224. }
  2225. }
  2226. if (ret == 1) {
  2227. /* Copy d mod q-1. */
  2228. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2229. if (ret != 1) {
  2230. WOLFSSL_ERROR_MSG("rsa dq error");
  2231. }
  2232. }
  2233. if (ret == 1) {
  2234. /* Copy 1/q mod p. */
  2235. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2236. if (ret != 1) {
  2237. WOLFSSL_ERROR_MSG("rsa u error");
  2238. }
  2239. }
  2240. #endif /* !RSA_LOW_MEM */
  2241. }
  2242. }
  2243. if (ret == 1) {
  2244. /* External values set. */
  2245. rsa->exSet = 1;
  2246. }
  2247. else {
  2248. /* Return 0 on failure. */
  2249. ret = 0;
  2250. }
  2251. return ret;
  2252. }
  2253. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  2254. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2255. #ifdef OPENSSL_EXTRA
  2256. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2257. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2258. *
  2259. * @param [in, out] rsa RSA key.
  2260. * @return 1 on success.
  2261. * @return 0 on failure.
  2262. */
  2263. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2264. {
  2265. int ret = 1;
  2266. WOLFSSL_ENTER("SetRsaInternal");
  2267. /* Validate parameters. */
  2268. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2269. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2270. ret = -1;
  2271. }
  2272. if (ret == 1) {
  2273. RsaKey* key = (RsaKey*)rsa->internal;
  2274. /* Copy down modulus if available. */
  2275. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2276. WOLFSSL_ERROR_MSG("rsa n key error");
  2277. ret = -1;
  2278. }
  2279. /* Copy down public exponent if available. */
  2280. if ((ret == 1) && (rsa->e != NULL) &&
  2281. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2282. WOLFSSL_ERROR_MSG("rsa e key error");
  2283. ret = -1;
  2284. }
  2285. /* Enough numbers for public key */
  2286. key->type = RSA_PUBLIC;
  2287. /* Copy down private exponent if available. */
  2288. if ((ret == 1) && (rsa->d != NULL)) {
  2289. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2290. WOLFSSL_ERROR_MSG("rsa d key error");
  2291. ret = -1;
  2292. }
  2293. else {
  2294. /* Enough numbers for private key */
  2295. key->type = RSA_PRIVATE;
  2296. }
  2297. }
  2298. /* Copy down first prime if available. */
  2299. if ((ret == 1) && (rsa->p != NULL) &&
  2300. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2301. WOLFSSL_ERROR_MSG("rsa p key error");
  2302. ret = -1;
  2303. }
  2304. /* Copy down second prime if available. */
  2305. if ((ret == 1) && (rsa->q != NULL) &&
  2306. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2307. WOLFSSL_ERROR_MSG("rsa q key error");
  2308. ret = -1;
  2309. }
  2310. #ifndef RSA_LOW_MEM
  2311. /* Copy down d mod p-1 if available. */
  2312. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2313. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2314. WOLFSSL_ERROR_MSG("rsa dP key error");
  2315. ret = -1;
  2316. }
  2317. /* Copy down d mod q-1 if available. */
  2318. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2319. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2320. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2321. ret = -1;
  2322. }
  2323. /* Copy down 1/q mod p if available. */
  2324. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2325. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2326. WOLFSSL_ERROR_MSG("rsa u key error");
  2327. ret = -1;
  2328. }
  2329. #endif /* !RSA_LOW_MEM */
  2330. if (ret == 1) {
  2331. /* All available numbers have been set down. */
  2332. rsa->inSet = 1;
  2333. }
  2334. }
  2335. return ret;
  2336. }
  2337. #endif /* HAVE_USER_RSA */
  2338. /* Set the RSA method into object.
  2339. *
  2340. * @param [in, out] rsa RSA key.
  2341. * @param [in] meth RSA method.
  2342. * @return 1 always.
  2343. */
  2344. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2345. {
  2346. if (rsa != NULL) {
  2347. /* Store the method into object. */
  2348. rsa->meth = meth;
  2349. /* Copy over flags. */
  2350. rsa->flags = meth->flags;
  2351. }
  2352. /* OpenSSL always assumes it will work. */
  2353. return 1;
  2354. }
  2355. /* Get the RSA method from the RSA object.
  2356. *
  2357. * @param [in] rsa RSA key.
  2358. * @return RSA method on success.
  2359. * @return NULL when RSA is NULL or no method set.
  2360. */
  2361. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2362. {
  2363. return (rsa != NULL) ? rsa->meth : NULL;
  2364. }
  2365. /* Get the size in bytes of the RSA key.
  2366. *
  2367. * Return compliant with OpenSSL
  2368. *
  2369. * @param [in] rsa RSA key.
  2370. * @return RSA modulus size in bytes.
  2371. * @return 0 on error.
  2372. */
  2373. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2374. {
  2375. int ret = 0;
  2376. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2377. if (rsa != NULL) {
  2378. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2379. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2380. /* Get key size in bytes using wolfCrypt RSA key. */
  2381. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2382. }
  2383. }
  2384. return ret;
  2385. }
  2386. /* Get the size in bits of the RSA key.
  2387. *
  2388. * Uses external modulus field.
  2389. *
  2390. * @param [in] rsa RSA key.
  2391. * @return RSA modulus size in bits.
  2392. * @return 0 on error.
  2393. */
  2394. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2395. {
  2396. int ret = 0;
  2397. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2398. if (rsa != NULL) {
  2399. /* Get number of bits in external modulus. */
  2400. ret = wolfSSL_BN_num_bits(rsa->n);
  2401. }
  2402. return ret;
  2403. }
  2404. #ifndef HAVE_USER_RSA
  2405. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2406. *
  2407. * Only for those that are not NULL parameters.
  2408. *
  2409. * @param [in] rsa RSA key.
  2410. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2411. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2412. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2413. */
  2414. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2415. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2416. const WOLFSSL_BIGNUM **iqmp)
  2417. {
  2418. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2419. /* For any parameters not NULL, return the BN from the key or NULL. */
  2420. if (dmp1 != NULL) {
  2421. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2422. }
  2423. if (dmq1 != NULL) {
  2424. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2425. }
  2426. if (iqmp != NULL) {
  2427. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2428. }
  2429. }
  2430. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2431. * into RSA key.
  2432. *
  2433. * If CRT parameter is NULL then there must be one in the RSA key already.
  2434. *
  2435. * @param [in, out] rsa RSA key.
  2436. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2437. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2438. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2439. * @return 1 on success.
  2440. * @return 0 on failure.
  2441. */
  2442. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2443. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2444. {
  2445. int ret = 1;
  2446. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2447. /* If a param is NULL in rsa then it must be non-NULL in the
  2448. * corresponding user input. */
  2449. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2450. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2451. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2452. WOLFSSL_ERROR_MSG("Bad parameters");
  2453. ret = 0;
  2454. }
  2455. if (ret == 1) {
  2456. /* Replace the BNs. */
  2457. if (dmp1 != NULL) {
  2458. wolfSSL_BN_clear_free(rsa->dmp1);
  2459. rsa->dmp1 = dmp1;
  2460. }
  2461. if (dmq1 != NULL) {
  2462. wolfSSL_BN_clear_free(rsa->dmq1);
  2463. rsa->dmq1 = dmq1;
  2464. }
  2465. if (iqmp != NULL) {
  2466. wolfSSL_BN_clear_free(rsa->iqmp);
  2467. rsa->iqmp = iqmp;
  2468. }
  2469. /* Set the values into the wolfCrypt RSA key. */
  2470. if (SetRsaInternal(rsa) != 1) {
  2471. if (dmp1 != NULL) {
  2472. rsa->dmp1 = NULL;
  2473. }
  2474. if (dmq1 != NULL) {
  2475. rsa->dmq1 = NULL;
  2476. }
  2477. if (iqmp != NULL) {
  2478. rsa->iqmp = NULL;
  2479. }
  2480. ret = 0;
  2481. }
  2482. }
  2483. return ret;
  2484. }
  2485. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2486. *
  2487. * @param [in] rsa RSA key.
  2488. * @param [out] p BN that is first prime. May be NULL.
  2489. * @param [out] q BN that is second prime. May be NULL.
  2490. */
  2491. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2492. const WOLFSSL_BIGNUM **q)
  2493. {
  2494. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2495. /* For any primes not NULL, return the BN from the key or NULL. */
  2496. if (p != NULL) {
  2497. *p = (rsa != NULL) ? rsa->p : NULL;
  2498. }
  2499. if (q != NULL) {
  2500. *q = (rsa != NULL) ? rsa->q : NULL;
  2501. }
  2502. }
  2503. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2504. *
  2505. * If factor parameter is NULL then there must be one in the RSA key already.
  2506. *
  2507. * @param [in, out] rsa RSA key.
  2508. * @param [in] p BN that is first prime. May be NULL.
  2509. * @param [in] q BN that is second prime. May be NULL.
  2510. * @return 1 on success.
  2511. * @return 0 on failure.
  2512. */
  2513. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2514. WOLFSSL_BIGNUM *q)
  2515. {
  2516. int ret = 1;
  2517. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2518. /* If a param is null in r then it must be non-null in the
  2519. * corresponding user input. */
  2520. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2521. ((rsa->q == NULL) && (q == NULL))) {
  2522. WOLFSSL_ERROR_MSG("Bad parameters");
  2523. ret = 0;
  2524. }
  2525. if (ret == 1) {
  2526. /* Replace the BNs. */
  2527. if (p != NULL) {
  2528. wolfSSL_BN_clear_free(rsa->p);
  2529. rsa->p = p;
  2530. }
  2531. if (q != NULL) {
  2532. wolfSSL_BN_clear_free(rsa->q);
  2533. rsa->q = q;
  2534. }
  2535. /* Set the values into the wolfCrypt RSA key. */
  2536. if (SetRsaInternal(rsa) != 1) {
  2537. if (p != NULL) {
  2538. rsa->p = NULL;
  2539. }
  2540. if (q != NULL) {
  2541. rsa->q = NULL;
  2542. }
  2543. ret = 0;
  2544. }
  2545. }
  2546. return ret;
  2547. }
  2548. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2549. * exponent, private exponent).
  2550. *
  2551. * @param [in] rsa RSA key.
  2552. * @param [out] n BN that is the modulus. May be NULL.
  2553. * @param [out] e BN that is the public exponent. May be NULL.
  2554. * @param [out] d BN that is the private exponent. May be NULL.
  2555. */
  2556. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2557. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2558. {
  2559. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2560. /* For any parameters not NULL, return the BN from the key or NULL. */
  2561. if (n != NULL) {
  2562. *n = (rsa != NULL) ? rsa->n : NULL;
  2563. }
  2564. if (e != NULL) {
  2565. *e = (rsa != NULL) ? rsa->e : NULL;
  2566. }
  2567. if (d != NULL) {
  2568. *d = (rsa != NULL) ? rsa->d : NULL;
  2569. }
  2570. }
  2571. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2572. * public exponent, private exponent).
  2573. *
  2574. * If BN parameter is NULL then there must be one in the RSA key already.
  2575. *
  2576. * @param [in,out] rsa RSA key.
  2577. * @param [in] n BN that is the modulus. May be NULL.
  2578. * @param [in] e BN that is the public exponent. May be NULL.
  2579. * @param [in] d BN that is the private exponent. May be NULL.
  2580. * @return 1 on success.
  2581. * @return 0 on failure.
  2582. */
  2583. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2584. WOLFSSL_BIGNUM *d)
  2585. {
  2586. int ret = 1;
  2587. /* If the fields n and e in r are NULL, the corresponding input
  2588. * parameters MUST be non-NULL for n and e. d may be
  2589. * left NULL (in case only the public key is used).
  2590. */
  2591. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2592. ((rsa->e == NULL) && (e == NULL))) {
  2593. ret = 0;
  2594. }
  2595. if (ret == 1) {
  2596. /* Replace the BNs. */
  2597. if (n != NULL) {
  2598. wolfSSL_BN_free(rsa->n);
  2599. rsa->n = n;
  2600. }
  2601. if (e != NULL) {
  2602. wolfSSL_BN_free(rsa->e);
  2603. rsa->e = e;
  2604. }
  2605. if (d != NULL) {
  2606. /* Private key is sensitive data. */
  2607. wolfSSL_BN_clear_free(rsa->d);
  2608. rsa->d = d;
  2609. }
  2610. /* Set the values into the wolfCrypt RSA key. */
  2611. if (SetRsaInternal(rsa) != 1) {
  2612. if (n != NULL) {
  2613. rsa->n = NULL;
  2614. }
  2615. if (e != NULL) {
  2616. rsa->e = NULL;
  2617. }
  2618. if (d != NULL) {
  2619. rsa->d = NULL;
  2620. }
  2621. ret = 0;
  2622. }
  2623. }
  2624. return ret;
  2625. }
  2626. #endif /* !HAVE_USER_RSA */
  2627. /* Get the flags of the RSA key.
  2628. *
  2629. * @param [in] rsa RSA key.
  2630. * @return Flags set in RSA key on success.
  2631. * @return 0 when RSA key is NULL.
  2632. */
  2633. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2634. {
  2635. int ret = 0;
  2636. /* Get flags from the RSA key if available. */
  2637. if (rsa != NULL) {
  2638. ret = rsa->flags;
  2639. }
  2640. return ret;
  2641. }
  2642. /* Set the flags into the RSA key.
  2643. *
  2644. * @param [in, out] rsa RSA key.
  2645. * @param [in] flags Flags to set.
  2646. */
  2647. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2648. {
  2649. /* Add the flags into RSA key if available. */
  2650. if (rsa != NULL) {
  2651. rsa->flags |= flags;
  2652. }
  2653. }
  2654. /* Clear the flags in the RSA key.
  2655. *
  2656. * @param [in, out] rsa RSA key.
  2657. * @param [in] flags Flags to clear.
  2658. */
  2659. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2660. {
  2661. /* Clear the flags passed in that are on the RSA key if available. */
  2662. if (rsa != NULL) {
  2663. rsa->flags &= ~flags;
  2664. }
  2665. }
  2666. /* Test the flags in the RSA key.
  2667. *
  2668. * @param [in] rsa RSA key.
  2669. * @return Matching flags of RSA key on success.
  2670. * @return 0 when RSA key is NULL.
  2671. */
  2672. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2673. {
  2674. /* Return the flags passed in that are set on the RSA key if available. */
  2675. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2676. }
  2677. /* Get the extra data, by index, associated with the RSA key.
  2678. *
  2679. * @param [in] rsa RSA key.
  2680. * @param [in] idx Index of extra data.
  2681. * @return Extra data (anonymous type) on success.
  2682. * @return NULL on failure.
  2683. */
  2684. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2685. {
  2686. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2687. #ifdef HAVE_EX_DATA
  2688. return (rsa == NULL) ? NULL :
  2689. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2690. #else
  2691. (void)rsa;
  2692. (void)idx;
  2693. return NULL;
  2694. #endif
  2695. }
  2696. /* Set extra data against the RSA key at an index.
  2697. *
  2698. * @param [in, out] rsa RSA key.
  2699. * @param [in] idx Index set set extra data at.
  2700. * @param [in] data Extra data of anonymous type.
  2701. * @return 1 on success.
  2702. * @return 0 on failure.
  2703. */
  2704. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2705. {
  2706. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2707. #ifdef HAVE_EX_DATA
  2708. return (rsa == NULL) ? 0 :
  2709. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2710. #else
  2711. (void)rsa;
  2712. (void)idx;
  2713. (void)data;
  2714. return 0;
  2715. #endif
  2716. }
  2717. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2718. /* Set the extra data and cleanup callback against the RSA key at an index.
  2719. *
  2720. * Not OpenSSL API.
  2721. *
  2722. * @param [in, out] rsa RSA key.
  2723. * @param [in] idx Index set set extra data at.
  2724. * @param [in] data Extra data of anonymous type.
  2725. * @param [in] freeCb Callback function to free extra data.
  2726. * @return 1 on success.
  2727. * @return 0 on failure.
  2728. */
  2729. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2730. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2731. {
  2732. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2733. return (rsa == NULL) ? 0 :
  2734. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2735. freeCb);
  2736. }
  2737. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2738. /*
  2739. * RSA check key APIs
  2740. */
  2741. #ifdef WOLFSSL_RSA_KEY_CHECK
  2742. /* Check that the RSA key is valid using wolfCrypt.
  2743. *
  2744. * @param [in] rsa RSA key.
  2745. * @return 1 on success.
  2746. * @return 0 on failure.
  2747. */
  2748. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2749. {
  2750. int ret = 1;
  2751. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2752. /* Validate parameters. */
  2753. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2754. ret = 0;
  2755. }
  2756. /* Constant RSA - assume internal data has been set. */
  2757. /* Check wolfCrypt RSA key. */
  2758. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2759. ret = 0;
  2760. }
  2761. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2762. return ret;
  2763. }
  2764. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2765. /*
  2766. * RSA generate APIs
  2767. */
  2768. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2769. /* Get a random number generator associated with the RSA key.
  2770. *
  2771. * If not able, then get the global if possible.
  2772. * *tmpRng must not be an initialized RNG.
  2773. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2774. * associated with the wolfCrypt RSA key.
  2775. *
  2776. * @param [in] rsa RSA key.
  2777. * @param [out] tmpRng Temporary random number generator.
  2778. * @param [out] initTmpRng Temporary random number generator was initialized.
  2779. *
  2780. * @return A wolfCrypt RNG to use on success.
  2781. * @return NULL on error.
  2782. */
  2783. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2784. {
  2785. WC_RNG* rng = NULL;
  2786. int err = 0;
  2787. /* Check validity of parameters. */
  2788. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2789. err = 1;
  2790. }
  2791. if (!err) {
  2792. /* Haven't initialized any RNG passed through tmpRng. */
  2793. *initTmpRng = 0;
  2794. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2795. /* Use wolfCrypt RSA key's RNG if available/set. */
  2796. rng = ((RsaKey*)rsa->internal)->rng;
  2797. #endif
  2798. }
  2799. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2800. /* Make an RNG with tmpRng or get global. */
  2801. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2802. if ((rng != NULL) && *initTmpRng) {
  2803. *tmpRng = rng;
  2804. }
  2805. }
  2806. return rng;
  2807. }
  2808. #endif
  2809. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2810. *
  2811. * @param [in, out] rsa RSA key.
  2812. * @param [in] bits Number of bits that the modulus must have.
  2813. * @param [in] e A BN object holding the public exponent to use.
  2814. * @param [in] cb Status callback. Unused.
  2815. * @return 0 on success.
  2816. * @return wolfSSL native error code on error.
  2817. */
  2818. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2819. WOLFSSL_BIGNUM* e, void* cb)
  2820. {
  2821. #ifdef WOLFSSL_KEY_GEN
  2822. int ret = 0;
  2823. #ifdef WOLFSSL_SMALL_STACK
  2824. WC_RNG* tmpRng = NULL;
  2825. #else
  2826. WC_RNG _tmpRng[1];
  2827. WC_RNG* tmpRng = _tmpRng;
  2828. #endif
  2829. int initTmpRng = 0;
  2830. WC_RNG* rng = NULL;
  2831. #endif
  2832. (void)cb;
  2833. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2834. #ifdef WOLFSSL_KEY_GEN
  2835. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2836. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2837. if (rng == NULL) {
  2838. /* Something went wrong so return memory error. */
  2839. ret = MEMORY_E;
  2840. }
  2841. if (ret == 0) {
  2842. /* Generate an RSA key. */
  2843. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2844. (long)wolfSSL_BN_get_word(e), rng);
  2845. if (ret != MP_OKAY) {
  2846. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2847. }
  2848. }
  2849. if (ret == 0) {
  2850. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2851. ret = SetRsaExternal(rsa);
  2852. if (ret == 1) {
  2853. /* Internal matches external. */
  2854. rsa->inSet = 1;
  2855. /* Return success. */
  2856. ret = 0;
  2857. }
  2858. else {
  2859. /* Something went wrong so return memory error. */
  2860. ret = MEMORY_E;
  2861. }
  2862. }
  2863. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2864. if (initTmpRng) {
  2865. wc_FreeRng(tmpRng);
  2866. }
  2867. #ifdef WOLFSSL_SMALL_STACK
  2868. /* Dispose of any allocated RNG. */
  2869. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2870. #endif
  2871. return ret;
  2872. #else
  2873. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2874. (void)rsa;
  2875. (void)e;
  2876. (void)bits;
  2877. return NOT_COMPILED_IN;
  2878. #endif
  2879. }
  2880. /* Generate an RSA key that has the specified modulus size and public exponent.
  2881. *
  2882. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2883. * down to nearest multiple of 8. For example generating a key of size
  2884. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2885. *
  2886. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2887. * @param [in] e Public exponent to use i.e. 65537.
  2888. * @param [in] cb Status callback. Unused.
  2889. * @param [in] data Data to pass to status callback. Unused.
  2890. * @return A new RSA key on success.
  2891. * @return NULL on failure.
  2892. */
  2893. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2894. void(*cb)(int, int, void*), void* data)
  2895. {
  2896. WOLFSSL_RSA* rsa = NULL;
  2897. WOLFSSL_BIGNUM* bn = NULL;
  2898. int err = 0;
  2899. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  2900. (void)cb;
  2901. (void)data;
  2902. /* Validate bits. */
  2903. if (bits < 0) {
  2904. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  2905. err = 1;
  2906. }
  2907. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  2908. * longer values. */
  2909. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  2910. WOLFSSL_ERROR_MSG("Error creating big number");
  2911. err = 1;
  2912. }
  2913. /* Set public exponent. */
  2914. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  2915. WOLFSSL_ERROR_MSG("Error using e value");
  2916. err = 1;
  2917. }
  2918. /* Create an RSA key object to hold generated key. */
  2919. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  2920. WOLFSSL_ERROR_MSG("memory error");
  2921. err = 1;
  2922. }
  2923. while (!err) {
  2924. int ret;
  2925. /* Use wolfCrypt to generate RSA key. */
  2926. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  2927. #ifdef HAVE_FIPS
  2928. /* Keep trying if failed to find a prime. */
  2929. if (ret == PRIME_GEN_E) {
  2930. continue;
  2931. }
  2932. #endif
  2933. if (ret != WOLFSSL_ERROR_NONE) {
  2934. /* Unrecoverable error in generation. */
  2935. err = 1;
  2936. }
  2937. /* Done generating - unrecoverable error or success. */
  2938. break;
  2939. }
  2940. if (err) {
  2941. /* Dispose of RSA key object if generation didn't work. */
  2942. wolfSSL_RSA_free(rsa);
  2943. /* Returning NULL on error. */
  2944. rsa = NULL;
  2945. }
  2946. /* Dispose of the temporary BN used for the public exponent. */
  2947. wolfSSL_BN_free(bn);
  2948. return rsa;
  2949. }
  2950. /* Generate an RSA key that has the specified modulus size and public exponent.
  2951. *
  2952. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2953. * down to nearest multiple of 8. For example generating a key of size
  2954. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2955. *
  2956. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2957. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  2958. * @param [in] cb Status callback. Unused.
  2959. * @return 1 on success.
  2960. * @return 0 on failure.
  2961. */
  2962. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  2963. void* cb)
  2964. {
  2965. int ret = 1;
  2966. /* Validate parameters. */
  2967. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2968. WOLFSSL_ERROR_MSG("bad arguments");
  2969. ret = 0;
  2970. }
  2971. else {
  2972. for (;;) {
  2973. /* Use wolfCrypt to generate RSA key. */
  2974. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  2975. #ifdef HAVE_FIPS
  2976. /* Keep trying again if public key value didn't work. */
  2977. if (gen_ret == PRIME_GEN_E) {
  2978. continue;
  2979. }
  2980. #endif
  2981. if (gen_ret != WOLFSSL_ERROR_NONE) {
  2982. /* Unrecoverable error in generation. */
  2983. ret = 0;
  2984. }
  2985. /* Done generating - unrecoverable error or success. */
  2986. break;
  2987. }
  2988. }
  2989. return ret;
  2990. }
  2991. #endif /* OPENSSL_EXTRA */
  2992. /*
  2993. * RSA padding APIs
  2994. */
  2995. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  2996. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  2997. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  2998. /* Add PKCS#1 PSS padding to hash.
  2999. *
  3000. *
  3001. * +-----------+
  3002. * | M |
  3003. * +-----------+
  3004. * |
  3005. * V
  3006. * Hash
  3007. * |
  3008. * V
  3009. * +--------+----------+----------+
  3010. * M' = |Padding1| mHash | salt |
  3011. * +--------+----------+----------+
  3012. * |
  3013. * +--------+----------+ V
  3014. * DB = |Padding2|maskedseed| Hash
  3015. * +--------+----------+ |
  3016. * | |
  3017. * V | +--+
  3018. * xor <--- MGF <---| |bc|
  3019. * | | +--+
  3020. * | | |
  3021. * V V V
  3022. * +-------------------+----------+--+
  3023. * EM = | maskedDB |maskedseed|bc|
  3024. * +-------------------+----------+--+
  3025. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3026. *
  3027. * @param [in] rsa RSA key.
  3028. * @param [out] em Encoded message.
  3029. * @param [in[ mHash Message hash.
  3030. * @param [in] hashAlg Hash algorithm.
  3031. * @param [in] saltLen Length of salt to generate.
  3032. * @return 1 on success.
  3033. * @return 0 on failure.
  3034. */
  3035. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3036. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3037. {
  3038. int ret = 1;
  3039. enum wc_HashType hashType;
  3040. int hashLen = 0;
  3041. int emLen = 0;
  3042. int mgf = 0;
  3043. int initTmpRng = 0;
  3044. WC_RNG *rng = NULL;
  3045. #ifdef WOLFSSL_SMALL_STACK
  3046. WC_RNG* tmpRng = NULL;
  3047. #else
  3048. WC_RNG _tmpRng[1];
  3049. WC_RNG* tmpRng = _tmpRng;
  3050. #endif
  3051. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3052. /* Validate parameters. */
  3053. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3054. ret = 0;
  3055. }
  3056. if (ret == 1) {
  3057. /* Get/create an RNG. */
  3058. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3059. if (rng == NULL) {
  3060. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3061. ret = 0;
  3062. }
  3063. }
  3064. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3065. /* Set the external data from the wolfCrypt RSA key if not done. */
  3066. if ((ret == 1) && (!rsa->exSet)) {
  3067. ret = SetRsaExternal(rsa);
  3068. }
  3069. if (ret == 1) {
  3070. /* Get the wolfCrypt hash algorithm type. */
  3071. hashType = EvpMd2MacType(hashAlg);
  3072. if (hashType > WC_HASH_TYPE_MAX) {
  3073. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3074. ret = 0;
  3075. }
  3076. }
  3077. if (ret == 1) {
  3078. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3079. mgf = wc_hash2mgf(hashType);
  3080. if (mgf == WC_MGF1NONE) {
  3081. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3082. ret = 0;
  3083. }
  3084. }
  3085. if (ret == 1) {
  3086. /* Get the length of the hash output. */
  3087. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3088. if (hashLen < 0) {
  3089. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3090. ret = 0;
  3091. }
  3092. }
  3093. if (ret == 1) {
  3094. /* Get length of RSA key - encrypted message length. */
  3095. emLen = wolfSSL_RSA_size(rsa);
  3096. if (ret <= 0) {
  3097. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3098. ret = 0;
  3099. }
  3100. }
  3101. if (ret == 1) {
  3102. /* Calculate the salt length to use for special cases. */
  3103. /* TODO: use special case wolfCrypt values? */
  3104. switch (saltLen) {
  3105. /* Negative saltLen values are treated differently. */
  3106. case RSA_PSS_SALTLEN_DIGEST:
  3107. saltLen = hashLen;
  3108. break;
  3109. case RSA_PSS_SALTLEN_MAX_SIGN:
  3110. case RSA_PSS_SALTLEN_MAX:
  3111. #ifdef WOLFSSL_PSS_LONG_SALT
  3112. saltLen = emLen - hashLen - 2;
  3113. #else
  3114. saltLen = hashLen;
  3115. #endif
  3116. break;
  3117. default:
  3118. if (saltLen < 0) {
  3119. /* No other negative values implemented. */
  3120. WOLFSSL_ERROR_MSG("invalid saltLen");
  3121. ret = 0;
  3122. }
  3123. }
  3124. }
  3125. if (ret == 1) {
  3126. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3127. if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen,
  3128. RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0,
  3129. saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3130. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3131. ret = 0;
  3132. }
  3133. }
  3134. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3135. if (initTmpRng) {
  3136. wc_FreeRng(tmpRng);
  3137. }
  3138. #ifdef WOLFSSL_SMALL_STACK
  3139. /* Dispose of any allocated RNG. */
  3140. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3141. #endif
  3142. return ret;
  3143. }
  3144. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3145. *
  3146. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3147. *
  3148. * @param [in] rsa RSA key.
  3149. * @param [in[ mHash Message hash.
  3150. * @param [in] hashAlg Hash algorithm.
  3151. * @param [in] em Encoded message.
  3152. * @param [in] saltLen Length of salt to generate.
  3153. * @return 1 on success.
  3154. * @return 0 on failure.
  3155. */
  3156. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3157. const WOLFSSL_EVP_MD *hashAlg,
  3158. const unsigned char *em, int saltLen)
  3159. {
  3160. int ret = 1;
  3161. int hashLen = 0;
  3162. int mgf = 0;
  3163. int emLen = 0;
  3164. int mPrimeLen = 0;
  3165. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3166. byte *mPrime = NULL;
  3167. byte *buf = NULL;
  3168. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3169. /* Validate parameters. */
  3170. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3171. ret = 0;
  3172. }
  3173. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3174. /* Set the external data from the wolfCrypt RSA key if not done. */
  3175. if ((ret == 1) && (!rsa->exSet)) {
  3176. ret = SetRsaExternal(rsa);
  3177. }
  3178. if (ret == 1) {
  3179. /* Get hash length for hash algorithm. */
  3180. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3181. if (hashLen < 0) {
  3182. ret = 0;
  3183. }
  3184. }
  3185. if (ret == 1) {
  3186. /* Get length of RSA key - encrypted message length. */
  3187. emLen = wolfSSL_RSA_size(rsa);
  3188. if (emLen <= 0) {
  3189. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3190. ret = 0;
  3191. }
  3192. }
  3193. if (ret == 1) {
  3194. /* Calculate the salt length to use for special cases. */
  3195. switch (saltLen) {
  3196. /* Negative saltLen values are treated differently */
  3197. case RSA_PSS_SALTLEN_DIGEST:
  3198. saltLen = hashLen;
  3199. break;
  3200. case RSA_PSS_SALTLEN_AUTO:
  3201. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3202. saltLen = RSA_PSS_SALT_LEN_DISCOVER;
  3203. break;
  3204. #endif
  3205. case RSA_PSS_SALTLEN_MAX:
  3206. #ifdef WOLFSSL_PSS_LONG_SALT
  3207. saltLen = emLen - hashLen - 2;
  3208. #else
  3209. saltLen = hashLen;
  3210. #endif
  3211. break;
  3212. default:
  3213. if (saltLen < 0) {
  3214. /* No other negative values implemented. */
  3215. WOLFSSL_ERROR_MSG("invalid saltLen");
  3216. ret = 0;
  3217. }
  3218. }
  3219. }
  3220. if (ret == 1) {
  3221. /* Get the wolfCrypt hash algorithm type. */
  3222. hashType = EvpMd2MacType(hashAlg);
  3223. if (hashType > WC_HASH_TYPE_MAX) {
  3224. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3225. ret = 0;
  3226. }
  3227. }
  3228. if (ret == 1) {
  3229. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3230. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3231. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3232. ret = 0;
  3233. }
  3234. }
  3235. if (ret == 1) {
  3236. /* Allocate buffer to unpad inline with. */
  3237. buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3238. if (buf == NULL) {
  3239. WOLFSSL_ERROR_MSG("malloc error");
  3240. ret = 0;
  3241. }
  3242. }
  3243. if (ret == 1) {
  3244. /* Copy encrypted message to temp for inline unpadding. */
  3245. XMEMCPY(buf, em, (size_t)emLen);
  3246. /* Remove and verify the PSS padding. */
  3247. mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime,
  3248. RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3249. wolfSSL_BN_num_bits(rsa->n), NULL);
  3250. if (mPrimeLen < 0) {
  3251. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3252. ret = 0;
  3253. }
  3254. }
  3255. if (ret == 1) {
  3256. /* Verify the hash is correct. */
  3257. if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime,
  3258. (word32)mPrimeLen, hashType, saltLen,
  3259. wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3260. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3261. ret = 0;
  3262. }
  3263. }
  3264. /* Dispose of any allocated buffer. */
  3265. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3266. return ret;
  3267. }
  3268. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3269. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3270. * WOLFSSL_NGINX) */
  3271. /*
  3272. * RSA sign/verify APIs
  3273. */
  3274. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3275. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3276. #else
  3277. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3278. #endif
  3279. #if defined(OPENSSL_EXTRA)
  3280. #if !defined(HAVE_USER_RSA)
  3281. /* Encode the message hash.
  3282. *
  3283. * Used by signing and verification.
  3284. *
  3285. * @param [in] hashAlg Hash algorithm OID.
  3286. * @param [in] hash Hash of message to encode for signing.
  3287. * @param [in] hLen Length of hash of message.
  3288. * @param [out] enc Encoded message hash.
  3289. * @param [out] encLen Length of encoded message hash.
  3290. * @param [in] padding Which padding scheme is being used.
  3291. * @return 1 on success.
  3292. * @return 0 on failure.
  3293. */
  3294. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3295. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3296. {
  3297. int ret = 1;
  3298. int hType = WC_HASH_TYPE_NONE;
  3299. /* Validate parameters. */
  3300. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3301. ret = 0;
  3302. }
  3303. if ((ret == 1) && (hashAlg != NID_undef) &&
  3304. (padding == RSA_PKCS1_PADDING)) {
  3305. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3306. hType = (int)nid2oid(hashAlg, oidHashType);
  3307. if (hType == -1) {
  3308. ret = 0;
  3309. }
  3310. }
  3311. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3312. /* PKCS#1.5 encoding. */
  3313. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3314. if (encSz == 0) {
  3315. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3316. ret = 0;
  3317. }
  3318. else {
  3319. *encLen = (unsigned int)encSz;
  3320. }
  3321. }
  3322. /* Other padding schemes require the hash as is. */
  3323. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3324. XMEMCPY(enc, hash, hLen);
  3325. *encLen = hLen;
  3326. }
  3327. return ret;
  3328. }
  3329. /* Sign the message hash using hash algorithm and RSA key.
  3330. *
  3331. * @param [in] hashAlg Hash algorithm OID.
  3332. * @param [in] hash Hash of message to encode for signing.
  3333. * @param [in] hLen Length of hash of message.
  3334. * @param [out] enc Encoded message hash.
  3335. * @param [out] encLen Length of encoded message hash.
  3336. * @param [in] rsa RSA key.
  3337. * @return 1 on success.
  3338. * @return 0 on failure.
  3339. */
  3340. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3341. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3342. {
  3343. if (sigLen != NULL) {
  3344. /* No size checking in this API */
  3345. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3346. }
  3347. /* flag is 1: output complete signature. */
  3348. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3349. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3350. }
  3351. /* Sign the message hash using hash algorithm and RSA key.
  3352. *
  3353. * Not OpenSSL API.
  3354. *
  3355. * @param [in] hashAlg Hash algorithm NID.
  3356. * @param [in] hash Hash of message to encode for signing.
  3357. * @param [in] hLen Length of hash of message.
  3358. * @param [out] enc Encoded message hash.
  3359. * @param [out] encLen Length of encoded message hash.
  3360. * @param [in] rsa RSA key.
  3361. * @param [in] flag When 1: Output encrypted signature.
  3362. * When 0: Output encoded hash.
  3363. * @return 1 on success.
  3364. * @return 0 on failure.
  3365. */
  3366. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3367. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3368. WOLFSSL_RSA* rsa, int flag)
  3369. {
  3370. int ret = 0;
  3371. if ((flag == 0) || (flag == 1)) {
  3372. if (sigLen != NULL) {
  3373. /* No size checking in this API */
  3374. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3375. }
  3376. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3377. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3378. }
  3379. return ret;
  3380. }
  3381. /**
  3382. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3383. *
  3384. * Not OpenSSL API.
  3385. *
  3386. * @param [in] hashAlg Hash NID
  3387. * @param [in] hash Message hash to sign.
  3388. * @param [in] mLen Length of message hash to sign.
  3389. * @param [out] sigRet Output buffer.
  3390. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3391. * On Output: length of data written to sigRet.
  3392. * @param [in] rsa RSA key used to sign the input.
  3393. * @param [in] flag 1: Output the signature.
  3394. * 0: Output the value that the unpadded signature
  3395. * should be compared to.
  3396. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3397. * RSA_PKCS1_PADDING are currently supported for
  3398. * signing.
  3399. * @return 1 on success.
  3400. * @return 0 on failure.
  3401. */
  3402. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3403. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3404. WOLFSSL_RSA* rsa, int flag, int padding)
  3405. {
  3406. int ret = 1;
  3407. word32 outLen = 0;
  3408. int signSz = 0;
  3409. WC_RNG* rng = NULL;
  3410. int initTmpRng = 0;
  3411. #ifdef WOLFSSL_SMALL_STACK
  3412. WC_RNG* tmpRng = NULL;
  3413. byte* encodedSig = NULL;
  3414. #else
  3415. WC_RNG _tmpRng[1];
  3416. WC_RNG* tmpRng = _tmpRng;
  3417. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3418. #endif
  3419. unsigned int encSz = 0;
  3420. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3421. if (flag == 0) {
  3422. /* Only encode message. */
  3423. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3424. padding);
  3425. }
  3426. /* Validate parameters. */
  3427. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3428. WOLFSSL_ERROR_MSG("Bad function arguments");
  3429. ret = 0;
  3430. }
  3431. /* Set wolfCrypt RSA key data from external if not already done. */
  3432. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3433. ret = 0;
  3434. }
  3435. if (ret == 1) {
  3436. /* Get the maximum signature length. */
  3437. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3438. /* Check not an error return. */
  3439. if (outLen == 0) {
  3440. WOLFSSL_ERROR_MSG("Bad RSA size");
  3441. ret = 0;
  3442. }
  3443. /* Check signature buffer is big enough. */
  3444. else if (outLen > *sigLen) {
  3445. WOLFSSL_ERROR_MSG("Output buffer too small");
  3446. ret = 0;
  3447. }
  3448. }
  3449. #ifdef WOLFSSL_SMALL_STACK
  3450. if (ret == 1) {
  3451. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3452. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3453. DYNAMIC_TYPE_SIGNATURE);
  3454. if (encodedSig == NULL) {
  3455. ret = 0;
  3456. }
  3457. }
  3458. #endif
  3459. if (ret == 1) {
  3460. /* Get/create an RNG. */
  3461. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3462. if (rng == NULL) {
  3463. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3464. ret = 0;
  3465. }
  3466. }
  3467. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3468. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3469. &encSz, padding) == 0)) {
  3470. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3471. ret = 0;
  3472. }
  3473. if (ret == 1) {
  3474. switch (padding) {
  3475. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3476. case RSA_NO_PADDING:
  3477. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3478. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3479. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3480. ret = 0;
  3481. }
  3482. break;
  3483. #endif
  3484. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3485. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3486. case RSA_PKCS1_PSS_PADDING:
  3487. {
  3488. enum wc_HashType hType =
  3489. wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3490. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3491. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3492. "OpenSSL uses max length by default.");
  3493. #endif
  3494. /* Create RSA PSS signature. */
  3495. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3496. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3497. (RsaKey*)rsa->internal, rng)) <= 0) {
  3498. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3499. ret = 0;
  3500. }
  3501. break;
  3502. }
  3503. #endif
  3504. #ifndef WC_NO_RSA_OAEP
  3505. case RSA_PKCS1_OAEP_PADDING:
  3506. /* Not a signature padding scheme. */
  3507. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3508. "signing");
  3509. ret = 0;
  3510. break;
  3511. #endif
  3512. case RSA_PKCS1_PADDING:
  3513. {
  3514. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3515. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3516. (RsaKey*)rsa->internal, rng)) <= 0) {
  3517. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3518. ret = 0;
  3519. }
  3520. break;
  3521. }
  3522. default:
  3523. WOLFSSL_ERROR_MSG("Unsupported padding");
  3524. ret = 0;
  3525. break;
  3526. }
  3527. }
  3528. if (ret == 1) {
  3529. /* Return the size of signature generated. */
  3530. *sigLen = (unsigned int)signSz;
  3531. }
  3532. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3533. if (initTmpRng) {
  3534. wc_FreeRng(tmpRng);
  3535. }
  3536. #ifdef WOLFSSL_SMALL_STACK
  3537. /* Dispose of any allocated RNG and encoded signature. */
  3538. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3539. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3540. #endif
  3541. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3542. return ret;
  3543. }
  3544. /**
  3545. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3546. *
  3547. * @param [in] hashAlg Hash NID
  3548. * @param [in] hash Message hash.
  3549. * @param [in] mLen Length of message hash.
  3550. * @param [in] sigRet Signature data.
  3551. * @param [in] sigLen Length of signature data.
  3552. * @param [in] rsa RSA key used to sign the input
  3553. * @return 1 on success.
  3554. * @return 0 on failure.
  3555. */
  3556. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3557. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3558. WOLFSSL_RSA* rsa)
  3559. {
  3560. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3561. RSA_PKCS1_PADDING);
  3562. }
  3563. /**
  3564. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3565. *
  3566. * Not OpenSSL API.
  3567. *
  3568. * @param [in] hashAlg Hash NID
  3569. * @param [in] hash Message hash.
  3570. * @param [in] mLen Length of message hash.
  3571. * @param [in] sigRet Signature data.
  3572. * @param [in] sigLen Length of signature data.
  3573. * @param [in] rsa RSA key used to sign the input
  3574. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3575. * RSA_PKCS1_PADDING are currently supported for
  3576. * signing.
  3577. * @return 1 on success.
  3578. * @return 0 on failure.
  3579. */
  3580. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3581. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3582. WOLFSSL_RSA* rsa, int padding)
  3583. {
  3584. int ret = 1;
  3585. #ifdef WOLFSSL_SMALL_STACK
  3586. unsigned char* encodedSig = NULL;
  3587. #else
  3588. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3589. #endif
  3590. unsigned char* sigDec = NULL;
  3591. unsigned int len = MAX_ENCODED_SIG_SZ;
  3592. int verLen = 0;
  3593. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3594. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3595. #endif
  3596. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3597. /* Validate parameters. */
  3598. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3599. WOLFSSL_ERROR_MSG("Bad function arguments");
  3600. ret = 0;
  3601. }
  3602. if (ret == 1) {
  3603. /* Allocate memory for decrypted signature. */
  3604. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3605. DYNAMIC_TYPE_TMP_BUFFER);
  3606. if (sigDec == NULL) {
  3607. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3608. ret = 0;
  3609. }
  3610. }
  3611. #ifdef WOLFSSL_SMALL_STACK
  3612. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3613. /* Allocate memory for encoded signature. */
  3614. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3615. DYNAMIC_TYPE_TMP_BUFFER);
  3616. if (encodedSig == NULL) {
  3617. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3618. ret = 0;
  3619. }
  3620. }
  3621. #endif
  3622. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3623. /* Make encoded signature to compare with decrypted signature. */
  3624. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3625. padding) <= 0) {
  3626. WOLFSSL_ERROR_MSG("Message Digest Error");
  3627. ret = 0;
  3628. }
  3629. }
  3630. if (ret == 1) {
  3631. /* Decrypt signature */
  3632. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3633. !defined(HAVE_SELFTEST)
  3634. hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3635. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3636. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3637. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3638. ret = 0;
  3639. }
  3640. #else
  3641. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3642. (RsaKey*)rsa->internal);
  3643. if (verLen < 0) {
  3644. ret = 0;
  3645. }
  3646. #endif
  3647. }
  3648. if (ret == 1) {
  3649. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3650. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3651. if (padding == RSA_PKCS1_PSS_PADDING) {
  3652. /* Check PSS padding is valid. */
  3653. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen,
  3654. hType, DEF_PSS_SALT_LEN,
  3655. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3656. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3657. ret = 0;
  3658. }
  3659. }
  3660. else
  3661. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3662. * FIPS_VERSION >= 5.1) */
  3663. /* Compare decrypted signature to encoded signature. */
  3664. if (((int)len != verLen) ||
  3665. (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) {
  3666. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3667. ret = 0;
  3668. }
  3669. }
  3670. /* Dispose of any allocated data. */
  3671. #ifdef WOLFSSL_SMALL_STACK
  3672. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3673. #endif
  3674. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3675. return ret;
  3676. }
  3677. /*
  3678. * RSA public/private encrypt/decrypt APIs
  3679. */
  3680. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  3681. /* Encrypt with the RSA public key.
  3682. *
  3683. * Return compliant with OpenSSL.
  3684. *
  3685. * @param [in] len Length of data to encrypt.
  3686. * @param [in] from Data to encrypt.
  3687. * @param [out] to Encrypted data.
  3688. * @param [in] rsa RSA key.
  3689. * @param [in] padding Type of padding to place around plaintext.
  3690. * @return Size of encrypted data on success.
  3691. * @return -1 on failure.
  3692. */
  3693. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3694. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3695. {
  3696. int ret = 0;
  3697. int initTmpRng = 0;
  3698. WC_RNG *rng = NULL;
  3699. #ifdef WOLFSSL_SMALL_STACK
  3700. WC_RNG* tmpRng = NULL;
  3701. #else
  3702. WC_RNG _tmpRng[1];
  3703. WC_RNG* tmpRng = _tmpRng;
  3704. #endif
  3705. #if !defined(HAVE_FIPS)
  3706. int mgf = WC_MGF1NONE;
  3707. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3708. int pad_type = WC_RSA_NO_PAD;
  3709. #endif
  3710. int outLen = 0;
  3711. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3712. /* Validate parameters. */
  3713. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3714. (from == NULL)) {
  3715. WOLFSSL_ERROR_MSG("Bad function arguments");
  3716. ret = -1;
  3717. }
  3718. if (ret == 0) {
  3719. #if !defined(HAVE_FIPS)
  3720. /* Convert to wolfCrypt padding, hash and MGF. */
  3721. switch (padding) {
  3722. case RSA_PKCS1_PADDING:
  3723. pad_type = WC_RSA_PKCSV15_PAD;
  3724. break;
  3725. case RSA_PKCS1_OAEP_PADDING:
  3726. pad_type = WC_RSA_OAEP_PAD;
  3727. hash = WC_HASH_TYPE_SHA;
  3728. mgf = WC_MGF1SHA1;
  3729. break;
  3730. case RSA_NO_PADDING:
  3731. pad_type = WC_RSA_NO_PAD;
  3732. break;
  3733. default:
  3734. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3735. "scheme");
  3736. ret = -1;
  3737. }
  3738. #else
  3739. /* Check for supported padding schemes in FIPS. */
  3740. /* TODO: Do we support more schemes in later versions of FIPS? */
  3741. if (padding != RSA_PKCS1_PADDING) {
  3742. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3743. "FIPS");
  3744. ret = -1;
  3745. }
  3746. #endif
  3747. }
  3748. /* Set wolfCrypt RSA key data from external if not already done. */
  3749. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3750. ret = -1;
  3751. }
  3752. if (ret == 0) {
  3753. /* Calculate maximum length of encrypted data. */
  3754. outLen = wolfSSL_RSA_size(rsa);
  3755. if (outLen == 0) {
  3756. WOLFSSL_ERROR_MSG("Bad RSA size");
  3757. ret = -1;
  3758. }
  3759. }
  3760. if (ret == 0) {
  3761. /* Get an RNG. */
  3762. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3763. if (rng == NULL) {
  3764. ret = -1;
  3765. }
  3766. }
  3767. if (ret == 0) {
  3768. /* Use wolfCrypt to public-encrypt with RSA key. */
  3769. #if !defined(HAVE_FIPS)
  3770. ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen,
  3771. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3772. #else
  3773. ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen,
  3774. (RsaKey*)rsa->internal, rng);
  3775. #endif
  3776. }
  3777. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3778. if (initTmpRng) {
  3779. wc_FreeRng(tmpRng);
  3780. }
  3781. #ifdef WOLFSSL_SMALL_STACK
  3782. /* Dispose of any allocated RNG. */
  3783. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3784. #endif
  3785. /* wolfCrypt error means return -1. */
  3786. if (ret <= 0) {
  3787. ret = -1;
  3788. }
  3789. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3790. return ret;
  3791. }
  3792. /* Decrypt with the RSA public key.
  3793. *
  3794. * Return compliant with OpenSSL.
  3795. *
  3796. * @param [in] len Length of encrypted data.
  3797. * @param [in] from Encrypted data.
  3798. * @param [out] to Decrypted data.
  3799. * @param [in] rsa RSA key.
  3800. * @param [in] padding Type of padding to around plaintext to remove.
  3801. * @return Size of decrypted data on success.
  3802. * @return -1 on failure.
  3803. */
  3804. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3805. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3806. {
  3807. int ret = 0;
  3808. #if !defined(HAVE_FIPS)
  3809. int mgf = WC_MGF1NONE;
  3810. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3811. int pad_type = WC_RSA_NO_PAD;
  3812. #endif
  3813. int outLen = 0;
  3814. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3815. /* Validate parameters. */
  3816. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3817. (from == NULL)) {
  3818. WOLFSSL_ERROR_MSG("Bad function arguments");
  3819. ret = -1;
  3820. }
  3821. if (ret == 0) {
  3822. #if !defined(HAVE_FIPS)
  3823. switch (padding) {
  3824. case RSA_PKCS1_PADDING:
  3825. pad_type = WC_RSA_PKCSV15_PAD;
  3826. break;
  3827. case RSA_PKCS1_OAEP_PADDING:
  3828. pad_type = WC_RSA_OAEP_PAD;
  3829. hash = WC_HASH_TYPE_SHA;
  3830. mgf = WC_MGF1SHA1;
  3831. break;
  3832. case RSA_NO_PADDING:
  3833. pad_type = WC_RSA_NO_PAD;
  3834. break;
  3835. default:
  3836. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3837. ret = -1;
  3838. }
  3839. #else
  3840. /* Check for supported padding schemes in FIPS. */
  3841. /* TODO: Do we support more schemes in later versions of FIPS? */
  3842. if (padding != RSA_PKCS1_PADDING) {
  3843. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3844. "FIPS");
  3845. ret = -1;
  3846. }
  3847. #endif
  3848. }
  3849. /* Set wolfCrypt RSA key data from external if not already done. */
  3850. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3851. ret = -1;
  3852. }
  3853. if (ret == 0) {
  3854. /* Calculate maximum length of decrypted data. */
  3855. outLen = wolfSSL_RSA_size(rsa);
  3856. if (outLen == 0) {
  3857. WOLFSSL_ERROR_MSG("Bad RSA size");
  3858. ret = -1;
  3859. }
  3860. }
  3861. if (ret == 0) {
  3862. /* Use wolfCrypt to private-decrypt with RSA key.
  3863. * Size of 'to' buffer must be size of RSA key */
  3864. #if !defined(HAVE_FIPS)
  3865. ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen,
  3866. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3867. #else
  3868. ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen,
  3869. (RsaKey*)rsa->internal);
  3870. #endif
  3871. }
  3872. /* wolfCrypt error means return -1. */
  3873. if (ret <= 0) {
  3874. ret = -1;
  3875. }
  3876. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  3877. return ret;
  3878. }
  3879. /* Decrypt with the RSA public key.
  3880. *
  3881. * @param [in] len Length of encrypted data.
  3882. * @param [in] from Encrypted data.
  3883. * @param [out] to Decrypted data.
  3884. * @param [in] rsa RSA key.
  3885. * @param [in] padding Type of padding to around plaintext to remove.
  3886. * @return Size of decrypted data on success.
  3887. * @return -1 on failure.
  3888. */
  3889. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3890. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3891. {
  3892. int ret = 0;
  3893. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3894. int pad_type = WC_RSA_NO_PAD;
  3895. #endif
  3896. int outLen = 0;
  3897. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  3898. /* Validate parameters. */
  3899. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3900. (from == NULL)) {
  3901. WOLFSSL_ERROR_MSG("Bad function arguments");
  3902. ret = -1;
  3903. }
  3904. if (ret == 0) {
  3905. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3906. switch (padding) {
  3907. case RSA_PKCS1_PADDING:
  3908. pad_type = WC_RSA_PKCSV15_PAD;
  3909. break;
  3910. case RSA_NO_PADDING:
  3911. pad_type = WC_RSA_NO_PAD;
  3912. break;
  3913. /* TODO: RSA_X931_PADDING not supported */
  3914. default:
  3915. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  3916. ret = -1;
  3917. }
  3918. #else
  3919. if (padding != RSA_PKCS1_PADDING) {
  3920. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  3921. "FIPS");
  3922. ret = -1;
  3923. }
  3924. #endif
  3925. }
  3926. /* Set wolfCrypt RSA key data from external if not already done. */
  3927. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3928. ret = -1;
  3929. }
  3930. if (ret == 0) {
  3931. /* Calculate maximum length of encrypted data. */
  3932. outLen = wolfSSL_RSA_size(rsa);
  3933. if (outLen == 0) {
  3934. WOLFSSL_ERROR_MSG("Bad RSA size");
  3935. ret = -1;
  3936. }
  3937. }
  3938. if (ret == 0) {
  3939. /* Use wolfCrypt to public-decrypt with RSA key. */
  3940. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3941. /* Size of 'to' buffer must be size of RSA key. */
  3942. ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen,
  3943. (RsaKey*)rsa->internal, pad_type);
  3944. #else
  3945. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  3946. ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen,
  3947. (RsaKey*)rsa->internal);
  3948. #endif
  3949. }
  3950. /* wolfCrypt error means return -1. */
  3951. if (ret <= 0) {
  3952. ret = -1;
  3953. }
  3954. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  3955. return ret;
  3956. }
  3957. /* Encrypt with the RSA private key.
  3958. *
  3959. * Calls wc_RsaSSL_Sign.
  3960. *
  3961. * @param [in] len Length of data to encrypt.
  3962. * @param [in] from Data to encrypt.
  3963. * @param [out] to Encrypted data.
  3964. * @param [in] rsa RSA key.
  3965. * @param [in] padding Type of padding to place around plaintext.
  3966. * @return Size of encrypted data on success.
  3967. * @return -1 on failure.
  3968. */
  3969. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  3970. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3971. {
  3972. int ret = 0;
  3973. int initTmpRng = 0;
  3974. WC_RNG *rng = NULL;
  3975. #ifdef WOLFSSL_SMALL_STACK
  3976. WC_RNG* tmpRng = NULL;
  3977. #else
  3978. WC_RNG _tmpRng[1];
  3979. WC_RNG* tmpRng = _tmpRng;
  3980. #endif
  3981. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  3982. /* Validate parameters. */
  3983. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3984. (from == NULL)) {
  3985. WOLFSSL_ERROR_MSG("Bad function arguments");
  3986. ret = -1;
  3987. }
  3988. if (ret == 0) {
  3989. switch (padding) {
  3990. case RSA_PKCS1_PADDING:
  3991. #ifdef WC_RSA_NO_PADDING
  3992. case RSA_NO_PADDING:
  3993. #endif
  3994. break;
  3995. /* TODO: RSA_X931_PADDING not supported */
  3996. default:
  3997. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  3998. ret = -1;
  3999. }
  4000. }
  4001. /* Set wolfCrypt RSA key data from external if not already done. */
  4002. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4003. ret = -1;
  4004. }
  4005. if (ret == 0) {
  4006. /* Get an RNG. */
  4007. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  4008. if (rng == NULL) {
  4009. ret = -1;
  4010. }
  4011. }
  4012. if (ret == 0) {
  4013. /* Use wolfCrypt to private-encrypt with RSA key.
  4014. * Size of output buffer must be size of RSA key. */
  4015. if (padding == RSA_PKCS1_PADDING) {
  4016. ret = wc_RsaSSL_Sign(from, (word32)len, to,
  4017. (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng);
  4018. }
  4019. #ifdef WC_RSA_NO_PADDING
  4020. else if (padding == RSA_NO_PADDING) {
  4021. word32 outLen = (word32)wolfSSL_RSA_size(rsa);
  4022. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  4023. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  4024. if (ret == 0)
  4025. ret = (int)outLen;
  4026. }
  4027. #endif
  4028. }
  4029. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4030. if (initTmpRng) {
  4031. wc_FreeRng(tmpRng);
  4032. }
  4033. #ifdef WOLFSSL_SMALL_STACK
  4034. /* Dispose of any allocated RNG. */
  4035. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4036. #endif
  4037. /* wolfCrypt error means return -1. */
  4038. if (ret <= 0) {
  4039. ret = -1;
  4040. }
  4041. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4042. return ret;
  4043. }
  4044. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  4045. /*
  4046. * RSA misc operation APIs
  4047. */
  4048. /* Calculate d mod p-1 and q-1 into BNs.
  4049. *
  4050. * Not OpenSSL API.
  4051. *
  4052. * @param [in, out] rsa RSA key.
  4053. * @return 1 on success.
  4054. * @return -1 on failure.
  4055. */
  4056. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4057. {
  4058. int ret = 1;
  4059. int err;
  4060. mp_int* t = NULL;
  4061. #ifdef WOLFSSL_SMALL_STACK
  4062. mp_int *tmp = NULL;
  4063. #else
  4064. mp_int tmp[1];
  4065. #endif
  4066. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4067. /* Validate parameters. */
  4068. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4069. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4070. WOLFSSL_ERROR_MSG("rsa no init error");
  4071. ret = -1;
  4072. }
  4073. #ifdef WOLFSSL_SMALL_STACK
  4074. if (ret == 1) {
  4075. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4076. DYNAMIC_TYPE_TMP_BUFFER);
  4077. if (tmp == NULL) {
  4078. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4079. ret = -1;
  4080. }
  4081. }
  4082. #endif
  4083. if (ret == 1) {
  4084. /* Initialize temp MP integer. */
  4085. if (mp_init(tmp) != MP_OKAY) {
  4086. WOLFSSL_ERROR_MSG("mp_init error");
  4087. ret = -1;
  4088. }
  4089. }
  4090. if (ret == 1) {
  4091. t = tmp;
  4092. /* Sub 1 from p into temp. */
  4093. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4094. if (err != MP_OKAY) {
  4095. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4096. ret = -1;
  4097. }
  4098. }
  4099. if (ret == 1) {
  4100. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4101. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4102. (mp_int*)rsa->dmp1->internal);
  4103. if (err != MP_OKAY) {
  4104. WOLFSSL_ERROR_MSG("mp_mod error");
  4105. ret = -1;
  4106. }
  4107. }
  4108. if (ret == 1) {
  4109. /* Sub 1 from q into temp. */
  4110. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4111. if (err != MP_OKAY) {
  4112. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4113. ret = -1;
  4114. }
  4115. }
  4116. if (ret == 1) {
  4117. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4118. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4119. (mp_int*)rsa->dmq1->internal);
  4120. if (err != MP_OKAY) {
  4121. WOLFSSL_ERROR_MSG("mp_mod error");
  4122. ret = -1;
  4123. }
  4124. }
  4125. mp_clear(t);
  4126. #ifdef WOLFSSL_SMALL_STACK
  4127. if (tmp != NULL)
  4128. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4129. #endif
  4130. return ret;
  4131. }
  4132. #endif /* !HAVE_USER_RSA */
  4133. #ifndef NO_WOLFSSL_STUB
  4134. /* Enable blinding for RSA key operations.
  4135. *
  4136. * Blinding is a compile time option in wolfCrypt.
  4137. *
  4138. * @param [in] rsa RSA key. Unused.
  4139. * @param [in] bnCtx BN context to use for blinding. Unused.
  4140. * @return 1 always.
  4141. */
  4142. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4143. {
  4144. WOLFSSL_STUB("RSA_blinding_on");
  4145. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4146. (void)rsa;
  4147. (void)bnCtx;
  4148. return 1; /* on by default */
  4149. }
  4150. #endif
  4151. #endif /* OPENSSL_EXTRA */
  4152. #endif /* !NO_RSA */
  4153. /*******************************************************************************
  4154. * END OF RSA API
  4155. ******************************************************************************/
  4156. /*******************************************************************************
  4157. * START OF DSA API
  4158. ******************************************************************************/
  4159. #ifndef NO_DSA
  4160. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4161. !defined(NO_STDIO_FILESYSTEM)
  4162. /* return code compliant with OpenSSL :
  4163. * 1 if success, 0 if error
  4164. */
  4165. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4166. {
  4167. int ret = 1;
  4168. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4169. if (fp == XBADFILE || dsa == NULL) {
  4170. ret = 0;
  4171. }
  4172. if (ret == 1 && dsa->p != NULL) {
  4173. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4174. if (pBits == 0) {
  4175. ret = 0;
  4176. }
  4177. else {
  4178. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4179. ret = 0;
  4180. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4181. ret = 0;
  4182. }
  4183. }
  4184. if (ret == 1 && dsa->priv_key != NULL) {
  4185. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4186. }
  4187. if (ret == 1 && dsa->pub_key != NULL) {
  4188. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4189. }
  4190. if (ret == 1 && dsa->p != NULL) {
  4191. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4192. }
  4193. if (ret == 1 && dsa->q != NULL) {
  4194. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4195. }
  4196. if (ret == 1 && dsa->g != NULL) {
  4197. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4198. }
  4199. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4200. return ret;
  4201. }
  4202. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4203. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4204. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4205. {
  4206. if (dsa) {
  4207. dsa->p = NULL;
  4208. dsa->q = NULL;
  4209. dsa->g = NULL;
  4210. dsa->pub_key = NULL;
  4211. dsa->priv_key = NULL;
  4212. dsa->internal = NULL;
  4213. dsa->inSet = 0;
  4214. dsa->exSet = 0;
  4215. }
  4216. }
  4217. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4218. {
  4219. WOLFSSL_DSA* external;
  4220. DsaKey* key;
  4221. WOLFSSL_MSG("wolfSSL_DSA_new");
  4222. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4223. if (key == NULL) {
  4224. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4225. return NULL;
  4226. }
  4227. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4228. DYNAMIC_TYPE_DSA);
  4229. if (external == NULL) {
  4230. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4231. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4232. return NULL;
  4233. }
  4234. InitwolfSSL_DSA(external);
  4235. if (wc_InitDsaKey(key) != 0) {
  4236. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4237. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4238. wolfSSL_DSA_free(external);
  4239. return NULL;
  4240. }
  4241. external->internal = key;
  4242. return external;
  4243. }
  4244. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4245. {
  4246. WOLFSSL_MSG("wolfSSL_DSA_free");
  4247. if (dsa) {
  4248. if (dsa->internal) {
  4249. FreeDsaKey((DsaKey*)dsa->internal);
  4250. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4251. dsa->internal = NULL;
  4252. }
  4253. wolfSSL_BN_free(dsa->priv_key);
  4254. wolfSSL_BN_free(dsa->pub_key);
  4255. wolfSSL_BN_free(dsa->g);
  4256. wolfSSL_BN_free(dsa->q);
  4257. wolfSSL_BN_free(dsa->p);
  4258. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4259. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4260. /* dsa = NULL, don't try to access or double free it */
  4261. }
  4262. }
  4263. /* wolfSSL -> OpenSSL */
  4264. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4265. {
  4266. DsaKey* key;
  4267. WOLFSSL_MSG("Entering SetDsaExternal");
  4268. if (dsa == NULL || dsa->internal == NULL) {
  4269. WOLFSSL_MSG("dsa key NULL error");
  4270. return -1;
  4271. }
  4272. key = (DsaKey*)dsa->internal;
  4273. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4274. WOLFSSL_MSG("dsa p key error");
  4275. return -1;
  4276. }
  4277. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4278. WOLFSSL_MSG("dsa q key error");
  4279. return -1;
  4280. }
  4281. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4282. WOLFSSL_MSG("dsa g key error");
  4283. return -1;
  4284. }
  4285. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4286. WOLFSSL_MSG("dsa y key error");
  4287. return -1;
  4288. }
  4289. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4290. WOLFSSL_MSG("dsa x key error");
  4291. return -1;
  4292. }
  4293. dsa->exSet = 1;
  4294. return 1;
  4295. }
  4296. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4297. #ifdef OPENSSL_EXTRA
  4298. /* Openssl -> WolfSSL */
  4299. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4300. {
  4301. DsaKey* key;
  4302. WOLFSSL_MSG("Entering SetDsaInternal");
  4303. if (dsa == NULL || dsa->internal == NULL) {
  4304. WOLFSSL_MSG("dsa key NULL error");
  4305. return -1;
  4306. }
  4307. key = (DsaKey*)dsa->internal;
  4308. if (dsa->p != NULL &&
  4309. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4310. WOLFSSL_MSG("rsa p key error");
  4311. return -1;
  4312. }
  4313. if (dsa->q != NULL &&
  4314. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4315. WOLFSSL_MSG("rsa q key error");
  4316. return -1;
  4317. }
  4318. if (dsa->g != NULL &&
  4319. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4320. WOLFSSL_MSG("rsa g key error");
  4321. return -1;
  4322. }
  4323. if (dsa->pub_key != NULL) {
  4324. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4325. WOLFSSL_MSG("rsa pub_key error");
  4326. return -1;
  4327. }
  4328. /* public key */
  4329. key->type = DSA_PUBLIC;
  4330. }
  4331. if (dsa->priv_key != NULL) {
  4332. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4333. WOLFSSL_MSG("rsa priv_key error");
  4334. return -1;
  4335. }
  4336. /* private key */
  4337. key->type = DSA_PRIVATE;
  4338. }
  4339. dsa->inSet = 1;
  4340. return 1;
  4341. }
  4342. /* return code compliant with OpenSSL :
  4343. * 1 if success, 0 if error
  4344. */
  4345. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4346. {
  4347. int ret = 0;
  4348. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4349. if (dsa == NULL || dsa->internal == NULL) {
  4350. WOLFSSL_MSG("Bad arguments");
  4351. return 0;
  4352. }
  4353. if (dsa->inSet == 0) {
  4354. WOLFSSL_MSG("No DSA internal set, do it");
  4355. if (SetDsaInternal(dsa) != 1) {
  4356. WOLFSSL_MSG("SetDsaInternal failed");
  4357. return ret;
  4358. }
  4359. }
  4360. #ifdef WOLFSSL_KEY_GEN
  4361. {
  4362. int initTmpRng = 0;
  4363. WC_RNG *rng = NULL;
  4364. #ifdef WOLFSSL_SMALL_STACK
  4365. WC_RNG *tmpRng;
  4366. #else
  4367. WC_RNG tmpRng[1];
  4368. #endif
  4369. #ifdef WOLFSSL_SMALL_STACK
  4370. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4371. if (tmpRng == NULL)
  4372. return -1;
  4373. #endif
  4374. if (wc_InitRng(tmpRng) == 0) {
  4375. rng = tmpRng;
  4376. initTmpRng = 1;
  4377. }
  4378. else {
  4379. WOLFSSL_MSG("Bad RNG Init, trying global");
  4380. rng = wolfssl_get_global_rng();
  4381. }
  4382. if (rng) {
  4383. /* These were allocated above by SetDsaInternal(). They should
  4384. * be cleared before wc_MakeDsaKey() which reinitializes
  4385. * x and y. */
  4386. mp_clear(&((DsaKey*)dsa->internal)->x);
  4387. mp_clear(&((DsaKey*)dsa->internal)->y);
  4388. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4389. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4390. else if (SetDsaExternal(dsa) != 1)
  4391. WOLFSSL_MSG("SetDsaExternal failed");
  4392. else
  4393. ret = 1;
  4394. }
  4395. if (initTmpRng)
  4396. wc_FreeRng(tmpRng);
  4397. #ifdef WOLFSSL_SMALL_STACK
  4398. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4399. #endif
  4400. }
  4401. #else /* WOLFSSL_KEY_GEN */
  4402. WOLFSSL_MSG("No Key Gen built in");
  4403. #endif
  4404. return ret;
  4405. }
  4406. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4407. */
  4408. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4409. int seedLen, int* counterRet, unsigned long* hRet,
  4410. WOLFSSL_BN_CB cb, void* CBArg)
  4411. {
  4412. WOLFSSL_DSA* dsa;
  4413. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4414. (void)cb;
  4415. (void)CBArg;
  4416. dsa = wolfSSL_DSA_new();
  4417. if (dsa == NULL) {
  4418. return NULL;
  4419. }
  4420. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4421. counterRet, hRet, NULL) != 1) {
  4422. wolfSSL_DSA_free(dsa);
  4423. return NULL;
  4424. }
  4425. return dsa;
  4426. }
  4427. /* return code compliant with OpenSSL :
  4428. * 1 if success, 0 if error
  4429. */
  4430. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4431. unsigned char* seed, int seedLen,
  4432. int* counterRet,
  4433. unsigned long* hRet, void* cb)
  4434. {
  4435. int ret = 0;
  4436. (void)bits;
  4437. (void)seed;
  4438. (void)seedLen;
  4439. (void)counterRet;
  4440. (void)hRet;
  4441. (void)cb;
  4442. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4443. if (dsa == NULL || dsa->internal == NULL) {
  4444. WOLFSSL_MSG("Bad arguments");
  4445. return 0;
  4446. }
  4447. #ifdef WOLFSSL_KEY_GEN
  4448. {
  4449. int initTmpRng = 0;
  4450. WC_RNG *rng = NULL;
  4451. #ifdef WOLFSSL_SMALL_STACK
  4452. WC_RNG *tmpRng;
  4453. #else
  4454. WC_RNG tmpRng[1];
  4455. #endif
  4456. #ifdef WOLFSSL_SMALL_STACK
  4457. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4458. if (tmpRng == NULL)
  4459. return -1;
  4460. #endif
  4461. if (wc_InitRng(tmpRng) == 0) {
  4462. rng = tmpRng;
  4463. initTmpRng = 1;
  4464. }
  4465. else {
  4466. WOLFSSL_MSG("Bad RNG Init, trying global");
  4467. rng = wolfssl_get_global_rng();
  4468. }
  4469. if (rng) {
  4470. if (wc_MakeDsaParameters(rng, bits,
  4471. (DsaKey*)dsa->internal) != MP_OKAY)
  4472. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4473. else if (SetDsaExternal(dsa) != 1)
  4474. WOLFSSL_MSG("SetDsaExternal failed");
  4475. else
  4476. ret = 1;
  4477. }
  4478. if (initTmpRng)
  4479. wc_FreeRng(tmpRng);
  4480. #ifdef WOLFSSL_SMALL_STACK
  4481. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4482. #endif
  4483. }
  4484. #else /* WOLFSSL_KEY_GEN */
  4485. WOLFSSL_MSG("No Key Gen built in");
  4486. #endif
  4487. return ret;
  4488. }
  4489. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4490. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4491. {
  4492. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4493. if (d != NULL) {
  4494. if (p != NULL)
  4495. *p = d->p;
  4496. if (q != NULL)
  4497. *q = d->q;
  4498. if (g != NULL)
  4499. *g = d->g;
  4500. }
  4501. }
  4502. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4503. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4504. {
  4505. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4506. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4507. WOLFSSL_MSG("Bad parameter");
  4508. return 0;
  4509. }
  4510. wolfSSL_BN_free(d->p);
  4511. wolfSSL_BN_free(d->q);
  4512. wolfSSL_BN_free(d->g);
  4513. d->p = p;
  4514. d->q = q;
  4515. d->g = g;
  4516. return 1;
  4517. }
  4518. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4519. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4520. {
  4521. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4522. if (d != NULL) {
  4523. if (pub_key != NULL)
  4524. *pub_key = d->pub_key;
  4525. if (priv_key != NULL)
  4526. *priv_key = d->priv_key;
  4527. }
  4528. }
  4529. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4530. WOLFSSL_BIGNUM *priv_key)
  4531. {
  4532. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4533. /* The private key may be NULL */
  4534. if (pub_key == NULL) {
  4535. WOLFSSL_MSG("Bad parameter");
  4536. return 0;
  4537. }
  4538. wolfSSL_BN_free(d->pub_key);
  4539. wolfSSL_BN_free(d->priv_key);
  4540. d->pub_key = pub_key;
  4541. d->priv_key = priv_key;
  4542. return 1;
  4543. }
  4544. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4545. {
  4546. WOLFSSL_DSA_SIG* sig;
  4547. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4548. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4549. DYNAMIC_TYPE_OPENSSL);
  4550. if (sig)
  4551. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4552. return sig;
  4553. }
  4554. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4555. {
  4556. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4557. if (sig) {
  4558. if (sig->r) {
  4559. wolfSSL_BN_free(sig->r);
  4560. }
  4561. if (sig->s) {
  4562. wolfSSL_BN_free(sig->s);
  4563. }
  4564. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4565. }
  4566. }
  4567. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4568. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4569. {
  4570. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4571. if (sig != NULL) {
  4572. *r = sig->r;
  4573. *s = sig->s;
  4574. }
  4575. }
  4576. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4577. WOLFSSL_BIGNUM *s)
  4578. {
  4579. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4580. if (r == NULL || s == NULL) {
  4581. WOLFSSL_MSG("Bad parameter");
  4582. return 0;
  4583. }
  4584. wolfSSL_BN_clear_free(sig->r);
  4585. wolfSSL_BN_clear_free(sig->s);
  4586. sig->r = r;
  4587. sig->s = s;
  4588. return 1;
  4589. }
  4590. #ifndef HAVE_SELFTEST
  4591. /**
  4592. *
  4593. * @param sig The input signature to encode
  4594. * @param out The output buffer. If *out is NULL then a new buffer is
  4595. * allocated. Otherwise the output is written to the buffer.
  4596. * @return length on success and -1 on error
  4597. */
  4598. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4599. {
  4600. /* Space for sequence + two asn ints */
  4601. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4602. word32 bufLen = sizeof(buf);
  4603. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4604. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4605. out == NULL) {
  4606. WOLFSSL_MSG("Bad function arguments");
  4607. return -1;
  4608. }
  4609. if (StoreECC_DSA_Sig(buf, &bufLen,
  4610. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4611. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4612. return -1;
  4613. }
  4614. if (*out == NULL) {
  4615. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4616. if (tmp == NULL) {
  4617. WOLFSSL_MSG("malloc error");
  4618. return -1;
  4619. }
  4620. *out = tmp;
  4621. }
  4622. XMEMCPY(*out, buf, bufLen);
  4623. return (int)bufLen;
  4624. }
  4625. /**
  4626. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4627. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4628. */
  4629. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4630. {
  4631. WOLFSSL_DSA_SIG* ret;
  4632. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4633. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4634. return NULL;
  4635. }
  4636. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4637. WOLFSSL_MSG("wolfSSL_BN_new error");
  4638. wolfSSL_DSA_SIG_free(ret);
  4639. return NULL;
  4640. }
  4641. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4642. WOLFSSL_MSG("wolfSSL_BN_new error");
  4643. wolfSSL_DSA_SIG_free(ret);
  4644. return NULL;
  4645. }
  4646. return ret;
  4647. }
  4648. /**
  4649. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4650. * ASN1_SEQUENCE
  4651. * ASN1_INTEGER (DSA r)
  4652. * ASN1_INTEGER (DSA s)
  4653. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4654. * length then this API interprets this as two unsigned binary numbers.
  4655. * @param sig If non-null then free'd first and then newly created
  4656. * WOLFSSL_DSA_SIG is assigned
  4657. * @param pp Input buffer that is moved forward on success
  4658. * @param length Length of input buffer
  4659. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4660. */
  4661. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4662. const unsigned char **pp, long length)
  4663. {
  4664. WOLFSSL_DSA_SIG* ret;
  4665. mp_int* r;
  4666. mp_int* s;
  4667. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4668. if (pp == NULL || *pp == NULL || length < 0) {
  4669. WOLFSSL_MSG("Bad function arguments");
  4670. return NULL;
  4671. }
  4672. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4673. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4674. return NULL;
  4675. }
  4676. r = (mp_int*)ret->r->internal;
  4677. s = (mp_int*)ret->s->internal;
  4678. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4679. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4680. /* Two raw numbers of length/2 size each */
  4681. if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) {
  4682. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4683. wolfSSL_DSA_SIG_free(ret);
  4684. return NULL;
  4685. }
  4686. if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) !=
  4687. 0) {
  4688. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4689. wolfSSL_DSA_SIG_free(ret);
  4690. return NULL;
  4691. }
  4692. *pp += length;
  4693. }
  4694. else {
  4695. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4696. wolfSSL_DSA_SIG_free(ret);
  4697. return NULL;
  4698. }
  4699. }
  4700. else {
  4701. /* DecodeECC_DSA_Sig success move pointer forward */
  4702. #ifndef NO_STRICT_ECDSA_LEN
  4703. *pp += length;
  4704. #else
  4705. {
  4706. /* We need to figure out how much to move by ourselves */
  4707. word32 idx = 0;
  4708. int len = 0;
  4709. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4710. WOLFSSL_MSG("GetSequence error");
  4711. wolfSSL_DSA_SIG_free(ret);
  4712. return NULL;
  4713. }
  4714. *pp += len;
  4715. }
  4716. #endif
  4717. }
  4718. if (sig != NULL) {
  4719. if (*sig != NULL)
  4720. wolfSSL_DSA_SIG_free(*sig);
  4721. *sig = ret;
  4722. }
  4723. return ret;
  4724. }
  4725. #endif /* HAVE_SELFTEST */
  4726. /* return 1 on success, < 0 otherwise */
  4727. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4728. WOLFSSL_DSA* dsa)
  4729. {
  4730. int ret = -1;
  4731. int initTmpRng = 0;
  4732. WC_RNG* rng = NULL;
  4733. #ifdef WOLFSSL_SMALL_STACK
  4734. WC_RNG* tmpRng = NULL;
  4735. #else
  4736. WC_RNG tmpRng[1];
  4737. #endif
  4738. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4739. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4740. WOLFSSL_MSG("Bad function arguments");
  4741. return ret;
  4742. }
  4743. if (dsa->inSet == 0) {
  4744. WOLFSSL_MSG("No DSA internal set, do it");
  4745. if (SetDsaInternal(dsa) != 1) {
  4746. WOLFSSL_MSG("SetDsaInternal failed");
  4747. return ret;
  4748. }
  4749. }
  4750. #ifdef WOLFSSL_SMALL_STACK
  4751. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4752. if (tmpRng == NULL)
  4753. return -1;
  4754. #endif
  4755. if (wc_InitRng(tmpRng) == 0) {
  4756. rng = tmpRng;
  4757. initTmpRng = 1;
  4758. }
  4759. else {
  4760. WOLFSSL_MSG("Bad RNG Init, trying global");
  4761. rng = wolfssl_get_global_rng();
  4762. }
  4763. if (rng) {
  4764. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4765. WOLFSSL_MSG("DsaSign failed");
  4766. else
  4767. ret = 1;
  4768. }
  4769. if (initTmpRng)
  4770. wc_FreeRng(tmpRng);
  4771. #ifdef WOLFSSL_SMALL_STACK
  4772. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4773. #endif
  4774. return ret;
  4775. }
  4776. #ifndef HAVE_SELFTEST
  4777. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4778. int inLen, WOLFSSL_DSA* dsa)
  4779. {
  4780. byte sigBin[DSA_MAX_SIG_SIZE];
  4781. const byte *tmp = sigBin;
  4782. int sigLen;
  4783. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4784. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4785. WOLFSSL_MSG("Bad function arguments");
  4786. return NULL;
  4787. }
  4788. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4789. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4790. return NULL;
  4791. }
  4792. if (dsa->internal == NULL) {
  4793. WOLFSSL_MSG("dsa->internal is null");
  4794. return NULL;
  4795. }
  4796. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4797. if (sigLen <= 0) {
  4798. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4799. return NULL;
  4800. }
  4801. /* 2 * sigLen for the two points r and s */
  4802. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4803. }
  4804. #endif /* !HAVE_SELFTEST */
  4805. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4806. WOLFSSL_DSA* dsa, int *dsacheck)
  4807. {
  4808. int ret = -1;
  4809. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4810. if (d == NULL || sig == NULL || dsa == NULL) {
  4811. WOLFSSL_MSG("Bad function arguments");
  4812. return -1;
  4813. }
  4814. if (dsa->inSet == 0)
  4815. {
  4816. WOLFSSL_MSG("No DSA internal set, do it");
  4817. if (SetDsaInternal(dsa) != 1) {
  4818. WOLFSSL_MSG("SetDsaInternal failed");
  4819. return -1;
  4820. }
  4821. }
  4822. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4823. if (ret != 0 || *dsacheck != 1) {
  4824. WOLFSSL_MSG("DsaVerify failed");
  4825. return ret;
  4826. }
  4827. return 1;
  4828. }
  4829. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4830. {
  4831. if (!d)
  4832. return 0;
  4833. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4834. return 0;
  4835. return wolfSSL_BN_num_bits(d->p);
  4836. }
  4837. #ifndef HAVE_SELFTEST
  4838. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4839. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4840. {
  4841. int dsacheck, sz;
  4842. byte sigBin[DSA_MAX_SIG_SIZE];
  4843. byte* sigBinPtr = sigBin;
  4844. DsaKey* key;
  4845. int qSz;
  4846. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4847. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4848. WOLFSSL_MSG("Bad function arguments");
  4849. return 0;
  4850. }
  4851. if (!sig->r || !sig->s) {
  4852. WOLFSSL_MSG("No signature found in DSA_SIG");
  4853. return 0;
  4854. }
  4855. if (dsa->inSet == 0) {
  4856. WOLFSSL_MSG("No DSA internal set, do it");
  4857. if (SetDsaInternal(dsa) != 1) {
  4858. WOLFSSL_MSG("SetDsaInternal failed");
  4859. return 0;
  4860. }
  4861. }
  4862. key = (DsaKey*)dsa->internal;
  4863. if (key == NULL) {
  4864. WOLFSSL_MSG("dsa->internal is null");
  4865. return 0;
  4866. }
  4867. qSz = mp_unsigned_bin_size(&key->q);
  4868. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4869. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4870. return 0;
  4871. }
  4872. /* read r */
  4873. /* front pad with zeros */
  4874. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4875. return 0;
  4876. while (sz++ < qSz)
  4877. *sigBinPtr++ = 0;
  4878. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4879. return 0;
  4880. /* Move to s */
  4881. sigBinPtr = sigBin + qSz;
  4882. /* read s */
  4883. /* front pad with zeros */
  4884. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4885. return 0;
  4886. while (sz++ < qSz)
  4887. *sigBinPtr++ = 0;
  4888. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4889. return 0;
  4890. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4891. != 1) || dsacheck != 1) {
  4892. return 0;
  4893. }
  4894. return 1;
  4895. }
  4896. #endif /* !HAVE_SELFTEST */
  4897. WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  4898. unsigned char** out)
  4899. {
  4900. int ret = 0;
  4901. word32 derLen = 0;
  4902. int preAllocated = 1;
  4903. DsaKey* key = NULL;
  4904. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  4905. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  4906. ret = BAD_FUNC_ARG;
  4907. }
  4908. if (ret == 0) {
  4909. key = (DsaKey*)dsa->internal;
  4910. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  4911. if (ret == LENGTH_ONLY_E) {
  4912. ret = 0;
  4913. }
  4914. }
  4915. if (ret == 0 && *out == NULL) {
  4916. /* If we're allocating out for the caller, we don't increment out just
  4917. past the end of the DER buffer. If out is already allocated, we do.
  4918. (OpenSSL convention) */
  4919. preAllocated = 0;
  4920. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  4921. if (*out == NULL) {
  4922. ret = MEMORY_E;
  4923. }
  4924. }
  4925. if (ret == 0) {
  4926. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  4927. }
  4928. if (ret >= 0 && preAllocated == 1) {
  4929. *out += derLen;
  4930. }
  4931. if (ret < 0 && preAllocated == 0) {
  4932. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  4933. }
  4934. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  4935. return ret;
  4936. }
  4937. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  4938. long derLen)
  4939. {
  4940. WOLFSSL_DSA* ret = NULL;
  4941. int err = 0;
  4942. word32 idx = 0;
  4943. int asnLen;
  4944. DsaKey* internalKey = NULL;
  4945. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  4946. if (der == NULL || *der == NULL || derLen <= 0) {
  4947. err = 1;
  4948. }
  4949. if (err == 0) {
  4950. ret = wolfSSL_DSA_new();
  4951. err = ret == NULL;
  4952. }
  4953. if (err == 0) {
  4954. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  4955. }
  4956. if (err == 0) {
  4957. internalKey = (DsaKey*)ret->internal;
  4958. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  4959. }
  4960. if (err == 0) {
  4961. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  4962. }
  4963. if (err == 0) {
  4964. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  4965. }
  4966. if (err == 0) {
  4967. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  4968. != 1;
  4969. }
  4970. if (err == 0) {
  4971. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  4972. != 1;
  4973. }
  4974. if (err == 0) {
  4975. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  4976. != 1;
  4977. }
  4978. if (err == 0 && dsa != NULL) {
  4979. *dsa = ret;
  4980. }
  4981. if (err != 0 && ret != NULL) {
  4982. wolfSSL_DSA_free(ret);
  4983. ret = NULL;
  4984. }
  4985. return ret;
  4986. }
  4987. #if defined(WOLFSSL_KEY_GEN)
  4988. #ifndef NO_BIO
  4989. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  4990. * Returns 1 or 0
  4991. */
  4992. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  4993. const EVP_CIPHER* cipher,
  4994. unsigned char* passwd, int len,
  4995. wc_pem_password_cb* cb, void* arg)
  4996. {
  4997. int ret = 0, der_max_len = 0, derSz = 0;
  4998. byte *derBuf;
  4999. WOLFSSL_EVP_PKEY* pkey;
  5000. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  5001. if (bio == NULL || dsa == NULL) {
  5002. WOLFSSL_MSG("Bad Function Arguments");
  5003. return 0;
  5004. }
  5005. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  5006. if (pkey == NULL) {
  5007. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  5008. return 0;
  5009. }
  5010. pkey->type = EVP_PKEY_DSA;
  5011. pkey->dsa = dsa;
  5012. pkey->ownDsa = 0;
  5013. /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */
  5014. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5015. derBuf = (byte*)XMALLOC((size_t)der_max_len, bio->heap,
  5016. DYNAMIC_TYPE_TMP_BUFFER);
  5017. if (derBuf == NULL) {
  5018. WOLFSSL_MSG("Malloc failed");
  5019. wolfSSL_EVP_PKEY_free(pkey);
  5020. return 0;
  5021. }
  5022. /* convert key to der format */
  5023. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5024. if (derSz < 0) {
  5025. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5026. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5027. wolfSSL_EVP_PKEY_free(pkey);
  5028. return 0;
  5029. }
  5030. pkey->pkey.ptr = (char*)XMALLOC((size_t)derSz, bio->heap,
  5031. DYNAMIC_TYPE_TMP_BUFFER);
  5032. if (pkey->pkey.ptr == NULL) {
  5033. WOLFSSL_MSG("key malloc failed");
  5034. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5035. wolfSSL_EVP_PKEY_free(pkey);
  5036. return 0;
  5037. }
  5038. /* add der info to the evp key */
  5039. pkey->pkey_sz = derSz;
  5040. XMEMCPY(pkey->pkey.ptr, derBuf, (size_t)derSz);
  5041. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5042. ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len,
  5043. cb, arg);
  5044. wolfSSL_EVP_PKEY_free(pkey);
  5045. return ret;
  5046. }
  5047. #ifndef HAVE_SELFTEST
  5048. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5049. * Returns 1 or 0
  5050. */
  5051. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5052. {
  5053. int ret = 0;
  5054. WOLFSSL_EVP_PKEY* pkey;
  5055. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5056. if (bio == NULL || dsa == NULL) {
  5057. WOLFSSL_MSG("Bad function arguments");
  5058. return 0;
  5059. }
  5060. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  5061. if (pkey == NULL) {
  5062. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  5063. return 0;
  5064. }
  5065. pkey->type = EVP_PKEY_DSA;
  5066. pkey->dsa = dsa;
  5067. pkey->ownDsa = 0;
  5068. ret = pem_write_bio_pubkey(bio, pkey);
  5069. wolfSSL_EVP_PKEY_free(pkey);
  5070. return ret;
  5071. }
  5072. #endif /* HAVE_SELFTEST */
  5073. #endif /* !NO_BIO */
  5074. /* return code compliant with OpenSSL :
  5075. * 1 if success, 0 if error
  5076. */
  5077. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5078. const EVP_CIPHER* cipher,
  5079. unsigned char* passwd, int passwdSz,
  5080. unsigned char **pem, int *pLen)
  5081. {
  5082. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5083. byte *derBuf, *tmp, *cipherInfo = NULL;
  5084. int der_max_len = 0, derSz = 0;
  5085. const int type = DSA_PRIVATEKEY_TYPE;
  5086. const char* header = NULL;
  5087. const char* footer = NULL;
  5088. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5089. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5090. WOLFSSL_MSG("Bad function arguments");
  5091. return 0;
  5092. }
  5093. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5094. return 0;
  5095. if (dsa->inSet == 0) {
  5096. WOLFSSL_MSG("No DSA internal set, do it");
  5097. if (SetDsaInternal(dsa) != 1) {
  5098. WOLFSSL_MSG("SetDsaInternal failed");
  5099. return 0;
  5100. }
  5101. }
  5102. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5103. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER);
  5104. if (derBuf == NULL) {
  5105. WOLFSSL_MSG("malloc failed");
  5106. return 0;
  5107. }
  5108. /* Key to DER */
  5109. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5110. if (derSz < 0) {
  5111. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5112. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5113. return 0;
  5114. }
  5115. /* encrypt DER buffer if required */
  5116. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5117. int ret;
  5118. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5119. passwd, passwdSz, &cipherInfo, der_max_len);
  5120. if (ret != 1) {
  5121. WOLFSSL_MSG("EncryptDerKey failed");
  5122. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5123. return ret;
  5124. }
  5125. /* tmp buffer with a max size */
  5126. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5127. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5128. }
  5129. else { /* tmp buffer with a max size */
  5130. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5131. (int)XSTRLEN(footer) + 1;
  5132. }
  5133. tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM);
  5134. if (tmp == NULL) {
  5135. WOLFSSL_MSG("malloc failed");
  5136. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5137. if (cipherInfo != NULL)
  5138. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5139. return 0;
  5140. }
  5141. /* DER to PEM */
  5142. *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo,
  5143. type);
  5144. if (*pLen <= 0) {
  5145. WOLFSSL_MSG("wc_DerToPemEx failed");
  5146. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5147. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5148. if (cipherInfo != NULL)
  5149. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5150. return 0;
  5151. }
  5152. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5153. if (cipherInfo != NULL)
  5154. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5155. *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY);
  5156. if (*pem == NULL) {
  5157. WOLFSSL_MSG("malloc failed");
  5158. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5159. return 0;
  5160. }
  5161. XMEMSET(*pem, 0, (size_t)((*pLen)+1));
  5162. if (XMEMCPY(*pem, tmp, (size_t)*pLen) == NULL) {
  5163. WOLFSSL_MSG("XMEMCPY failed");
  5164. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5165. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5166. return 0;
  5167. }
  5168. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5169. return 1;
  5170. #else
  5171. (void)dsa;
  5172. (void)cipher;
  5173. (void)passwd;
  5174. (void)passwdSz;
  5175. (void)pem;
  5176. (void)pLen;
  5177. return 0;
  5178. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5179. }
  5180. #ifndef NO_FILESYSTEM
  5181. /* return code compliant with OpenSSL :
  5182. * 1 if success, 0 if error
  5183. */
  5184. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5185. const EVP_CIPHER *enc,
  5186. unsigned char *kstr, int klen,
  5187. wc_pem_password_cb *cb, void *u)
  5188. {
  5189. byte *pem;
  5190. int pLen, ret;
  5191. (void)cb;
  5192. (void)u;
  5193. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5194. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5195. WOLFSSL_MSG("Bad function arguments");
  5196. return 0;
  5197. }
  5198. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5199. &pLen);
  5200. if (ret != 1) {
  5201. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5202. return 0;
  5203. }
  5204. ret = (int)XFWRITE(pem, (size_t)pLen, 1, fp);
  5205. if (ret != 1) {
  5206. WOLFSSL_MSG("DSA private key file write failed");
  5207. return 0;
  5208. }
  5209. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5210. return 1;
  5211. }
  5212. #endif /* NO_FILESYSTEM */
  5213. #endif /* defined(WOLFSSL_KEY_GEN) */
  5214. #ifndef NO_FILESYSTEM
  5215. /* return code compliant with OpenSSL :
  5216. * 1 if success, 0 if error
  5217. */
  5218. #ifndef NO_WOLFSSL_STUB
  5219. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5220. {
  5221. (void)fp;
  5222. (void)x;
  5223. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5224. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5225. return 0;
  5226. }
  5227. #endif
  5228. #endif /* NO_FILESYSTEM */
  5229. #ifndef NO_BIO
  5230. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5231. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5232. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5233. * the results to be an DSA key.
  5234. *
  5235. * bio structure to read DSA private key from
  5236. * dsa if not null is then set to the result
  5237. * cb password callback for reading PEM
  5238. * pass password string
  5239. *
  5240. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5241. */
  5242. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5243. WOLFSSL_DSA** dsa,
  5244. wc_pem_password_cb* cb,
  5245. void* pass)
  5246. {
  5247. WOLFSSL_EVP_PKEY* pkey = NULL;
  5248. WOLFSSL_DSA* local;
  5249. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5250. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5251. if (pkey == NULL) {
  5252. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5253. return NULL;
  5254. }
  5255. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5256. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5257. * to avoid having it free'd */
  5258. pkey->ownDsa = 0;
  5259. local = pkey->dsa;
  5260. if (dsa != NULL) {
  5261. *dsa = local;
  5262. }
  5263. wolfSSL_EVP_PKEY_free(pkey);
  5264. return local;
  5265. }
  5266. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5267. * Returns 1 or 0
  5268. */
  5269. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5270. wc_pem_password_cb* cb, void* pass)
  5271. {
  5272. WOLFSSL_EVP_PKEY* pkey;
  5273. WOLFSSL_DSA* local;
  5274. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5275. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5276. if (pkey == NULL) {
  5277. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5278. return NULL;
  5279. }
  5280. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5281. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5282. * to avoid having it free'd */
  5283. pkey->ownDsa = 0;
  5284. local = pkey->dsa;
  5285. if (dsa != NULL) {
  5286. *dsa = local;
  5287. }
  5288. wolfSSL_EVP_PKEY_free(pkey);
  5289. return local;
  5290. }
  5291. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5292. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5293. #endif /* NO_BIO */
  5294. #endif /* OPENSSL_EXTRA */
  5295. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5296. /* return 1 if success, -1 if error */
  5297. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5298. {
  5299. word32 idx = 0;
  5300. int ret;
  5301. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5302. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5303. WOLFSSL_MSG("Bad function arguments");
  5304. return -1;
  5305. }
  5306. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5307. (word32)derSz);
  5308. if (ret < 0) {
  5309. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5310. return -1;
  5311. }
  5312. if (SetDsaExternal(dsa) != 1) {
  5313. WOLFSSL_MSG("SetDsaExternal failed");
  5314. return -1;
  5315. }
  5316. dsa->inSet = 1;
  5317. return 1;
  5318. }
  5319. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5320. returns 1 on success, or 0 on failure. */
  5321. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5322. int derSz, int opt)
  5323. {
  5324. word32 idx = 0;
  5325. int ret;
  5326. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5327. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5328. WOLFSSL_MSG("Bad function arguments");
  5329. return -1;
  5330. }
  5331. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5332. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5333. (word32)derSz);
  5334. }
  5335. else {
  5336. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5337. (word32)derSz);
  5338. }
  5339. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5340. WOLFSSL_ERROR_VERBOSE(ret);
  5341. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5342. return -1;
  5343. }
  5344. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5345. WOLFSSL_ERROR_VERBOSE(ret);
  5346. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5347. return -1;
  5348. }
  5349. if (SetDsaExternal(dsa) != 1) {
  5350. WOLFSSL_MSG("SetDsaExternal failed");
  5351. return -1;
  5352. }
  5353. dsa->inSet = 1;
  5354. return 1;
  5355. }
  5356. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5357. #ifdef OPENSSL_EXTRA
  5358. #ifndef NO_BIO
  5359. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5360. wc_pem_password_cb *cb, void *u)
  5361. {
  5362. WOLFSSL_DSA* dsa;
  5363. DsaKey* key;
  5364. int length;
  5365. unsigned char* buf;
  5366. word32 bufSz;
  5367. int ret;
  5368. word32 idx = 0;
  5369. DerBuffer* pDer;
  5370. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5371. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5372. if (ret <= 0) {
  5373. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5374. return NULL;
  5375. }
  5376. bufSz = (word32)ret;
  5377. if (cb != NULL || u != NULL) {
  5378. /*
  5379. * cb is for a call back when encountering encrypted PEM files
  5380. * if cb == NULL and u != NULL then u = null terminated password string
  5381. */
  5382. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5383. }
  5384. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5385. NULL) < 0 ) {
  5386. WOLFSSL_MSG("Issue converting from PEM to DER");
  5387. return NULL;
  5388. }
  5389. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5390. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5391. FreeDer(&pDer);
  5392. return NULL;
  5393. }
  5394. dsa = wolfSSL_DSA_new();
  5395. if (dsa == NULL) {
  5396. FreeDer(&pDer);
  5397. WOLFSSL_MSG("Error creating DSA struct");
  5398. return NULL;
  5399. }
  5400. key = (DsaKey*)dsa->internal;
  5401. if (key == NULL) {
  5402. FreeDer(&pDer);
  5403. wolfSSL_DSA_free(dsa);
  5404. WOLFSSL_MSG("Error finding DSA key struct");
  5405. return NULL;
  5406. }
  5407. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5408. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5409. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5410. WOLFSSL_MSG("dsa key error");
  5411. FreeDer(&pDer);
  5412. wolfSSL_DSA_free(dsa);
  5413. return NULL;
  5414. }
  5415. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5416. WOLFSSL_MSG("dsa p key error");
  5417. FreeDer(&pDer);
  5418. wolfSSL_DSA_free(dsa);
  5419. return NULL;
  5420. }
  5421. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5422. WOLFSSL_MSG("dsa q key error");
  5423. FreeDer(&pDer);
  5424. wolfSSL_DSA_free(dsa);
  5425. return NULL;
  5426. }
  5427. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5428. WOLFSSL_MSG("dsa g key error");
  5429. FreeDer(&pDer);
  5430. wolfSSL_DSA_free(dsa);
  5431. return NULL;
  5432. }
  5433. if (x != NULL) {
  5434. *x = dsa;
  5435. }
  5436. FreeDer(&pDer);
  5437. return dsa;
  5438. }
  5439. #endif /* !NO_BIO */
  5440. #if !defined(NO_DH)
  5441. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5442. {
  5443. WOLFSSL_DH* dh;
  5444. DhKey* key;
  5445. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5446. if (dsa == NULL) {
  5447. return NULL;
  5448. }
  5449. dh = wolfSSL_DH_new();
  5450. if (dh == NULL) {
  5451. return NULL;
  5452. }
  5453. key = (DhKey*)dh->internal;
  5454. if (dsa->p != NULL &&
  5455. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5456. != 1) {
  5457. WOLFSSL_MSG("rsa p key error");
  5458. wolfSSL_DH_free(dh);
  5459. return NULL;
  5460. }
  5461. if (dsa->g != NULL &&
  5462. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5463. != 1) {
  5464. WOLFSSL_MSG("rsa g key error");
  5465. wolfSSL_DH_free(dh);
  5466. return NULL;
  5467. }
  5468. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5469. WOLFSSL_MSG("dsa p key error");
  5470. wolfSSL_DH_free(dh);
  5471. return NULL;
  5472. }
  5473. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5474. WOLFSSL_MSG("dsa g key error");
  5475. wolfSSL_DH_free(dh);
  5476. return NULL;
  5477. }
  5478. return dh;
  5479. }
  5480. #endif /* !NO_DH */
  5481. #endif /* OPENSSL_EXTRA */
  5482. #endif /* !NO_DSA */
  5483. /*******************************************************************************
  5484. * END OF DSA API
  5485. ******************************************************************************/
  5486. /*******************************************************************************
  5487. * START OF DH API
  5488. ******************************************************************************/
  5489. #ifndef NO_DH
  5490. #ifdef OPENSSL_EXTRA
  5491. /*
  5492. * DH constructor/deconstructor APIs
  5493. */
  5494. /* Allocate and initialize a new DH key.
  5495. *
  5496. * @return DH key on success.
  5497. * @return NULL on failure.
  5498. */
  5499. WOLFSSL_DH* wolfSSL_DH_new(void)
  5500. {
  5501. int err = 0;
  5502. WOLFSSL_DH* dh = NULL;
  5503. DhKey* key = NULL;
  5504. WOLFSSL_ENTER("wolfSSL_DH_new");
  5505. /* Allocate OpenSSL DH key. */
  5506. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5507. if (dh == NULL) {
  5508. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5509. err = 1;
  5510. }
  5511. if (!err) {
  5512. /* Clear key data. */
  5513. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5514. /* Initialize reference counting. */
  5515. wolfSSL_RefInit(&dh->ref, &err);
  5516. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5517. }
  5518. if (!err) {
  5519. #endif
  5520. /* Allocate wolfSSL DH key. */
  5521. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5522. if (key == NULL) {
  5523. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5524. err = 1;
  5525. }
  5526. }
  5527. if (!err) {
  5528. /* Set and initialize wolfSSL DH key. */
  5529. dh->internal = key;
  5530. if (wc_InitDhKey(key) != 0) {
  5531. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5532. err = 1;
  5533. }
  5534. }
  5535. if (err && (dh != NULL)) {
  5536. /* Dispose of the allocated memory. */
  5537. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5538. wolfSSL_RefFree(&dh->ref);
  5539. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5540. dh = NULL;
  5541. }
  5542. return dh;
  5543. }
  5544. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5545. /* Set the DH parameters based on the NID.
  5546. *
  5547. * @param [in, out] dh DH key to set.
  5548. * @param [in] nid Numeric ID of predefined DH parameters.
  5549. * @return 0 on success.
  5550. * @return 1 on failure.
  5551. */
  5552. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5553. {
  5554. int err = 0;
  5555. const DhParams* params = NULL;
  5556. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5557. * FIPS v2 module */
  5558. switch (nid) {
  5559. #ifdef HAVE_FFDHE_2048
  5560. case NID_ffdhe2048:
  5561. params = wc_Dh_ffdhe2048_Get();
  5562. break;
  5563. #endif /* HAVE_FFDHE_2048 */
  5564. #ifdef HAVE_FFDHE_3072
  5565. case NID_ffdhe3072:
  5566. params = wc_Dh_ffdhe3072_Get();
  5567. break;
  5568. #endif /* HAVE_FFDHE_3072 */
  5569. #ifdef HAVE_FFDHE_4096
  5570. case NID_ffdhe4096:
  5571. params = wc_Dh_ffdhe4096_Get();
  5572. break;
  5573. #endif /* HAVE_FFDHE_4096 */
  5574. default:
  5575. break;
  5576. }
  5577. if (params == NULL) {
  5578. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5579. err = 1;
  5580. }
  5581. if (!err) {
  5582. /* Set prime from data retrieved. */
  5583. dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL);
  5584. if (dh->p == NULL) {
  5585. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5586. err = 1;
  5587. }
  5588. }
  5589. if (!err) {
  5590. /* Set generator from data retrieved. */
  5591. dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL);
  5592. if (dh->g == NULL) {
  5593. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5594. err = 1;
  5595. }
  5596. }
  5597. #ifdef HAVE_FFDHE_Q
  5598. if (!err) {
  5599. /* Set order from data retrieved. */
  5600. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5601. if (dh->q == NULL) {
  5602. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5603. err = 1;
  5604. }
  5605. }
  5606. #endif
  5607. /* Synchronize the external into internal DH key's parameters. */
  5608. if ((!err) && (SetDhInternal(dh) != 1)) {
  5609. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5610. err = 1;
  5611. }
  5612. if (!err) {
  5613. /* External DH key parameters were set. */
  5614. dh->exSet = 1;
  5615. }
  5616. if (err == 1) {
  5617. /* Dispose of any external parameters. */
  5618. #ifdef HAVE_FFDHE_Q
  5619. wolfSSL_BN_free(dh->q);
  5620. dh->q = NULL;
  5621. #endif
  5622. wolfSSL_BN_free(dh->p);
  5623. dh->p = NULL;
  5624. wolfSSL_BN_free(dh->g);
  5625. dh->g = NULL;
  5626. }
  5627. return err;
  5628. }
  5629. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5630. FIPS_VERSION_GT(2,0))
  5631. /* Set the DH parameters based on the NID.
  5632. *
  5633. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5634. *
  5635. * @param [in, out] dh DH key to set.
  5636. * @param [in] nid Numeric ID of predefined DH parameters.
  5637. * @return 0 on success.
  5638. * @return 1 on failure.
  5639. */
  5640. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5641. {
  5642. int err = 0;
  5643. int name = 0;
  5644. #ifdef HAVE_FFDHE_Q
  5645. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5646. #else
  5647. int elements = ELEMENT_P | ELEMENT_G;
  5648. #endif /* HAVE_FFDHE_Q */
  5649. switch (nid) {
  5650. #ifdef HAVE_FFDHE_2048
  5651. case NID_ffdhe2048:
  5652. name = WC_FFDHE_2048;
  5653. break;
  5654. #endif /* HAVE_FFDHE_2048 */
  5655. #ifdef HAVE_FFDHE_3072
  5656. case NID_ffdhe3072:
  5657. name = WC_FFDHE_3072;
  5658. break;
  5659. #endif /* HAVE_FFDHE_3072 */
  5660. #ifdef HAVE_FFDHE_4096
  5661. case NID_ffdhe4096:
  5662. name = WC_FFDHE_4096;
  5663. break;
  5664. #endif /* HAVE_FFDHE_4096 */
  5665. default:
  5666. err = 1;
  5667. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5668. break;
  5669. }
  5670. /* Set the internal DH key's parameters based on name. */
  5671. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5672. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5673. err = 1;
  5674. }
  5675. /* Synchronize the internal into external DH key's parameters. */
  5676. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5677. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5678. err = 1;
  5679. }
  5680. return err;
  5681. }
  5682. #else
  5683. /* Set the DH parameters based on the NID.
  5684. *
  5685. * Pre-defined DH parameters not available.
  5686. *
  5687. * @param [in, out] dh DH key to set.
  5688. * @param [in] nid Numeric ID of predefined DH parameters.
  5689. * @return 1 for failure.
  5690. */
  5691. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5692. {
  5693. return 1;
  5694. }
  5695. #endif
  5696. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5697. *
  5698. * @param [in] nid Numeric ID of DH parameters.
  5699. *
  5700. * @return DH key on success.
  5701. * @return NULL on failure.
  5702. */
  5703. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5704. {
  5705. WOLFSSL_DH* dh = NULL;
  5706. int err = 0;
  5707. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5708. /* Allocate a new DH key. */
  5709. dh = wolfSSL_DH_new();
  5710. if (dh == NULL) {
  5711. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5712. err = 1;
  5713. }
  5714. if (!err) {
  5715. /* Set the parameters based on NID. */
  5716. err = wolfssl_dh_set_nid(dh, nid);
  5717. }
  5718. if (err && (dh != NULL)) {
  5719. /* Dispose of the key on failure to set. */
  5720. wolfSSL_DH_free(dh);
  5721. dh = NULL;
  5722. }
  5723. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5724. return dh;
  5725. }
  5726. /* Dispose of DH key and allocated data.
  5727. *
  5728. * Cannot use dh after this call.
  5729. *
  5730. * @param [in] dh DH key to free.
  5731. */
  5732. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5733. {
  5734. int doFree = 0;
  5735. WOLFSSL_ENTER("wolfSSL_DH_free");
  5736. if (dh != NULL) {
  5737. int err;
  5738. /* Only free if all references to it are done */
  5739. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5740. /* Ignore errors - doFree will be 0 on error. */
  5741. (void)err;
  5742. }
  5743. if (doFree) {
  5744. /* Dispose of allocated reference counting data. */
  5745. wolfSSL_RefFree(&dh->ref);
  5746. /* Dispose of wolfSSL DH key. */
  5747. if (dh->internal) {
  5748. wc_FreeDhKey((DhKey*)dh->internal);
  5749. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5750. dh->internal = NULL;
  5751. }
  5752. /* Dispose of any allocated BNs. */
  5753. wolfSSL_BN_free(dh->priv_key);
  5754. wolfSSL_BN_free(dh->pub_key);
  5755. wolfSSL_BN_free(dh->g);
  5756. wolfSSL_BN_free(dh->p);
  5757. wolfSSL_BN_free(dh->q);
  5758. /* Set back to NULLs for safety. */
  5759. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5760. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5761. }
  5762. }
  5763. /* Increments ref count of DH key.
  5764. *
  5765. * @param [in, out] dh DH key.
  5766. * @return 1 on success
  5767. * @return 0 on error
  5768. */
  5769. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5770. {
  5771. int err = 1;
  5772. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5773. if (dh != NULL) {
  5774. wolfSSL_RefInc(&dh->ref, &err);
  5775. }
  5776. return !err;
  5777. }
  5778. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5779. defined(OPENSSL_EXTRA)
  5780. #ifdef WOLFSSL_DH_EXTRA
  5781. /* Duplicate the DH key.
  5782. *
  5783. * Internal DH key in 'dh' is updated if necessary.
  5784. *
  5785. * @param [in, out] dh DH key to duplicate.
  5786. * @return NULL on failure.
  5787. * @return DH key on success.
  5788. */
  5789. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5790. {
  5791. WOLFSSL_DH* ret = NULL;
  5792. int err = 0;
  5793. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5794. /* Validate parameters. */
  5795. if (dh == NULL) {
  5796. WOLFSSL_ERROR_MSG("Bad parameter");
  5797. err = 1;
  5798. }
  5799. /* Ensure internal DH key is set. */
  5800. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5801. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5802. err = 1;
  5803. }
  5804. /* Create a new DH key object. */
  5805. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5806. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5807. err = 1;
  5808. }
  5809. /* Copy internal DH key from original to new. */
  5810. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5811. MP_OKAY)) {
  5812. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5813. err = 1;
  5814. }
  5815. if (!err) {
  5816. ret->inSet = 1;
  5817. /* Synchronize the internal into external DH key's parameters. */
  5818. if (SetDhExternal(ret) != 1) {
  5819. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5820. err = 1;
  5821. }
  5822. }
  5823. /* Dispose of any allocated DH key on error. */
  5824. if (err && (ret != NULL)) {
  5825. wolfSSL_DH_free(ret);
  5826. ret = NULL;
  5827. }
  5828. return ret;
  5829. }
  5830. #endif /* WOLFSSL_DH_EXTRA */
  5831. #endif
  5832. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5833. *
  5834. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5835. * Subgroup."
  5836. *
  5837. * @return NULL on failure.
  5838. * @return DH Key on success.
  5839. */
  5840. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5841. {
  5842. WOLFSSL_DH* dh;
  5843. int err = 0;
  5844. static const byte pHex[] = {
  5845. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5846. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5847. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5848. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5849. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5850. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5851. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5852. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5853. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5854. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5855. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5856. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5857. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5858. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5859. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5860. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5861. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5862. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5863. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5864. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5865. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5866. 0x1E, 0x1A, 0x15, 0x97
  5867. };
  5868. static const byte gHex[] = {
  5869. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5870. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5871. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5872. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5873. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5874. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5875. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5876. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5877. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5878. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5879. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5880. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5881. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  5882. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  5883. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  5884. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  5885. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  5886. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  5887. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  5888. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  5889. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  5890. 0x6C, 0xC4, 0x16, 0x59
  5891. };
  5892. static const byte qHex[] = {
  5893. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  5894. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  5895. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  5896. };
  5897. /* Create a new DH key to return. */
  5898. dh = wolfSSL_DH_new();
  5899. if (dh == NULL) {
  5900. err = 1;
  5901. }
  5902. if (!err) {
  5903. /* Set prime. */
  5904. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  5905. if (dh->p == NULL) {
  5906. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5907. err = 1;
  5908. }
  5909. }
  5910. if (!err) {
  5911. /* Set generator. */
  5912. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  5913. if (dh->g == NULL) {
  5914. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5915. err = 1;
  5916. }
  5917. }
  5918. if (!err) {
  5919. /* Set order. */
  5920. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  5921. if (dh->q == NULL) {
  5922. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5923. err = 1;
  5924. }
  5925. }
  5926. /* Set values into wolfSSL DH key. */
  5927. if ((!err) && (SetDhInternal(dh) != 1)) {
  5928. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  5929. err = 1;
  5930. }
  5931. if (!err) {
  5932. /* External DH key parameters were set. */
  5933. dh->exSet = 1;
  5934. }
  5935. /* Dispose of any allocated DH key on error. */
  5936. if (err && (dh != NULL)) {
  5937. wolfSSL_DH_free(dh);
  5938. dh = NULL;
  5939. }
  5940. return dh;
  5941. }
  5942. /* TODO: consider changing strings to byte arrays. */
  5943. /* Returns a big number with the 768-bit prime from RFC 2409.
  5944. *
  5945. * @param [in, out] bn If not NULL then this BN is set and returned.
  5946. * If NULL then a new BN is created, set and returned.
  5947. *
  5948. * @return NULL on failure.
  5949. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  5950. */
  5951. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  5952. {
  5953. #if WOLFSSL_MAX_BN_BITS >= 768
  5954. static const char prm[] = {
  5955. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5956. "C4C6628B80DC1CD129024E088A67CC74"
  5957. "020BBEA63B139B22514A08798E3404DD"
  5958. "EF9519B3CD3A431B302B0A6DF25F1437"
  5959. "4FE1356D6D51C245E485B576625E7EC6"
  5960. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  5961. };
  5962. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  5963. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5964. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5965. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  5966. bn = NULL;
  5967. }
  5968. return bn;
  5969. #else
  5970. (void)bn;
  5971. return NULL;
  5972. #endif
  5973. }
  5974. /* Returns a big number with the 1024-bit prime from RFC 2409.
  5975. *
  5976. * @param [in, out] bn If not NULL then this BN is set and returned.
  5977. * If NULL then a new BN is created, set and returned.
  5978. *
  5979. * @return NULL on failure.
  5980. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  5981. */
  5982. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  5983. {
  5984. #if WOLFSSL_MAX_BN_BITS >= 1024
  5985. static const char prm[] = {
  5986. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5987. "C4C6628B80DC1CD129024E088A67CC74"
  5988. "020BBEA63B139B22514A08798E3404DD"
  5989. "EF9519B3CD3A431B302B0A6DF25F1437"
  5990. "4FE1356D6D51C245E485B576625E7EC6"
  5991. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5992. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5993. "49286651ECE65381FFFFFFFFFFFFFFFF"
  5994. };
  5995. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  5996. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5997. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5998. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  5999. bn = NULL;
  6000. }
  6001. return bn;
  6002. #else
  6003. (void)bn;
  6004. return NULL;
  6005. #endif
  6006. }
  6007. /* Returns a big number with the 1536-bit prime from RFC 3526.
  6008. *
  6009. * @param [in, out] bn If not NULL then this BN is set and returned.
  6010. * If NULL then a new BN is created, set and returned.
  6011. *
  6012. * @return NULL on failure.
  6013. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  6014. */
  6015. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  6016. {
  6017. #if WOLFSSL_MAX_BN_BITS >= 1536
  6018. static const char prm[] = {
  6019. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6020. "C4C6628B80DC1CD129024E088A67CC74"
  6021. "020BBEA63B139B22514A08798E3404DD"
  6022. "EF9519B3CD3A431B302B0A6DF25F1437"
  6023. "4FE1356D6D51C245E485B576625E7EC6"
  6024. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6025. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6026. "49286651ECE45B3DC2007CB8A163BF05"
  6027. "98DA48361C55D39A69163FA8FD24CF5F"
  6028. "83655D23DCA3AD961C62F356208552BB"
  6029. "9ED529077096966D670C354E4ABC9804"
  6030. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6031. };
  6032. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6033. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6034. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6035. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6036. bn = NULL;
  6037. }
  6038. return bn;
  6039. #else
  6040. (void)bn;
  6041. return NULL;
  6042. #endif
  6043. }
  6044. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6045. *
  6046. * @param [in, out] bn If not NULL then this BN is set and returned.
  6047. * If NULL then a new BN is created, set and returned.
  6048. *
  6049. * @return NULL on failure.
  6050. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6051. */
  6052. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6053. {
  6054. #if WOLFSSL_MAX_BN_BITS >= 2048
  6055. static const char prm[] = {
  6056. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6057. "C4C6628B80DC1CD129024E088A67CC74"
  6058. "020BBEA63B139B22514A08798E3404DD"
  6059. "EF9519B3CD3A431B302B0A6DF25F1437"
  6060. "4FE1356D6D51C245E485B576625E7EC6"
  6061. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6062. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6063. "49286651ECE45B3DC2007CB8A163BF05"
  6064. "98DA48361C55D39A69163FA8FD24CF5F"
  6065. "83655D23DCA3AD961C62F356208552BB"
  6066. "9ED529077096966D670C354E4ABC9804"
  6067. "F1746C08CA18217C32905E462E36CE3B"
  6068. "E39E772C180E86039B2783A2EC07A28F"
  6069. "B5C55DF06F4C52C9DE2BCBF695581718"
  6070. "3995497CEA956AE515D2261898FA0510"
  6071. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6072. };
  6073. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6074. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6075. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6076. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6077. bn = NULL;
  6078. }
  6079. return bn;
  6080. #else
  6081. (void)bn;
  6082. return NULL;
  6083. #endif
  6084. }
  6085. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6086. *
  6087. * @param [in, out] bn If not NULL then this BN is set and returned.
  6088. * If NULL then a new BN is created, set and returned.
  6089. *
  6090. * @return NULL on failure.
  6091. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6092. */
  6093. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6094. {
  6095. #if WOLFSSL_MAX_BN_BITS >= 3072
  6096. static const char prm[] = {
  6097. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6098. "C4C6628B80DC1CD129024E088A67CC74"
  6099. "020BBEA63B139B22514A08798E3404DD"
  6100. "EF9519B3CD3A431B302B0A6DF25F1437"
  6101. "4FE1356D6D51C245E485B576625E7EC6"
  6102. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6103. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6104. "49286651ECE45B3DC2007CB8A163BF05"
  6105. "98DA48361C55D39A69163FA8FD24CF5F"
  6106. "83655D23DCA3AD961C62F356208552BB"
  6107. "9ED529077096966D670C354E4ABC9804"
  6108. "F1746C08CA18217C32905E462E36CE3B"
  6109. "E39E772C180E86039B2783A2EC07A28F"
  6110. "B5C55DF06F4C52C9DE2BCBF695581718"
  6111. "3995497CEA956AE515D2261898FA0510"
  6112. "15728E5A8AAAC42DAD33170D04507A33"
  6113. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6114. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6115. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6116. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6117. "D87602733EC86A64521F2B18177B200C"
  6118. "BBE117577A615D6C770988C0BAD946E2"
  6119. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6120. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6121. };
  6122. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6123. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6124. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6125. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6126. bn = NULL;
  6127. }
  6128. return bn;
  6129. #else
  6130. (void)bn;
  6131. return NULL;
  6132. #endif
  6133. }
  6134. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6135. *
  6136. * @param [in, out] bn If not NULL then this BN is set and returned.
  6137. * If NULL then a new BN is created, set and returned.
  6138. *
  6139. * @return NULL on failure.
  6140. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6141. */
  6142. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6143. {
  6144. #if WOLFSSL_MAX_BN_BITS >= 4096
  6145. static const char prm[] = {
  6146. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6147. "C4C6628B80DC1CD129024E088A67CC74"
  6148. "020BBEA63B139B22514A08798E3404DD"
  6149. "EF9519B3CD3A431B302B0A6DF25F1437"
  6150. "4FE1356D6D51C245E485B576625E7EC6"
  6151. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6152. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6153. "49286651ECE45B3DC2007CB8A163BF05"
  6154. "98DA48361C55D39A69163FA8FD24CF5F"
  6155. "83655D23DCA3AD961C62F356208552BB"
  6156. "9ED529077096966D670C354E4ABC9804"
  6157. "F1746C08CA18217C32905E462E36CE3B"
  6158. "E39E772C180E86039B2783A2EC07A28F"
  6159. "B5C55DF06F4C52C9DE2BCBF695581718"
  6160. "3995497CEA956AE515D2261898FA0510"
  6161. "15728E5A8AAAC42DAD33170D04507A33"
  6162. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6163. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6164. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6165. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6166. "D87602733EC86A64521F2B18177B200C"
  6167. "BBE117577A615D6C770988C0BAD946E2"
  6168. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6169. "4B82D120A92108011A723C12A787E6D7"
  6170. "88719A10BDBA5B2699C327186AF4E23C"
  6171. "1A946834B6150BDA2583E9CA2AD44CE8"
  6172. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6173. "287C59474E6BC05D99B2964FA090C3A2"
  6174. "233BA186515BE7ED1F612970CEE2D7AF"
  6175. "B81BDD762170481CD0069127D5B05AA9"
  6176. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6177. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6178. };
  6179. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6180. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6181. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6182. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6183. bn = NULL;
  6184. }
  6185. return bn;
  6186. #else
  6187. (void)bn;
  6188. return NULL;
  6189. #endif
  6190. }
  6191. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6192. *
  6193. * @param [in, out] bn If not NULL then this BN is set and returned.
  6194. * If NULL then a new BN is created, set and returned.
  6195. *
  6196. * @return NULL on failure.
  6197. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6198. */
  6199. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6200. {
  6201. #if WOLFSSL_MAX_BN_BITS >= 6144
  6202. static const char prm[] = {
  6203. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6204. "C4C6628B80DC1CD129024E088A67CC74"
  6205. "020BBEA63B139B22514A08798E3404DD"
  6206. "EF9519B3CD3A431B302B0A6DF25F1437"
  6207. "4FE1356D6D51C245E485B576625E7EC6"
  6208. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6209. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6210. "49286651ECE45B3DC2007CB8A163BF05"
  6211. "98DA48361C55D39A69163FA8FD24CF5F"
  6212. "83655D23DCA3AD961C62F356208552BB"
  6213. "9ED529077096966D670C354E4ABC9804"
  6214. "F1746C08CA18217C32905E462E36CE3B"
  6215. "E39E772C180E86039B2783A2EC07A28F"
  6216. "B5C55DF06F4C52C9DE2BCBF695581718"
  6217. "3995497CEA956AE515D2261898FA0510"
  6218. "15728E5A8AAAC42DAD33170D04507A33"
  6219. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6220. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6221. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6222. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6223. "D87602733EC86A64521F2B18177B200C"
  6224. "BBE117577A615D6C770988C0BAD946E2"
  6225. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6226. "4B82D120A92108011A723C12A787E6D7"
  6227. "88719A10BDBA5B2699C327186AF4E23C"
  6228. "1A946834B6150BDA2583E9CA2AD44CE8"
  6229. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6230. "287C59474E6BC05D99B2964FA090C3A2"
  6231. "233BA186515BE7ED1F612970CEE2D7AF"
  6232. "B81BDD762170481CD0069127D5B05AA9"
  6233. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6234. "4DF435C93402849236C3FAB4D27C7026"
  6235. "C1D4DCB2602646DEC9751E763DBA37BD"
  6236. "F8FF9406AD9E530EE5DB382F413001AE"
  6237. "B06A53ED9027D831179727B0865A8918"
  6238. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6239. "DB7F1447E6CC254B332051512BD7AF42"
  6240. "6FB8F401378CD2BF5983CA01C64B92EC"
  6241. "F032EA15D1721D03F482D7CE6E74FEF6"
  6242. "D55E702F46980C82B5A84031900B1C9E"
  6243. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6244. "0F1D45B7FF585AC54BD407B22B4154AA"
  6245. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6246. "A79715EEF29BE32806A1D58BB7C5DA76"
  6247. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6248. "DA56C9EC2EF29632387FE8D76E3C0468"
  6249. "043E8F663F4860EE12BF2D5B0B7474D6"
  6250. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6251. };
  6252. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6253. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6254. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6255. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6256. bn = NULL;
  6257. }
  6258. return bn;
  6259. #else
  6260. (void)bn;
  6261. return NULL;
  6262. #endif
  6263. }
  6264. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6265. *
  6266. * @param [in, out] bn If not NULL then this BN is set and returned.
  6267. * If NULL then a new BN is created, set and returned.
  6268. *
  6269. * @return NULL on failure.
  6270. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6271. */
  6272. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6273. {
  6274. #if WOLFSSL_MAX_BN_BITS >= 8192
  6275. static const char prm[] = {
  6276. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6277. "C4C6628B80DC1CD129024E088A67CC74"
  6278. "020BBEA63B139B22514A08798E3404DD"
  6279. "EF9519B3CD3A431B302B0A6DF25F1437"
  6280. "4FE1356D6D51C245E485B576625E7EC6"
  6281. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6282. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6283. "49286651ECE45B3DC2007CB8A163BF05"
  6284. "98DA48361C55D39A69163FA8FD24CF5F"
  6285. "83655D23DCA3AD961C62F356208552BB"
  6286. "9ED529077096966D670C354E4ABC9804"
  6287. "F1746C08CA18217C32905E462E36CE3B"
  6288. "E39E772C180E86039B2783A2EC07A28F"
  6289. "B5C55DF06F4C52C9DE2BCBF695581718"
  6290. "3995497CEA956AE515D2261898FA0510"
  6291. "15728E5A8AAAC42DAD33170D04507A33"
  6292. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6293. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6294. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6295. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6296. "D87602733EC86A64521F2B18177B200C"
  6297. "BBE117577A615D6C770988C0BAD946E2"
  6298. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6299. "4B82D120A92108011A723C12A787E6D7"
  6300. "88719A10BDBA5B2699C327186AF4E23C"
  6301. "1A946834B6150BDA2583E9CA2AD44CE8"
  6302. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6303. "287C59474E6BC05D99B2964FA090C3A2"
  6304. "233BA186515BE7ED1F612970CEE2D7AF"
  6305. "B81BDD762170481CD0069127D5B05AA9"
  6306. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6307. "4DF435C93402849236C3FAB4D27C7026"
  6308. "C1D4DCB2602646DEC9751E763DBA37BD"
  6309. "F8FF9406AD9E530EE5DB382F413001AE"
  6310. "B06A53ED9027D831179727B0865A8918"
  6311. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6312. "DB7F1447E6CC254B332051512BD7AF42"
  6313. "6FB8F401378CD2BF5983CA01C64B92EC"
  6314. "F032EA15D1721D03F482D7CE6E74FEF6"
  6315. "D55E702F46980C82B5A84031900B1C9E"
  6316. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6317. "0F1D45B7FF585AC54BD407B22B4154AA"
  6318. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6319. "A79715EEF29BE32806A1D58BB7C5DA76"
  6320. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6321. "DA56C9EC2EF29632387FE8D76E3C0468"
  6322. "043E8F663F4860EE12BF2D5B0B7474D6"
  6323. "E694F91E6DBE115974A3926F12FEE5E4"
  6324. "38777CB6A932DF8CD8BEC4D073B931BA"
  6325. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6326. "2576F6936BA424663AAB639C5AE4F568"
  6327. "3423B4742BF1C978238F16CBE39D652D"
  6328. "E3FDB8BEFC848AD922222E04A4037C07"
  6329. "13EB57A81A23F0C73473FC646CEA306B"
  6330. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6331. "79683303ED5BDD3A062B3CF5B3A278A6"
  6332. "6D2A13F83F44F82DDF310EE074AB6A36"
  6333. "4597E899A0255DC164F31CC50846851D"
  6334. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6335. "FAF36BC31ECFA268359046F4EB879F92"
  6336. "4009438B481C6CD7889A002ED5EE382B"
  6337. "C9190DA6FC026E479558E4475677E9AA"
  6338. "9E3050E2765694DFC81F56E880B96E71"
  6339. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6340. };
  6341. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6342. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6343. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6344. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6345. bn = NULL;
  6346. }
  6347. return bn;
  6348. #else
  6349. (void)bn;
  6350. return NULL;
  6351. #endif
  6352. }
  6353. /*
  6354. * DH to/from bin APIs
  6355. */
  6356. #ifndef NO_CERTS
  6357. /* Load the DER encoded DH parameters/key into DH key.
  6358. *
  6359. * @param [in, out] dh DH key to load parameters into.
  6360. * @param [in] der Buffer holding DER encoded parameters data.
  6361. * @param [in, out] idx On in, index at which DH key DER data starts.
  6362. * On out, index after DH key DER data.
  6363. * @param [in] derSz Size of DER buffer in bytes.
  6364. *
  6365. * @return 0 on success.
  6366. * @return 1 when decoding DER or setting the external key fails.
  6367. */
  6368. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6369. word32* idx, word32 derSz)
  6370. {
  6371. int err = 0;
  6372. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6373. int ret;
  6374. /* Decode DH parameters/key from DER. */
  6375. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6376. if (ret != 0) {
  6377. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6378. err = 1;
  6379. }
  6380. if (!err) {
  6381. /* wolfSSL DH key set. */
  6382. dh->inSet = 1;
  6383. /* Set the external DH key based on wolfSSL DH key. */
  6384. if (SetDhExternal(dh) != 1) {
  6385. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6386. err = 1;
  6387. }
  6388. }
  6389. #else
  6390. byte* p;
  6391. byte* g;
  6392. word32 pSz = MAX_DH_SIZE;
  6393. word32 gSz = MAX_DH_SIZE;
  6394. /* Only DH parameters supported. */
  6395. /* Load external and set internal. */
  6396. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6397. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6398. if ((p == NULL) || (g == NULL)) {
  6399. err = 1;
  6400. }
  6401. /* Extract the p and g as data from the DER encoded DH parameters. */
  6402. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6403. &gSz) < 0)) {
  6404. err = 1;
  6405. }
  6406. if (!err) {
  6407. /* Put p and g in as big numbers - free existing BNs. */
  6408. if (dh->p != NULL) {
  6409. wolfSSL_BN_free(dh->p);
  6410. dh->p = NULL;
  6411. }
  6412. if (dh->g != NULL) {
  6413. wolfSSL_BN_free(dh->g);
  6414. dh->g = NULL;
  6415. }
  6416. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6417. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6418. if (dh->p == NULL || dh->g == NULL) {
  6419. err = 1;
  6420. }
  6421. else {
  6422. /* External DH key parameters were set. */
  6423. dh->exSet = 1;
  6424. }
  6425. }
  6426. /* Set internal as the outside has been updated. */
  6427. if ((!err) && (SetDhInternal(dh) != 1)) {
  6428. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6429. err = 1;
  6430. }
  6431. if (!err) {
  6432. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6433. }
  6434. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6435. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6436. #endif
  6437. return err;
  6438. }
  6439. #ifdef OPENSSL_ALL
  6440. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6441. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6442. *
  6443. * @param [out] dh DH key to put parameters into. May be NULL.
  6444. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6445. * Value updated to end of data when dh is not NULL.
  6446. * @param [in] length Length of data available in bytes.
  6447. *
  6448. * @return DH key on success.
  6449. * @return NULL on failure.
  6450. */
  6451. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6452. long length)
  6453. {
  6454. WOLFSSL_DH *newDh = NULL;
  6455. word32 idx = 0;
  6456. int err = 0;
  6457. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6458. /* Validate parameters. */
  6459. if ((pp == NULL) || (length <= 0)) {
  6460. WOLFSSL_ERROR_MSG("bad argument");
  6461. err = 1;
  6462. }
  6463. /* Create new DH key to return. */
  6464. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6465. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6466. err = 1;
  6467. }
  6468. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6469. (word32)length) != 0)) {
  6470. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6471. err = 1;
  6472. }
  6473. if ((!err) && (dh != NULL)) {
  6474. /* Return through parameter too. */
  6475. *dh = newDh;
  6476. /* Move buffer on by the used amount. */
  6477. *pp += idx;
  6478. }
  6479. if (err && (newDh != NULL)) {
  6480. /* Dispose of any created DH key. */
  6481. wolfSSL_DH_free(newDh);
  6482. newDh = NULL;
  6483. }
  6484. return newDh;
  6485. }
  6486. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6487. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6488. *
  6489. * @params [in] dh DH key with parameters to encode.
  6490. * @params [in, out] out Pointer to buffer to encode into.
  6491. * When NULL or pointer to NULL, only length returned.
  6492. * @return 0 on error.
  6493. * @return Size of DER encoding in bytes on success.
  6494. */
  6495. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6496. {
  6497. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6498. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6499. word32 len = (word32)-1;
  6500. int err = 0;
  6501. /* Validate parameters. */
  6502. if (dh == NULL) {
  6503. WOLFSSL_ERROR_MSG("Bad parameters");
  6504. err = 1;
  6505. }
  6506. /* Push external DH data into internal DH key if not set. */
  6507. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6508. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6509. err = 1;
  6510. }
  6511. if (!err) {
  6512. int ret;
  6513. unsigned char* der = NULL;
  6514. /* Use *out when available otherwise NULL. */
  6515. if (out != NULL) {
  6516. der = *out;
  6517. }
  6518. /* Get length and/or encode. */
  6519. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6520. /* Length of encoded data is returned on success. */
  6521. if (ret > 0) {
  6522. *out += len;
  6523. }
  6524. /* An error occurred unless only length returned. */
  6525. else if (ret != LENGTH_ONLY_E) {
  6526. err = 1;
  6527. }
  6528. }
  6529. /* Set return to 0 on error. */
  6530. if (err) {
  6531. len = 0;
  6532. }
  6533. return (int)len;
  6534. #else
  6535. word32 len;
  6536. int ret = 0;
  6537. int pSz;
  6538. int gSz;
  6539. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6540. /* Validate parameters. */
  6541. if (dh == NULL) {
  6542. WOLFSSL_ERROR_MSG("Bad parameters");
  6543. len = 0;
  6544. }
  6545. else {
  6546. /* SEQ <len>
  6547. * INT <len> [0x00] <prime>
  6548. * INT <len> [0x00] <generator>
  6549. * Integers have 0x00 prepended if the top bit of positive number is
  6550. * set.
  6551. */
  6552. /* Get total length of prime including any prepended zeros. */
  6553. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6554. mp_leading_bit((mp_int*)dh->p->internal);
  6555. /* Get total length of generator including any prepended zeros. */
  6556. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6557. mp_leading_bit((mp_int*)dh->g->internal);
  6558. /* Calculate length of data in sequence. */
  6559. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6560. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6561. /* Add in the length of the SEQUENCE. */
  6562. len += 1 + ASN_LEN_SIZE(len);
  6563. if ((out != NULL) && (*out != NULL)) {
  6564. /* Encode parameters. */
  6565. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6566. (mp_int*)dh->g->internal);
  6567. if (ret != MP_OKAY) {
  6568. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6569. len = 0;
  6570. }
  6571. else {
  6572. /* Move pointer on if encoded. */
  6573. *out += len;
  6574. }
  6575. }
  6576. }
  6577. return (int)len;
  6578. #endif
  6579. }
  6580. #endif /* OPENSSL_ALL */
  6581. #endif /* !NO_CERTS */
  6582. #endif /* OPENSSL_EXTRA */
  6583. #if defined(OPENSSL_EXTRA) || \
  6584. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6585. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6586. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6587. /* Load the DER encoded DH parameters into DH key.
  6588. *
  6589. * @param [in, out] dh DH key to load parameters into.
  6590. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6591. * @param [in] derSz Size of DER data in buffer in bytes.
  6592. *
  6593. * @return 1 on success.
  6594. * @return -1 when DH or derBuf is NULL,
  6595. * internal DH key in DH is NULL,
  6596. * derSz is 0 or less,
  6597. * error decoding DER data or
  6598. * setting external parameter values fails.
  6599. */
  6600. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6601. {
  6602. int ret = 1;
  6603. word32 idx = 0;
  6604. /* Validate parameters. */
  6605. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6606. (derSz <= 0)) {
  6607. WOLFSSL_ERROR_MSG("Bad function arguments");
  6608. ret = -1;
  6609. }
  6610. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6611. (word32)derSz) != 0)) {
  6612. WOLFSSL_ERROR_MSG("DH key decode failed");
  6613. ret = -1;
  6614. }
  6615. return ret;
  6616. }
  6617. #endif
  6618. /*
  6619. * DH PEM APIs
  6620. */
  6621. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6622. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6623. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6624. /* Create a DH key by reading the PEM encoded data from the BIO.
  6625. *
  6626. * @param [in] bio BIO object to read from.
  6627. * @param [in, out] dh DH key to use. May be NULL.
  6628. * @param [in] pem PEM data to decode.
  6629. * @param [in] pemSz Size of PEM data in bytes.
  6630. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6631. * freed after use.
  6632. * @return DH key on success.
  6633. * @return NULL on failure.
  6634. */
  6635. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6636. unsigned char* pem, int pemSz, int memAlloced)
  6637. {
  6638. WOLFSSL_DH* localDh = NULL;
  6639. DerBuffer *der = NULL;
  6640. int err = 0;
  6641. /* Convert PEM to DER assuming DH Parameter format. */
  6642. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6643. NULL) < 0)) {
  6644. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6645. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6646. != 0) {
  6647. err = 1;
  6648. }
  6649. /* If Success on X9.42 DH format, clear error from failed DH format */
  6650. else {
  6651. unsigned long error;
  6652. CLEAR_ASN_NO_PEM_HEADER_ERROR(error);
  6653. }
  6654. }
  6655. if (memAlloced) {
  6656. /* PEM data no longer needed. */
  6657. XFREE(pem, NULL, DYNAMIC_TYPE_PEM);
  6658. }
  6659. if (!err) {
  6660. /* Use the DH key passed in or allocate a new one. */
  6661. if (dh != NULL) {
  6662. localDh = *dh;
  6663. }
  6664. if (localDh == NULL) {
  6665. localDh = wolfSSL_DH_new();
  6666. if (localDh == NULL) {
  6667. err = 1;
  6668. }
  6669. }
  6670. }
  6671. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6672. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length)
  6673. != 1)) {
  6674. /* Free an allocated DH key. */
  6675. if ((dh == NULL) || (localDh != *dh)) {
  6676. wolfSSL_DH_free(localDh);
  6677. }
  6678. localDh = NULL;
  6679. err = 1;
  6680. }
  6681. /* Return the DH key on success. */
  6682. if ((!err) && (dh != NULL)) {
  6683. *dh = localDh;
  6684. }
  6685. /* Dispose of DER data. */
  6686. if (der != NULL) {
  6687. FreeDer(&der);
  6688. }
  6689. return localDh;
  6690. }
  6691. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6692. #ifndef NO_BIO
  6693. /* Create a DH key by reading the PEM encoded data from the BIO.
  6694. *
  6695. * DH parameters are public data and are not expected to be encrypted.
  6696. *
  6697. * @param [in] bio BIO object to read from.
  6698. * @param [in, out] dh DH key to When pointer to
  6699. * NULL, a new DH key is created.
  6700. * @param [in] cb Password callback when PEM encrypted. Not used.
  6701. * @param [in] pass NUL terminated string for passphrase when PEM
  6702. * encrypted. Not used.
  6703. * @return DH key on success.
  6704. * @return NULL on failure.
  6705. */
  6706. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6707. wc_pem_password_cb *cb, void *pass)
  6708. {
  6709. WOLFSSL_DH* localDh = NULL;
  6710. int err = 0;
  6711. unsigned char* mem = NULL;
  6712. int size = 0;
  6713. int memAlloced = 0;
  6714. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6715. (void)cb;
  6716. (void)pass;
  6717. /* Validate parameters. */
  6718. if (bio == NULL) {
  6719. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6720. err = 1;
  6721. }
  6722. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6723. */
  6724. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6725. != 0)) {
  6726. err = 1;
  6727. }
  6728. if (!err) {
  6729. /* Create a DH key from the PEM - try two different headers. */
  6730. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6731. }
  6732. return localDh;
  6733. }
  6734. #endif /* !NO_BIO */
  6735. #ifndef NO_FILESYSTEM
  6736. /* Read DH parameters from a file pointer into DH key.
  6737. *
  6738. * DH parameters are public data and are not expected to be encrypted.
  6739. *
  6740. * @param [in] fp File pointer to read DH parameter file from.
  6741. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6742. * NULL, a new DH key is created.
  6743. * @param [in] cb Password callback when PEM encrypted. Not used.
  6744. * @param [in] pass NUL terminated string for passphrase when PEM
  6745. * encrypted. Not used.
  6746. *
  6747. * @return NULL on failure.
  6748. * @return DH key with parameters set on success.
  6749. */
  6750. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6751. wc_pem_password_cb* cb, void* pass)
  6752. {
  6753. WOLFSSL_DH* localDh = NULL;
  6754. int err = 0;
  6755. unsigned char* mem = NULL;
  6756. int size = 0;
  6757. (void)cb;
  6758. (void)pass;
  6759. /* Read data from file pointer. */
  6760. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6761. err = 1;
  6762. }
  6763. if (!err) {
  6764. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6765. }
  6766. return localDh;
  6767. }
  6768. #endif /* !NO_FILESYSTEM */
  6769. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6770. /* Encoded parameter data in DH key as DER.
  6771. *
  6772. * @param [in, out] dh DH key object to encode.
  6773. * @param [out] out Buffer containing DER encoding.
  6774. * @param [in] heap Heap hint.
  6775. * @return <0 on error.
  6776. * @return Length of DER encoded DH parameters in bytes.
  6777. */
  6778. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6779. void* heap)
  6780. {
  6781. int ret = -1;
  6782. int err = 0;
  6783. byte* der = NULL;
  6784. word32 derSz;
  6785. DhKey* key;
  6786. (void)heap;
  6787. /* Set internal parameters based on external parameters. */
  6788. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6789. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6790. err = 1;
  6791. }
  6792. if (!err) {
  6793. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6794. key = (DhKey*)dh->internal;
  6795. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6796. if (ret != LENGTH_ONLY_E) {
  6797. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6798. err = 1;
  6799. }
  6800. }
  6801. if (!err) {
  6802. /* Allocate memory for DER encoding. */
  6803. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6804. if (der == NULL) {
  6805. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6806. err = 1;
  6807. }
  6808. }
  6809. if (!err) {
  6810. /* Encode DH parameters into DER buffer. */
  6811. ret = wc_DhParamsToDer(key, der, &derSz);
  6812. if (ret < 0) {
  6813. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6814. err = 1;
  6815. }
  6816. }
  6817. if (!err) {
  6818. *out = der;
  6819. der = NULL;
  6820. }
  6821. if (der != NULL) {
  6822. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6823. }
  6824. return ret;
  6825. }
  6826. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6827. * passed in.
  6828. *
  6829. * @param [in] fp File pointer to write to.
  6830. * @param [in] dh DH key to write.
  6831. * @return 1 on success.
  6832. * @return 0 on failure.
  6833. */
  6834. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6835. {
  6836. int ret = 1;
  6837. int derSz;
  6838. byte* derBuf = NULL;
  6839. void* heap = NULL;
  6840. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6841. /* Validate parameters. */
  6842. if ((fp == XBADFILE) || (dh == NULL)) {
  6843. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6844. ret = 0;
  6845. }
  6846. if (ret == 1) {
  6847. DhKey* key = (DhKey*)dh->internal;
  6848. if (key)
  6849. heap = key->heap;
  6850. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6851. WOLFSSL_ERROR_MSG("DER encoding failed");
  6852. ret = 0;
  6853. }
  6854. if (derBuf == NULL) {
  6855. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6856. ret = 0;
  6857. }
  6858. }
  6859. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6860. DH_PARAM_TYPE, NULL) != WOLFSSL_SUCCESS)) {
  6861. ret = 0;
  6862. }
  6863. /* Dispose of DER buffer. */
  6864. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6865. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6866. return ret;
  6867. }
  6868. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6869. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6870. * OPENSSL_EXTRA */
  6871. /*
  6872. * DH get/set APIs
  6873. */
  6874. #ifdef OPENSSL_EXTRA
  6875. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6876. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6877. /* Set the members of DhKey into WOLFSSL_DH
  6878. * Specify elements to set via the 2nd parameter
  6879. *
  6880. * @param [in, out] dh DH key to synchronize.
  6881. * @param [in] elm Elements to synchronize.
  6882. * @return 1 on success.
  6883. * @return -1 on failure.
  6884. */
  6885. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  6886. {
  6887. int ret = 1;
  6888. DhKey *key = NULL;
  6889. WOLFSSL_ENTER("SetDhExternal_ex");
  6890. /* Validate parameters. */
  6891. if ((dh == NULL) || (dh->internal == NULL)) {
  6892. WOLFSSL_ERROR_MSG("dh key NULL error");
  6893. ret = -1;
  6894. }
  6895. if (ret == 1) {
  6896. /* Get the wolfSSL DH key. */
  6897. key = (DhKey*)dh->internal;
  6898. }
  6899. if ((ret == 1) && (elm & ELEMENT_P)) {
  6900. /* Set the prime. */
  6901. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  6902. WOLFSSL_ERROR_MSG("dh param p error");
  6903. ret = -1;
  6904. }
  6905. }
  6906. if ((ret == 1) && (elm & ELEMENT_G)) {
  6907. /* Set the generator. */
  6908. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  6909. WOLFSSL_ERROR_MSG("dh param g error");
  6910. ret = -1;
  6911. }
  6912. }
  6913. if ((ret == 1) && (elm & ELEMENT_Q)) {
  6914. /* Set the order. */
  6915. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  6916. WOLFSSL_ERROR_MSG("dh param q error");
  6917. ret = -1;
  6918. }
  6919. }
  6920. #ifdef WOLFSSL_DH_EXTRA
  6921. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  6922. /* Set the private key. */
  6923. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  6924. WOLFSSL_ERROR_MSG("No DH Private Key");
  6925. ret = -1;
  6926. }
  6927. }
  6928. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  6929. /* Set the public key. */
  6930. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  6931. WOLFSSL_ERROR_MSG("No DH Public Key");
  6932. ret = -1;
  6933. }
  6934. }
  6935. #endif /* WOLFSSL_DH_EXTRA */
  6936. if (ret == 1) {
  6937. /* On success record that the external values have been set. */
  6938. dh->exSet = 1;
  6939. }
  6940. return ret;
  6941. }
  6942. /* Set the members of DhKey into WOLFSSL_DH
  6943. * DhKey was populated from wc_DhKeyDecode
  6944. * p, g, pub_key and priv_key are set.
  6945. *
  6946. * @param [in, out] dh DH key to synchronize.
  6947. * @return 1 on success.
  6948. * @return -1 on failure.
  6949. */
  6950. int SetDhExternal(WOLFSSL_DH *dh)
  6951. {
  6952. /* Assuming Q not required when using this API. */
  6953. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  6954. WOLFSSL_ENTER("SetDhExternal");
  6955. return SetDhExternal_ex(dh, elements);
  6956. }
  6957. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  6958. /* Set the internal/wolfSSL DH key with data from the external parts.
  6959. *
  6960. * @param [in, out] dh DH key to synchronize.
  6961. * @return 1 on success.
  6962. * @return -1 on failure.
  6963. */
  6964. int SetDhInternal(WOLFSSL_DH* dh)
  6965. {
  6966. int ret = 1;
  6967. DhKey *key = NULL;
  6968. WOLFSSL_ENTER("SetDhInternal");
  6969. /* Validate parameters. */
  6970. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  6971. WOLFSSL_ERROR_MSG("Bad function arguments");
  6972. ret = -1;
  6973. }
  6974. if (ret == 1) {
  6975. /* Get the wolfSSL DH key. */
  6976. key = (DhKey*)dh->internal;
  6977. /* Clear out key and initialize. */
  6978. wc_FreeDhKey(key);
  6979. if (wc_InitDhKey(key) != 0) {
  6980. ret = -1;
  6981. }
  6982. }
  6983. if (ret == 1) {
  6984. /* Transfer prime. */
  6985. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  6986. ret = -1;
  6987. }
  6988. }
  6989. if (ret == 1) {
  6990. /* Transfer generator. */
  6991. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  6992. ret = -1;
  6993. }
  6994. }
  6995. #ifdef HAVE_FFDHE_Q
  6996. /* Transfer order if available. */
  6997. if ((ret == 1) && (dh->q != NULL)) {
  6998. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  6999. ret = -1;
  7000. }
  7001. }
  7002. #endif
  7003. #ifdef WOLFSSL_DH_EXTRA
  7004. /* Transfer private key if available. */
  7005. if ((ret == 1) && (dh->priv_key != NULL) &&
  7006. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  7007. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7008. ret = -1;
  7009. }
  7010. }
  7011. /* Transfer public key if available. */
  7012. if ((ret == 1) && (dh->pub_key != NULL) &&
  7013. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  7014. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7015. ret = -1;
  7016. }
  7017. }
  7018. #endif /* WOLFSSL_DH_EXTRA */
  7019. if (ret == 1) {
  7020. /* On success record that the internal values have been set. */
  7021. dh->inSet = 1;
  7022. }
  7023. return ret;
  7024. }
  7025. /* Get the size, in bytes, of the DH key.
  7026. *
  7027. * Return code compliant with OpenSSL.
  7028. *
  7029. * @param [in] dh DH key.
  7030. * @return -1 on error.
  7031. * @return Size of DH key in bytes on success.
  7032. */
  7033. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7034. {
  7035. int ret = -1;
  7036. WOLFSSL_ENTER("wolfSSL_DH_size");
  7037. /* Validate parameter. */
  7038. if (dh != NULL) {
  7039. /* Size of key is size of prime in bytes. */
  7040. ret = wolfSSL_BN_num_bytes(dh->p);
  7041. }
  7042. return ret;
  7043. }
  7044. /**
  7045. * Return parameters p, q and/or g of the DH key.
  7046. *
  7047. * @param [in] dh DH key to retrieve parameters from.
  7048. * @param [out] p Pointer to return prime in. May be NULL.
  7049. * @param [out] q Pointer to return order in. May be NULL.
  7050. * @param [out] g Pointer to return generator in. May be NULL.
  7051. */
  7052. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7053. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7054. {
  7055. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7056. if (dh != NULL) {
  7057. /* Return prime if required. */
  7058. if (p != NULL) {
  7059. *p = dh->p;
  7060. }
  7061. /* Return order if required. */
  7062. if (q != NULL) {
  7063. *q = dh->q;
  7064. }
  7065. /* Return generator if required. */
  7066. if (g != NULL) {
  7067. *g = dh->g;
  7068. }
  7069. }
  7070. }
  7071. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7072. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7073. #if defined(OPENSSL_ALL) || \
  7074. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7075. /* Sets the parameters p, g and optionally q into the DH key.
  7076. *
  7077. * Ownership of p, q and g get taken over by "dh" on success and should be
  7078. * free'd with a call to wolfSSL_DH_free -- not individually.
  7079. *
  7080. * @param [in, out] dh DH key to set.
  7081. * @param [in] p Prime value to set. May be NULL when value already
  7082. * present.
  7083. * @param [in] q Order value to set. May be NULL.
  7084. * @param [in] g Generator value to set. May be NULL when value already
  7085. * present.
  7086. * @return 1 on success.
  7087. * @return 0 on failure.
  7088. */
  7089. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7090. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7091. {
  7092. int ret = 1;
  7093. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7094. /* Validate parameters - q is optional. */
  7095. if (dh == NULL) {
  7096. WOLFSSL_ERROR_MSG("Bad function arguments");
  7097. ret = 0;
  7098. }
  7099. /* p can be NULL if we already have one set. */
  7100. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7101. WOLFSSL_ERROR_MSG("Bad function arguments");
  7102. ret = 0;
  7103. }
  7104. /* g can be NULL if we already have one set. */
  7105. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7106. WOLFSSL_ERROR_MSG("Bad function arguments");
  7107. ret = 0;
  7108. }
  7109. if (ret == 1) {
  7110. /* Invalidate internal key. */
  7111. dh->inSet = 0;
  7112. /* Free external representation of parameters and set with those passed
  7113. * in. */
  7114. if (p != NULL) {
  7115. wolfSSL_BN_free(dh->p);
  7116. dh->p = p;
  7117. }
  7118. if (q != NULL) {
  7119. wolfSSL_BN_free(dh->q);
  7120. dh->q = q;
  7121. }
  7122. if (g != NULL) {
  7123. wolfSSL_BN_free(dh->g);
  7124. dh->g = g;
  7125. }
  7126. /* External DH key parameters were set. */
  7127. dh->exSet = 1;
  7128. /* Set internal/wolfSSL DH key as well. */
  7129. if (SetDhInternal(dh) != 1) {
  7130. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7131. /* Don't keep parameters on failure. */
  7132. dh->p = NULL;
  7133. dh->q = NULL;
  7134. dh->g = NULL;
  7135. /* Internal and external DH key not set. */
  7136. dh->inSet = 0;
  7137. dh->exSet = 0;
  7138. ret = 0;
  7139. }
  7140. }
  7141. return ret;
  7142. }
  7143. /* Set the length of the DH private key in bits.
  7144. *
  7145. * Length field is checked at generation.
  7146. *
  7147. * @param [in, out] dh DH key to set.
  7148. * @param [in] len Length of DH private key in bytes.
  7149. * @return 0 on failure.
  7150. * @return 1 on success.
  7151. */
  7152. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7153. {
  7154. int ret = 1;
  7155. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7156. /* Validate parameter. */
  7157. if (dh == NULL) {
  7158. WOLFSSL_ERROR_MSG("Bad function arguments");
  7159. ret = 0;
  7160. }
  7161. else {
  7162. /* Store length. */
  7163. dh->length = (int)len;
  7164. }
  7165. return ret;
  7166. }
  7167. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7168. #endif
  7169. /* Get the public and private keys requested.
  7170. *
  7171. * @param [in] dh DH key to get keys from.
  7172. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7173. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7174. */
  7175. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7176. const WOLFSSL_BIGNUM **priv_key)
  7177. {
  7178. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7179. /* Get only when valid DH passed in. */
  7180. if (dh != NULL) {
  7181. /* Return public key if required and available. */
  7182. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7183. *pub_key = dh->pub_key;
  7184. }
  7185. /* Return private key if required and available. */
  7186. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7187. *priv_key = dh->priv_key;
  7188. }
  7189. }
  7190. }
  7191. /* Set the public and/or private key.
  7192. *
  7193. * @param [in, out] dh DH key to have keys set into.
  7194. * @param [in] pub_key Public key to set. May be NULL.
  7195. * @param [in] priv_key Private key to set. May be NULL.
  7196. * @return 0 on failure.
  7197. * @return 1 on success.
  7198. */
  7199. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7200. WOLFSSL_BIGNUM *priv_key)
  7201. {
  7202. int ret = 1;
  7203. #ifdef WOLFSSL_DH_EXTRA
  7204. DhKey *key = NULL;
  7205. #endif
  7206. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7207. /* Validate parameters. */
  7208. if (dh == NULL) {
  7209. ret = 0;
  7210. }
  7211. #ifdef WOLFSSL_DH_EXTRA
  7212. else {
  7213. key = (DhKey*)dh->internal;
  7214. }
  7215. #endif
  7216. /* Replace public key when one passed in. */
  7217. if ((ret == 1) && (pub_key != NULL)) {
  7218. wolfSSL_BN_free(dh->pub_key);
  7219. dh->pub_key = pub_key;
  7220. #ifdef WOLFSSL_DH_EXTRA
  7221. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7222. ret = 0;
  7223. }
  7224. #endif
  7225. }
  7226. /* Replace private key when one passed in. */
  7227. if ((ret == 1) && (priv_key != NULL)) {
  7228. wolfSSL_BN_clear_free(dh->priv_key);
  7229. dh->priv_key = priv_key;
  7230. #ifdef WOLFSSL_DH_EXTRA
  7231. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7232. ret = 0;
  7233. }
  7234. #endif
  7235. }
  7236. return ret;
  7237. }
  7238. #endif /* OPENSSL_EXTRA */
  7239. /*
  7240. * DH check APIs
  7241. */
  7242. #ifdef OPENSSL_EXTRA
  7243. #ifndef NO_CERTS
  7244. #ifdef OPENSSL_ALL
  7245. /* Check whether BN number is a prime.
  7246. *
  7247. * @param [in] n Number to check.
  7248. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7249. * @return 1 on success.
  7250. * @return 0 on error.
  7251. */
  7252. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7253. {
  7254. int ret = 1;
  7255. #ifdef WOLFSSL_SMALL_STACK
  7256. WC_RNG* tmpRng = NULL;
  7257. #else
  7258. WC_RNG tmpRng[1];
  7259. #endif
  7260. WC_RNG* rng;
  7261. int localRng;
  7262. /* Make an RNG with tmpRng or get global. */
  7263. rng = wolfssl_make_rng(tmpRng, &localRng);
  7264. if (rng == NULL) {
  7265. ret = 0;
  7266. }
  7267. if (ret == 1) {
  7268. mp_int* prime = (mp_int*)n->internal;
  7269. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7270. ret = 0;
  7271. }
  7272. /* Free local random number generator if created. */
  7273. if (localRng) {
  7274. wc_FreeRng(rng);
  7275. #ifdef WOLFSSL_SMALL_STACK
  7276. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7277. #endif
  7278. }
  7279. }
  7280. return ret;
  7281. }
  7282. /* Checks the Diffie-Hellman parameters.
  7283. *
  7284. * Checks that the generator and prime are available.
  7285. * Checks that the prime is prime.
  7286. * OpenSSL expects codes to be non-NULL.
  7287. *
  7288. * @param [in] dh DH key to check.
  7289. * @param [out] codes Codes of checks that failed.
  7290. * @return 1 on success.
  7291. * @return 0 when DH is NULL, there were errors or failed to create a random
  7292. * number generator.
  7293. */
  7294. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7295. {
  7296. int ret = 1;
  7297. int errors = 0;
  7298. WOLFSSL_ENTER("wolfSSL_DH_check");
  7299. /* Validate parameters. */
  7300. if (dh == NULL) {
  7301. ret = 0;
  7302. }
  7303. /* Check generator available. */
  7304. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7305. errors |= DH_NOT_SUITABLE_GENERATOR;
  7306. }
  7307. if (ret == 1) {
  7308. /* Check prime available. */
  7309. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7310. errors |= DH_CHECK_P_NOT_PRIME;
  7311. }
  7312. else {
  7313. /* Test if dh->p is prime. */
  7314. int isPrime = MP_NO;
  7315. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7316. /* Set error code if parameter p is not prime. */
  7317. if ((ret == 1) && (isPrime != MP_YES)) {
  7318. errors |= DH_CHECK_P_NOT_PRIME;
  7319. }
  7320. }
  7321. }
  7322. /* Return errors when user wants exact issues. */
  7323. if (codes != NULL) {
  7324. *codes = errors;
  7325. }
  7326. else if (errors) {
  7327. ret = 0;
  7328. }
  7329. return ret;
  7330. }
  7331. #endif /* OPENSSL_ALL */
  7332. #endif /* !NO_CERTS */
  7333. #endif /* OPENSSL_EXTRA */
  7334. /*
  7335. * DH generate APIs
  7336. */
  7337. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7338. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7339. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7340. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7341. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7342. /* Generate DH parameters.
  7343. *
  7344. * @param [in] prime_len Length of prime in bits.
  7345. * @param [in] generator Generator value to use.
  7346. * @param [in] callback Called with progress information. Unused.
  7347. * @param [in] cb_arg User callback argument. Unused.
  7348. * @return NULL on failure.
  7349. * @return DH key on success.
  7350. */
  7351. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7352. void (*callback) (int, int, void *), void *cb_arg)
  7353. {
  7354. WOLFSSL_DH* dh = NULL;
  7355. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7356. /* Not supported by wolfSSl APIs. */
  7357. (void)callback;
  7358. (void)cb_arg;
  7359. /* Create an empty DH key. */
  7360. if ((dh = wolfSSL_DH_new()) == NULL) {
  7361. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7362. }
  7363. /* Generate parameters into DH key. */
  7364. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7365. != 1) {
  7366. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7367. wolfSSL_DH_free(dh);
  7368. dh = NULL;
  7369. }
  7370. return dh;
  7371. }
  7372. /* Generate DH parameters.
  7373. *
  7374. * @param [in] dh DH key to generate parameters into.
  7375. * @param [in] prime_len Length of prime in bits.
  7376. * @param [in] generator Generator value to use.
  7377. * @param [in] callback Called with progress information. Unused.
  7378. * @param [in] cb_arg User callback argument. Unused.
  7379. * @return 0 on failure.
  7380. * @return 1 on success.
  7381. */
  7382. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7383. int generator, void (*callback) (int, int, void *))
  7384. {
  7385. int ret = 1;
  7386. DhKey* key;
  7387. #ifdef WOLFSSL_SMALL_STACK
  7388. WC_RNG* tmpRng = NULL;
  7389. #else
  7390. WC_RNG tmpRng[1];
  7391. #endif
  7392. WC_RNG* rng = NULL;
  7393. int localRng = 0;
  7394. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7395. /* Not supported by wolfSSL APIs. */
  7396. (void)callback;
  7397. (void)generator;
  7398. /* Validate parameters. */
  7399. if (dh == NULL) {
  7400. WOLFSSL_ERROR_MSG("Bad parameter");
  7401. ret = 0;
  7402. }
  7403. if (ret == 1) {
  7404. /* Make an RNG with tmpRng or get global. */
  7405. rng = wolfssl_make_rng(tmpRng, &localRng);
  7406. if (rng == NULL) {
  7407. WOLFSSL_ERROR_MSG("No RNG to use");
  7408. ret = 0;
  7409. }
  7410. }
  7411. if (ret == 1) {
  7412. /* Get internal/wolfSSL DH key. */
  7413. key = (DhKey*)dh->internal;
  7414. /* Clear out data from internal DH key. */
  7415. wc_FreeDhKey(key);
  7416. /* Re-initialize internal DH key. */
  7417. if (wc_InitDhKey(key) != 0) {
  7418. ret = 0;
  7419. }
  7420. }
  7421. if (ret == 1) {
  7422. /* Generate parameters into internal DH key. */
  7423. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7424. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7425. ret = 0;
  7426. }
  7427. }
  7428. /* Free local random number generator if created. */
  7429. if (localRng) {
  7430. wc_FreeRng(rng);
  7431. #ifdef WOLFSSL_SMALL_STACK
  7432. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7433. #endif
  7434. }
  7435. if (ret == 1) {
  7436. /* Internal parameters set by generation. */
  7437. dh->inSet = 1;
  7438. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7439. /* Synchronize the external to the internal parameters. */
  7440. if (SetDhExternal(dh) != 1) {
  7441. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7442. ret = 0;
  7443. }
  7444. }
  7445. return ret;
  7446. }
  7447. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7448. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7449. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7450. * HAVE_SBLIM_SFCB)) */
  7451. #ifdef OPENSSL_EXTRA
  7452. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7453. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7454. /* Generate a public/private key pair base on parameters.
  7455. *
  7456. * @param [in, out] dh DH key to generate keys into.
  7457. * @return 1 on success.
  7458. * @return 0 on error.
  7459. */
  7460. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7461. {
  7462. int ret = 1;
  7463. word32 pubSz = 0;
  7464. word32 privSz = 0;
  7465. int localRng = 0;
  7466. WC_RNG* rng = NULL;
  7467. #ifdef WOLFSSL_SMALL_STACK
  7468. WC_RNG* tmpRng = NULL;
  7469. #else
  7470. WC_RNG tmpRng[1];
  7471. #endif
  7472. unsigned char* pub = NULL;
  7473. unsigned char* priv = NULL;
  7474. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7475. /* Validate parameters. */
  7476. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7477. WOLFSSL_ERROR_MSG("Bad function arguments");
  7478. ret = 0;
  7479. }
  7480. /* Synchronize the external and internal parameters. */
  7481. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7482. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7483. ret = 0;
  7484. }
  7485. if (ret == 1) {
  7486. /* Make a new RNG or use global. */
  7487. rng = wolfssl_make_rng(tmpRng, &localRng);
  7488. /* Check we have a random number generator. */
  7489. if (rng == NULL) {
  7490. ret = 0;
  7491. }
  7492. }
  7493. if (ret == 1) {
  7494. /* Get the size of the prime in bytes. */
  7495. pubSz = (word32)wolfSSL_BN_num_bytes(dh->p);
  7496. if (pubSz == 0) {
  7497. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7498. ret = 0;
  7499. }
  7500. }
  7501. if (ret == 1) {
  7502. /* Private key size can be as much as the size of the prime. */
  7503. if (dh->length) {
  7504. privSz = (word32)(dh->length / 8); /* to bytes */
  7505. }
  7506. else {
  7507. privSz = pubSz;
  7508. }
  7509. /* Allocate public and private key arrays. */
  7510. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7511. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7512. if (pub == NULL || priv == NULL) {
  7513. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7514. ret = 0;
  7515. }
  7516. }
  7517. if (ret == 1) {
  7518. /* Dispose of old public and private keys. */
  7519. wolfSSL_BN_free(dh->pub_key);
  7520. wolfSSL_BN_free(dh->priv_key);
  7521. /* Allocate new public and private keys. */
  7522. dh->pub_key = wolfSSL_BN_new();
  7523. dh->priv_key = wolfSSL_BN_new();
  7524. if (dh->pub_key == NULL) {
  7525. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7526. ret = 0;
  7527. }
  7528. if (dh->priv_key == NULL) {
  7529. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7530. ret = 0;
  7531. }
  7532. }
  7533. PRIVATE_KEY_UNLOCK();
  7534. /* Generate public and private keys into arrays. */
  7535. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7536. &privSz, pub, &pubSz) < 0)) {
  7537. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7538. ret = 0;
  7539. }
  7540. /* Set public key from array. */
  7541. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) ==
  7542. NULL)) {
  7543. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7544. ret = 0;
  7545. }
  7546. /* Set private key from array. */
  7547. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) ==
  7548. NULL)) {
  7549. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7550. ret = 0;
  7551. }
  7552. PRIVATE_KEY_LOCK();
  7553. if (localRng) {
  7554. /* Free an initialized local random number generator. */
  7555. wc_FreeRng(rng);
  7556. #ifdef WOLFSSL_SMALL_STACK
  7557. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7558. #endif
  7559. }
  7560. /* Dispose of allocated data. */
  7561. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7562. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7563. return ret;
  7564. }
  7565. /* Compute the shared key from the private key and peer's public key.
  7566. *
  7567. * Return code compliant with OpenSSL.
  7568. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7569. * supported.
  7570. *
  7571. * @param [out] key Buffer to place shared key.
  7572. * @param [in] otherPub Peer's public key.
  7573. * @param [in] dh DH key containing private key.
  7574. * @return -1 on error.
  7575. * @return Size of shared secret in bytes on success.
  7576. */
  7577. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7578. WOLFSSL_DH* dh)
  7579. {
  7580. int ret = 0;
  7581. word32 keySz = 0;
  7582. int pubSz = MAX_DHKEY_SZ;
  7583. int privSz = MAX_DHKEY_SZ;
  7584. int sz;
  7585. #ifdef WOLFSSL_SMALL_STACK
  7586. unsigned char* pub = NULL;
  7587. unsigned char* priv = NULL;
  7588. #else
  7589. unsigned char pub [MAX_DHKEY_SZ];
  7590. unsigned char priv[MAX_DHKEY_SZ];
  7591. #endif
  7592. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7593. /* Validate parameters. */
  7594. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7595. WOLFSSL_ERROR_MSG("Bad function arguments");
  7596. ret = -1;
  7597. }
  7598. /* Get the maximum size of computed DH key. */
  7599. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7600. WOLFSSL_ERROR_MSG("Bad DH_size");
  7601. ret = -1;
  7602. }
  7603. if (ret == 0) {
  7604. /* Validate the size of the private key. */
  7605. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7606. if (sz > (int)privSz) {
  7607. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7608. ret = -1;
  7609. }
  7610. }
  7611. if (ret == 0) {
  7612. #ifdef WOLFSSL_SMALL_STACK
  7613. /* Keep real private key size to minimize amount allocated. */
  7614. privSz = sz;
  7615. #endif
  7616. /* Validate the size of the public key. */
  7617. sz = wolfSSL_BN_num_bytes(otherPub);
  7618. if (sz > pubSz) {
  7619. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7620. ret = -1;
  7621. }
  7622. }
  7623. if (ret == 0) {
  7624. #ifdef WOLFSSL_SMALL_STACK
  7625. /* Allocate memory for the public key array. */
  7626. pub = (unsigned char*)XMALLOC((size_t)sz, NULL,
  7627. DYNAMIC_TYPE_PUBLIC_KEY);
  7628. if (pub == NULL)
  7629. ret = -1;
  7630. }
  7631. if (ret == 0) {
  7632. /* Allocate memory for the private key array. */
  7633. priv = (unsigned char*)XMALLOC((size_t)privSz, NULL,
  7634. DYNAMIC_TYPE_PRIVATE_KEY);
  7635. if (priv == NULL) {
  7636. ret = -1;
  7637. }
  7638. }
  7639. if (ret == 0) {
  7640. #endif
  7641. /* Get the private key into the array. */
  7642. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7643. if (privSz <= 0) {
  7644. ret = -1;
  7645. }
  7646. }
  7647. if (ret == 0) {
  7648. /* Get the public key into the array. */
  7649. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7650. if (privSz <= 0) {
  7651. ret = -1;
  7652. }
  7653. }
  7654. /* Synchronize the external into the internal parameters. */
  7655. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7656. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7657. ret = -1;
  7658. }
  7659. PRIVATE_KEY_UNLOCK();
  7660. /* Calculate shared secret from private and public keys. */
  7661. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7662. (word32)privSz, pub, (word32)pubSz) < 0)) {
  7663. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7664. ret = -1;
  7665. }
  7666. if (ret == 0) {
  7667. /* Return actual length. */
  7668. ret = (int)keySz;
  7669. }
  7670. PRIVATE_KEY_LOCK();
  7671. #ifdef WOLFSSL_SMALL_STACK
  7672. if (priv != NULL)
  7673. #endif
  7674. {
  7675. /* Zeroize sensitive data. */
  7676. ForceZero(priv, (word32)privSz);
  7677. }
  7678. #ifdef WOLFSSL_SMALL_STACK
  7679. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7680. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7681. #endif
  7682. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7683. return ret;
  7684. }
  7685. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7686. * HAVE_FIPS_VERSION > 2 */
  7687. #endif /* OPENSSL_EXTRA */
  7688. #endif /* NO_DH */
  7689. /*******************************************************************************
  7690. * END OF DH API
  7691. ******************************************************************************/
  7692. /*******************************************************************************
  7693. * START OF EC API
  7694. ******************************************************************************/
  7695. #ifdef HAVE_ECC
  7696. #if defined(OPENSSL_EXTRA)
  7697. /* Start EC_curve */
  7698. /* Get the NIST name for the numeric ID.
  7699. *
  7700. * @param [in] nid Numeric ID of an EC curve.
  7701. * @return String representing NIST name of EC curve on success.
  7702. * @return NULL on error.
  7703. */
  7704. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7705. {
  7706. const char* name = NULL;
  7707. const WOLF_EC_NIST_NAME* nist_name;
  7708. /* Attempt to find the curve info matching the NID passed in. */
  7709. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7710. if (nist_name->nid == nid) {
  7711. /* NID found - return name. */
  7712. name = nist_name->name;
  7713. break;
  7714. }
  7715. }
  7716. return name;
  7717. }
  7718. /* Get the numeric ID for the NIST name.
  7719. *
  7720. * @param [in] name NIST name of EC curve.
  7721. * @return NID matching NIST name on success.
  7722. * @return 0 on error.
  7723. */
  7724. int wolfSSL_EC_curve_nist2nid(const char* name)
  7725. {
  7726. int nid = 0;
  7727. const WOLF_EC_NIST_NAME* nist_name;
  7728. /* Attempt to find the curve info matching the NIST name passed in. */
  7729. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7730. if (XSTRCMP(nist_name->name, name) == 0) {
  7731. /* Name found - return NID. */
  7732. nid = nist_name->nid;
  7733. break;
  7734. }
  7735. }
  7736. return nid;
  7737. }
  7738. #endif /* OPENSSL_EXTRA */
  7739. /* End EC_curve */
  7740. /* Start EC_METHOD */
  7741. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7742. /* Get the EC method of the EC group object.
  7743. *
  7744. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7745. * the NID.
  7746. *
  7747. * @param [in] group EC group object.
  7748. * @return EC method.
  7749. */
  7750. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7751. const WOLFSSL_EC_GROUP *group)
  7752. {
  7753. /* No method table used so just return the same object. */
  7754. return group;
  7755. }
  7756. /* Get field type for method.
  7757. *
  7758. * Only prime fields are supported.
  7759. *
  7760. * @param [in] meth EC method.
  7761. * @return X9.63 prime field NID on success.
  7762. * @return 0 on error.
  7763. */
  7764. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7765. {
  7766. int nid = 0;
  7767. if (meth != NULL) {
  7768. /* Only field type supported by code base. */
  7769. nid = NID_X9_62_prime_field;
  7770. }
  7771. return nid;
  7772. }
  7773. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7774. /* End EC_METHOD */
  7775. /* Start EC_GROUP */
  7776. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7777. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7778. * value.
  7779. *
  7780. * @param [in] n ECC curve id.
  7781. * @return ECC curve NID (OpenSSL compatible value).
  7782. */
  7783. int EccEnumToNID(int n)
  7784. {
  7785. WOLFSSL_ENTER("EccEnumToNID");
  7786. switch(n) {
  7787. case ECC_SECP192R1:
  7788. return NID_X9_62_prime192v1;
  7789. case ECC_PRIME192V2:
  7790. return NID_X9_62_prime192v2;
  7791. case ECC_PRIME192V3:
  7792. return NID_X9_62_prime192v3;
  7793. case ECC_PRIME239V1:
  7794. return NID_X9_62_prime239v1;
  7795. case ECC_PRIME239V2:
  7796. return NID_X9_62_prime239v2;
  7797. case ECC_PRIME239V3:
  7798. return NID_X9_62_prime239v3;
  7799. case ECC_SECP256R1:
  7800. return NID_X9_62_prime256v1;
  7801. case ECC_SECP112R1:
  7802. return NID_secp112r1;
  7803. case ECC_SECP112R2:
  7804. return NID_secp112r2;
  7805. case ECC_SECP128R1:
  7806. return NID_secp128r1;
  7807. case ECC_SECP128R2:
  7808. return NID_secp128r2;
  7809. case ECC_SECP160R1:
  7810. return NID_secp160r1;
  7811. case ECC_SECP160R2:
  7812. return NID_secp160r2;
  7813. case ECC_SECP224R1:
  7814. return NID_secp224r1;
  7815. case ECC_SECP384R1:
  7816. return NID_secp384r1;
  7817. case ECC_SECP521R1:
  7818. return NID_secp521r1;
  7819. case ECC_SECP160K1:
  7820. return NID_secp160k1;
  7821. case ECC_SECP192K1:
  7822. return NID_secp192k1;
  7823. case ECC_SECP224K1:
  7824. return NID_secp224k1;
  7825. case ECC_SECP256K1:
  7826. return NID_secp256k1;
  7827. case ECC_BRAINPOOLP160R1:
  7828. return NID_brainpoolP160r1;
  7829. case ECC_BRAINPOOLP192R1:
  7830. return NID_brainpoolP192r1;
  7831. case ECC_BRAINPOOLP224R1:
  7832. return NID_brainpoolP224r1;
  7833. case ECC_BRAINPOOLP256R1:
  7834. return NID_brainpoolP256r1;
  7835. case ECC_BRAINPOOLP320R1:
  7836. return NID_brainpoolP320r1;
  7837. case ECC_BRAINPOOLP384R1:
  7838. return NID_brainpoolP384r1;
  7839. case ECC_BRAINPOOLP512R1:
  7840. return NID_brainpoolP512r1;
  7841. #ifdef WOLFSSL_SM2
  7842. case ECC_SM2P256V1:
  7843. return NID_sm2;
  7844. #endif
  7845. default:
  7846. WOLFSSL_MSG("NID not found");
  7847. return -1;
  7848. }
  7849. }
  7850. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7851. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7852. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  7853. *
  7854. * Used by ecc_sets[].
  7855. *
  7856. * @param [in] n OpenSSL NID of EC curve.
  7857. * @return wolfCrypt EC curve id.
  7858. * @return -1 on error.
  7859. */
  7860. int NIDToEccEnum(int nid)
  7861. {
  7862. /* -1 on error. */
  7863. int id = -1;
  7864. WOLFSSL_ENTER("NIDToEccEnum");
  7865. switch (nid) {
  7866. case NID_X9_62_prime192v1:
  7867. id = ECC_SECP192R1;
  7868. break;
  7869. case NID_X9_62_prime192v2:
  7870. id = ECC_PRIME192V2;
  7871. break;
  7872. case NID_X9_62_prime192v3:
  7873. id = ECC_PRIME192V3;
  7874. break;
  7875. case NID_X9_62_prime239v1:
  7876. id = ECC_PRIME239V1;
  7877. break;
  7878. case NID_X9_62_prime239v2:
  7879. id = ECC_PRIME239V2;
  7880. break;
  7881. case NID_X9_62_prime239v3:
  7882. id = ECC_PRIME239V3;
  7883. break;
  7884. case NID_X9_62_prime256v1:
  7885. id = ECC_SECP256R1;
  7886. break;
  7887. case NID_secp112r1:
  7888. id = ECC_SECP112R1;
  7889. break;
  7890. case NID_secp112r2:
  7891. id = ECC_SECP112R2;
  7892. break;
  7893. case NID_secp128r1:
  7894. id = ECC_SECP128R1;
  7895. break;
  7896. case NID_secp128r2:
  7897. id = ECC_SECP128R2;
  7898. break;
  7899. case NID_secp160r1:
  7900. id = ECC_SECP160R1;
  7901. break;
  7902. case NID_secp160r2:
  7903. id = ECC_SECP160R2;
  7904. break;
  7905. case NID_secp224r1:
  7906. id = ECC_SECP224R1;
  7907. break;
  7908. case NID_secp384r1:
  7909. id = ECC_SECP384R1;
  7910. break;
  7911. case NID_secp521r1:
  7912. id = ECC_SECP521R1;
  7913. break;
  7914. case NID_secp160k1:
  7915. id = ECC_SECP160K1;
  7916. break;
  7917. case NID_secp192k1:
  7918. id = ECC_SECP192K1;
  7919. break;
  7920. case NID_secp224k1:
  7921. id = ECC_SECP224K1;
  7922. break;
  7923. case NID_secp256k1:
  7924. id = ECC_SECP256K1;
  7925. break;
  7926. case NID_brainpoolP160r1:
  7927. id = ECC_BRAINPOOLP160R1;
  7928. break;
  7929. case NID_brainpoolP192r1:
  7930. id = ECC_BRAINPOOLP192R1;
  7931. break;
  7932. case NID_brainpoolP224r1:
  7933. id = ECC_BRAINPOOLP224R1;
  7934. break;
  7935. case NID_brainpoolP256r1:
  7936. id = ECC_BRAINPOOLP256R1;
  7937. break;
  7938. case NID_brainpoolP320r1:
  7939. id = ECC_BRAINPOOLP320R1;
  7940. break;
  7941. case NID_brainpoolP384r1:
  7942. id = ECC_BRAINPOOLP384R1;
  7943. break;
  7944. case NID_brainpoolP512r1:
  7945. id = ECC_BRAINPOOLP512R1;
  7946. break;
  7947. default:
  7948. WOLFSSL_MSG("NID not found");
  7949. }
  7950. return id;
  7951. }
  7952. /* Set the fields of the EC group based on numeric ID.
  7953. *
  7954. * @param [in, out] group EC group.
  7955. * @param [in] nid Numeric ID of an EC curve.
  7956. */
  7957. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  7958. {
  7959. int eccEnum;
  7960. int realNid;
  7961. /* Convert ecc_curve_id enum to NID. */
  7962. if ((realNid = EccEnumToNID(nid)) != -1) {
  7963. /* ecc_curve_id enum passed in - have real NID value set. */
  7964. eccEnum = nid;
  7965. }
  7966. else {
  7967. /* NID passed in is OpenSSL type. */
  7968. realNid = nid;
  7969. /* Convert NID to ecc_curve_id enum. */
  7970. eccEnum = NIDToEccEnum(nid);
  7971. }
  7972. /* Set the numeric ID of the curve */
  7973. group->curve_nid = realNid;
  7974. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  7975. group->curve_idx = -1;
  7976. /* Find index and OID sum for curve if wolfCrypt supports it. */
  7977. if (eccEnum != -1) {
  7978. int i;
  7979. /* Find id and set the internal curve idx and OID sum. */
  7980. for (i = 0; ecc_sets[i].size != 0; i++) {
  7981. if (ecc_sets[i].id == eccEnum) {
  7982. /* Found id in wolfCrypt supported EC curves. */
  7983. group->curve_idx = i;
  7984. group->curve_oid = (int)ecc_sets[i].oidSum;
  7985. break;
  7986. }
  7987. }
  7988. }
  7989. }
  7990. /* Create a new EC group with the numeric ID for an EC curve.
  7991. *
  7992. * @param [in] nid Numeric ID of an EC curve.
  7993. * @return New, allocated EC group on success.
  7994. * @return NULL on error.
  7995. */
  7996. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  7997. {
  7998. int err = 0;
  7999. WOLFSSL_EC_GROUP* group;
  8000. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  8001. /* Allocate EC group. */
  8002. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  8003. DYNAMIC_TYPE_ECC);
  8004. if (group == NULL) {
  8005. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  8006. err = 1;
  8007. }
  8008. if (!err) {
  8009. /* Reset all fields. */
  8010. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  8011. /* Set the fields of group based on the numeric ID. */
  8012. ec_group_set_nid(group, nid);
  8013. }
  8014. return group;
  8015. }
  8016. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8017. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8018. /* Dispose of the EC group.
  8019. *
  8020. * Cannot use group after this call.
  8021. *
  8022. * @param [in] group EC group to free.
  8023. */
  8024. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8025. {
  8026. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8027. /* Dispose of EC group. */
  8028. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8029. }
  8030. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8031. #ifdef OPENSSL_EXTRA
  8032. #ifndef NO_BIO
  8033. /* Creates an EC group from the DER encoding.
  8034. *
  8035. * Only named curves supported.
  8036. *
  8037. * @param [out] group Reference to EC group object.
  8038. * @param [in] in Buffer holding DER encoding of curve.
  8039. * @param [in] inSz Length of data in buffer.
  8040. * @return EC group on success.
  8041. * @return NULL on error.
  8042. */
  8043. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  8044. const unsigned char* in, long inSz)
  8045. {
  8046. int err = 0;
  8047. WOLFSSL_EC_GROUP* ret = NULL;
  8048. word32 idx = 0;
  8049. word32 oid = 0;
  8050. int id = 0;
  8051. /* Use the group passed in. */
  8052. if ((group != NULL) && (*group != NULL)) {
  8053. ret = *group;
  8054. }
  8055. /* Only support named curves. */
  8056. if (in[0] != ASN_OBJECT_ID) {
  8057. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8058. err = 1;
  8059. }
  8060. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8061. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8062. 0)) {
  8063. err = 1;
  8064. }
  8065. if (!err) {
  8066. /* Get the internal ID for OID. */
  8067. id = wc_ecc_get_oid(oid, NULL, NULL);
  8068. if (id < 0) {
  8069. err = 1;
  8070. }
  8071. }
  8072. if (!err) {
  8073. /* Get the NID for the internal ID. */
  8074. int nid = EccEnumToNID(id);
  8075. if (ret == NULL) {
  8076. /* Create a new EC group with the numeric ID. */
  8077. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8078. if (ret == NULL) {
  8079. err = 1;
  8080. }
  8081. }
  8082. else {
  8083. ec_group_set_nid(ret, nid);
  8084. }
  8085. }
  8086. if ((!err) && (group != NULL)) {
  8087. /* Return the EC group through reference. */
  8088. *group = ret;
  8089. }
  8090. if (err) {
  8091. if ((ret != NULL) && (ret != *group)) {
  8092. wolfSSL_EC_GROUP_free(ret);
  8093. }
  8094. ret = NULL;
  8095. }
  8096. return ret;
  8097. }
  8098. /* Creates a new EC group from the PEM encoding in the BIO.
  8099. *
  8100. * @param [in] bio BIO to read PEM encoding from.
  8101. * @param [out] group Reference to EC group object.
  8102. * @param [in] cb Password callback when PEM encrypted.
  8103. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8104. * @return EC group on success.
  8105. * @return NULL on error.
  8106. */
  8107. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8108. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8109. {
  8110. int err = 0;
  8111. WOLFSSL_EC_GROUP* ret = NULL;
  8112. DerBuffer* der = NULL;
  8113. int keyFormat = 0;
  8114. if (bio == NULL) {
  8115. err = 1;
  8116. }
  8117. /* Read parameters from BIO and convert PEM to DER. */
  8118. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8119. &keyFormat, &der) < 0)) {
  8120. err = 1;
  8121. }
  8122. if (!err) {
  8123. /* Create EC group from DER encoding. */
  8124. ret = wolfssl_ec_group_d2i(group, der->buffer, der->length);
  8125. if (ret == NULL) {
  8126. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8127. }
  8128. }
  8129. /* Dispose of any allocated data. */
  8130. FreeDer(&der);
  8131. return ret;
  8132. }
  8133. #endif /* !NO_BIO */
  8134. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8135. /* Copy an EC group.
  8136. *
  8137. * Only used by wolfSSL_EC_KEY_dup at this time.
  8138. *
  8139. * @param [in, out] dst Destination EC group.
  8140. * @param [in] src Source EC group.
  8141. * @return 0 on success.
  8142. */
  8143. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8144. const WOLFSSL_EC_GROUP* src)
  8145. {
  8146. /* Copy the fields. */
  8147. dst->curve_idx = src->curve_idx;
  8148. dst->curve_nid = src->curve_nid;
  8149. dst->curve_oid = src->curve_oid;
  8150. return 0;
  8151. }
  8152. #endif /* OPENSSL_ALL && !NO_CERTS */
  8153. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8154. *
  8155. * @param [in] src EC group to duplicate.
  8156. *
  8157. * @return EC group on success.
  8158. * @return NULL on error.
  8159. */
  8160. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8161. {
  8162. WOLFSSL_EC_GROUP* newGroup = NULL;
  8163. if (src != NULL) {
  8164. /* Create new group base on NID in original EC group. */
  8165. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8166. }
  8167. return newGroup;
  8168. }
  8169. /* Compare two EC groups.
  8170. *
  8171. * Return code compliant with OpenSSL.
  8172. *
  8173. * @param [in] a First EC group.
  8174. * @param [in] b Second EC group.
  8175. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8176. *
  8177. * @return 0 if equal.
  8178. * @return 1 if not equal.
  8179. * @return -1 on error.
  8180. */
  8181. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8182. WOLFSSL_BN_CTX *ctx)
  8183. {
  8184. int ret;
  8185. /* No BN operations performed. */
  8186. (void)ctx;
  8187. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8188. /* Validate parameters. */
  8189. if ((a == NULL) || (b == NULL)) {
  8190. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8191. /* Return error value. */
  8192. ret = -1;
  8193. }
  8194. /* Compare NID and wolfSSL curve index. */
  8195. else {
  8196. /* 0 when same, 1 when not. */
  8197. ret = ((a->curve_nid == b->curve_nid) &&
  8198. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8199. }
  8200. return ret;
  8201. }
  8202. #ifndef NO_WOLFSSL_STUB
  8203. /* Set the ASN.1 flag that indicate encoding of curve.
  8204. *
  8205. * Stub function - flag not used elsewhere.
  8206. * Always encoded as named curve.
  8207. *
  8208. * @param [in] group EC group to modify.
  8209. * @param [in] flag ASN.1 flag to set. Valid values:
  8210. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8211. */
  8212. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8213. {
  8214. (void)group;
  8215. (void)flag;
  8216. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8217. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8218. }
  8219. #endif
  8220. /* Get the curve NID of the group.
  8221. *
  8222. * Return code compliant with OpenSSL.
  8223. *
  8224. * @param [in] group EC group.
  8225. * @return Curve NID on success.
  8226. * @return 0 on error.
  8227. */
  8228. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8229. {
  8230. int nid = 0;
  8231. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8232. if (group == NULL) {
  8233. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8234. }
  8235. else {
  8236. nid = group->curve_nid;
  8237. }
  8238. return nid;
  8239. }
  8240. /* Get the degree (curve size in bits) of the EC group.
  8241. *
  8242. * Return code compliant with OpenSSL.
  8243. *
  8244. * @return Degree of the curve on success.
  8245. * @return 0 on error.
  8246. */
  8247. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8248. {
  8249. int degree = 0;
  8250. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8251. if (group == NULL) {
  8252. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8253. }
  8254. else {
  8255. switch (group->curve_nid) {
  8256. case NID_secp112r1:
  8257. case NID_secp112r2:
  8258. degree = 112;
  8259. break;
  8260. case NID_secp128r1:
  8261. case NID_secp128r2:
  8262. degree = 128;
  8263. break;
  8264. case NID_secp160k1:
  8265. case NID_secp160r1:
  8266. case NID_secp160r2:
  8267. case NID_brainpoolP160r1:
  8268. degree = 160;
  8269. break;
  8270. case NID_secp192k1:
  8271. case NID_brainpoolP192r1:
  8272. case NID_X9_62_prime192v1:
  8273. case NID_X9_62_prime192v2:
  8274. case NID_X9_62_prime192v3:
  8275. degree = 192;
  8276. break;
  8277. case NID_secp224k1:
  8278. case NID_secp224r1:
  8279. case NID_brainpoolP224r1:
  8280. degree = 224;
  8281. break;
  8282. case NID_X9_62_prime239v1:
  8283. case NID_X9_62_prime239v2:
  8284. case NID_X9_62_prime239v3:
  8285. degree = 239;
  8286. break;
  8287. case NID_secp256k1:
  8288. case NID_brainpoolP256r1:
  8289. case NID_X9_62_prime256v1:
  8290. degree = 256;
  8291. break;
  8292. case NID_brainpoolP320r1:
  8293. degree = 320;
  8294. break;
  8295. case NID_secp384r1:
  8296. case NID_brainpoolP384r1:
  8297. degree = 384;
  8298. break;
  8299. case NID_brainpoolP512r1:
  8300. degree = 512;
  8301. break;
  8302. case NID_secp521r1:
  8303. degree = 521;
  8304. break;
  8305. }
  8306. }
  8307. return degree;
  8308. }
  8309. #endif /* OPENSSL_EXTRA */
  8310. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8311. /* Get the length of the order in bits of the EC group.
  8312. *
  8313. * TODO: consider switch statement or calculating directly from hex string
  8314. * array instead of using mp_int.
  8315. *
  8316. * @param [in] group EC group.
  8317. * @return Length of order in bits on success.
  8318. * @return 0 on error.
  8319. */
  8320. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8321. {
  8322. int ret = 0;
  8323. #ifdef WOLFSSL_SMALL_STACK
  8324. mp_int *order = NULL;
  8325. #else
  8326. mp_int order[1];
  8327. #endif
  8328. /* Validate parameter. */
  8329. if ((group == NULL) || (group->curve_idx < 0)) {
  8330. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8331. ret = -1;
  8332. }
  8333. #ifdef WOLFSSL_SMALL_STACK
  8334. if (ret == 0) {
  8335. /* Allocate memory for mp_int that will hold order value. */
  8336. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8337. DYNAMIC_TYPE_TMP_BUFFER);
  8338. if (order == NULL) {
  8339. ret = -1;
  8340. }
  8341. }
  8342. #endif
  8343. if (ret == 0) {
  8344. /* Initialize mp_int. */
  8345. ret = mp_init(order);
  8346. }
  8347. if (ret == 0) {
  8348. /* Read hex string of order from wolfCrypt array of curves. */
  8349. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8350. MP_RADIX_HEX);
  8351. if (ret == 0) {
  8352. /* Get bits of order. */
  8353. ret = mp_count_bits(order);
  8354. }
  8355. /* Clear and free mp_int. */
  8356. mp_clear(order);
  8357. }
  8358. #ifdef WOLFSSL_SMALL_STACK
  8359. /* Deallocate order. */
  8360. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8361. #endif
  8362. /* Convert error code to length of 0. */
  8363. if (ret < 0) {
  8364. ret = 0;
  8365. }
  8366. return ret;
  8367. }
  8368. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8369. #if defined(OPENSSL_EXTRA)
  8370. /* Get the order of the group as a BN.
  8371. *
  8372. * Return code compliant with OpenSSL.
  8373. *
  8374. * @param [in] group EC group.
  8375. * @param [in, out] order BN to hold order value.
  8376. * @param [in] ctx Context to use for BN operations. Unused.
  8377. * @return 1 on success.
  8378. * @return 0 on error.
  8379. */
  8380. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8381. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8382. {
  8383. int ret = 1;
  8384. mp_int* mp = NULL;
  8385. /* No BN operations performed - done with mp_int in BN. */
  8386. (void)ctx;
  8387. /* Validate parameters. */
  8388. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8389. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8390. ret = 0;
  8391. }
  8392. if (ret == 1) {
  8393. mp = (mp_int*)order->internal;
  8394. }
  8395. /* Initialize */
  8396. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8397. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8398. ret = 0;
  8399. }
  8400. /* Read hex string of order from wolfCrypt array of curves. */
  8401. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8402. MP_RADIX_HEX) != MP_OKAY)) {
  8403. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8404. /* Zero out any partial value but don't free. */
  8405. mp_zero(mp);
  8406. ret = 0;
  8407. }
  8408. return ret;
  8409. }
  8410. #endif /* OPENSSL_EXTRA */
  8411. /* End EC_GROUP */
  8412. /* Start EC_POINT */
  8413. #if defined(OPENSSL_EXTRA)
  8414. /* Set data of EC point into internal, wolfCrypt EC point object.
  8415. *
  8416. * EC_POINT Openssl -> WolfSSL
  8417. *
  8418. * @param [in, out] p EC point to update.
  8419. * @return 1 on success.
  8420. * @return -1 on failure.
  8421. */
  8422. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8423. {
  8424. int ret = 1;
  8425. WOLFSSL_ENTER("ec_point_internal_set");
  8426. /* Validate parameter. */
  8427. if ((p == NULL) || (p->internal == NULL)) {
  8428. WOLFSSL_MSG("ECPoint NULL error");
  8429. ret = -1;
  8430. }
  8431. else {
  8432. /* Get internal point as a wolfCrypt EC point. */
  8433. ecc_point* point = (ecc_point*)p->internal;
  8434. /* Set X ordinate if available. */
  8435. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8436. WOLFSSL_MSG("ecc point X error");
  8437. ret = -1;
  8438. }
  8439. /* Set Y ordinate if available. */
  8440. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8441. point->y) != 1)) {
  8442. WOLFSSL_MSG("ecc point Y error");
  8443. ret = -1;
  8444. }
  8445. /* Set Z ordinate if available. */
  8446. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8447. point->z) != 1)) {
  8448. WOLFSSL_MSG("ecc point Z error");
  8449. ret = -1;
  8450. }
  8451. /* Internal values set when operations succeeded. */
  8452. p->inSet = (ret == 1);
  8453. }
  8454. return ret;
  8455. }
  8456. /* Set data of internal, wolfCrypt EC point object into EC point.
  8457. *
  8458. * EC_POINT WolfSSL -> OpenSSL
  8459. *
  8460. * @param [in, out] p EC point to update.
  8461. * @return 1 on success.
  8462. * @return -1 on failure.
  8463. */
  8464. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8465. {
  8466. int ret = 1;
  8467. WOLFSSL_ENTER("ec_point_external_set");
  8468. /* Validate parameter. */
  8469. if ((p == NULL) || (p->internal == NULL)) {
  8470. WOLFSSL_MSG("ECPoint NULL error");
  8471. ret = -1;
  8472. }
  8473. else {
  8474. /* Get internal point as a wolfCrypt EC point. */
  8475. ecc_point* point = (ecc_point*)p->internal;
  8476. /* Set X ordinate. */
  8477. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8478. WOLFSSL_MSG("ecc point X error");
  8479. ret = -1;
  8480. }
  8481. /* Set Y ordinate. */
  8482. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8483. WOLFSSL_MSG("ecc point Y error");
  8484. ret = -1;
  8485. }
  8486. /* Set Z ordinate. */
  8487. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8488. WOLFSSL_MSG("ecc point Z error");
  8489. ret = -1;
  8490. }
  8491. /* External values set when operations succeeded. */
  8492. p->exSet = (ret == 1);
  8493. }
  8494. return ret;
  8495. }
  8496. /* Setup internals of EC point.
  8497. *
  8498. * Assumes point is not NULL.
  8499. *
  8500. * @param [in, out] point EC point to update.
  8501. * @return 1 on success.
  8502. * @return 0 on failure.
  8503. */
  8504. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8505. int ret = 1;
  8506. /* Check if internal values need setting. */
  8507. if (!point->inSet) {
  8508. WOLFSSL_MSG("No ECPoint internal set, do it");
  8509. /* Forcing to non-constant type to update internals. */
  8510. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8511. WOLFSSL_MSG("ec_point_internal_set failed");
  8512. ret = 0;
  8513. }
  8514. }
  8515. return ret;
  8516. }
  8517. /* Create a new EC point from the group.
  8518. *
  8519. * @param [in] group EC group.
  8520. * @return EC point on success.
  8521. * @return NULL on error.
  8522. */
  8523. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8524. {
  8525. int err = 0;
  8526. WOLFSSL_EC_POINT* point = NULL;
  8527. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8528. /* Validate parameter. */
  8529. if (group == NULL) {
  8530. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8531. err = 1;
  8532. }
  8533. if (!err) {
  8534. /* Allocate memory for new EC point. */
  8535. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8536. DYNAMIC_TYPE_ECC);
  8537. if (point == NULL) {
  8538. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8539. err = 1;
  8540. }
  8541. }
  8542. if (!err) {
  8543. /* Clear fields of EC point. */
  8544. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8545. /* Allocate internal EC point. */
  8546. point->internal = wc_ecc_new_point();
  8547. if (point->internal == NULL) {
  8548. WOLFSSL_MSG("ecc_new_point failure");
  8549. err = 1;
  8550. }
  8551. }
  8552. if (err) {
  8553. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8554. point = NULL;
  8555. }
  8556. return point;
  8557. }
  8558. #endif /* OPENSSL_EXTRA */
  8559. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8560. /* Dispose of the EC point.
  8561. *
  8562. * Cannot use point after this call.
  8563. *
  8564. * @param [in, out] point EC point to free.
  8565. */
  8566. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8567. {
  8568. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8569. if (point != NULL) {
  8570. if (point->internal != NULL) {
  8571. wc_ecc_del_point((ecc_point*)point->internal);
  8572. point->internal = NULL;
  8573. }
  8574. /* Free ordinates. */
  8575. wolfSSL_BN_free(point->X);
  8576. wolfSSL_BN_free(point->Y);
  8577. wolfSSL_BN_free(point->Z);
  8578. /* Clear fields. */
  8579. point->X = NULL;
  8580. point->Y = NULL;
  8581. point->Z = NULL;
  8582. point->inSet = 0;
  8583. point->exSet = 0;
  8584. /* Dispose of EC point. */
  8585. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8586. }
  8587. }
  8588. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8589. #ifdef OPENSSL_EXTRA
  8590. /* Clear and dispose of the EC point.
  8591. *
  8592. * Cannot use point after this call.
  8593. *
  8594. * @param [in, out] point EC point to free.
  8595. */
  8596. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8597. {
  8598. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8599. if (point != NULL) {
  8600. if (point->internal != NULL) {
  8601. /* Force internal point to be zeros. */
  8602. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8603. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8604. #else
  8605. ecc_point* p = (ecc_point*)point->internal;
  8606. mp_forcezero(p->x);
  8607. mp_forcezero(p->y);
  8608. mp_forcezero(p->z);
  8609. #endif
  8610. wc_ecc_del_point((ecc_point*)point->internal);
  8611. point->internal = NULL;
  8612. }
  8613. /* Clear the ordinates before freeing. */
  8614. wolfSSL_BN_clear_free(point->X);
  8615. wolfSSL_BN_clear_free(point->Y);
  8616. wolfSSL_BN_clear_free(point->Z);
  8617. /* Clear fields. */
  8618. point->X = NULL;
  8619. point->Y = NULL;
  8620. point->Z = NULL;
  8621. point->inSet = 0;
  8622. point->exSet = 0;
  8623. /* Dispose of EC point. */
  8624. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8625. }
  8626. }
  8627. /* Print out the internals of EC point in debug and when logging callback set.
  8628. *
  8629. * Not an OpenSSL API.
  8630. *
  8631. * TODO: Use WOLFSSL_MSG_EX()?
  8632. *
  8633. * @param [in] msg Message to prepend.
  8634. * @param [in] point EC point to print.
  8635. */
  8636. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8637. {
  8638. #if defined(DEBUG_WOLFSSL)
  8639. char *num;
  8640. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8641. /* Only print when debugging on. */
  8642. if (WOLFSSL_IS_DEBUG_ON()) {
  8643. if (point == NULL) {
  8644. /* No point passed in so just put out "NULL". */
  8645. WOLFSSL_MSG_EX("%s = NULL\n", msg);
  8646. }
  8647. else {
  8648. /* Put out message and status of internal/external data set. */
  8649. WOLFSSL_MSG_EX("%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8650. point->exSet);
  8651. /* Get x-ordinate as a hex string and print. */
  8652. num = wolfSSL_BN_bn2hex(point->X);
  8653. WOLFSSL_MSG_EX("\tX = %s\n", num);
  8654. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8655. /* Get x-ordinate as a hex string and print. */
  8656. num = wolfSSL_BN_bn2hex(point->Y);
  8657. WOLFSSL_MSG_EX("\tY = %s\n", num);
  8658. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8659. /* Get z-ordinate as a hex string and print. */
  8660. num = wolfSSL_BN_bn2hex(point->Z);
  8661. WOLFSSL_MSG_EX("\tZ = %s\n", num);
  8662. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8663. }
  8664. }
  8665. #else
  8666. (void)msg;
  8667. (void)point;
  8668. #endif
  8669. }
  8670. #ifndef HAVE_SELFTEST
  8671. /* Convert EC point to hex string that as either uncompressed or compressed.
  8672. *
  8673. * ECC point compression types were not included in selftest ecc.h
  8674. *
  8675. * @param [in] group EC group for point.
  8676. * @param [in] point EC point to encode.
  8677. * @param [in] form Format of encoding. Valid values:
  8678. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8679. * @param [in] ctx Context to use for BN operations. Unused.
  8680. * @return Allocated hex string on success.
  8681. * @return NULL on error.
  8682. */
  8683. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8684. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8685. {
  8686. static const char* hexDigit = "0123456789ABCDEF";
  8687. char* hex = NULL;
  8688. int i;
  8689. int sz = 0;
  8690. int len = 0;
  8691. int err = 0;
  8692. /* No BN operations performed. */
  8693. (void)ctx;
  8694. /* Validate parameters. */
  8695. if ((group == NULL) || (point == NULL)) {
  8696. err = 1;
  8697. }
  8698. /* Get curve id expects a positive index. */
  8699. if ((!err) && (group->curve_idx < 0)) {
  8700. err = 1;
  8701. }
  8702. if (!err) {
  8703. /* Get curve id to look up ordinate size. */
  8704. int id = wc_ecc_get_curve_id(group->curve_idx);
  8705. /* Get size of ordinate. */
  8706. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8707. err = 1;
  8708. }
  8709. }
  8710. if (!err) {
  8711. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8712. len = sz + 1;
  8713. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8714. /* Include y ordinate when uncompressed. */
  8715. len += sz;
  8716. }
  8717. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8718. */
  8719. hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC);
  8720. if (hex == NULL) {
  8721. err = 1;
  8722. }
  8723. }
  8724. if (!err) {
  8725. /* Make bytes all zeros to allow for ordinate values less than max size.
  8726. */
  8727. XMEMSET(hex, 0, (size_t)(2 * len + 1));
  8728. /* Calculate offset as leading zeros not encoded. */
  8729. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8730. /* Put in x-ordinate after format byte. */
  8731. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8732. 0) {
  8733. err = 1;
  8734. }
  8735. }
  8736. if (!err) {
  8737. if (form == POINT_CONVERSION_COMPRESSED) {
  8738. /* Compressed format byte value dependent on whether y-ordinate is
  8739. * odd.
  8740. */
  8741. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8742. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8743. /* No y-ordinate. */
  8744. }
  8745. else {
  8746. /* Put in uncompressed format byte. */
  8747. hex[0] = ECC_POINT_UNCOMP;
  8748. /* Calculate offset as leading zeros not encoded. */
  8749. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8750. /* Put in y-ordinate after x-ordinate. */
  8751. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8752. (byte*)(hex + i)) < 0) {
  8753. err = 1;
  8754. }
  8755. }
  8756. }
  8757. if (!err) {
  8758. /* Convert binary encoding to hex string. */
  8759. /* Start at end so as not to overwrite. */
  8760. for (i = len-1; i >= 0; i--) {
  8761. /* Get byte value and store has hex string. */
  8762. byte b = (byte)hex[i];
  8763. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8764. hex[i * 2 ] = hexDigit[b >> 4];
  8765. }
  8766. /* Memset put trailing zero or '\0' on end of string. */
  8767. }
  8768. if (err && (hex != NULL)) {
  8769. /* Dispose of allocated data not being returned. */
  8770. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8771. hex = NULL;
  8772. }
  8773. /* Return hex string encoding. */
  8774. return hex;
  8775. }
  8776. #endif /* HAVE_SELFTEST */
  8777. /* Encode the EC point as an uncompressed point in DER.
  8778. *
  8779. * Return code compliant with OpenSSL.
  8780. * Not OpenSSL API.
  8781. *
  8782. * @param [in] group EC group point belongs to.
  8783. * @param [in] point EC point to encode.
  8784. * @param [out] out Buffer to encode into. May be NULL.
  8785. * @param [in, out] len On in, length of buffer in bytes.
  8786. * On out, length of encoding in bytes.
  8787. * @return 1 on success.
  8788. * @return 0 on error.
  8789. */
  8790. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8791. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  8792. {
  8793. int res = 1;
  8794. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8795. /* Validate parameters. */
  8796. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  8797. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8798. res = 0;
  8799. }
  8800. /* Ensure points internals are set up. */
  8801. if ((res == 1) && (ec_point_setup(point) != 1)) {
  8802. res = 0;
  8803. }
  8804. /* Dump the point if encoding. */
  8805. if ((res == 1) && (out != NULL)) {
  8806. wolfSSL_EC_POINT_dump("i2d p", point);
  8807. }
  8808. if (res == 1) {
  8809. /* DER encode point in uncompressed format. */
  8810. int ret = wc_ecc_export_point_der(group->curve_idx,
  8811. (ecc_point*)point->internal, out, len);
  8812. /* Check return. When out is NULL, return will be length only error. */
  8813. if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) {
  8814. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8815. res = 0;
  8816. }
  8817. }
  8818. return res;
  8819. }
  8820. /* Decode the uncompressed point in DER into EC point.
  8821. *
  8822. * Return code compliant with OpenSSL.
  8823. * Not OpenSSL API.
  8824. *
  8825. * @param [in] in Buffer containing DER encoded point.
  8826. * @param [in] len Length of data in bytes.
  8827. * @param [in] group EC group associated with point.
  8828. * @param [in, out] point EC point to set data into.
  8829. * @return 1 on success.
  8830. * @return 0 on error.
  8831. */
  8832. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  8833. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  8834. {
  8835. int ret = 1;
  8836. WOLFSSL_BIGNUM* x = NULL;
  8837. WOLFSSL_BIGNUM* y = NULL;
  8838. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8839. /* Validate parameters. */
  8840. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  8841. (point->internal == NULL)) {
  8842. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8843. ret = 0;
  8844. }
  8845. if (ret == 1) {
  8846. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8847. /* Import point into internal EC point. */
  8848. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8849. (ecc_point*)point->internal, 0) != MP_OKAY) {
  8850. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8851. ret = 0;
  8852. }
  8853. #else
  8854. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8855. if (in[0] == 0x04) {
  8856. /* Import point into internal EC point. */
  8857. if (wc_ecc_import_point_der((unsigned char *)in, len,
  8858. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  8859. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8860. ret = 0;
  8861. }
  8862. }
  8863. else {
  8864. WOLFSSL_MSG("Only uncompressed points supported with "
  8865. "HAVE_SELFTEST");
  8866. ret = 0;
  8867. }
  8868. #endif
  8869. }
  8870. if (ret == 1)
  8871. point->inSet = 1;
  8872. /* Set new external point. */
  8873. if (ret == 1 && ec_point_external_set(point) != 1) {
  8874. WOLFSSL_MSG("ec_point_external_set failed");
  8875. ret = 0;
  8876. }
  8877. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  8878. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  8879. x = wolfSSL_BN_new();
  8880. y = wolfSSL_BN_new();
  8881. if (x == NULL || y == NULL)
  8882. ret = 0;
  8883. if (ret == 1 && wolfSSL_EC_POINT_get_affine_coordinates_GFp(group,
  8884. point, x, y, NULL) != 1) {
  8885. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp failed");
  8886. ret = 0;
  8887. }
  8888. /* wolfSSL_EC_POINT_set_affine_coordinates_GFp check that the point is
  8889. * on the curve. */
  8890. if (ret == 1 && wolfSSL_EC_POINT_set_affine_coordinates_GFp(group,
  8891. point, x, y, NULL) != 1) {
  8892. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp failed");
  8893. ret = 0;
  8894. }
  8895. #else
  8896. WOLFSSL_MSG("Importing non-affine point. This may cause issues in math "
  8897. "operations later on.");
  8898. #endif
  8899. }
  8900. if (ret == 1) {
  8901. /* Dump new point. */
  8902. wolfSSL_EC_POINT_dump("d2i p", point);
  8903. }
  8904. wolfSSL_BN_free(x);
  8905. wolfSSL_BN_free(y);
  8906. return ret;
  8907. }
  8908. /* Encode point as octet string.
  8909. *
  8910. * HYBRID not supported.
  8911. *
  8912. * @param [in] group EC group that point belongs to.
  8913. * @param [in] point EC point to encode.
  8914. * @param [in] form Format of encoding. Valid values:
  8915. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  8916. * @param [out] buf Buffer to write encoding into.
  8917. * @param [in] len Length of buffer.
  8918. * @param [in] ctx Context to use for BN operations. Unused.
  8919. * @return Length of encoded data on success.
  8920. * @return 0 on error.
  8921. */
  8922. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  8923. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  8924. WOLFSSL_BN_CTX *ctx)
  8925. {
  8926. int err = 0;
  8927. word32 enc_len = (word32)len;
  8928. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8929. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  8930. #endif /* !HAVE_SELFTEST */
  8931. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  8932. /* No BN operations performed. */
  8933. (void)ctx;
  8934. /* Validate parameters. */
  8935. if ((group == NULL) || (point == NULL)) {
  8936. err = 1;
  8937. }
  8938. /* Ensure points internals are set up. */
  8939. if ((!err) && (ec_point_setup(point) != 1)) {
  8940. err = 1;
  8941. }
  8942. /* Special case when point is infinity. */
  8943. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  8944. /* Encoding is a single octet: 0x00. */
  8945. enc_len = 1;
  8946. if (buf != NULL) {
  8947. /* Check whether buffer has space. */
  8948. if (len < 1) {
  8949. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  8950. err = 1;
  8951. }
  8952. else {
  8953. /* Put in encoding of infinity. */
  8954. buf[0] = 0x00;
  8955. }
  8956. }
  8957. }
  8958. /* Not infinity. */
  8959. else if (!err) {
  8960. /* Validate format. */
  8961. if (form != POINT_CONVERSION_UNCOMPRESSED
  8962. #ifndef HAVE_SELFTEST
  8963. && form != POINT_CONVERSION_COMPRESSED
  8964. #endif /* !HAVE_SELFTEST */
  8965. ) {
  8966. WOLFSSL_MSG("Unsupported point form");
  8967. err = 1;
  8968. }
  8969. if (!err) {
  8970. int ret;
  8971. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8972. /* Encode as compressed or uncompressed. */
  8973. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  8974. (ecc_point*)point->internal, buf, &enc_len, compressed);
  8975. #else
  8976. /* Encode uncompressed point in DER format. */
  8977. ret = wc_ecc_export_point_der(group->curve_idx,
  8978. (ecc_point*)point->internal, buf, &enc_len);
  8979. #endif /* !HAVE_SELFTEST */
  8980. /* Check return. When buf is NULL, return will be length only
  8981. * error.
  8982. */
  8983. if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) {
  8984. err = 1;
  8985. }
  8986. }
  8987. }
  8988. #if defined(DEBUG_WOLFSSL)
  8989. if (!err) {
  8990. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_point2oct point", point);
  8991. WOLFSSL_MSG("\twolfSSL_EC_POINT_point2oct output:");
  8992. WOLFSSL_BUFFER(buf, enc_len);
  8993. }
  8994. #endif
  8995. /* On error, return encoding length of 0. */
  8996. if (err) {
  8997. enc_len = 0;
  8998. }
  8999. return (size_t)enc_len;
  9000. }
  9001. /* Convert octet string to EC point.
  9002. *
  9003. * @param [in] group EC group.
  9004. * @param [in, out] point EC point to set data into.
  9005. * @param [in] buf Buffer holding octet string.
  9006. * @param [in] len Length of data in buffer in bytes.
  9007. * @param [in] ctx Context to use for BN operations. Unused.
  9008. */
  9009. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  9010. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  9011. WOLFSSL_BN_CTX *ctx)
  9012. {
  9013. int ret;
  9014. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9015. /* No BN operations performed. */
  9016. (void)ctx;
  9017. /* Validate parameters. */
  9018. if ((group == NULL) || (point == NULL)) {
  9019. ret = 0;
  9020. }
  9021. else {
  9022. /* Decode DER encoding into EC point. */
  9023. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  9024. point);
  9025. }
  9026. return ret;
  9027. }
  9028. /* Convert an EC point to a single BN.
  9029. *
  9030. * @param [in] group EC group.
  9031. * @param [in] point EC point.
  9032. * @param [in] form Format of encoding. Valid values:
  9033. * POINT_CONVERSION_UNCOMPRESSED,
  9034. * POINT_CONVERSION_COMPRESSED.
  9035. * @param [in, out] bn BN to hold point value.
  9036. * When NULL a new BN is allocated otherwise this is
  9037. * returned on success.
  9038. * @param [in] ctx Context to use for BN operations. Unused.
  9039. * @return BN object with point as a value on success.
  9040. * @return NULL on error.
  9041. */
  9042. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  9043. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  9044. WOLFSSL_BN_CTX* ctx)
  9045. {
  9046. int err = 0;
  9047. size_t len = 0;
  9048. byte *buf = NULL;
  9049. WOLFSSL_BIGNUM *ret = NULL;
  9050. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9051. /* Validate parameters. */
  9052. if ((group == NULL) || (point == NULL)) {
  9053. err = 1;
  9054. }
  9055. /* Calculate length of octet encoding. */
  9056. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  9057. 0, ctx)) == 0)) {
  9058. err = 1;
  9059. }
  9060. /* Allocate buffer to hold octet encoding. */
  9061. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  9062. NULL)) {
  9063. WOLFSSL_MSG("malloc failed");
  9064. err = 1;
  9065. }
  9066. /* Encode EC point as an octet string. */
  9067. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  9068. ctx) != len)) {
  9069. err = 1;
  9070. }
  9071. /* Load BN with octet string data. */
  9072. if (!err) {
  9073. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  9074. }
  9075. /* Dispose of any allocated data. */
  9076. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9077. return ret;
  9078. }
  9079. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9080. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9081. /* Check if EC point is on the the curve defined by the EC group.
  9082. *
  9083. * @param [in] group EC group defining curve.
  9084. * @param [in] point EC point to check.
  9085. * @param [in] ctx Context to use for BN operations. Unused.
  9086. * @return 1 when point is on curve.
  9087. * @return 0 when point is not on curve or error.
  9088. */
  9089. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9090. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9091. {
  9092. int err = 0;
  9093. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9094. /* No BN operations performed. */
  9095. (void)ctx;
  9096. /* Validate parameters. */
  9097. if ((group == NULL) || (point == NULL)) {
  9098. WOLFSSL_MSG("Invalid arguments");
  9099. err = 1;
  9100. }
  9101. /* Ensure internal EC point set. */
  9102. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9103. (WOLFSSL_EC_POINT*)point) != 1) {
  9104. WOLFSSL_MSG("ec_point_internal_set error");
  9105. err = 1;
  9106. }
  9107. /* Check point is on curve from group. */
  9108. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9109. group->curve_idx) != MP_OKAY)) {
  9110. err = 1;
  9111. }
  9112. /* Return boolean of on curve. No error means on curve. */
  9113. return !err;
  9114. }
  9115. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9116. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9117. /* Convert Jacobian ordinates to affine.
  9118. *
  9119. * @param [in] group EC group.
  9120. * @param [in] point EC point to get coordinates from.
  9121. * @return 1 on success.
  9122. * @return 0 on error.
  9123. */
  9124. int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9125. WOLFSSL_EC_POINT *point)
  9126. {
  9127. int err = 0;
  9128. mp_digit mp = 0;
  9129. #ifdef WOLFSSL_SMALL_STACK
  9130. mp_int* modulus;
  9131. #else
  9132. mp_int modulus[1];
  9133. #endif
  9134. #ifdef WOLFSSL_SMALL_STACK
  9135. /* Allocate memory for curve's prime modulus. */
  9136. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9137. if (modulus == NULL) {
  9138. err = 1;
  9139. }
  9140. #endif
  9141. /* Initialize the MP integer. */
  9142. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9143. WOLFSSL_MSG("mp_init failed");
  9144. err = 1;
  9145. }
  9146. if (!err) {
  9147. /* Get the modulus from the hex string in the EC curve set. */
  9148. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9149. MP_RADIX_HEX) != MP_OKAY) {
  9150. WOLFSSL_MSG("mp_read_radix failed");
  9151. err = 1;
  9152. }
  9153. /* Get Montgomery multiplier for the modulus as ordinates in
  9154. * Montgomery form.
  9155. */
  9156. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9157. WOLFSSL_MSG("mp_montgomery_setup failed");
  9158. err = 1;
  9159. }
  9160. /* Map internal EC point from Jacobian to affine. */
  9161. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9162. MP_OKAY)) {
  9163. WOLFSSL_MSG("ecc_map failed");
  9164. err = 1;
  9165. }
  9166. /* Set new ordinates into external EC point. */
  9167. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9168. WOLFSSL_MSG("ec_point_external_set failed");
  9169. err = 1;
  9170. }
  9171. point->exSet = !err;
  9172. mp_clear(modulus);
  9173. }
  9174. #ifdef WOLFSSL_SMALL_STACK
  9175. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9176. #endif
  9177. return err;
  9178. }
  9179. /* Get the affine coordinates of the EC point on a Prime curve.
  9180. *
  9181. * When z-ordinate is not one then coordinates are Jacobian and need to be
  9182. * converted to affine before storing in BNs.
  9183. *
  9184. * Return code compliant with OpenSSL.
  9185. *
  9186. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9187. *
  9188. * @param [in] group EC group.
  9189. * @param [in] point EC point to get coordinates from.
  9190. * @param [in, out] x BN to hold x-ordinate.
  9191. * @param [in, out] y BN to hold y-ordinate.
  9192. * @param [in] ctx Context to use for BN operations. Unused.
  9193. * @return 1 on success.
  9194. * @return 0 on error.
  9195. */
  9196. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9197. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9198. WOLFSSL_BN_CTX* ctx)
  9199. {
  9200. int ret = 1;
  9201. /* BN operations don't need context. */
  9202. (void)ctx;
  9203. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9204. /* Validate parameters. */
  9205. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9206. (x == NULL) || (y == NULL)) {
  9207. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9208. ret = 0;
  9209. }
  9210. /* Don't return point at infinity. */
  9211. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9212. ret = 0;
  9213. }
  9214. /* Ensure internal EC point has values of external EC point. */
  9215. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9216. ret = 0;
  9217. }
  9218. /* Check whether ordinates are in Jacobian form. */
  9219. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9220. /* Convert from Jacobian to affine. */
  9221. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9222. ret = 0;
  9223. }
  9224. }
  9225. /* Copy the externally set x and y ordinates. */
  9226. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9227. ret = 0;
  9228. }
  9229. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9230. ret = 0;
  9231. }
  9232. return ret;
  9233. }
  9234. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9235. /* Sets the affine coordinates that belong on a prime curve.
  9236. *
  9237. * @param [in] group EC group.
  9238. * @param [in, out] point EC point to set coordinates into.
  9239. * @param [in] x BN holding x-ordinate.
  9240. * @param [in] y BN holding y-ordinate.
  9241. * @param [in] ctx Context to use for BN operations. Unused.
  9242. * @return 1 on success.
  9243. * @return 0 on error.
  9244. */
  9245. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9246. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9247. WOLFSSL_BN_CTX* ctx)
  9248. {
  9249. int ret = 1;
  9250. /* BN operations don't need context. */
  9251. (void)ctx;
  9252. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9253. /* Validate parameters. */
  9254. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9255. (x == NULL) || (y == NULL)) {
  9256. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9257. ret = 0;
  9258. }
  9259. /* Ensure we have a object for x-ordinate. */
  9260. if ((ret == 1) && (point->X == NULL) &&
  9261. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9262. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9263. ret = 0;
  9264. }
  9265. /* Ensure we have a object for y-ordinate. */
  9266. if ((ret == 1) && (point->Y == NULL) &&
  9267. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9268. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9269. ret = 0;
  9270. }
  9271. /* Ensure we have a object for z-ordinate. */
  9272. if ((ret == 1) && (point->Z == NULL) &&
  9273. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9274. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9275. ret = 0;
  9276. }
  9277. /* Copy the x-ordinate. */
  9278. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9279. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9280. ret = 0;
  9281. }
  9282. /* Copy the y-ordinate. */
  9283. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9284. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9285. ret = 0;
  9286. }
  9287. /* z-ordinate is one for affine coordinates. */
  9288. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9289. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9290. ret = 0;
  9291. }
  9292. /* Copy the new point data to internal object. */
  9293. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9294. WOLFSSL_MSG("ec_point_internal_set failed");
  9295. ret = 0;
  9296. }
  9297. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9298. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9299. /* Check that the point is valid. */
  9300. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9301. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9302. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9303. ret = 0;
  9304. }
  9305. #endif
  9306. return ret;
  9307. }
  9308. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9309. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9310. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9311. /* Add two points on the same together.
  9312. *
  9313. * @param [in] curveIdx Index of curve in ecc_set.
  9314. * @param [out] r Result point.
  9315. * @param [in] p1 First point to add.
  9316. * @param [in] p2 Second point to add.
  9317. * @return 1 on success.
  9318. * @return 0 on error.
  9319. */
  9320. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9321. ecc_point* p2)
  9322. {
  9323. int ret = 1;
  9324. #ifdef WOLFSSL_SMALL_STACK
  9325. mp_int* a = NULL;
  9326. mp_int* prime = NULL;
  9327. mp_int* mu = NULL;
  9328. #else
  9329. mp_int a[1];
  9330. mp_int prime[1];
  9331. mp_int mu[1];
  9332. #endif
  9333. mp_digit mp = 0;
  9334. ecc_point* montP1 = NULL;
  9335. ecc_point* montP2 = NULL;
  9336. #ifdef WOLFSSL_SMALL_STACK
  9337. if (ret == 1) {
  9338. /* Allocate memory for curve parameter: a. */
  9339. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9340. if (a == NULL) {
  9341. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9342. ret = 0;
  9343. }
  9344. }
  9345. if (ret == 1) {
  9346. /* Allocate memory for curve parameter: prime. */
  9347. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9348. if (prime == NULL) {
  9349. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9350. ret = 0;
  9351. }
  9352. }
  9353. if (ret == 1) {
  9354. /* Allocate memory for mu (Montgomery normalizer). */
  9355. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9356. if (mu == NULL) {
  9357. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9358. ret = 0;
  9359. }
  9360. }
  9361. if (ret == 1) {
  9362. /* Zero out all MP int data in case initialization fails. */
  9363. XMEMSET(a, 0, sizeof(mp_int));
  9364. XMEMSET(prime, 0, sizeof(mp_int));
  9365. XMEMSET(mu, 0, sizeof(mp_int));
  9366. }
  9367. #endif
  9368. /* Initialize the MP ints. */
  9369. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9370. MP_OKAY)) {
  9371. WOLFSSL_MSG("mp_init_multi error");
  9372. ret = 0;
  9373. }
  9374. /* Read the curve parameter: a. */
  9375. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9376. MP_OKAY)) {
  9377. WOLFSSL_MSG("mp_read_radix a error");
  9378. ret = 0;
  9379. }
  9380. /* Read the curve parameter: prime. */
  9381. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9382. MP_RADIX_HEX) != MP_OKAY)) {
  9383. WOLFSSL_MSG("mp_read_radix prime error");
  9384. ret = 0;
  9385. }
  9386. /* Calculate the Montgomery product. */
  9387. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9388. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9389. ret = 0;
  9390. }
  9391. /* TODO: use the heap filed of one of the points? */
  9392. /* Allocate new points to hold the Montgomery form values. */
  9393. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9394. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9395. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9396. ret = 0;
  9397. }
  9398. /* Calculate the Montgomery normalizer. */
  9399. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9400. MP_OKAY)) {
  9401. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9402. ret = 0;
  9403. }
  9404. /* Convert to Montgomery form. */
  9405. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9406. /* Copy the points if the normalizer is 1. */
  9407. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9408. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9409. WOLFSSL_MSG("wc_ecc_copy_point error");
  9410. ret = 0;
  9411. }
  9412. }
  9413. else if (ret == 1) {
  9414. /* Multiply each ordinate by the Montgomery normalizer. */
  9415. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9416. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9417. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9418. WOLFSSL_MSG("mp_mulmod error");
  9419. ret = 0;
  9420. }
  9421. /* Multiply each ordinate by the Montgomery normalizer. */
  9422. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9423. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9424. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9425. WOLFSSL_MSG("mp_mulmod error");
  9426. ret = 0;
  9427. }
  9428. }
  9429. /* Perform point addition with internal EC point objects - Jacobian form
  9430. * result.
  9431. */
  9432. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9433. mp) != MP_OKAY)) {
  9434. WOLFSSL_MSG("ecc_projective_add_point error");
  9435. ret = 0;
  9436. }
  9437. /* Map point back to affine coordinates. Converts from Montogomery form. */
  9438. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9439. WOLFSSL_MSG("ecc_map error");
  9440. ret = 0;
  9441. }
  9442. /* Dispose of allocated memory. */
  9443. mp_clear(a);
  9444. mp_clear(prime);
  9445. mp_clear(mu);
  9446. wc_ecc_del_point_h(montP1, NULL);
  9447. wc_ecc_del_point_h(montP2, NULL);
  9448. #ifdef WOLFSSL_SMALL_STACK
  9449. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9450. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9451. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9452. #endif
  9453. return ret;
  9454. }
  9455. /* Add two points on the same curve together.
  9456. *
  9457. * @param [in] group EC group.
  9458. * @param [out] r EC point that is result of point addition.
  9459. * @param [in] p1 First EC point to add.
  9460. * @param [in] p2 Second EC point to add.
  9461. * @param [in] ctx Context to use for BN operations. Unused.
  9462. * @return 1 on success.
  9463. * @return 0 on error.
  9464. */
  9465. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9466. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9467. {
  9468. int ret = 1;
  9469. /* No BN operations performed. */
  9470. (void)ctx;
  9471. /* Validate parameters. */
  9472. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9473. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9474. ret = 0;
  9475. }
  9476. /* Ensure the internal objects of the EC points are setup. */
  9477. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9478. (ec_point_setup(p2) != 1))) {
  9479. WOLFSSL_MSG("ec_point_setup error");
  9480. ret = 0;
  9481. }
  9482. #ifdef DEBUG_WOLFSSL
  9483. if (ret == 1) {
  9484. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9485. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9486. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9487. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p1", p1);
  9488. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p2", p2);
  9489. if (curve != NULL)
  9490. WOLFSSL_MSG_EX("curve name: %s", curve);
  9491. if (nistName != NULL)
  9492. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9493. }
  9494. #endif
  9495. if (ret == 1) {
  9496. /* Add points using wolfCrypt objects. */
  9497. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9498. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9499. }
  9500. /* Copy internal EC point values out to external EC point. */
  9501. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9502. WOLFSSL_MSG("ec_point_external_set error");
  9503. ret = 0;
  9504. }
  9505. #ifdef DEBUG_WOLFSSL
  9506. if (ret == 1) {
  9507. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add result", r);
  9508. }
  9509. #endif
  9510. return ret;
  9511. }
  9512. /* Sum the scalar multiplications of the base point and n, and q and m.
  9513. *
  9514. * r = base point * n + q * m
  9515. *
  9516. * @param [out] r EC point that is result of operation.
  9517. * @param [in] b Base point of curve.
  9518. * @param [in] n Scalar to multiply by base point.
  9519. * @param [in] q EC point to be scalar multiplied.
  9520. * @param [in] m Scalar to multiply q by.
  9521. * @param [in] a Parameter A of curve.
  9522. * @param [in] prime Prime (modulus) of curve.
  9523. * @return 1 on success.
  9524. * @return 0 on error.
  9525. */
  9526. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9527. mp_int* m, mp_int* a, mp_int* prime)
  9528. {
  9529. int ret = 1;
  9530. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9531. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9532. WOLFSSL_MSG("ecc_mul2add error");
  9533. ret = 0;
  9534. }
  9535. #else
  9536. ecc_point* tmp = NULL;
  9537. mp_digit mp = 0;
  9538. /* Calculate Montgomery product. */
  9539. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9540. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9541. ret = 0;
  9542. }
  9543. /* Create temporary point to hold: q * m */
  9544. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9545. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9546. ret = 0;
  9547. }
  9548. /* r = base point * n */
  9549. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9550. MP_OKAY)) {
  9551. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9552. ret = 0;
  9553. }
  9554. /* tmp = q * m */
  9555. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9556. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9557. ret = 0;
  9558. }
  9559. /* r = r + tmp */
  9560. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9561. MP_OKAY)) {
  9562. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9563. ret = 0;
  9564. }
  9565. /* Map point back to affine coordinates. Converts from Montogomery
  9566. * form. */
  9567. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9568. WOLFSSL_MSG("ecc_map nqm error");
  9569. ret = 0;
  9570. }
  9571. /* Dispose of allocated temporary point. */
  9572. wc_ecc_del_point(tmp);
  9573. #endif
  9574. return ret;
  9575. }
  9576. /* Sum the scalar multiplications of the base point and n, and q and m.
  9577. *
  9578. * r = base point * n + q * m
  9579. *
  9580. * @param [in] curveIdx Index of curve in ecc_set.
  9581. * @param [out] r EC point that is result of operation.
  9582. * @param [in] n Scalar to multiply by base point. May be NULL.
  9583. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9584. * @param [in] m Scalar to multiply q by. May be NULL.
  9585. * @return 1 on success.
  9586. * @return 0 on error.
  9587. */
  9588. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9589. ecc_point* q, mp_int* m)
  9590. {
  9591. int ret = 1;
  9592. #ifdef WOLFSSL_SMALL_STACK
  9593. mp_int* a = NULL;
  9594. mp_int* prime = NULL;
  9595. #else
  9596. mp_int a[1], prime[1];
  9597. #endif
  9598. #ifdef WOLFSSL_SMALL_STACK
  9599. /* Allocate MP integer for curve parameter: a. */
  9600. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9601. if (a == NULL) {
  9602. ret = 0;
  9603. }
  9604. if (ret == 1) {
  9605. /* Allocate MP integer for curve parameter: prime. */
  9606. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9607. if (prime == NULL) {
  9608. ret = 0;
  9609. }
  9610. }
  9611. #endif
  9612. /* Initialize the MP ints. */
  9613. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9614. MP_OKAY)) {
  9615. WOLFSSL_MSG("mp_init_multi error");
  9616. ret = 0;
  9617. }
  9618. /* Read the curve parameter: prime. */
  9619. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9620. MP_RADIX_HEX) != MP_OKAY)) {
  9621. WOLFSSL_MSG("mp_read_radix prime error");
  9622. ret = 0;
  9623. }
  9624. /* Read the curve parameter: a. */
  9625. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9626. MP_RADIX_HEX) != MP_OKAY)) {
  9627. WOLFSSL_MSG("mp_read_radix a error");
  9628. ret = 0;
  9629. }
  9630. if ((ret == 1) && (n != NULL)) {
  9631. /* Get generator - base point. */
  9632. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9633. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9634. WOLFSSL_MSG("wc_ecc_get_generator error");
  9635. ret = 0;
  9636. }
  9637. #else
  9638. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9639. /* Read generator (base point) x-ordinate. */
  9640. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9641. MP_RADIX_HEX) != MP_OKAY)) {
  9642. WOLFSSL_MSG("mp_read_radix Gx error");
  9643. ret = 0;
  9644. }
  9645. /* Read generator (base point) y-ordinate. */
  9646. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9647. MP_RADIX_HEX) != MP_OKAY)) {
  9648. WOLFSSL_MSG("mp_read_radix Gy error");
  9649. ret = 0;
  9650. }
  9651. /* z-ordinate is one as point is affine. */
  9652. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9653. WOLFSSL_MSG("mp_set Gz error");
  9654. ret = 0;
  9655. }
  9656. #endif /* NOPT_FIPS_VERSION == 2 */
  9657. }
  9658. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9659. /* r = base point * n + q * m */
  9660. ret = ec_mul2add(r, r, n, q, m, a, prime);
  9661. }
  9662. /* Not all values present, see if we are only doing base point * n. */
  9663. else if ((ret == 1) && (n != NULL)) {
  9664. /* r = base point * n */
  9665. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9666. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9667. ret = 0;
  9668. }
  9669. }
  9670. /* Not all values present, see if we are only doing q * m. */
  9671. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9672. /* r = q * m */
  9673. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9674. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9675. ret = 0;
  9676. }
  9677. }
  9678. /* No values to use. */
  9679. else if (ret == 1) {
  9680. /* Set result to infinity as no values passed in. */
  9681. mp_zero(r->x);
  9682. mp_zero(r->y);
  9683. mp_zero(r->z);
  9684. }
  9685. mp_clear(a);
  9686. mp_clear(prime);
  9687. #ifdef WOLFSSL_SMALL_STACK
  9688. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9689. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9690. #endif
  9691. return ret;
  9692. }
  9693. /* Sum the scalar multiplications of the base point and n, and q and m.
  9694. *
  9695. * r = base point * n + q * m
  9696. *
  9697. * Return code compliant with OpenSSL.
  9698. *
  9699. * @param [in] group EC group.
  9700. * @param [out] r EC point that is result of operation.
  9701. * @param [in] n Scalar to multiply by base point. May be NULL.
  9702. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9703. * @param [in] m Scalar to multiply q by. May be NULL.
  9704. * @param [in] ctx Context to use for BN operations. Unused.
  9705. * @return 1 on success.
  9706. * @return 0 on error.
  9707. */
  9708. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9709. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  9710. WOLFSSL_BN_CTX *ctx)
  9711. {
  9712. int ret = 1;
  9713. /* No BN operations performed. */
  9714. (void)ctx;
  9715. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9716. /* Validate parameters. */
  9717. if ((group == NULL) || (r == NULL)) {
  9718. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9719. ret = 0;
  9720. }
  9721. /* Ensure the internal representation of the EC point q is setup. */
  9722. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  9723. WOLFSSL_MSG("ec_point_setup error");
  9724. ret = 0;
  9725. }
  9726. #ifdef DEBUG_WOLFSSL
  9727. if (ret == 1) {
  9728. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9729. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9730. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9731. char* num;
  9732. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul input q", q);
  9733. num = wolfSSL_BN_bn2hex(n);
  9734. WOLFSSL_MSG_EX("\tn = %s", num);
  9735. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9736. num = wolfSSL_BN_bn2hex(m);
  9737. WOLFSSL_MSG_EX("\tm = %s", num);
  9738. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9739. if (curve != NULL)
  9740. WOLFSSL_MSG_EX("curve name: %s", curve);
  9741. if (nistName != NULL)
  9742. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9743. }
  9744. #endif
  9745. if (ret == 1) {
  9746. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  9747. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  9748. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  9749. /* Perform multiplication with wolfCrypt objects. */
  9750. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  9751. ni, qi, mi);
  9752. }
  9753. /* Only on success is the internal point guaranteed to be set. */
  9754. if (r != NULL) {
  9755. r->inSet = (ret == 1);
  9756. }
  9757. /* Copy internal EC point values out to external EC point. */
  9758. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9759. WOLFSSL_MSG("ec_point_external_set error");
  9760. ret = 0;
  9761. }
  9762. #ifdef DEBUG_WOLFSSL
  9763. if (ret == 1) {
  9764. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul result", r);
  9765. }
  9766. #endif
  9767. return ret;
  9768. }
  9769. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9770. * !WOLFSSL_SP_MATH */
  9771. /* Invert the point on the curve.
  9772. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9773. *
  9774. * @param [in] curveIdx Index of curve in ecc_set.
  9775. * @param [in, out] point EC point to invert.
  9776. * @return 1 on success.
  9777. * @return 0 on error.
  9778. */
  9779. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  9780. {
  9781. int ret = 1;
  9782. #ifdef WOLFSSL_SMALL_STACK
  9783. mp_int* prime = NULL;
  9784. #else
  9785. mp_int prime[1];
  9786. #endif
  9787. #ifdef WOLFSSL_SMALL_STACK
  9788. /* Allocate memory for an MP int to hold the prime of the curve. */
  9789. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9790. if (prime == NULL) {
  9791. ret = 0;
  9792. }
  9793. #endif
  9794. /* Initialize MP int. */
  9795. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  9796. WOLFSSL_MSG("mp_init_multi error");
  9797. ret = 0;
  9798. }
  9799. /* Read the curve parameter: prime. */
  9800. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9801. MP_RADIX_HEX) != MP_OKAY)) {
  9802. WOLFSSL_MSG("mp_read_radix prime error");
  9803. ret = 0;
  9804. }
  9805. /* y = (prime - y) mod prime. */
  9806. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  9807. point->y) != MP_OKAY)) {
  9808. WOLFSSL_MSG("mp_sub error");
  9809. ret = 0;
  9810. }
  9811. /* Dispose of memory associated with MP. */
  9812. mp_free(prime);
  9813. #ifdef WOLFSSL_SMALL_STACK
  9814. /* Dispose of dynamically allocated temporaries. */
  9815. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9816. #endif
  9817. return ret;
  9818. }
  9819. /* Invert the point on the curve.
  9820. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9821. *
  9822. * @param [in] group EC group.
  9823. * @param [in, out] point EC point to invert.
  9824. * @param [in] ctx Context to use for BN operations. Unused.
  9825. * @return 1 on success.
  9826. * @return 0 on error.
  9827. */
  9828. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  9829. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9830. {
  9831. int ret = 1;
  9832. /* No BN operations performed. */
  9833. (void)ctx;
  9834. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9835. /* Validate parameters. */
  9836. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9837. ret = 0;
  9838. }
  9839. /* Ensure internal representation of point is setup. */
  9840. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9841. ret = 0;
  9842. }
  9843. #ifdef DEBUG_WOLFSSL
  9844. if (ret == 1) {
  9845. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9846. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9847. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9848. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert input", point);
  9849. if (curve != NULL)
  9850. WOLFSSL_MSG_EX("curve name: %s", curve);
  9851. if (nistName != NULL)
  9852. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9853. }
  9854. #endif
  9855. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  9856. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9857. if (ec_point_convert_to_affine(group, point) != 0)
  9858. ret = 0;
  9859. #else
  9860. WOLFSSL_MSG("wolfSSL_EC_POINT_invert called on non-affine point");
  9861. ret = 0;
  9862. #endif
  9863. }
  9864. if (ret == 1) {
  9865. /* Perform inversion using wolfCrypt objects. */
  9866. ret = wolfssl_ec_point_invert(group->curve_idx,
  9867. (ecc_point*)point->internal);
  9868. }
  9869. /* Set the external EC point representation based on internal. */
  9870. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  9871. WOLFSSL_MSG("ec_point_external_set error");
  9872. ret = 0;
  9873. }
  9874. #ifdef DEBUG_WOLFSSL
  9875. if (ret == 1) {
  9876. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert result", point);
  9877. }
  9878. #endif
  9879. return ret;
  9880. }
  9881. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  9882. /* Compare two points on a the same curve.
  9883. *
  9884. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  9885. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9886. * When equal:
  9887. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9888. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  9889. *
  9890. * @param [in] group EC group.
  9891. * @param [in] a EC point to compare.
  9892. * @param [in] b EC point to compare.
  9893. * @return 0 when equal.
  9894. * @return 1 when different.
  9895. * @return -1 on error.
  9896. */
  9897. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  9898. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  9899. {
  9900. int ret = 0;
  9901. BIGNUM* at = BN_new();
  9902. BIGNUM* bt = BN_new();
  9903. BIGNUM* az = BN_new();
  9904. BIGNUM* bz = BN_new();
  9905. BIGNUM* mod = BN_new();
  9906. /* Check that the big numbers were allocated. */
  9907. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  9908. (mod == NULL)) {
  9909. ret = -1;
  9910. }
  9911. /* Get the modulus for the curve. */
  9912. if ((ret == 0) &&
  9913. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  9914. ret = -1;
  9915. }
  9916. if (ret == 0) {
  9917. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  9918. if (BN_is_one(a->Z)) {
  9919. if (BN_copy(bt, b->X) == NULL) {
  9920. ret = -1;
  9921. }
  9922. }
  9923. /* az = Az ^ 2 */
  9924. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  9925. ret = -1;
  9926. }
  9927. /* bt = Bx * az = Bx * (Az ^ 2) */
  9928. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  9929. ret = -1;
  9930. }
  9931. }
  9932. if (ret == 0) {
  9933. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  9934. if (BN_is_one(b->Z)) {
  9935. if (BN_copy(at, a->X) == NULL) {
  9936. ret = -1;
  9937. }
  9938. }
  9939. /* bz = Bz ^ 2 */
  9940. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  9941. ret = -1;
  9942. }
  9943. /* at = Ax * bz = Ax * (Bz ^ 2) */
  9944. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  9945. ret = -1;
  9946. }
  9947. }
  9948. /* Compare x-ordinates. */
  9949. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9950. ret = 1;
  9951. }
  9952. if (ret == 0) {
  9953. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  9954. if (BN_is_one(a->Z)) {
  9955. if (BN_copy(bt, b->Y) == NULL) {
  9956. ret = -1;
  9957. }
  9958. }
  9959. /* az = az * Az = Az ^ 3 */
  9960. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  9961. ret = -1;
  9962. }
  9963. /* bt = By * az = By * (Az ^ 3) */
  9964. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  9965. ret = -1;
  9966. }
  9967. }
  9968. if (ret == 0) {
  9969. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  9970. if (BN_is_one(b->Z)) {
  9971. if (BN_copy(at, a->Y) == NULL) {
  9972. ret = -1;
  9973. }
  9974. }
  9975. /* bz = bz * Bz = Bz ^ 3 */
  9976. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  9977. ret = -1;
  9978. }
  9979. /* at = Ay * bz = Ay * (Bz ^ 3) */
  9980. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  9981. ret = -1;
  9982. }
  9983. }
  9984. /* Compare y-ordinates. */
  9985. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9986. ret = 1;
  9987. }
  9988. BN_free(mod);
  9989. BN_free(bz);
  9990. BN_free(az);
  9991. BN_free(bt);
  9992. BN_free(at);
  9993. return ret;
  9994. }
  9995. #endif
  9996. /* Compare two points on a the same curve.
  9997. *
  9998. * Return code compliant with OpenSSL.
  9999. *
  10000. * @param [in] group EC group.
  10001. * @param [in] a EC point to compare.
  10002. * @param [in] b EC point to compare.
  10003. * @param [in] ctx Context to use for BN operations. Unused.
  10004. * @return 0 when equal.
  10005. * @return 1 when different.
  10006. * @return -1 on error.
  10007. */
  10008. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  10009. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10010. {
  10011. int ret = 0;
  10012. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  10013. /* Validate parameters. */
  10014. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  10015. (b == NULL) || (b->internal == NULL)) {
  10016. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  10017. ret = -1;
  10018. }
  10019. if (ret != -1) {
  10020. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10021. /* If same Z ordinate then no need to convert to affine. */
  10022. if (BN_cmp(a->Z, b->Z) == 0) {
  10023. /* Compare */
  10024. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  10025. }
  10026. else {
  10027. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  10028. }
  10029. #else
  10030. /* No BN operations performed. */
  10031. (void)ctx;
  10032. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  10033. (ecc_point*)b->internal) != MP_EQ);
  10034. #endif
  10035. }
  10036. return ret;
  10037. }
  10038. /* Copy EC point.
  10039. *
  10040. * @param [out] dest EC point to copy into.
  10041. * @param [in] src EC point to copy.
  10042. * @return 1 on success.
  10043. * @return 0 on error.
  10044. */
  10045. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  10046. {
  10047. int ret = 1;
  10048. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  10049. /* Validate parameters. */
  10050. if ((dest == NULL) || (src == NULL)) {
  10051. ret = 0;
  10052. }
  10053. /* Ensure internal EC point of src is setup. */
  10054. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  10055. ret = 0;
  10056. }
  10057. /* Copy internal EC points. */
  10058. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  10059. (ecc_point*)dest->internal) != MP_OKAY)) {
  10060. ret = 0;
  10061. }
  10062. if (ret == 1) {
  10063. /* Destinatation internal point is set. */
  10064. dest->inSet = 1;
  10065. /* Set the external EC point of dest based on internal. */
  10066. if (ec_point_external_set(dest) != 1) {
  10067. ret = 0;
  10068. }
  10069. }
  10070. return ret;
  10071. }
  10072. /* Checks whether point is at infinity.
  10073. *
  10074. * Return code compliant with OpenSSL.
  10075. *
  10076. * @param [in] group EC group.
  10077. * @param [in] point EC point to check.
  10078. * @return 1 when at infinity.
  10079. * @return 0 when not at infinity.
  10080. */
  10081. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  10082. const WOLFSSL_EC_POINT *point)
  10083. {
  10084. int ret = 1;
  10085. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  10086. /* Validate parameters. */
  10087. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10088. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  10089. ret = 0;
  10090. }
  10091. /* Ensure internal EC point is setup. */
  10092. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10093. ret = 0;
  10094. }
  10095. if (ret == 1) {
  10096. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10097. /* Check for infinity. */
  10098. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  10099. if (ret < 0) {
  10100. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  10101. /* Error return is 0 by OpenSSL. */
  10102. ret = 0;
  10103. }
  10104. #else
  10105. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  10106. ret = 0;
  10107. #endif
  10108. }
  10109. return ret;
  10110. }
  10111. #endif /* OPENSSL_EXTRA */
  10112. /* End EC_POINT */
  10113. /* Start EC_KEY */
  10114. #ifdef OPENSSL_EXTRA
  10115. /*
  10116. * EC key constructor/deconstructor APIs
  10117. */
  10118. /* Allocate a new EC key.
  10119. *
  10120. * Not OpenSSL API.
  10121. *
  10122. * @param [in] heap Heap hint for dynamic memory allocation.
  10123. * @param [in] devId Device identifier value.
  10124. * @return New, allocated EC key on success.
  10125. * @return NULL on error.
  10126. */
  10127. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  10128. {
  10129. WOLFSSL_EC_KEY *key = NULL;
  10130. int err = 0;
  10131. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  10132. /* Allocate memory for EC key. */
  10133. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  10134. DYNAMIC_TYPE_ECC);
  10135. if (key == NULL) {
  10136. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  10137. err = 1;
  10138. }
  10139. if (!err) {
  10140. /* Reset all fields to 0. */
  10141. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  10142. /* Cache heap hint. */
  10143. key->heap = heap;
  10144. /* Initialize fields to defaults. */
  10145. key->form = POINT_CONVERSION_UNCOMPRESSED;
  10146. /* Initialize reference count. */
  10147. wolfSSL_RefInit(&key->ref, &err);
  10148. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  10149. }
  10150. if (!err) {
  10151. #endif
  10152. /* Allocate memory for internal EC key representation. */
  10153. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  10154. DYNAMIC_TYPE_ECC);
  10155. if (key->internal == NULL) {
  10156. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10157. err = 1;
  10158. }
  10159. }
  10160. if (!err) {
  10161. /* Initialize wolfCrypt EC key. */
  10162. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10163. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10164. err = 1;
  10165. }
  10166. }
  10167. if (!err) {
  10168. /* Group unknown at creation */
  10169. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10170. if (key->group == NULL) {
  10171. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10172. err = 1;
  10173. }
  10174. }
  10175. if (!err) {
  10176. /* Allocate a point as public key. */
  10177. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10178. if (key->pub_key == NULL) {
  10179. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10180. err = 1;
  10181. }
  10182. }
  10183. if (!err) {
  10184. /* Allocate a BN as private key. */
  10185. key->priv_key = wolfSSL_BN_new();
  10186. if (key->priv_key == NULL) {
  10187. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10188. err = 1;
  10189. }
  10190. }
  10191. if (err) {
  10192. /* Dispose of EC key on error. */
  10193. wolfSSL_EC_KEY_free(key);
  10194. key = NULL;
  10195. }
  10196. /* Return new EC key object. */
  10197. return key;
  10198. }
  10199. /* Allocate a new EC key.
  10200. *
  10201. * @return New, allocated EC key on success.
  10202. * @return NULL on error.
  10203. */
  10204. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10205. {
  10206. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10207. }
  10208. /* Create new EC key with the group having the specified numeric ID.
  10209. *
  10210. * @param [in] nid Numeric ID.
  10211. * @return New, allocated EC key on success.
  10212. * @return NULL on error.
  10213. */
  10214. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10215. {
  10216. WOLFSSL_EC_KEY *key;
  10217. int err = 0;
  10218. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10219. /* Allocate empty, EC key. */
  10220. key = wolfSSL_EC_KEY_new();
  10221. if (key == NULL) {
  10222. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10223. err = 1;
  10224. }
  10225. if (!err) {
  10226. /* Set group to be nid. */
  10227. ec_group_set_nid(key->group, nid);
  10228. if (key->group->curve_idx == -1) {
  10229. wolfSSL_EC_KEY_free(key);
  10230. key = NULL;
  10231. }
  10232. }
  10233. /* Return the new EC key object. */
  10234. return key;
  10235. }
  10236. /* Dispose of the EC key and allocated data.
  10237. *
  10238. * Cannot use key after this call.
  10239. *
  10240. * @param [in] key EC key to free.
  10241. */
  10242. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10243. {
  10244. int doFree = 0;
  10245. int err;
  10246. (void)err;
  10247. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10248. if (key != NULL) {
  10249. void* heap = key->heap;
  10250. /* Decrement reference count. */
  10251. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10252. if (doFree) {
  10253. /* Dispose of allocated reference counting data. */
  10254. wolfSSL_RefFree(&key->ref);
  10255. /* Dispose of private key. */
  10256. wolfSSL_BN_free(key->priv_key);
  10257. wolfSSL_EC_POINT_free(key->pub_key);
  10258. wolfSSL_EC_GROUP_free(key->group);
  10259. if (key->internal != NULL) {
  10260. /* Dispose of wolfCrypt representation of EC key. */
  10261. wc_ecc_free((ecc_key*)key->internal);
  10262. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10263. }
  10264. /* Set back to NULLs for safety. */
  10265. ForceZero(key, sizeof(*key));
  10266. /* Dispose of the memory associated with the EC key. */
  10267. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10268. (void)heap;
  10269. }
  10270. }
  10271. }
  10272. /* Increments ref count of EC key.
  10273. *
  10274. * @param [in, out] key EC key.
  10275. * @return 1 on success
  10276. * @return 0 on error
  10277. */
  10278. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10279. {
  10280. int err = 1;
  10281. if (key != NULL) {
  10282. wolfSSL_RefInc(&key->ref, &err);
  10283. }
  10284. return !err;
  10285. }
  10286. #ifndef NO_CERTS
  10287. #if defined(OPENSSL_ALL)
  10288. /* Copy the internal, wolfCrypt EC key.
  10289. *
  10290. * @param [in, out] dst Destination wolfCrypt EC key.
  10291. * @param [in] src Source wolfCrypt EC key.
  10292. * @return 0 on success.
  10293. * @return Negative on error.
  10294. */
  10295. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10296. {
  10297. int ret;
  10298. /* Copy public key. */
  10299. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10300. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10301. #else
  10302. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10303. #endif
  10304. if (ret != MP_OKAY) {
  10305. WOLFSSL_MSG("wc_ecc_copy_point error");
  10306. }
  10307. if (ret == 0) {
  10308. /* Copy private key. */
  10309. ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst));
  10310. if (ret != MP_OKAY) {
  10311. WOLFSSL_MSG("mp_copy error");
  10312. }
  10313. }
  10314. if (ret == 0) {
  10315. /* Copy domain parameters. */
  10316. if (src->dp) {
  10317. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10318. if (ret != 0) {
  10319. WOLFSSL_MSG("wc_ecc_set_curve error");
  10320. }
  10321. }
  10322. }
  10323. if (ret == 0) {
  10324. /* Copy the other components. */
  10325. dst->type = src->type;
  10326. dst->idx = src->idx;
  10327. dst->state = src->state;
  10328. dst->flags = src->flags;
  10329. }
  10330. return ret;
  10331. }
  10332. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10333. *
  10334. * Copies the internal representation as well.
  10335. *
  10336. * @param [in] src EC key to duplicate.
  10337. *
  10338. * @return EC key on success.
  10339. * @return NULL on error.
  10340. */
  10341. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10342. {
  10343. int err = 0;
  10344. WOLFSSL_EC_KEY* newKey = NULL;
  10345. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10346. /* Validate EC key. */
  10347. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10348. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10349. WOLFSSL_MSG("src NULL error");
  10350. err = 1;
  10351. }
  10352. if (!err) {
  10353. /* Create a new, empty key. */
  10354. newKey = wolfSSL_EC_KEY_new();
  10355. if (newKey == NULL) {
  10356. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10357. err = 1;
  10358. }
  10359. }
  10360. if (!err) {
  10361. /* Copy internal EC key. */
  10362. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10363. (ecc_key*)src->internal) != 0) {
  10364. WOLFSSL_MSG("Copying internal EC key error");
  10365. err = 1;
  10366. }
  10367. }
  10368. if (!err) {
  10369. /* Internal key set. */
  10370. newKey->inSet = 1;
  10371. /* Copy group */
  10372. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10373. }
  10374. /* Copy public key. */
  10375. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10376. WOLFSSL_MSG("Copying EC public key error");
  10377. err = 1;
  10378. }
  10379. if (!err) {
  10380. /* Set header size of private key in PKCS#8 format.*/
  10381. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10382. /* Copy private key. */
  10383. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10384. WOLFSSL_MSG("Copying EC private key error");
  10385. err = 1;
  10386. }
  10387. }
  10388. if (err) {
  10389. /* Dispose of EC key on error. */
  10390. wolfSSL_EC_KEY_free(newKey);
  10391. newKey = NULL;
  10392. }
  10393. /* Return the new EC key. */
  10394. return newKey;
  10395. }
  10396. #endif /* OPENSSL_ALL */
  10397. #endif /* !NO_CERTS */
  10398. /*
  10399. * EC key to/from bin/octet APIs
  10400. */
  10401. /* Create an EC key from the octet encoded public key.
  10402. *
  10403. * Behaviour checked against OpenSSL.
  10404. *
  10405. * @param [out] key Reference to EC key. Must pass in a valid object with
  10406. * group set.
  10407. * @param [in, out] in On in, reference to buffer that contains data.
  10408. * On out, reference to buffer after public key data.
  10409. * @param [in] len Length of data in the buffer. Must be length of the
  10410. * encoded public key.
  10411. * @return Allocated EC key on success.
  10412. * @return NULL on error.
  10413. */
  10414. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10415. const unsigned char **in, long len)
  10416. {
  10417. int err = 0;
  10418. WOLFSSL_EC_KEY* ret = NULL;
  10419. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10420. /* Validate parameters: EC group needed to perform import. */
  10421. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10422. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10423. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10424. err = 1;
  10425. }
  10426. if (!err) {
  10427. /* Return the EC key object passed in. */
  10428. ret = *key;
  10429. /* Import point into public key field. */
  10430. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in,
  10431. (size_t)len, NULL) != 1) {
  10432. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10433. ret = NULL;
  10434. err = 1;
  10435. }
  10436. }
  10437. if (!err) {
  10438. /* Assumed length passed in is all the data. */
  10439. *in += len;
  10440. }
  10441. return ret;
  10442. }
  10443. /* Puts the encoded public key into out.
  10444. *
  10445. * Passing in NULL for out returns length only.
  10446. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10447. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10448. *
  10449. * @param [in] key EC key to encode.
  10450. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10451. * point to NULL.
  10452. * @return Length of encoding in bytes on success.
  10453. * @return 0 on error.
  10454. */
  10455. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10456. {
  10457. int ret = 1;
  10458. size_t len = 0;
  10459. int form = POINT_CONVERSION_UNCOMPRESSED;
  10460. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10461. /* Validate parameters. */
  10462. if (key == NULL) {
  10463. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10464. ret = 0;
  10465. }
  10466. /* Ensure the external key data is set from the internal EC key. */
  10467. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10468. key) != 1)) {
  10469. WOLFSSL_MSG("SetECKeyExternal failure");
  10470. ret = 0;
  10471. }
  10472. if (ret == 1) {
  10473. #ifdef HAVE_COMP_KEY
  10474. /* Default to compressed form if not set */
  10475. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10476. POINT_CONVERSION_UNCOMPRESSED :
  10477. POINT_CONVERSION_COMPRESSED;
  10478. #endif
  10479. /* Calculate length of point encoding. */
  10480. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10481. 0, NULL);
  10482. }
  10483. /* Encode if length calculated and pointer supplied to update. */
  10484. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10485. unsigned char *tmp = NULL;
  10486. /* Allocate buffer for encoding if no buffer supplied. */
  10487. if (*out == NULL) {
  10488. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10489. if (tmp == NULL) {
  10490. WOLFSSL_MSG("malloc failed");
  10491. ret = 0;
  10492. }
  10493. }
  10494. else {
  10495. /* Get buffer to encode into. */
  10496. tmp = *out;
  10497. }
  10498. /* Encode public key into buffer. */
  10499. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10500. form, tmp, len, NULL) == 0)) {
  10501. ret = 0;
  10502. }
  10503. if (ret == 1) {
  10504. /* Return buffer if allocated. */
  10505. if (*out == NULL) {
  10506. *out = tmp;
  10507. }
  10508. else {
  10509. /* Step over encoded data if not allocated. */
  10510. *out += len;
  10511. }
  10512. }
  10513. else if (*out == NULL) {
  10514. /* Dispose of allocated buffer. */
  10515. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10516. }
  10517. }
  10518. if (ret == 1) {
  10519. /* Return length on success. */
  10520. ret = (int)len;
  10521. }
  10522. return ret;
  10523. }
  10524. #ifdef HAVE_ECC_KEY_IMPORT
  10525. /* Create a EC key from the DER encoded private key.
  10526. *
  10527. * @param [out] key Reference to EC key.
  10528. * @param [in, out] in On in, reference to buffer that contains DER data.
  10529. * On out, reference to buffer after private key data.
  10530. * @param [in] long Length of data in the buffer. May be larger than the
  10531. * length of the encoded private key.
  10532. * @return Allocated EC key on success.
  10533. * @return NULL on error.
  10534. */
  10535. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10536. const unsigned char** in, long len)
  10537. {
  10538. int err = 0;
  10539. word32 idx = 0;
  10540. WOLFSSL_EC_KEY* ret = NULL;
  10541. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10542. /* Validate parameters. */
  10543. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10544. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10545. err = 1;
  10546. }
  10547. /* Create a new, empty EC key. */
  10548. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10549. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10550. err = 1;
  10551. }
  10552. /* Decode the private key DER data into internal EC key. */
  10553. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10554. (word32)len) != 0)) {
  10555. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10556. err = 1;
  10557. }
  10558. if (!err) {
  10559. /* Internal EC key setup. */
  10560. ret->inSet = 1;
  10561. /* Set the EC key from the internal values. */
  10562. if (SetECKeyExternal(ret) != 1) {
  10563. WOLFSSL_MSG("SetECKeyExternal error");
  10564. err = 1;
  10565. }
  10566. }
  10567. if (!err) {
  10568. /* Move buffer on to next byte after data used. */
  10569. *in += idx;
  10570. if (key) {
  10571. /* Return new EC key through reference. */
  10572. *key = ret;
  10573. }
  10574. }
  10575. if (err && (ret != NULL)) {
  10576. /* Dispose of allocated EC key. */
  10577. wolfSSL_EC_KEY_free(ret);
  10578. ret = NULL;
  10579. }
  10580. return ret;
  10581. }
  10582. #endif /* HAVE_ECC_KEY_IMPORT */
  10583. /* Enecode the private key of the EC key into the buffer as DER.
  10584. *
  10585. * @param [in] key EC key to encode.
  10586. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10587. * On out, reference to buffer adter the encoding.
  10588. * May be NULL.
  10589. * @return Length of DER encoding on success.
  10590. * @return 0 on error.
  10591. */
  10592. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10593. {
  10594. int err = 0;
  10595. word32 len = 0;
  10596. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10597. /* Validate parameters. */
  10598. if (key == NULL) {
  10599. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10600. err = 1;
  10601. }
  10602. /* Update the internal EC key if not set. */
  10603. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10604. 1)) {
  10605. WOLFSSL_MSG("SetECKeyInternal error");
  10606. err = 1;
  10607. }
  10608. /* Calculate the length of the private key DER encoding using internal EC
  10609. * key. */
  10610. if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal,
  10611. 0)) <= 0)) {
  10612. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10613. err = 1;
  10614. }
  10615. /* Only return length when out is NULL. */
  10616. if ((!err) && (out != NULL)) {
  10617. unsigned char* buf = NULL;
  10618. /* Must have a buffer to encode into. */
  10619. if (*out == NULL) {
  10620. /* Allocate a new buffer of appropriate length. */
  10621. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10622. if (buf == NULL) {
  10623. /* Error and return 0. */
  10624. err = 1;
  10625. len = 0;
  10626. }
  10627. else {
  10628. /* Return the allocated buffer. */
  10629. *out = buf;
  10630. }
  10631. }
  10632. /* Encode the internal EC key as a private key in DER format. */
  10633. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10634. len) < 0) {
  10635. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10636. err = 1;
  10637. }
  10638. else if (buf != *out) {
  10639. /* Move the reference to byte past encoded private key. */
  10640. *out += len;
  10641. }
  10642. /* Dispose of any allocated buffer on error. */
  10643. if (err && (*out == buf)) {
  10644. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10645. *out = NULL;
  10646. }
  10647. }
  10648. return (int)len;
  10649. }
  10650. /* Load private key into EC key from DER encoding.
  10651. *
  10652. * Not an OpenSSL compatibility API.
  10653. *
  10654. * @param [in, out] key EC key to put private key values into.
  10655. * @param [in] derBuf Buffer holding DER encoding.
  10656. * @param [in] derSz Size of DER encoding in bytes.
  10657. * @return 1 on success.
  10658. * @return -1 on error.
  10659. */
  10660. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10661. int derSz)
  10662. {
  10663. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10664. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10665. }
  10666. /* Load private/public key into EC key from DER encoding.
  10667. *
  10668. * Not an OpenSSL compatibility API.
  10669. *
  10670. * @param [in, out] key EC key to put private/public key values into.
  10671. * @param [in] derBuf Buffer holding DER encoding.
  10672. * @param [in] derSz Size of DER encoding in bytes.
  10673. * @param [in] opt Key type option. Valid values:
  10674. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10675. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10676. * @return 1 on success.
  10677. * @return -1 on error.
  10678. */
  10679. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10680. int derSz, int opt)
  10681. {
  10682. int res = 1;
  10683. int ret;
  10684. word32 idx = 0;
  10685. word32 algId;
  10686. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10687. /* Validate parameters. */
  10688. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10689. (derSz <= 0)) {
  10690. WOLFSSL_MSG("Bad function arguments");
  10691. res = -1;
  10692. }
  10693. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10694. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10695. res = -1;
  10696. }
  10697. if (res == 1) {
  10698. /* Assume no PKCS#8 header. */
  10699. key->pkcs8HeaderSz = 0;
  10700. /* Check if input buffer has PKCS8 header. In the case that it does not
  10701. * have a PKCS8 header then do not error out.
  10702. */
  10703. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10704. (word32)derSz, &algId)) > 0) {
  10705. WOLFSSL_MSG("Found PKCS8 header");
  10706. key->pkcs8HeaderSz = (word16)idx;
  10707. res = 1;
  10708. }
  10709. /* Error out on parsing error. */
  10710. else if (ret != ASN_PARSE_E) {
  10711. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10712. res = -1;
  10713. }
  10714. }
  10715. if (res == 1) {
  10716. /* Load into internal EC key based on key type option. */
  10717. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10718. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10719. (word32)derSz);
  10720. }
  10721. else {
  10722. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10723. (word32)derSz);
  10724. if (ret < 0) {
  10725. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  10726. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  10727. if (tmp == NULL) {
  10728. ret = -1;
  10729. }
  10730. else {
  10731. /* We now try again as x.963 [point type][x][opt y]. */
  10732. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  10733. INVALID_DEVID);
  10734. if (ret == 0) {
  10735. ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp);
  10736. if (ret == 0) {
  10737. /* Take ownership of new key - set tmp to the old
  10738. * key which will then be freed below. */
  10739. ecc_key *old = (ecc_key *)key->internal;
  10740. key->internal = tmp;
  10741. tmp = old;
  10742. idx = (word32)derSz;
  10743. }
  10744. wc_ecc_free(tmp);
  10745. }
  10746. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  10747. DYNAMIC_TYPE_ECC);
  10748. }
  10749. }
  10750. }
  10751. if (ret < 0) {
  10752. /* Error returned from wolfSSL. */
  10753. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10754. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10755. }
  10756. else {
  10757. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10758. }
  10759. res = -1;
  10760. }
  10761. /* Internal key updated - update whether it is a valid key. */
  10762. key->inSet = (res == 1);
  10763. }
  10764. /* Set the external EC key based on value in internal. */
  10765. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  10766. WOLFSSL_MSG("SetECKeyExternal failed");
  10767. res = -1;
  10768. }
  10769. return res;
  10770. }
  10771. /*
  10772. * EC key PEM APIs
  10773. */
  10774. #if (defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM)) || \
  10775. (!defined(NO_BIO) && (defined(WOLFSSL_KEY_GEN) || \
  10776. defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)))
  10777. /* Encode the EC public key as DER.
  10778. *
  10779. * Also used by pem_write_pubkey().
  10780. *
  10781. * @param [in] key EC key to encode.
  10782. * @param [out] der Pointer through which buffer is returned.
  10783. * @param [in] heap Heap hint.
  10784. * @return Size of encoding on success.
  10785. * @return 0 on error.
  10786. */
  10787. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  10788. unsigned char** der, void* heap)
  10789. {
  10790. int sz;
  10791. unsigned char* buf = NULL;
  10792. (void)heap;
  10793. /* Calculate encoded size to allocate. */
  10794. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  10795. if (sz <= 0) {
  10796. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  10797. sz = 0;
  10798. }
  10799. if (sz > 0) {
  10800. /* Allocate memory to hold encoding. */
  10801. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10802. if (buf == NULL) {
  10803. WOLFSSL_MSG("malloc failed");
  10804. sz = 0;
  10805. }
  10806. }
  10807. if (sz > 0) {
  10808. /* Encode public key to DER using wolfSSL. */
  10809. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1);
  10810. if (sz < 0) {
  10811. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  10812. sz = 0;
  10813. }
  10814. }
  10815. /* Return buffer on success. */
  10816. if (sz > 0) {
  10817. *der = buf;
  10818. }
  10819. else {
  10820. /* Dispose of any dynamically allocated data not returned. */
  10821. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10822. }
  10823. return sz;
  10824. }
  10825. #endif
  10826. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  10827. /*
  10828. * Return code compliant with OpenSSL.
  10829. *
  10830. * @param [in] fp File pointer to write PEM encoding to.
  10831. * @param [in] key EC key to encode and write.
  10832. * @return 1 on success.
  10833. * @return 0 on error.
  10834. */
  10835. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10836. {
  10837. int ret = 1;
  10838. unsigned char* derBuf = NULL;
  10839. int derSz = 0;
  10840. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10841. /* Validate parameters. */
  10842. if ((fp == XBADFILE) || (key == NULL)) {
  10843. WOLFSSL_MSG("Bad argument.");
  10844. return 0;
  10845. }
  10846. /* Encode public key in EC key as DER. */
  10847. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  10848. if (derSz == 0) {
  10849. ret = 0;
  10850. }
  10851. /* Write out to file the PEM encoding of the DER. */
  10852. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  10853. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  10854. ret = 0;
  10855. }
  10856. /* Dispose of any dynamically allocated data. */
  10857. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10858. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10859. return ret;
  10860. }
  10861. #endif
  10862. #ifndef NO_BIO
  10863. /* Read a PEM encoded EC public key from a BIO.
  10864. *
  10865. * @param [in] bio BIO to read EC public key from.
  10866. * @param [out] out Pointer to return EC key object through. May be NULL.
  10867. * @param [in] cb Password callback when PEM encrypted.
  10868. * @param [in] pass NUL terminated string for passphrase when PEM
  10869. * encrypted.
  10870. * @return New EC key object on success.
  10871. * @return NULL on error.
  10872. */
  10873. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10874. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10875. {
  10876. int err = 0;
  10877. WOLFSSL_EC_KEY* ec = NULL;
  10878. DerBuffer* der = NULL;
  10879. int keyFormat = 0;
  10880. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10881. /* Validate parameters. */
  10882. if (bio == NULL) {
  10883. err = 1;
  10884. }
  10885. if (!err) {
  10886. /* Create an empty EC key. */
  10887. ec = wolfSSL_EC_KEY_new();
  10888. if (ec == NULL) {
  10889. err = 1;
  10890. }
  10891. }
  10892. /* Read a PEM key in to a new DER buffer. */
  10893. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  10894. &keyFormat, &der) <= 0)) {
  10895. err = 1;
  10896. }
  10897. /* Load the EC key with the public key from the DER encoding. */
  10898. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  10899. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  10900. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10901. err = 1;
  10902. }
  10903. /* Dispose of dynamically allocated data not needed anymore. */
  10904. FreeDer(&der);
  10905. if (err) {
  10906. wolfSSL_EC_KEY_free(ec);
  10907. ec = NULL;
  10908. }
  10909. /* Return EC key through out if required. */
  10910. if ((out != NULL) && (ec != NULL)) {
  10911. *out = ec;
  10912. }
  10913. return ec;
  10914. }
  10915. /* Read a PEM encoded EC private key from a BIO.
  10916. *
  10917. * @param [in] bio BIO to read EC private key from.
  10918. * @param [out] out Pointer to return EC key object through. May be NULL.
  10919. * @param [in] cb Password callback when PEM encrypted.
  10920. * @param [in] pass NUL terminated string for passphrase when PEM
  10921. * encrypted.
  10922. * @return New EC key object on success.
  10923. * @return NULL on error.
  10924. */
  10925. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  10926. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10927. {
  10928. int err = 0;
  10929. WOLFSSL_EC_KEY* ec = NULL;
  10930. DerBuffer* der = NULL;
  10931. int keyFormat = 0;
  10932. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  10933. /* Validate parameters. */
  10934. if (bio == NULL) {
  10935. err = 1;
  10936. }
  10937. if (!err) {
  10938. /* Create an empty EC key. */
  10939. ec = wolfSSL_EC_KEY_new();
  10940. if (ec == NULL) {
  10941. err = 1;
  10942. }
  10943. }
  10944. /* Read a PEM key in to a new DER buffer.
  10945. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  10946. * pem_read_bio_key(), and then check key format if it is EC.
  10947. */
  10948. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  10949. &keyFormat, &der) <= 0)) {
  10950. err = 1;
  10951. }
  10952. if (keyFormat != ECDSAk) {
  10953. WOLFSSL_ERROR_MSG("Error not EC key format");
  10954. err = 1;
  10955. }
  10956. /* Load the EC key with the private key from the DER encoding. */
  10957. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  10958. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  10959. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10960. err = 1;
  10961. }
  10962. /* Dispose of dynamically allocated data not needed anymore. */
  10963. FreeDer(&der);
  10964. if (err) {
  10965. wolfSSL_EC_KEY_free(ec);
  10966. ec = NULL;
  10967. }
  10968. /* Return EC key through out if required. */
  10969. if ((out != NULL) && (ec != NULL)) {
  10970. *out = ec;
  10971. }
  10972. return ec;
  10973. }
  10974. #endif /* !NO_BIO */
  10975. #if defined(WOLFSSL_KEY_GEN)
  10976. #ifndef NO_BIO
  10977. /* Write out the EC public key as PEM to the BIO.
  10978. *
  10979. * @param [in] bio BIO to write PEM encoding to.
  10980. * @param [in] ec EC public key to encode.
  10981. * @return 1 on success.
  10982. * @return 0 on error.
  10983. */
  10984. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  10985. {
  10986. int ret = 1;
  10987. unsigned char* derBuf = NULL;
  10988. int derSz = 0;
  10989. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  10990. /* Validate parameters. */
  10991. if ((bio == NULL) || (ec == NULL)) {
  10992. WOLFSSL_MSG("Bad Function Arguments");
  10993. return 0;
  10994. }
  10995. /* Encode public key in EC key as DER. */
  10996. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  10997. if (derSz == 0) {
  10998. ret = 0;
  10999. }
  11000. /* Write out to BIO the PEM encoding of the EC private key. */
  11001. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  11002. ECC_PUBLICKEY_TYPE) != 1)) {
  11003. ret = 0;
  11004. }
  11005. /* Dispose of any dynamically allocated data. */
  11006. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11007. return ret;
  11008. }
  11009. /* Write out the EC private key as PEM to the BIO.
  11010. *
  11011. * Return code compliant with OpenSSL.
  11012. *
  11013. * @param [in] bio BIO to write PEM encoding to.
  11014. * @param [in] ec EC private key to encode.
  11015. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11016. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11017. * @param [in] passwdSz Length of password string when PEM encrypted.
  11018. * @param [in] cb Password callback when PEM encrypted. Unused.
  11019. * @param [in] pass NUL terminated string for passphrase when PEM
  11020. * encrypted. Unused.
  11021. * @return 1 on success.
  11022. * @return 0 on error.
  11023. */
  11024. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  11025. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11026. wc_pem_password_cb* cb, void* arg)
  11027. {
  11028. int ret = 1;
  11029. unsigned char* pem = NULL;
  11030. int pLen = 0;
  11031. (void)cb;
  11032. (void)arg;
  11033. /* Validate parameters. */
  11034. if ((bio == NULL) || (ec == NULL)) {
  11035. ret = 0;
  11036. }
  11037. /* Write EC private key to PEM. */
  11038. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11039. passwdSz, &pem, &pLen) != 1)) {
  11040. ret = 0;
  11041. }
  11042. /* Write PEM to BIO. */
  11043. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  11044. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  11045. ret = 0;
  11046. }
  11047. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11048. return ret;
  11049. }
  11050. #endif /* !NO_BIO */
  11051. /* Encode the EC private key as PEM into buffer.
  11052. *
  11053. * Return code compliant with OpenSSL.
  11054. * Not an OpenSSL API.
  11055. *
  11056. * @param [in] ec EC private key to encode.
  11057. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11058. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11059. * @param [in] passwdSz Length of password string when PEM encrypted.
  11060. * @param [out] pem Newly allocated buffer holding PEM encoding.
  11061. * @param [out] pLen Length of PEM encoding in bytes.
  11062. * @return 1 on success.
  11063. * @return 0 on error.
  11064. */
  11065. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  11066. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11067. unsigned char **pem, int *pLen)
  11068. {
  11069. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  11070. int ret = 1;
  11071. byte* derBuf = NULL;
  11072. word32 der_max_len = 0;
  11073. int derSz = 0;
  11074. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  11075. /* Validate parameters. */
  11076. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  11077. (ec->internal == NULL)) {
  11078. WOLFSSL_MSG("Bad function arguments");
  11079. ret = 0;
  11080. }
  11081. /* Ensure internal EC key is set from external. */
  11082. if ((ret == 1) && (ec->inSet == 0)) {
  11083. WOLFSSL_MSG("No ECC internal set, do it");
  11084. if (SetECKeyInternal(ec) != 1) {
  11085. WOLFSSL_MSG("SetECKeyInternal failed");
  11086. ret = 0;
  11087. }
  11088. }
  11089. if (ret == 1) {
  11090. /* Calculate maximum size of DER encoding.
  11091. * 4 > size of pub, priv + ASN.1 additional information */
  11092. der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) +
  11093. AES_BLOCK_SIZE;
  11094. /* Allocate buffer big enough to hold encoding. */
  11095. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL,
  11096. DYNAMIC_TYPE_TMP_BUFFER);
  11097. if (derBuf == NULL) {
  11098. WOLFSSL_MSG("malloc failed");
  11099. ret = 0;
  11100. }
  11101. }
  11102. if (ret == 1) {
  11103. /* Encode EC private key as DER. */
  11104. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  11105. if (derSz < 0) {
  11106. WOLFSSL_MSG("wc_EccKeyToDer failed");
  11107. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  11108. ret = 0;
  11109. }
  11110. }
  11111. /* Convert DER to PEM - possibly encrypting. */
  11112. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  11113. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  11114. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  11115. ret = 0;
  11116. }
  11117. return ret;
  11118. #else
  11119. (void)ec;
  11120. (void)cipher;
  11121. (void)passwd;
  11122. (void)passwdSz;
  11123. (void)pem;
  11124. (void)pLen;
  11125. return 0;
  11126. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  11127. }
  11128. #ifndef NO_FILESYSTEM
  11129. /* Write out the EC private key as PEM to file.
  11130. *
  11131. * Return code compliant with OpenSSL.
  11132. *
  11133. * @param [in] fp File pointer to write PEM encoding to.
  11134. * @param [in] ec EC private key to encode.
  11135. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11136. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11137. * @param [in] passwdSz Length of password string when PEM encrypted.
  11138. * @param [in] cb Password callback when PEM encrypted. Unused.
  11139. * @param [in] pass NUL terminated string for passphrase when PEM
  11140. * encrypted. Unused.
  11141. * @return 1 on success.
  11142. * @return 0 on error.
  11143. */
  11144. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  11145. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  11146. wc_pem_password_cb *cb, void *pass)
  11147. {
  11148. int ret = 1;
  11149. byte *pem = NULL;
  11150. int pLen = 0;
  11151. (void)cb;
  11152. (void)pass;
  11153. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  11154. /* Validate parameters. */
  11155. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  11156. WOLFSSL_MSG("Bad function arguments");
  11157. ret = 0;
  11158. }
  11159. /* Write EC private key to PEM. */
  11160. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11161. passwdSz, &pem, &pLen) != 1)) {
  11162. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11163. ret = 0;
  11164. }
  11165. /* Write out to file the PEM encoding of the EC private key. */
  11166. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  11167. WOLFSSL_MSG("ECC private key file write failed");
  11168. ret = 0;
  11169. }
  11170. /* Dispose of any dynamically allocated data. */
  11171. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11172. return ret;
  11173. }
  11174. #endif /* NO_FILESYSTEM */
  11175. #endif /* defined(WOLFSSL_KEY_GEN) */
  11176. /*
  11177. * EC key print APIs
  11178. */
  11179. #ifndef NO_CERTS
  11180. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11181. !defined(NO_STDIO_FILESYSTEM)
  11182. /* Print the EC key to a file pointer as text.
  11183. *
  11184. * @param [in] fp File pointer.
  11185. * @param [in] key EC key to print.
  11186. * @param [in] indent Number of spaces to place before each line printed.
  11187. * @return 1 on success.
  11188. * @return 0 on failure.
  11189. */
  11190. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11191. {
  11192. int ret = 1;
  11193. int bits = 0;
  11194. int priv = 0;
  11195. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11196. /* Validate parameters. */
  11197. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11198. (indent < 0)) {
  11199. ret = 0;
  11200. }
  11201. if (ret == 1) {
  11202. /* Get EC groups order size in bits. */
  11203. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11204. if (bits <= 0) {
  11205. WOLFSSL_MSG("Failed to get group order bits.");
  11206. ret = 0;
  11207. }
  11208. }
  11209. if (ret == 1) {
  11210. const char* keyType;
  11211. /* Determine whether this is a private or public key. */
  11212. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11213. keyType = "Private-Key";
  11214. priv = 1;
  11215. }
  11216. else {
  11217. keyType = "Public-Key";
  11218. }
  11219. /* Print key header. */
  11220. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11221. ret = 0;
  11222. }
  11223. }
  11224. if ((ret == 1) && priv) {
  11225. /* Print the private key BN. */
  11226. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11227. }
  11228. /* Check for public key data in EC key. */
  11229. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11230. /* Get the public key point as one BN. */
  11231. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11232. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11233. if (pubBn == NULL) {
  11234. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11235. ret = 0;
  11236. }
  11237. else {
  11238. /* Print the public key in a BN. */
  11239. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11240. wolfSSL_BN_free(pubBn);
  11241. }
  11242. }
  11243. if (ret == 1) {
  11244. /* Get the NID of the group. */
  11245. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11246. if (nid > 0) {
  11247. /* Convert the NID into a long name and NIST name. */
  11248. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11249. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11250. /* Print OID name if known. */
  11251. if ((curve != NULL) &&
  11252. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11253. ret = 0;
  11254. }
  11255. /* Print NIST curve name if known. */
  11256. if ((nistName != NULL) &&
  11257. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11258. nistName) < 0)) {
  11259. ret = 0;
  11260. }
  11261. }
  11262. }
  11263. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11264. return ret;
  11265. }
  11266. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11267. #endif /* !NO_CERTS */
  11268. /*
  11269. * EC_KEY get/set/test APIs
  11270. */
  11271. /* Set data of internal, wolfCrypt EC key object into EC key.
  11272. *
  11273. * EC_KEY wolfSSL -> OpenSSL
  11274. *
  11275. * @param [in, out] p EC key to update.
  11276. * @return 1 on success.
  11277. * @return -1 on failure.
  11278. */
  11279. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11280. {
  11281. int ret = 1;
  11282. WOLFSSL_ENTER("SetECKeyExternal");
  11283. /* Validate parameter. */
  11284. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11285. WOLFSSL_MSG("ec key NULL error");
  11286. ret = -1;
  11287. }
  11288. else {
  11289. ecc_key* key = (ecc_key*)eckey->internal;
  11290. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11291. eckey->group->curve_oid = (int)key->dp->oidSum;
  11292. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11293. eckey->group->curve_idx = key->idx;
  11294. if (eckey->pub_key->internal != NULL) {
  11295. /* Copy internal public point from internal key's public point. */
  11296. if (wc_ecc_copy_point(&key->pubkey,
  11297. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11298. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11299. ret = -1;
  11300. }
  11301. /* Set external public key from internal wolfCrypt, public key. */
  11302. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11303. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11304. ret = -1;
  11305. }
  11306. }
  11307. /* set the external privkey */
  11308. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11309. (wolfssl_bn_set_value(&eckey->priv_key,
  11310. wc_ecc_key_get_priv(key)) != 1)) {
  11311. WOLFSSL_MSG("ec priv key error");
  11312. ret = -1;
  11313. }
  11314. /* External values set when operations succeeded. */
  11315. eckey->exSet = (ret == 1);
  11316. }
  11317. return ret;
  11318. }
  11319. /* Set data of EC key into internal, wolfCrypt EC key object.
  11320. *
  11321. * EC_KEY Openssl -> WolfSSL
  11322. *
  11323. * @param [in, out] p EC key to update.
  11324. * @return 1 on success.
  11325. * @return -1 on failure.
  11326. */
  11327. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11328. {
  11329. int ret = 1;
  11330. WOLFSSL_ENTER("SetECKeyInternal");
  11331. /* Validate parameter. */
  11332. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11333. (eckey->group == NULL)) {
  11334. WOLFSSL_MSG("ec key NULL error");
  11335. ret = -1;
  11336. }
  11337. else {
  11338. ecc_key* key = (ecc_key*)eckey->internal;
  11339. int pubSet = 0;
  11340. /* Validate group. */
  11341. if ((eckey->group->curve_idx < 0) ||
  11342. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11343. WOLFSSL_MSG("invalid curve idx");
  11344. ret = -1;
  11345. }
  11346. if (ret == 1) {
  11347. /* Set group (idx of curve and corresponding domain parameters). */
  11348. key->idx = eckey->group->curve_idx;
  11349. key->dp = &ecc_sets[key->idx];
  11350. pubSet = (eckey->pub_key != NULL);
  11351. }
  11352. /* Set public key (point). */
  11353. if ((ret == 1) && pubSet) {
  11354. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11355. WOLFSSL_MSG("ec key pub error");
  11356. ret = -1;
  11357. }
  11358. /* Copy public point to key. */
  11359. if ((ret == 1) && (wc_ecc_copy_point(
  11360. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11361. MP_OKAY)) {
  11362. WOLFSSL_MSG("wc_ecc_copy_point error");
  11363. ret = -1;
  11364. }
  11365. if (ret == 1) {
  11366. /* Set that the internal key is a public key */
  11367. key->type = ECC_PUBLICKEY;
  11368. }
  11369. }
  11370. /* set privkey */
  11371. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11372. if (wolfssl_bn_get_value(eckey->priv_key,
  11373. wc_ecc_key_get_priv(key)) != 1) {
  11374. WOLFSSL_MSG("ec key priv error");
  11375. ret = -1;
  11376. }
  11377. /* private key */
  11378. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11379. if (pubSet) {
  11380. key->type = ECC_PRIVATEKEY;
  11381. }
  11382. else {
  11383. key->type = ECC_PRIVATEKEY_ONLY;
  11384. }
  11385. }
  11386. }
  11387. /* Internal values set when operations succeeded. */
  11388. eckey->inSet = (ret == 1);
  11389. }
  11390. return ret;
  11391. }
  11392. /* Get point conversion format of EC key.
  11393. *
  11394. * @param [in] key EC key.
  11395. * @return Point conversion format on success.
  11396. * @return -1 on error.
  11397. */
  11398. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11399. {
  11400. int ret = -1;
  11401. if (key != NULL) {
  11402. ret = key->form;
  11403. }
  11404. return ret;
  11405. }
  11406. /* Set point conversion format into EC key.
  11407. *
  11408. * @param [in, out] key EC key to set format into.
  11409. * @param [in] form Point conversion format. Valid values:
  11410. * POINT_CONVERSION_UNCOMPRESSED,
  11411. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11412. */
  11413. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11414. {
  11415. if (key == NULL) {
  11416. WOLFSSL_MSG("Key passed in NULL");
  11417. }
  11418. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11419. #ifdef HAVE_COMP_KEY
  11420. || form == POINT_CONVERSION_COMPRESSED
  11421. #endif
  11422. ) {
  11423. key->form = (unsigned char)form;
  11424. }
  11425. else {
  11426. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11427. }
  11428. }
  11429. /* Get the EC group object that is in EC key.
  11430. *
  11431. * @param [in] key EC key.
  11432. * @return EC group object on success.
  11433. * @return NULL when key is NULL.
  11434. */
  11435. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11436. {
  11437. WOLFSSL_EC_GROUP* group = NULL;
  11438. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11439. if (key != NULL) {
  11440. group = key->group;
  11441. }
  11442. return group;
  11443. }
  11444. /* Set the group in WOLFSSL_EC_KEY
  11445. *
  11446. * @param [in, out] key EC key to update.
  11447. * @param [in] group EC group to copy.
  11448. * @return 1 on success
  11449. * @return 0 on failure.
  11450. */
  11451. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11452. {
  11453. int ret = 1;
  11454. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11455. /* Validate parameters. */
  11456. if ((key == NULL) || (group == NULL)) {
  11457. ret = 0;
  11458. }
  11459. if (ret == 1) {
  11460. /* Dispose of the current group. */
  11461. if (key->group != NULL) {
  11462. wolfSSL_EC_GROUP_free(key->group);
  11463. }
  11464. /* Duplicate the passed in group into EC key. */
  11465. key->group = wolfSSL_EC_GROUP_dup(group);
  11466. if (key->group == NULL) {
  11467. ret = 0;
  11468. }
  11469. }
  11470. return ret;
  11471. }
  11472. /* Get the BN object that is the private key in the EC key.
  11473. *
  11474. * @param [in] key EC key.
  11475. * @return BN object on success.
  11476. * @return NULL when key is NULL or private key is not set.
  11477. */
  11478. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11479. {
  11480. WOLFSSL_BIGNUM* priv_key = NULL;
  11481. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11482. /* Validate parameter. */
  11483. if (key == NULL) {
  11484. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11485. }
  11486. /* Only return private key if it is not 0. */
  11487. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11488. priv_key = key->priv_key;
  11489. }
  11490. return priv_key;
  11491. }
  11492. /* Sets the private key value into EC key.
  11493. *
  11494. * Return code compliant with OpenSSL.
  11495. *
  11496. * @param [in, out] key EC key to set.
  11497. * @param [in] priv_key Private key value in a BN.
  11498. * @return 1 on success
  11499. * @return 0 on failure.
  11500. */
  11501. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11502. const WOLFSSL_BIGNUM *priv_key)
  11503. {
  11504. int ret = 1;
  11505. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11506. /* Validate parameters. */
  11507. if ((key == NULL) || (priv_key == NULL)) {
  11508. WOLFSSL_MSG("Bad arguments");
  11509. ret = 0;
  11510. }
  11511. /* Check for obvious invalid values. */
  11512. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11513. wolfSSL_BN_is_one(priv_key)) {
  11514. WOLFSSL_MSG("Invalid private key value");
  11515. ret = 0;
  11516. }
  11517. if (ret == 1) {
  11518. /* Free key if previously set. */
  11519. if (key->priv_key != NULL) {
  11520. wolfSSL_BN_free(key->priv_key);
  11521. }
  11522. /* Duplicate the BN passed in. */
  11523. key->priv_key = wolfSSL_BN_dup(priv_key);
  11524. if (key->priv_key == NULL) {
  11525. WOLFSSL_MSG("key ecc priv key NULL");
  11526. ret = 0;
  11527. }
  11528. }
  11529. /* Set the external values into internal EC key. */
  11530. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11531. WOLFSSL_MSG("SetECKeyInternal failed");
  11532. /* Dispose of new private key on error. */
  11533. wolfSSL_BN_free(key->priv_key);
  11534. key->priv_key = NULL;
  11535. ret = 0;
  11536. }
  11537. return ret;
  11538. }
  11539. /* Get the public key EC point object that is in EC key.
  11540. *
  11541. * @param [in] key EC key.
  11542. * @return EC point object that is the public key on success.
  11543. * @return NULL when key is NULL.
  11544. */
  11545. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11546. {
  11547. WOLFSSL_EC_POINT* pub_key = NULL;
  11548. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11549. if (key != NULL) {
  11550. pub_key = key->pub_key;
  11551. }
  11552. return pub_key;
  11553. }
  11554. /*
  11555. * Return code compliant with OpenSSL.
  11556. *
  11557. * @param [in, out] key EC key.
  11558. * @param [in] pub Public key as an EC point.
  11559. * @return 1 on success
  11560. * @return 0 on failure.
  11561. */
  11562. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11563. const WOLFSSL_EC_POINT *pub)
  11564. {
  11565. int ret = 1;
  11566. ecc_point *pub_p = NULL;
  11567. ecc_point *key_p = NULL;
  11568. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11569. /* Validate parameters. */
  11570. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11571. (pub->internal == NULL)) {
  11572. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11573. ret = 0;
  11574. }
  11575. /* Ensure the internal EC key is set. */
  11576. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11577. WOLFSSL_MSG("SetECKeyInternal failed");
  11578. ret = 0;
  11579. }
  11580. /* Ensure the internal EC point of pub is setup. */
  11581. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11582. ret = 0;
  11583. }
  11584. if (ret == 1) {
  11585. /* Get the internal point of pub and the public key in key. */
  11586. pub_p = (ecc_point*)pub->internal;
  11587. key_p = (ecc_point*)key->pub_key->internal;
  11588. /* Create new point if required. */
  11589. if (key_p == NULL) {
  11590. key_p = wc_ecc_new_point();
  11591. key->pub_key->internal = (void*)key_p;
  11592. }
  11593. /* Check point available. */
  11594. if (key_p == NULL) {
  11595. WOLFSSL_MSG("key ecc point NULL");
  11596. ret = 0;
  11597. }
  11598. }
  11599. /* Copy the internal pub point into internal key point. */
  11600. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11601. WOLFSSL_MSG("ecc_copy_point failure");
  11602. ret = 0;
  11603. }
  11604. /* Copy the internal point data into external. */
  11605. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11606. WOLFSSL_MSG("SetECKeyInternal failed");
  11607. ret = 0;
  11608. }
  11609. /* Copy the internal key into external. */
  11610. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11611. WOLFSSL_MSG("SetECKeyInternal failed");
  11612. ret = 0;
  11613. }
  11614. if (ret == 1) {
  11615. /* Dump out the point and the key's public key for debug. */
  11616. wolfSSL_EC_POINT_dump("pub", pub);
  11617. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11618. }
  11619. return ret;
  11620. }
  11621. #ifndef NO_WOLFSSL_STUB
  11622. /* Set the ASN.1 encoding flag against the EC key.
  11623. *
  11624. * No implementation as only named curves supported for encoding.
  11625. *
  11626. * @param [in, out] key EC key.
  11627. * @param [in] flag ASN.1 flag to set. Valid values:
  11628. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11629. */
  11630. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11631. {
  11632. (void)key;
  11633. (void)asn1_flag;
  11634. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11635. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11636. }
  11637. #endif
  11638. /*
  11639. * EC key generate key APIs
  11640. */
  11641. /* Generate an EC key.
  11642. *
  11643. * Uses the internal curve index set in the EC key or the default.
  11644. *
  11645. * @param [in, out] key EC key.
  11646. * @return 1 on success
  11647. * @return 0 on failure.
  11648. */
  11649. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11650. {
  11651. int res = 1;
  11652. int initTmpRng = 0;
  11653. WC_RNG* rng = NULL;
  11654. #ifdef WOLFSSL_SMALL_STACK
  11655. WC_RNG* tmpRng = NULL;
  11656. #else
  11657. WC_RNG tmpRng[1];
  11658. #endif
  11659. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11660. /* Validate parameters. */
  11661. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11662. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11663. res = 0;
  11664. }
  11665. if (res == 1) {
  11666. /* Check if we know which internal curve index to use. */
  11667. if (key->group->curve_idx < 0) {
  11668. /* Generate key using the default curve. */
  11669. key->group->curve_idx = ECC_CURVE_DEF;
  11670. }
  11671. /* Create a random number generator. */
  11672. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  11673. if (rng == NULL) {
  11674. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to set RNG");
  11675. res = 0;
  11676. }
  11677. }
  11678. if (res == 1) {
  11679. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  11680. * is 0 then pass ECC_CURVE_DEF as arg */
  11681. int eccEnum = key->group->curve_nid ?
  11682. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  11683. /* Get the internal EC key. */
  11684. ecc_key* ecKey = (ecc_key*)key->internal;
  11685. /* Make the key using internal API. */
  11686. int ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  11687. #if defined(WOLFSSL_ASYNC_CRYPT)
  11688. /* Wait on asynchronouse operation. */
  11689. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  11690. #endif
  11691. if (ret != 0) {
  11692. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  11693. res = 0;
  11694. }
  11695. }
  11696. /* Dispose of local random number generator if initialized. */
  11697. if (initTmpRng) {
  11698. wc_FreeRng(rng);
  11699. #ifdef WOLFSSL_SMALL_STACK
  11700. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  11701. #endif
  11702. }
  11703. /* Set the external key from new internal key values. */
  11704. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11705. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  11706. res = 0;
  11707. }
  11708. return res;
  11709. }
  11710. /*
  11711. * EC key check key APIs
  11712. */
  11713. /* Check that the EC key is valid.
  11714. *
  11715. * @param [in] key EC key.
  11716. * @return 1 on valid.
  11717. * @return 0 on invalid or error.
  11718. */
  11719. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  11720. {
  11721. int ret = 1;
  11722. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  11723. /* Validate parameter. */
  11724. if ((key == NULL) || (key->internal == NULL)) {
  11725. WOLFSSL_MSG("Bad parameter");
  11726. ret = 0;
  11727. }
  11728. /* Set the external EC key values into internal if not already. */
  11729. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  11730. (WOLFSSL_EC_KEY*)key) != 1)) {
  11731. WOLFSSL_MSG("SetECKeyInternal failed");
  11732. ret = 0;
  11733. }
  11734. if (ret == 1) {
  11735. /* Have internal EC implementation check key. */
  11736. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  11737. }
  11738. return ret;
  11739. }
  11740. /* End EC_KEY */
  11741. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  11742. /* Get the supported, built-in EC curves
  11743. *
  11744. * @param [in, out] curves Pre-allocated list to put supported curves into.
  11745. * @param [in] len Maximum number of items to place in list.
  11746. * @return Number of built-in EC curves when curves is NULL or len is 0.
  11747. * @return Number of items placed in list otherwise.
  11748. */
  11749. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  11750. size_t len)
  11751. {
  11752. size_t i;
  11753. size_t cnt;
  11754. #ifdef HAVE_SELFTEST
  11755. /* Defined in ecc.h when available. */
  11756. size_t ecc_sets_count;
  11757. /* Count the pre-defined curves since global not available. */
  11758. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  11759. /* Do nothing. */
  11760. }
  11761. ecc_sets_count = i;
  11762. #endif
  11763. /* Assume we are going to return total count. */
  11764. cnt = ecc_sets_count;
  11765. /* Check we have a list that can hold data. */
  11766. if ((curves != NULL) && (len != 0)) {
  11767. /* Limit count to length of list. */
  11768. if (cnt > len) {
  11769. cnt = len;
  11770. }
  11771. /* Put in built-in EC curve nid and short name. */
  11772. for (i = 0; i < cnt; i++) {
  11773. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  11774. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  11775. }
  11776. }
  11777. return cnt;
  11778. }
  11779. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  11780. /* Start ECDSA_SIG */
  11781. /* Allocate a new ECDSA signature object.
  11782. *
  11783. * @return New, allocated ECDSA signature object on success.
  11784. * @return NULL on error.
  11785. */
  11786. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  11787. {
  11788. int err = 0;
  11789. WOLFSSL_ECDSA_SIG *sig;
  11790. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  11791. /* Allocate memory for ECDSA signature object. */
  11792. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  11793. DYNAMIC_TYPE_ECC);
  11794. if (sig == NULL) {
  11795. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  11796. err = 1;
  11797. }
  11798. if (!err) {
  11799. /* Set s to NULL in case of error. */
  11800. sig->s = NULL;
  11801. /* Allocate BN into r. */
  11802. sig->r = wolfSSL_BN_new();
  11803. if (sig->r == NULL) {
  11804. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  11805. err = 1;
  11806. }
  11807. }
  11808. if (!err) {
  11809. /* Allocate BN into s. */
  11810. sig->s = wolfSSL_BN_new();
  11811. if (sig->s == NULL) {
  11812. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  11813. err = 1;
  11814. }
  11815. }
  11816. if (err && (sig != NULL)) {
  11817. /* Dispose of allocated memory. */
  11818. wolfSSL_ECDSA_SIG_free(sig);
  11819. sig = NULL;
  11820. }
  11821. return sig;
  11822. }
  11823. /* Dispose of ECDSA signature object.
  11824. *
  11825. * Cannot use object after this call.
  11826. *
  11827. * @param [in] sig ECDSA signature object to free.
  11828. */
  11829. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  11830. {
  11831. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  11832. if (sig != NULL) {
  11833. /* Dispose of BNs allocated for r and s. */
  11834. wolfSSL_BN_free(sig->r);
  11835. wolfSSL_BN_free(sig->s);
  11836. /* Dispose of memory associated with ECDSA signature object. */
  11837. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  11838. }
  11839. }
  11840. /* Create an ECDSA signature from the DER encoding.
  11841. *
  11842. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  11843. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  11844. * On out, reference to buffer after signature data.
  11845. * @param [in] len Length of the data in the buffer. May be more than
  11846. * the length of the signature.
  11847. * @return ECDSA signature object on success.
  11848. * @return NULL on error.
  11849. */
  11850. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  11851. const unsigned char** pp, long len)
  11852. {
  11853. int err = 0;
  11854. /* ECDSA signature object to return. */
  11855. WOLFSSL_ECDSA_SIG *s = NULL;
  11856. /* Validate parameter. */
  11857. if (pp == NULL) {
  11858. err = 1;
  11859. }
  11860. if (!err) {
  11861. if (sig != NULL) {
  11862. /* Use the ECDSA signature object passed in. */
  11863. s = *sig;
  11864. }
  11865. if (s == NULL) {
  11866. /* No ECDSA signature object passed in - create a new one. */
  11867. s = wolfSSL_ECDSA_SIG_new();
  11868. if (s == NULL) {
  11869. err = 1;
  11870. }
  11871. }
  11872. }
  11873. if (!err) {
  11874. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  11875. mp_free((mp_int*)s->r->internal);
  11876. mp_free((mp_int*)s->s->internal);
  11877. /* Decode the signature into internal r and s fields. */
  11878. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  11879. (mp_int*)s->s->internal) != MP_OKAY) {
  11880. err = 1;
  11881. }
  11882. }
  11883. if (!err) {
  11884. /* Move pointer passed signature data successfully decoded. */
  11885. *pp += wolfssl_der_length(*pp, (int)len);
  11886. if (sig != NULL) {
  11887. /* Update reference to ECDSA signature object. */
  11888. *sig = s;
  11889. }
  11890. }
  11891. /* Dispose of newly allocated object on error. */
  11892. if (err) {
  11893. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  11894. wolfSSL_ECDSA_SIG_free(s);
  11895. }
  11896. /* Return NULL for object on error. */
  11897. s = NULL;
  11898. }
  11899. return s;
  11900. }
  11901. /* Encode the ECDSA signature as DER.
  11902. *
  11903. * @param [in] sig ECDSA signature object.
  11904. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  11905. * On out, reference to buffer after encoding.
  11906. * May be NULL or point to NULL in which case no encoding
  11907. * is done.
  11908. * @return Length of encoding on success.
  11909. * @return 0 on error.
  11910. */
  11911. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  11912. {
  11913. word32 len = 0;
  11914. /* Validate parameter. */
  11915. if (sig != NULL) {
  11916. /* ASN.1: SEQ + INT + INT
  11917. * ASN.1 Integer must be a positive value - prepend zero if number has
  11918. * top bit set.
  11919. */
  11920. /* Get total length of r including any prepended zero. */
  11921. word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) +
  11922. mp_unsigned_bin_size((mp_int*)sig->r->internal));
  11923. /* Get total length of s including any prepended zero. */
  11924. word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) +
  11925. mp_unsigned_bin_size((mp_int*)sig->s->internal));
  11926. /* Calculate length of data in sequence. */
  11927. len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen +
  11928. (word32)1 + ASN_LEN_SIZE(sLen) + sLen;
  11929. /* Add in the length of the SEQUENCE. */
  11930. len += (word32)1 + ASN_LEN_SIZE(len);
  11931. /* Encode only if there is a buffer to encode into. */
  11932. if ((pp != NULL) && (*pp != NULL)) {
  11933. /* Encode using the internal representations of r and s. */
  11934. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  11935. (mp_int*)sig->s->internal) != MP_OKAY) {
  11936. /* No bytes encoded. */
  11937. len = 0;
  11938. }
  11939. else {
  11940. /* Update pointer to after encoding. */
  11941. *pp += len;
  11942. }
  11943. }
  11944. }
  11945. return (int)len;
  11946. }
  11947. /* Get the pointer to the fields of the ECDSA signature.
  11948. *
  11949. * r and s untouched when sig is NULL.
  11950. *
  11951. * @param [in] sig ECDSA signature object.
  11952. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  11953. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  11954. */
  11955. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  11956. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  11957. {
  11958. /* Validate parameter. */
  11959. if (sig != NULL) {
  11960. /* Return the r BN when pointer to return through. */
  11961. if (r != NULL) {
  11962. *r = sig->r;
  11963. }
  11964. /* Return the s BN when pointer to return through. */
  11965. if (s != NULL) {
  11966. *s = sig->s;
  11967. }
  11968. }
  11969. }
  11970. /* Set the pointers to the fields of the ECDSA signature.
  11971. *
  11972. * @param [in, out] sig ECDSA signature object to update.
  11973. * @param [in] r R field of ECDSA signature as a BN.
  11974. * @param [in] s S field of ECDSA signature as a BN.
  11975. * @return 1 on success.
  11976. * @return 0 on error.
  11977. */
  11978. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  11979. WOLFSSL_BIGNUM* s)
  11980. {
  11981. int ret = 1;
  11982. /* Validate parameters. */
  11983. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  11984. ret = 0;
  11985. }
  11986. if (ret == 1) {
  11987. /* Dispose of old BN objects. */
  11988. wolfSSL_BN_free(sig->r);
  11989. wolfSSL_BN_free(sig->s);
  11990. /* Assign new BN objects. */
  11991. sig->r = r;
  11992. sig->s = s;
  11993. }
  11994. return ret;
  11995. }
  11996. /* End ECDSA_SIG */
  11997. /* Start ECDSA */
  11998. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  11999. *
  12000. * @param [in] key EC key.
  12001. * @return Size of DER encoded signature on success.
  12002. * @return 0 on error.
  12003. */
  12004. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  12005. {
  12006. int err = 0;
  12007. int len = 0;
  12008. const EC_GROUP *group = NULL;
  12009. int bits = 0;
  12010. /* Validate parameter. */
  12011. if (key == NULL) {
  12012. err = 1;
  12013. }
  12014. /* Get group from key to get order bits. */
  12015. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  12016. err = 1;
  12017. }
  12018. /* Get order bits of group. */
  12019. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  12020. /* Group is not set. */
  12021. err = 1;
  12022. }
  12023. if (!err) {
  12024. /* r and s are mod order. */
  12025. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  12026. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  12027. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  12028. bytes + bytes; /* max r and s in bytes */
  12029. }
  12030. return len;
  12031. }
  12032. /* Create ECDSA signature by signing digest with key.
  12033. *
  12034. * @param [in] dgst Digest to sign.
  12035. * @param [in] dLen Length of digest in bytes.
  12036. * @param [in] key EC key to sign with.
  12037. * @return ECDSA signature object on success.
  12038. * @return NULL on error.
  12039. */
  12040. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  12041. WOLFSSL_EC_KEY *key)
  12042. {
  12043. int err = 0;
  12044. WOLFSSL_ECDSA_SIG *sig = NULL;
  12045. #ifdef WOLFSSL_SMALL_STACK
  12046. byte* out = NULL;
  12047. #else
  12048. byte out[ECC_BUFSIZE];
  12049. #endif
  12050. unsigned int outLen = ECC_BUFSIZE;
  12051. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  12052. /* Validate parameters. */
  12053. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  12054. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  12055. err = 1;
  12056. }
  12057. /* Ensure internal EC key is set from external. */
  12058. if ((!err) && (key->inSet == 0)) {
  12059. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  12060. if (SetECKeyInternal(key) != 1) {
  12061. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  12062. err = 1;
  12063. }
  12064. }
  12065. #ifdef WOLFSSL_SMALL_STACK
  12066. if (!err) {
  12067. /* Allocate buffer to hold encoded signature. */
  12068. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12069. if (out == NULL) {
  12070. err = 1;
  12071. }
  12072. }
  12073. #endif
  12074. /* Sign the digest with the key to create encoded ECDSA signature. */
  12075. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  12076. err = 1;
  12077. }
  12078. if (!err) {
  12079. const byte* p = out;
  12080. /* Decode the ECDSA signature into a new object. */
  12081. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  12082. }
  12083. #ifdef WOLFSSL_SMALL_STACK
  12084. /* Dispose of any temporary dynamically allocated data. */
  12085. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12086. #endif
  12087. return sig;
  12088. }
  12089. /* Verify ECDSA signature in the object using digest and key.
  12090. *
  12091. * Return code compliant with OpenSSL.
  12092. *
  12093. * @param [in] dgst Digest to verify.
  12094. * @param [in] dLen Length of the digest in bytes.
  12095. * @param [in] sig ECDSA signature object.
  12096. * @param [in] key EC key containing public key.
  12097. * @return 1 when signature is valid.
  12098. * @return 0 when signature is invalid.
  12099. * @return -1 on error.
  12100. */
  12101. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  12102. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  12103. {
  12104. int ret = 1;
  12105. int verified = 0;
  12106. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  12107. byte signature[ECC_MAX_SIG_SIZE];
  12108. int signatureLen;
  12109. byte* p = signature;
  12110. #endif
  12111. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  12112. /* Validate parameters. */
  12113. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  12114. (key->internal == NULL)) {
  12115. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  12116. ret = -1;
  12117. }
  12118. /* Ensure internal EC key is set from external. */
  12119. if ((ret == 1) && (key->inSet == 0)) {
  12120. WOLFSSL_MSG("No EC key internal set, do it");
  12121. if (SetECKeyInternal(key) != 1) {
  12122. WOLFSSL_MSG("SetECKeyInternal failed");
  12123. ret = -1;
  12124. }
  12125. }
  12126. if (ret == 1) {
  12127. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12128. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  12129. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  12130. (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified,
  12131. (ecc_key *)key->internal) != MP_OKAY) {
  12132. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12133. ret = -1;
  12134. }
  12135. else if (verified == 0) {
  12136. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12137. ret = 0;
  12138. }
  12139. #else
  12140. signatureLen = i2d_ECDSA_SIG(sig, &p);
  12141. if (signatureLen > 0) {
  12142. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  12143. ret = wc_ecc_verify_hash(signature, signatureLen, dgst,
  12144. (word32)dLen, &verified, (ecc_key*)key->internal);
  12145. if (ret != MP_OKAY) {
  12146. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12147. ret = -1;
  12148. }
  12149. else if (verified == 0) {
  12150. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12151. ret = 0;
  12152. }
  12153. }
  12154. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12155. }
  12156. return ret;
  12157. }
  12158. /* Sign the digest with the key to produce a DER encode signature.
  12159. *
  12160. * @param [in] type Digest algorithm used to create digest. Unused.
  12161. * @param [in] digest Digest of the message to sign.
  12162. * @param [in] digestSz Size of the digest in bytes.
  12163. * @param [out] sig Buffer to hold signature.
  12164. * @param [in, out] sigSz On in, size of buffer in bytes.
  12165. * On out, size of signatre in bytes.
  12166. * @param [in] key EC key containing private key.
  12167. * @return 1 on success.
  12168. * @return 0 on error.
  12169. */
  12170. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12171. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12172. {
  12173. int ret = 1;
  12174. WC_RNG* rng = NULL;
  12175. #ifdef WOLFSSL_SMALL_STACK
  12176. WC_RNG* tmpRng = NULL;
  12177. #else
  12178. WC_RNG tmpRng[1];
  12179. #endif
  12180. int initTmpRng = 0;
  12181. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12182. /* Digest algorithm not used in DER encoding. */
  12183. (void)type;
  12184. /* Validate parameters. */
  12185. if (key == NULL) {
  12186. ret = 0;
  12187. }
  12188. if (ret == 1) {
  12189. /* Make an RNG - create local or get global. */
  12190. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12191. if (rng == NULL) {
  12192. ret = 0;
  12193. }
  12194. }
  12195. /* Sign the digest with the key using the RNG and put signature into buffer
  12196. * update sigSz to be actual length.
  12197. */
  12198. if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz,
  12199. rng, (ecc_key*)key->internal) != 0)) {
  12200. ret = 0;
  12201. }
  12202. if (initTmpRng) {
  12203. wc_FreeRng(rng);
  12204. #ifdef WOLFSSL_SMALL_STACK
  12205. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12206. #endif
  12207. }
  12208. return ret;
  12209. }
  12210. /* Verify the signature with the digest and key.
  12211. *
  12212. * @param [in] type Digest algorithm used to create digest. Unused.
  12213. * @param [in] digest Digest of the message to verify.
  12214. * @param [in] digestSz Size of the digest in bytes.
  12215. * @param [in] sig Buffer holding signature.
  12216. * @param [in] sigSz Size of signature data in bytes.
  12217. * @param [in] key EC key containing public key.
  12218. * @return 1 when signature is valid.
  12219. * @return 0 when signature is invalid or error.
  12220. */
  12221. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12222. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12223. {
  12224. int ret = 1;
  12225. int verify = 0;
  12226. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12227. /* Digest algorithm not used in DER encoding. */
  12228. (void)type;
  12229. /* Validate parameters. */
  12230. if (key == NULL) {
  12231. ret = 0;
  12232. }
  12233. /* Verify signature using digest and key. */
  12234. if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest,
  12235. (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) {
  12236. ret = 0;
  12237. }
  12238. /* When no error, verification may still have failed - check now. */
  12239. if ((ret == 1) && (verify != 1)) {
  12240. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12241. ret = 0;
  12242. }
  12243. return ret;
  12244. }
  12245. /* End ECDSA */
  12246. /* Start ECDH */
  12247. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12248. /* Compute the shared secret (key) using ECDH.
  12249. *
  12250. * KDF not supported.
  12251. *
  12252. * Return code compliant with OpenSSL.
  12253. *
  12254. * @param [out] out Buffer to hold key.
  12255. * @param [in] outLen Length of buffer in bytes.
  12256. * @param [in] pubKey Public key as an EC point.
  12257. * @param [in] privKey EC key holding a private key.
  12258. * @param [in] kdf Key derivation function to apply to secret.
  12259. * @return Length of computed key on success
  12260. * @return 0 on error.
  12261. */
  12262. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12263. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12264. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12265. {
  12266. int err = 0;
  12267. word32 len = 0;
  12268. ecc_key* key = NULL;
  12269. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12270. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12271. int setGlobalRNG = 0;
  12272. #endif
  12273. /* TODO: support using the KDF. */
  12274. (void)kdf;
  12275. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12276. /* Validate parameters. */
  12277. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12278. (privKey == NULL) || (privKey->internal == NULL)) {
  12279. WOLFSSL_MSG("Bad function arguments");
  12280. err = 1;
  12281. }
  12282. /* Ensure internal EC key is set from external. */
  12283. if ((!err) && (privKey->inSet == 0)) {
  12284. WOLFSSL_MSG("No EC key internal set, do it");
  12285. if (SetECKeyInternal(privKey) != 1) {
  12286. WOLFSSL_MSG("SetECKeyInternal failed");
  12287. err = 1;
  12288. }
  12289. }
  12290. if (!err) {
  12291. int ret;
  12292. /* Get the internal key. */
  12293. key = (ecc_key*)privKey->internal;
  12294. /* Set length into variable of type suitable for wolfSSL API. */
  12295. len = (word32)outLen;
  12296. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12297. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12298. /* An RNG is needed. */
  12299. if (key->rng == NULL) {
  12300. key->rng = wolfssl_make_global_rng();
  12301. /* RNG set and needs to be unset. */
  12302. setGlobalRNG = 1;
  12303. }
  12304. #endif
  12305. PRIVATE_KEY_UNLOCK();
  12306. /* Create secret using wolfSSL. */
  12307. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12308. (byte *)out, &len);
  12309. PRIVATE_KEY_LOCK();
  12310. if (ret != MP_OKAY) {
  12311. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12312. err = 1;
  12313. }
  12314. }
  12315. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12316. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12317. /* Remove global from key. */
  12318. if (setGlobalRNG) {
  12319. key->rng = NULL;
  12320. }
  12321. #endif
  12322. if (err) {
  12323. /* Make returned value zero. */
  12324. len = 0;
  12325. }
  12326. return (int)len;
  12327. }
  12328. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12329. /* End ECDH */
  12330. #endif /* OPENSSL_EXTRA */
  12331. #endif /* HAVE_ECC */
  12332. /*******************************************************************************
  12333. * END OF EC API
  12334. ******************************************************************************/
  12335. #endif /* !WOLFSSL_PK_INCLUDED */