pk.c 466 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349
  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. /*******************************************************************************
  46. * COMMON FUNCTIONS
  47. ******************************************************************************/
  48. /* Calculate the number of bytes require to represent a length value in ASN.
  49. *
  50. * @param [in] l Length value to use.
  51. * @return Number of bytes required to represent length value.
  52. */
  53. #define ASN_LEN_SIZE(l) \
  54. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  55. #if defined(OPENSSL_EXTRA)
  56. #ifndef NO_ASN
  57. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  58. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  59. /* Convert the PEM encoding in the buffer to DER.
  60. *
  61. * @param [in] pem Buffer containing PEM encoded data.
  62. * @param [in] pemSz Size of data in buffer in bytes.
  63. * @param [in] cb Password callback when PEM encrypted.
  64. * @param [in] pass NUL terminated string for passphrase when PEM
  65. * encrypted.
  66. * @param [in] keyType Type of key to match against PEM header/footer.
  67. * @param [out] keyFormat Format of key.
  68. * @param [out] der Buffer holding DER encoding.
  69. * @return Negative on failure.
  70. * @return Number of bytes consumed on success.
  71. */
  72. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  73. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  74. {
  75. #ifdef WOLFSSL_SMALL_STACK
  76. EncryptedInfo* info = NULL;
  77. #else
  78. EncryptedInfo info[1];
  79. #endif /* WOLFSSL_SMALL_STACK */
  80. wc_pem_password_cb* localCb = NULL;
  81. int ret = 0;
  82. if (cb != NULL) {
  83. localCb = cb;
  84. }
  85. else if (pass != NULL) {
  86. localCb = wolfSSL_PEM_def_callback;
  87. }
  88. #ifdef WOLFSSL_SMALL_STACK
  89. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  90. DYNAMIC_TYPE_ENCRYPTEDINFO);
  91. if (info == NULL) {
  92. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  93. ret = MEMORY_E;
  94. }
  95. #endif /* WOLFSSL_SMALL_STACK */
  96. if (ret == 0) {
  97. XMEMSET(info, 0, sizeof(EncryptedInfo));
  98. info->passwd_cb = localCb;
  99. info->passwd_userdata = pass;
  100. /* Do not strip PKCS8 header */
  101. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  102. info, keyFormat);
  103. if (ret < 0) {
  104. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  105. }
  106. }
  107. if (ret >= 0) {
  108. ret = (int)info->consumed;
  109. }
  110. #ifdef WOLFSSL_SMALL_STACK
  111. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  112. #endif
  113. return ret;
  114. }
  115. #endif
  116. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  117. #ifndef NO_BIO
  118. /* Read PEM data from a BIO and decode to DER in a new buffer.
  119. *
  120. * @param [in, out] bio BIO object to read with.
  121. * @param [in] cb Password callback when PEM encrypted.
  122. * @param [in] pass NUL terminated string for passphrase when PEM
  123. * encrypted.
  124. * @param [in] keyType Type of key to match against PEM header/footer.
  125. * @param [out] keyFormat Format of key.
  126. * @param [out] der Buffer holding DER encoding.
  127. * @return Negative on failure.
  128. * @return Number of bytes consumed on success.
  129. */
  130. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  131. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  132. {
  133. int ret;
  134. char* mem = NULL;
  135. int memSz;
  136. int alloced = 0;
  137. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  138. if (ret == 0) {
  139. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  140. /* Write left over data back to BIO if not a file BIO */
  141. if ((ret > 0) && ((memSz - ret) > 0) &&
  142. (bio->type != WOLFSSL_BIO_FILE)) {
  143. int res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  144. if (res != memSz - ret) {
  145. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  146. if (res < 0) {
  147. ret = res;
  148. }
  149. else {
  150. ret = MEMORY_E;
  151. }
  152. }
  153. }
  154. if (alloced) {
  155. XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  156. }
  157. }
  158. return ret;
  159. }
  160. #endif /* !NO_BIO */
  161. #if !defined(NO_FILESYSTEM)
  162. /* Read PEM data from a file and decode to DER in a new buffer.
  163. *
  164. * @param [in] fp File pointer to read with.
  165. * @param [in] cb Password callback when PEM encrypted.
  166. * @param [in] pass NUL terminated string for passphrase when PEM
  167. * encrypted.
  168. * @param [in] keyType Type of key to match against PEM header/footer.
  169. * @param [out] keyFormat Format of key.
  170. * @param [out] der Buffer holding DER encoding.
  171. * @return Negative on failure.
  172. * @return Number of bytes consumed on success.
  173. */
  174. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  175. int keyType, int* keyFormat, DerBuffer** der)
  176. {
  177. int ret;
  178. char* mem = NULL;
  179. int memSz;
  180. ret = wolfssl_read_file(fp, &mem, &memSz);
  181. if (ret == 0) {
  182. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  183. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  184. }
  185. return ret;
  186. }
  187. #endif /* !NO_FILESYSTEM */
  188. #endif
  189. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) \
  190. || !defined(WOLFCRYPT_ONLY))
  191. /* Convert DER data to PEM in an allocated buffer.
  192. *
  193. * @param [in] der Buffer containing DER data.
  194. * @param [in] derSz Size of DER data in bytes.
  195. * @param [in] type Type of key being encoded.
  196. * @param [in] heap Heap hint for dynamic memory allocation.
  197. * @param [out] out Allocated buffer containing PEM.
  198. * @param [out] outSz Size of PEM encoding.
  199. * @return 1 on success.
  200. * @return 0 on error.
  201. */
  202. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  203. void* heap, byte** out, int* outSz)
  204. {
  205. int ret = 1;
  206. int pemSz;
  207. byte* pem = NULL;
  208. (void)heap;
  209. /* Convert DER to PEM - to get size. */
  210. pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
  211. if (pemSz < 0) {
  212. ret = 0;
  213. }
  214. if (ret == 1) {
  215. /* Allocate memory for PEM to be encoded into. */
  216. pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  217. if (pem == NULL) {
  218. ret = 0;
  219. }
  220. }
  221. /* Convert DER to PEM. */
  222. if ((ret == 1) && (wc_DerToPem(der, (word32)derSz, pem, (word32)pemSz,
  223. type) < 0)) {
  224. ret = 0;
  225. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  226. pem = NULL;
  227. }
  228. *out = pem;
  229. *outSz = pemSz;
  230. return ret;
  231. }
  232. #ifndef NO_BIO
  233. /* Write the DER data as PEM into BIO.
  234. *
  235. * @param [in] der Buffer containing DER data.
  236. * @param [in] derSz Size of DER data in bytes.
  237. * @param [in, out] bio BIO object to write with.
  238. * @param [in] type Type of key being encoded.
  239. * @return 1 on success.
  240. * @return 0 on error.
  241. */
  242. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  243. WOLFSSL_BIO* bio, int type)
  244. {
  245. int ret;
  246. int pemSz;
  247. byte* pem = NULL;
  248. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  249. if (ret == 1) {
  250. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  251. if (len != pemSz) {
  252. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  253. ret = 0;
  254. }
  255. }
  256. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  257. return ret;
  258. }
  259. #endif
  260. #endif
  261. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || \
  262. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  263. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  264. #if !defined(NO_FILESYSTEM)
  265. /* Write the DER data as PEM into file pointer.
  266. *
  267. * @param [in] der Buffer containing DER data.
  268. * @param [in] derSz Size of DER data in bytes.
  269. * @param [in] fp File pointer to write with.
  270. * @param [in] type Type of key being encoded.
  271. * @param [in] heap Heap hint for dynamic memory allocation.
  272. * @return 1 on success.
  273. * @return 0 on error.
  274. */
  275. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  276. XFILE fp, int type, void* heap)
  277. {
  278. int ret;
  279. int pemSz;
  280. byte* pem = NULL;
  281. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  282. if (ret == 1) {
  283. int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
  284. if (len != pemSz) {
  285. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  286. ret = 0;
  287. }
  288. }
  289. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  290. return ret;
  291. }
  292. #endif
  293. #endif
  294. #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
  295. /* Encrypt private key into PEM format.
  296. *
  297. * DER is encrypted in place.
  298. *
  299. * @param [in] der DER encoding of private key.
  300. * @param [in] derSz Size of DER in bytes.
  301. * @param [in] cipher EVP cipher.
  302. * @param [in] passwd Password to use with encryption.
  303. * @param [in] passedSz Size of password in bytes.
  304. * @param [out] cipherInfo PEM cipher information lines.
  305. * @param [in] maxDerSz Maximum size of DER buffer.
  306. * @return 1 on success.
  307. * @return 0 on error.
  308. */
  309. int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher,
  310. unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz)
  311. {
  312. int ret = 0;
  313. int paddingSz = 0;
  314. word32 idx;
  315. word32 cipherInfoSz;
  316. #ifdef WOLFSSL_SMALL_STACK
  317. EncryptedInfo* info = NULL;
  318. #else
  319. EncryptedInfo info[1];
  320. #endif
  321. WOLFSSL_ENTER("EncryptDerKey");
  322. /* Validate parameters. */
  323. if ((der == NULL) || (derSz == NULL) || (cipher == NULL) ||
  324. (passwd == NULL) || (cipherInfo == NULL)) {
  325. ret = BAD_FUNC_ARG;
  326. }
  327. #ifdef WOLFSSL_SMALL_STACK
  328. if (ret == 0) {
  329. /* Allocate encrypted info. */
  330. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  331. DYNAMIC_TYPE_ENCRYPTEDINFO);
  332. if (info == NULL) {
  333. WOLFSSL_MSG("malloc failed");
  334. ret = 0;
  335. }
  336. }
  337. #endif
  338. if (ret == 0) {
  339. /* Clear the encrypted info and set name. */
  340. XMEMSET(info, 0, sizeof(EncryptedInfo));
  341. XSTRNCPY(info->name, cipher, NAME_SZ - 1);
  342. info->name[NAME_SZ - 1] = '\0'; /* null term */
  343. /* Get encrypted info from name. */
  344. ret = wc_EncryptedInfoGet(info, info->name);
  345. if (ret != 0) {
  346. WOLFSSL_MSG("unsupported cipher");
  347. }
  348. }
  349. if (ret == 0) {
  350. /* Generate a random salt. */
  351. if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) {
  352. WOLFSSL_MSG("generate iv failed");
  353. ret = -1;
  354. }
  355. }
  356. if (ret == 0) {
  357. /* Calculate padding size - always a padding block. */
  358. paddingSz = info->ivSz - ((*derSz) % info->ivSz);
  359. /* Check der is big enough. */
  360. if (maxDerSz < (*derSz) + paddingSz) {
  361. WOLFSSL_MSG("not enough DER buffer allocated");
  362. ret = BAD_FUNC_ARG;
  363. }
  364. }
  365. if (ret == 0) {
  366. /* Set padding bytes to padding length. */
  367. XMEMSET(der + (*derSz), (byte)paddingSz, paddingSz);
  368. /* Add padding to DER size. */
  369. (*derSz) += (int)paddingSz;
  370. /* Encrypt DER buffer. */
  371. ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz, WC_MD5);
  372. if (ret != 0) {
  373. WOLFSSL_MSG("encrypt key failed");
  374. }
  375. }
  376. if (ret == 0) {
  377. /* Create cipher info : 'cipher_name,Salt(hex)' */
  378. cipherInfoSz = (word32)(2 * info->ivSz + XSTRLEN(info->name) + 2);
  379. /* Allocate memory for PEM encryption lines. */
  380. *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, DYNAMIC_TYPE_STRING);
  381. if (*cipherInfo == NULL) {
  382. WOLFSSL_MSG("malloc failed");
  383. ret = MEMORY_E;
  384. }
  385. }
  386. if (ret == 0) {
  387. /* Copy in name and add on comma. */
  388. XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz);
  389. XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz);
  390. /* Find end of string. */
  391. idx = (word32)XSTRLEN((char*)*cipherInfo);
  392. /* Calculate remaining bytes. */
  393. cipherInfoSz -= idx;
  394. /* Encode IV into PEM encryption lines. */
  395. ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo + idx,
  396. &cipherInfoSz);
  397. if (ret != 0) {
  398. WOLFSSL_MSG("Base16_Encode failed");
  399. XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  400. *cipherInfo = NULL;
  401. }
  402. }
  403. #ifdef WOLFSSL_SMALL_STACK
  404. /* Free dynamically allocated info. */
  405. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  406. #endif
  407. return ret == 0;
  408. }
  409. #endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */
  410. #if defined(WOLFSSL_KEY_GEN) && \
  411. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  412. (!defined(NO_RSA) || defined(HAVE_ECC))
  413. /* Encrypt the DER in PEM format.
  414. *
  415. * @param [in] der DER encoded private key.
  416. * @param [in] derSz Size of DER in bytes.
  417. * @param [in] cipher EVP cipher.
  418. * @param [in] passwd Password to use in encryption.
  419. * @param [in] passwdSz Size of password in bytes.
  420. * @param [in] type PEM type of write out.
  421. * @param [in] heap Dynamic memory hint.
  422. * @param [out] out Allocated buffer containing PEM encoding.
  423. * heap was NULL and dynamic type is DYNAMIC_TYPE_KEY.
  424. * @param [out] outSz Size of PEM encoding in bytes.
  425. * @return 1 on success.
  426. * @return 0 on failure.
  427. */
  428. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  429. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  430. void* heap, byte** out, int* outSz)
  431. {
  432. int ret = 1;
  433. byte* tmp = NULL;
  434. byte* cipherInfo = NULL;
  435. int pemSz = 0;
  436. /* Macro doesn't always use it. */
  437. (void)heap;
  438. /* Encrypt DER buffer if required. */
  439. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  440. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  441. byte *tmpBuf;
  442. /* Add space for padding. */
  443. tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
  444. DYNAMIC_TYPE_TMP_BUFFER);
  445. if (tmpBuf == NULL) {
  446. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  447. ret = 0; /* der buffer is free'd at the end of the function */
  448. }
  449. else {
  450. der = tmpBuf;
  451. /* Encrypt DER inline. */
  452. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  453. &cipherInfo, derSz + blockSz);
  454. if (ret != 1) {
  455. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  456. }
  457. }
  458. }
  459. if (ret == 1) {
  460. /* Calculate PEM encoding size. */
  461. pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
  462. if (pemSz <= 0) {
  463. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  464. ret = 0;
  465. }
  466. }
  467. if (ret == 1) {
  468. /* Allocate space for PEM encoding plus a NUL terminator. */
  469. tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
  470. if (tmp == NULL) {
  471. WOLFSSL_ERROR_MSG("malloc failed");
  472. ret = 0;
  473. }
  474. }
  475. if (ret == 1) {
  476. /* DER to PEM */
  477. pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
  478. cipherInfo, type);
  479. if (pemSz <= 0) {
  480. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  481. ret = 0;
  482. }
  483. }
  484. if (ret == 1) {
  485. /* NUL terminate string - PEM. */
  486. tmp[pemSz] = 0x00;
  487. /* Return allocated buffer and size. */
  488. *out = tmp;
  489. *outSz = pemSz;
  490. /* Don't free returning buffer. */
  491. tmp = NULL;
  492. }
  493. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  494. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  495. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  496. return ret;
  497. }
  498. #endif
  499. #endif /* !NO_ASN */
  500. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  501. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  502. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  503. /* Print the number bn in hex with name field and indentation indent to file fp.
  504. *
  505. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  506. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  507. *
  508. * @param [in] fp File pointer to write to.
  509. * @param [in] indent Number of spaces to prepend to each line.
  510. * @param [in] field Name of field.
  511. * @param [in] bn Big number to print.
  512. * @return 1 on success.
  513. * @return 0 on failure.
  514. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  515. * bn or NULL.
  516. */
  517. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  518. const WOLFSSL_BIGNUM* bn)
  519. {
  520. static const int HEX_INDENT = 4;
  521. static const int MAX_DIGITS_PER_LINE = 30;
  522. int ret = 1;
  523. int i = 0;
  524. char* buf = NULL;
  525. /* Internal function - assume parameters are valid. */
  526. /* Convert BN to hexadecimal character array (allocates buffer). */
  527. buf = wolfSSL_BN_bn2hex(bn);
  528. if (buf == NULL) {
  529. ret = 0;
  530. }
  531. if (ret == 1) {
  532. /* Print leading spaces, name and spaces before data. */
  533. if (indent > 0) {
  534. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  535. ret = 0;
  536. }
  537. }
  538. if (ret == 1) {
  539. if (XFPRINTF(fp, "%s:\n", field) < 0)
  540. ret = 0;
  541. }
  542. if (ret == 1) {
  543. if (indent > 0) {
  544. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  545. ret = 0;
  546. }
  547. }
  548. if (ret == 1) {
  549. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  550. ret = 0;
  551. }
  552. if (ret == 1) {
  553. /* Print first byte - should always exist. */
  554. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  555. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  556. ret = 0;
  557. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  558. ret = 0;
  559. }
  560. }
  561. if (ret == 1) {
  562. /* Print each hexadecimal character with byte separator. */
  563. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  564. /* Byte separator every two nibbles - one byte. */
  565. if (XFPRINTF(fp, ":") < 0) {
  566. ret = 0;
  567. break;
  568. }
  569. /* New line after every 15 bytes - 30 nibbles. */
  570. if (i % MAX_DIGITS_PER_LINE == 0) {
  571. if (XFPRINTF(fp, "\n") < 0) {
  572. ret = 0;
  573. break;
  574. }
  575. if (indent > 0) {
  576. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  577. ret = 0;
  578. break;
  579. }
  580. }
  581. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  582. ret = 0;
  583. break;
  584. }
  585. }
  586. /* Print two nibbles - one byte. */
  587. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  588. ret = 0;
  589. break;
  590. }
  591. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  592. ret = 0;
  593. break;
  594. }
  595. }
  596. /* Ensure on new line after data. */
  597. if (XFPRINTF(fp, "\n") < 0) {
  598. ret = 0;
  599. }
  600. }
  601. /* Dispose of any allocated character array. */
  602. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  603. return ret;
  604. }
  605. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  606. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  607. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA)
  608. /* snprintf() must be available */
  609. /* Maximum number of extra indent spaces on each line. */
  610. #define PRINT_NUM_MAX_INDENT 48
  611. /* Maximum size of a line containing a value. */
  612. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  613. /* Number of leading spaces on each line. */
  614. #define PRINT_NUM_INDENT_CNT 4
  615. /* Indent spaces for number lines. */
  616. #define PRINT_NUM_INDENT " "
  617. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  618. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  619. /* Print indent to BIO.
  620. *
  621. * @param [in] bio BIO object to write to.
  622. * @param [in] line Buffer to put characters to before writing to BIO.
  623. * @param [in] lineLen Length of buffer.
  624. * @return 1 on success.
  625. * @return 0 on failure.
  626. */
  627. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  628. int indent)
  629. {
  630. int ret = 1;
  631. if (indent > 0) {
  632. /* Print indent spaces. */
  633. int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
  634. if (len_wanted >= lineLen) {
  635. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  636. ret = 0;
  637. }
  638. else {
  639. /* Write indents string to BIO */
  640. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  641. ret = 0;
  642. }
  643. }
  644. }
  645. return ret;
  646. }
  647. /* Print out name, and value in decimal and hex to BIO.
  648. *
  649. * @param [in] bio BIO object to write to.
  650. * @param [in] value MP integer to write.
  651. * @param [in] name Name of value.
  652. * @param [in] indent Number of leading spaces before line.
  653. * @return 1 on success.
  654. * @return 0 on failure.
  655. */
  656. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  657. const char* name, int indent)
  658. {
  659. int ret = 1;
  660. int len;
  661. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  662. /* Get the length of hex encoded value. */
  663. len = mp_unsigned_bin_size(value);
  664. /* Value must no more than 32-bits - 4 bytes. */
  665. if ((len < 0) || (len > 4)) {
  666. WOLFSSL_ERROR_MSG("Error getting exponent size");
  667. ret = 0;
  668. }
  669. if (ret == 1) {
  670. /* Print any indent spaces. */
  671. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  672. }
  673. if (ret == 1) {
  674. /* Get 32-bits of value. */
  675. word32 v = (word32)value->dp[0];
  676. /* Print the line to the string. */
  677. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  678. v);
  679. if (len >= (int)sizeof(line)) {
  680. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  681. ret = 0;
  682. } else {
  683. /* Write string to BIO */
  684. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  685. ret = 0;
  686. }
  687. }
  688. }
  689. return ret;
  690. }
  691. /* Print out name and multi-precision number to BIO.
  692. *
  693. * @param [in] bio BIO object to write to.
  694. * @param [in] num MP integer to write.
  695. * @param [in] name Name of value.
  696. * @param [in] indent Number of leading spaces before each line.
  697. * @return 1 on success.
  698. * @return 0 on failure.
  699. */
  700. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  701. int indent)
  702. {
  703. int ret = 1;
  704. int rawLen = 0;
  705. byte* rawKey = NULL;
  706. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  707. int li = 0; /* Line index. */
  708. int i;
  709. /* Allocate a buffer to hold binary encoded data. */
  710. rawLen = mp_unsigned_bin_size(num);
  711. if (rawLen == 0) {
  712. WOLFSSL_ERROR_MSG("Invalid number");
  713. ret = 0;
  714. }
  715. if (ret == 1) {
  716. rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  717. if (rawKey == NULL) {
  718. WOLFSSL_ERROR_MSG("Memory allocation error");
  719. ret = 0;
  720. }
  721. }
  722. /* Encode number as big-endian byte array. */
  723. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  724. ret = 0;
  725. }
  726. if (ret == 1) {
  727. /* Print any indent spaces. */
  728. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  729. }
  730. if (ret == 1) {
  731. /* Print header string line to string. */
  732. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  733. if (li >= (int)sizeof(line)) {
  734. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  735. ret = 0;
  736. }
  737. else {
  738. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  739. ret = 0;
  740. }
  741. }
  742. }
  743. if (ret == 1) {
  744. /* Print any indent spaces. */
  745. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  746. }
  747. if (ret == 1) {
  748. /* Start first digit line with spaces.
  749. * Writing out zeros ensures number is a positive value. */
  750. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  751. mp_leading_bit(num) ? "00:" : "");
  752. if (li >= (int)sizeof(line)) {
  753. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  754. ret = 0;
  755. }
  756. }
  757. /* Put out each line of numbers. */
  758. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  759. /* Encode another byte as 2 hex digits and append colon. */
  760. int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
  761. "%02x:", rawKey[i]);
  762. /* Check if there was room -- if not, print the current line, not
  763. * including the newest octet.
  764. */
  765. if (len_wanted >= (int)sizeof(line) - li) {
  766. /* bump current octet to the next line. */
  767. --i;
  768. /* More bytes coming so add a line break. */
  769. line[li++] = '\n';
  770. /* Write out the line. */
  771. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  772. ret = 0;
  773. }
  774. if (ret == 1) {
  775. /* Print any indent spaces. */
  776. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  777. }
  778. /* Put the leading spaces on new line. */
  779. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  780. li = PRINT_NUM_INDENT_CNT;
  781. }
  782. else {
  783. li += len_wanted;
  784. }
  785. }
  786. if (ret == 1) {
  787. /* Put out last line - replace last colon with carriage return. */
  788. line[li-1] = '\n';
  789. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  790. ret = 0;
  791. }
  792. }
  793. /* Dispose of any allocated data. */
  794. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  795. return ret;
  796. }
  797. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA */
  798. #endif /* OPENSSL_EXTRA */
  799. #if !defined(NO_CERTS) || (defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || \
  800. (!defined(NO_DH) && defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || \
  801. defined(HAVE_ECC)))
  802. /* Uses the DER SEQUENCE to determine size of DER data.
  803. *
  804. * Outer SEQUENCE encapsulates all the DER encoding.
  805. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  806. *
  807. * @param [in] seq Buffer holding DER encoded sequence.
  808. * @param [in] len Length of data in buffer (may be larger than SEQ).
  809. * @return Size of complete DER encoding on success.
  810. * @return 0 on failure.
  811. */
  812. static int wolfssl_der_length(const unsigned char* seq, int len)
  813. {
  814. int ret = 0;
  815. word32 i = 0;
  816. /* Check it is a SEQUENCE and get the length of the underlying data.
  817. * i is updated to be after SEQUENCE header bytes.
  818. */
  819. if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
  820. /* Add SEQUENCE header length to underlying data length. */
  821. ret += (int)i;
  822. }
  823. return ret;
  824. }
  825. #endif
  826. /*******************************************************************************
  827. * START OF RSA API
  828. ******************************************************************************/
  829. #ifndef NO_RSA
  830. /*
  831. * RSA METHOD
  832. * Could be used to hold function pointers to implementations of RSA operations.
  833. */
  834. #if defined(OPENSSL_EXTRA)
  835. /* Return a blank RSA method and set the name and flags.
  836. *
  837. * Only one implementation of RSA operations.
  838. * name is duplicated.
  839. *
  840. * @param [in] name Name to use in method.
  841. * @param [in] flags Flags to set into method.
  842. * @return Newly allocated RSA method on success.
  843. * @return NULL on failure.
  844. */
  845. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  846. {
  847. WOLFSSL_RSA_METHOD* meth = NULL;
  848. int name_len = 0;
  849. int err;
  850. /* Validate name is not NULL. */
  851. err = (name == NULL);
  852. if (!err) {
  853. /* Allocate an RSA METHOD to return. */
  854. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  855. DYNAMIC_TYPE_OPENSSL);
  856. err = (meth == NULL);
  857. }
  858. if (!err) {
  859. XMEMSET(meth, 0, sizeof(*meth));
  860. meth->flags = flags;
  861. meth->dynamic = 1;
  862. name_len = (int)XSTRLEN(name);
  863. meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL,
  864. DYNAMIC_TYPE_OPENSSL);
  865. err = (meth->name == NULL);
  866. }
  867. if (!err) {
  868. XMEMCPY(meth->name, name, (size_t)(name_len + 1));
  869. }
  870. if (err) {
  871. /* meth->name won't be allocated on error. */
  872. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  873. meth = NULL;
  874. }
  875. return meth;
  876. }
  877. /* Default RSA method is one with wolfSSL name and no flags.
  878. *
  879. * @return Newly allocated wolfSSL RSA method on success.
  880. * @return NULL on failure.
  881. */
  882. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  883. {
  884. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  885. 0, /* No flags. */
  886. (char*)"wolfSSL RSA",
  887. 0 /* Static definition. */
  888. };
  889. return &wolfssl_rsa_meth;
  890. }
  891. /* Dispose of RSA method and allocated data.
  892. *
  893. * @param [in] meth RSA method to free.
  894. */
  895. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  896. {
  897. /* Free method if available and dynamically allocated. */
  898. if ((meth != NULL) && meth->dynamic) {
  899. /* Name was duplicated and must be freed. */
  900. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  901. /* Dispose of RSA method. */
  902. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  903. }
  904. }
  905. #ifndef NO_WOLFSSL_STUB
  906. /* Stub function for any RSA method setting function.
  907. *
  908. * Nothing is stored - not even flags or name.
  909. *
  910. * @param [in] meth RSA method.
  911. * @param [in] p A pointer.
  912. * @return 1 to indicate success.
  913. */
  914. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  915. {
  916. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  917. (void)meth;
  918. (void)p;
  919. return 1;
  920. }
  921. #endif /* !NO_WOLFSSL_STUB */
  922. #endif /* OPENSSL_EXTRA */
  923. /*
  924. * RSA constructor/deconstructor APIs
  925. */
  926. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  927. /* Dispose of RSA key and allocated data.
  928. *
  929. * Cannot use rsa after this call.
  930. *
  931. * @param [in] rsa RSA key to free.
  932. */
  933. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  934. {
  935. int doFree = 1;
  936. WOLFSSL_ENTER("wolfSSL_RSA_free");
  937. /* Validate parameter. */
  938. if (rsa == NULL) {
  939. doFree = 0;
  940. }
  941. if (doFree) {
  942. int err;
  943. /* Decrement reference count. */
  944. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  945. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  946. (void)err;
  947. #endif
  948. }
  949. if (doFree) {
  950. void* heap = rsa->heap;
  951. /* Dispose of allocated reference counting data. */
  952. wolfSSL_RefFree(&rsa->ref);
  953. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  954. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  955. #endif
  956. if (rsa->internal != NULL) {
  957. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  958. /* Check if RNG is owned before freeing it. */
  959. if (rsa->ownRng) {
  960. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  961. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  962. wc_FreeRng(rng);
  963. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  964. }
  965. /* RNG isn't freed by wolfCrypt RSA free. */
  966. }
  967. #endif
  968. /* Dispose of allocated data in wolfCrypt RSA key. */
  969. wc_FreeRsaKey((RsaKey*)rsa->internal);
  970. /* Dispose of memory for wolfCrypt RSA key. */
  971. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  972. }
  973. /* Dispose of external representation of RSA values. */
  974. wolfSSL_BN_clear_free(rsa->iqmp);
  975. wolfSSL_BN_clear_free(rsa->dmq1);
  976. wolfSSL_BN_clear_free(rsa->dmp1);
  977. wolfSSL_BN_clear_free(rsa->q);
  978. wolfSSL_BN_clear_free(rsa->p);
  979. wolfSSL_BN_clear_free(rsa->d);
  980. wolfSSL_BN_free(rsa->e);
  981. wolfSSL_BN_free(rsa->n);
  982. #if defined(OPENSSL_EXTRA)
  983. if (rsa->meth) {
  984. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  985. }
  986. #endif
  987. /* Set back to NULLs for safety. */
  988. ForceZero(rsa, sizeof(*rsa));
  989. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  990. (void)heap;
  991. }
  992. }
  993. /* Allocate and initialize a new RSA key.
  994. *
  995. * Not OpenSSL API.
  996. *
  997. * @param [in] heap Heap hint for dynamic memory allocation.
  998. * @param [in] devId Device identifier value.
  999. * @return RSA key on success.
  1000. * @return NULL on failure.
  1001. */
  1002. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  1003. {
  1004. WOLFSSL_RSA* rsa = NULL;
  1005. RsaKey* key = NULL;
  1006. int err = 0;
  1007. int rsaKeyInited = 0;
  1008. WOLFSSL_ENTER("wolfSSL_RSA_new");
  1009. /* Allocate memory for new wolfCrypt RSA key. */
  1010. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  1011. if (key == NULL) {
  1012. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  1013. err = 1;
  1014. }
  1015. if (!err) {
  1016. /* Allocate memory for new RSA key. */
  1017. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  1018. DYNAMIC_TYPE_RSA);
  1019. if (rsa == NULL) {
  1020. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  1021. err = 1;
  1022. }
  1023. }
  1024. if (!err) {
  1025. /* Clear all fields of RSA key. */
  1026. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  1027. /* Cache heap to use for all allocations. */
  1028. rsa->heap = heap;
  1029. #ifdef OPENSSL_EXTRA
  1030. /* Always have a method set. */
  1031. rsa->meth = wolfSSL_RSA_get_default_method();
  1032. #endif
  1033. /* Initialize reference counting. */
  1034. wolfSSL_RefInit(&rsa->ref, &err);
  1035. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  1036. }
  1037. if (!err) {
  1038. #endif
  1039. /* Initialize wolfCrypt RSA key. */
  1040. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  1041. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  1042. err = 1;
  1043. }
  1044. else {
  1045. rsaKeyInited = 1;
  1046. }
  1047. }
  1048. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  1049. if (!err) {
  1050. WC_RNG* rng;
  1051. /* Create a local RNG. */
  1052. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  1053. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  1054. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  1055. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  1056. rng = NULL;
  1057. }
  1058. rsa->ownRng = 1;
  1059. if (rng == NULL) {
  1060. /* Get the wolfSSL global RNG - not thread safe. */
  1061. rng = wolfssl_get_global_rng();
  1062. rsa->ownRng = 0;
  1063. }
  1064. if (rng == NULL) {
  1065. /* Couldn't create global either. */
  1066. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  1067. err = 1;
  1068. }
  1069. else {
  1070. /* Set the local or global RNG into the wolfCrypt RSA key. */
  1071. (void)wc_RsaSetRNG(key, rng);
  1072. /* Won't fail as key and rng are not NULL. */
  1073. }
  1074. }
  1075. #endif /* !HAVE_FIPS && WC_RSA_BLINDING */
  1076. if (!err) {
  1077. /* Set wolfCrypt RSA key into RSA key. */
  1078. rsa->internal = key;
  1079. /* Data from external RSA key has not been set into internal one. */
  1080. rsa->inSet = 0;
  1081. }
  1082. if (err) {
  1083. /* Dispose of any allocated data on error. */
  1084. /* No failure after RNG allocation - no need to free RNG. */
  1085. if (rsaKeyInited) {
  1086. wc_FreeRsaKey(key);
  1087. }
  1088. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  1089. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  1090. /* Return NULL. */
  1091. rsa = NULL;
  1092. }
  1093. return rsa;
  1094. }
  1095. /* Allocate and initialize a new RSA key.
  1096. *
  1097. * @return RSA key on success.
  1098. * @return NULL on failure.
  1099. */
  1100. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  1101. {
  1102. /* Call wolfSSL API to do work. */
  1103. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  1104. }
  1105. /* Increments ref count of RSA key.
  1106. *
  1107. * @param [in, out] rsa RSA key.
  1108. * @return 1 on success
  1109. * @return 0 on error
  1110. */
  1111. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  1112. {
  1113. int err = 0;
  1114. if (rsa != NULL) {
  1115. wolfSSL_RefInc(&rsa->ref, &err);
  1116. }
  1117. return !err;
  1118. }
  1119. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1120. #ifdef OPENSSL_EXTRA
  1121. #if defined(WOLFSSL_KEY_GEN)
  1122. /* Allocate a new RSA key and make it a copy.
  1123. *
  1124. * Encodes to and from DER to copy.
  1125. *
  1126. * @param [in] rsa RSA key to duplicate.
  1127. * @return RSA key on success.
  1128. * @return NULL on error.
  1129. */
  1130. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1131. {
  1132. WOLFSSL_RSA* ret = NULL;
  1133. int derSz = 0;
  1134. byte* derBuf = NULL;
  1135. int err;
  1136. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1137. err = (rsa == NULL);
  1138. if (!err) {
  1139. /* Create a new RSA key to return. */
  1140. ret = wolfSSL_RSA_new();
  1141. if (ret == NULL) {
  1142. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1143. err = 1;
  1144. }
  1145. }
  1146. if (!err) {
  1147. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1148. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1149. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1150. err = 1;
  1151. }
  1152. }
  1153. if (!err) {
  1154. /* Decode DER of the RSA public key into new key. */
  1155. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1156. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1157. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1158. err = 1;
  1159. }
  1160. }
  1161. /* Dispose of any allocated DER buffer. */
  1162. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1163. if (err) {
  1164. /* Disposes of any created RSA key - on error. */
  1165. wolfSSL_RSA_free(ret);
  1166. ret = NULL;
  1167. }
  1168. return ret;
  1169. }
  1170. /* wolfSSL_RSAPrivateKey_dup not supported */
  1171. #endif /* WOLFSSL_KEY_GEN */
  1172. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1173. void* heap);
  1174. /*
  1175. * RSA to/from bin APIs
  1176. */
  1177. /* Convert RSA public key data to internal.
  1178. *
  1179. * Creates new RSA key from the DER encoded RSA public key.
  1180. *
  1181. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1182. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1183. * @param [in] derSz Length of the data in the DER buffer.
  1184. * @return RSA key on success.
  1185. * @return NULL on failure.
  1186. */
  1187. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1188. const unsigned char **derBuf, long derSz)
  1189. {
  1190. WOLFSSL_RSA *rsa = NULL;
  1191. int err = 0;
  1192. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1193. /* Validate parameters. */
  1194. if (derBuf == NULL) {
  1195. WOLFSSL_ERROR_MSG("Bad argument");
  1196. err = 1;
  1197. }
  1198. /* Create a new RSA key to return. */
  1199. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1200. WOLFSSL_ERROR_MSG("RSA_new failed");
  1201. err = 1;
  1202. }
  1203. /* Decode RSA key from DER. */
  1204. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1205. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1206. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1207. err = 1;
  1208. }
  1209. if ((!err) && (out != NULL)) {
  1210. /* Return through parameter too. */
  1211. *out = rsa;
  1212. /* Move buffer on by the used amount. */
  1213. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1214. }
  1215. if (err) {
  1216. /* Dispose of any created RSA key. */
  1217. wolfSSL_RSA_free(rsa);
  1218. rsa = NULL;
  1219. }
  1220. return rsa;
  1221. }
  1222. /* Convert RSA private key data to internal.
  1223. *
  1224. * Create a new RSA key from the DER encoded RSA private key.
  1225. *
  1226. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1227. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1228. * @param [in] derSz Length of the data in the DER buffer.
  1229. * @return RSA key on success.
  1230. * @return NULL on failure.
  1231. */
  1232. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1233. const unsigned char **derBuf, long derSz)
  1234. {
  1235. WOLFSSL_RSA *rsa = NULL;
  1236. int err = 0;
  1237. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1238. /* Validate parameters. */
  1239. if (derBuf == NULL) {
  1240. WOLFSSL_ERROR_MSG("Bad argument");
  1241. err = 1;
  1242. }
  1243. /* Create a new RSA key to return. */
  1244. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1245. WOLFSSL_ERROR_MSG("RSA_new failed");
  1246. err = 1;
  1247. }
  1248. /* Decode RSA key from DER. */
  1249. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1250. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1251. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1252. err = 1;
  1253. }
  1254. if ((!err) && (out != NULL)) {
  1255. /* Return through parameter too. */
  1256. *out = rsa;
  1257. /* Move buffer on by the used amount. */
  1258. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1259. }
  1260. if (err) {
  1261. /* Dispose of any created RSA key. */
  1262. wolfSSL_RSA_free(rsa);
  1263. rsa = NULL;
  1264. }
  1265. return rsa;
  1266. }
  1267. /* Converts an internal RSA structure to DER format for the private key.
  1268. *
  1269. * If "pp" is null then buffer size only is returned.
  1270. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1271. * responsible for free'ing it.
  1272. *
  1273. * @param [in] rsa RSA key.
  1274. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1275. * May be NULL.
  1276. * On out, newly allocated buffer or pointer to byte after
  1277. * encoding in passed in buffer.
  1278. *
  1279. * @return Size of DER encoding on success
  1280. * @return BAD_FUNC_ARG when rsa is NULL.
  1281. * @return 0 on failure.
  1282. */
  1283. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1284. {
  1285. int ret;
  1286. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1287. /* Validate parameters. */
  1288. if (rsa == NULL) {
  1289. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1290. ret = BAD_FUNC_ARG;
  1291. }
  1292. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1293. * No heap hint as this gets returned to the user */
  1294. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1295. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1296. ret = 0;
  1297. }
  1298. /* Size of DER encoding. */
  1299. return ret;
  1300. }
  1301. /* Converts an internal RSA structure to DER format for the public key.
  1302. *
  1303. * If "pp" is null then buffer size only is returned.
  1304. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1305. * responsible for free'ing it.
  1306. *
  1307. * @param [in] rsa RSA key.
  1308. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1309. * May be NULL.
  1310. * On out, newly allocated buffer or pointer to byte after
  1311. * encoding in passed in buffer.
  1312. * @return Size of DER encoding on success
  1313. * @return BAD_FUNC_ARG when rsa is NULL.
  1314. * @return 0 on failure.
  1315. */
  1316. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1317. {
  1318. int ret;
  1319. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1320. /* check for bad functions arguments */
  1321. if (rsa == NULL) {
  1322. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1323. ret = BAD_FUNC_ARG;
  1324. }
  1325. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1326. * No heap hint as this gets returned to the user */
  1327. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1328. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1329. ret = 0;
  1330. }
  1331. return ret;
  1332. }
  1333. #endif /* OPENSSL_EXTRA */
  1334. /*
  1335. * RSA to/from BIO APIs
  1336. */
  1337. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1338. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1339. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1340. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_BIO)
  1341. /* Read DER data from a BIO.
  1342. *
  1343. * DER structures start with a constructed sequence. Use this to calculate the
  1344. * total length of the DER data.
  1345. *
  1346. * @param [in] bio BIO object to read from.
  1347. * @param [out] out Buffer holding DER encoding.
  1348. * @return Number of bytes to DER encoding on success.
  1349. * @return 0 on failure.
  1350. */
  1351. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1352. {
  1353. int err = 0;
  1354. unsigned char seq[MAX_SEQ_SZ];
  1355. unsigned char* der = NULL;
  1356. int derLen = 0;
  1357. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1358. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1359. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1360. err = 1;
  1361. }
  1362. /* Calculate complete DER encoding length. */
  1363. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1364. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1365. err = 1;
  1366. }
  1367. /* Allocate a buffer to read DER data into. */
  1368. if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap,
  1369. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1370. WOLFSSL_ERROR_MSG("Malloc failure");
  1371. err = 1;
  1372. }
  1373. if (!err) {
  1374. /* Calculate the unread amount. */
  1375. int len = derLen - (int)sizeof(seq);
  1376. /* Copy the previously read data into the buffer. */
  1377. XMEMCPY(der, seq, sizeof(seq));
  1378. /* Read rest of DER data from BIO. */
  1379. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1380. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1381. err = 1;
  1382. }
  1383. }
  1384. if (!err) {
  1385. /* Return buffer through parameter. */
  1386. *out = der;
  1387. }
  1388. if (err) {
  1389. /* Dispose of any allocated buffer on error. */
  1390. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1391. derLen = 0;
  1392. }
  1393. return derLen;
  1394. }
  1395. /* Reads the RSA private key data from a BIO to the internal form.
  1396. *
  1397. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1398. *
  1399. * @param [in] bio BIO object to read from.
  1400. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1401. * @return RSA key on success.
  1402. * @return NULL on failure.
  1403. */
  1404. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1405. {
  1406. WOLFSSL_RSA* key = NULL;
  1407. unsigned char* der = NULL;
  1408. int derLen = 0;
  1409. int err;
  1410. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1411. /* Validate parameters. */
  1412. err = (bio == NULL);
  1413. /* Read just DER encoding from BIO - buffer allocated in call. */
  1414. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1415. err = 1;
  1416. }
  1417. if (!err) {
  1418. /* Keep der for call to deallocate. */
  1419. const unsigned char* cder = der;
  1420. /* Create an RSA key from the data from the BIO. */
  1421. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1422. err = (key == NULL);
  1423. }
  1424. if ((!err) && (out != NULL)) {
  1425. /* Return the created RSA key through the parameter. */
  1426. *out = key;
  1427. }
  1428. if (err) {
  1429. /* Dispose of created key on error. */
  1430. wolfSSL_RSA_free(key);
  1431. key = NULL;
  1432. }
  1433. /* Dispose of allocated data. */
  1434. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1435. return key;
  1436. }
  1437. #endif /* defined(WOLFSSL_KEY_GEN) && !NO_BIO */
  1438. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1439. /*
  1440. * RSA DER APIs
  1441. */
  1442. #ifdef OPENSSL_EXTRA
  1443. /* Create a DER encoding of key.
  1444. *
  1445. * Not OpenSSL API.
  1446. *
  1447. * @param [in] rsa RSA key.
  1448. * @param [out] outBuf Allocated buffer containing DER encoding.
  1449. * May be NULL.
  1450. * @param [in] publicKey Whether to encode as public key.
  1451. * @param [in] heap Heap hint.
  1452. * @return Encoding size on success.
  1453. * @return Negative on failure.
  1454. */
  1455. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1456. void* heap)
  1457. {
  1458. byte* p = NULL;
  1459. int ret;
  1460. if (outBuf != NULL) {
  1461. p = *outBuf;
  1462. }
  1463. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1464. if ((ret > 0) && (p != NULL)) {
  1465. *outBuf = p;
  1466. }
  1467. return ret;
  1468. }
  1469. /* Create a DER encoding of key.
  1470. *
  1471. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1472. *
  1473. * @param [in] rsa RSA key.
  1474. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1475. * May be NULL.
  1476. * On out, newly allocated buffer or pointer to byte
  1477. * after encoding in passed in buffer.
  1478. * @param [in] publicKey Whether to encode as public key.
  1479. * @param [in] heap Heap hint.
  1480. * @return Encoding size on success.
  1481. * @return Negative on failure.
  1482. */
  1483. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1484. void* heap)
  1485. {
  1486. int ret = 1;
  1487. int derSz = 0;
  1488. byte* derBuf = NULL;
  1489. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1490. /* Unused if memory is disabled. */
  1491. (void)heap;
  1492. /* Validate parameters. */
  1493. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1494. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1495. ret = BAD_FUNC_ARG;
  1496. }
  1497. /* Push external RSA data into internal RSA key if not set. */
  1498. if ((ret == 1) && (!rsa->inSet)) {
  1499. ret = SetRsaInternal(rsa);
  1500. }
  1501. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1502. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1503. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1504. ret = BAD_FUNC_ARG;
  1505. }
  1506. if (ret == 1) {
  1507. if (publicKey) {
  1508. /* Calculate length of DER encoded RSA public key. */
  1509. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1510. if (derSz < 0) {
  1511. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1512. ret = derSz;
  1513. }
  1514. }
  1515. else {
  1516. /* Calculate length of DER encoded RSA private key. */
  1517. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1518. if (derSz < 0) {
  1519. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1520. ret = derSz;
  1521. }
  1522. }
  1523. }
  1524. if ((ret == 1) && (outBuf != NULL)) {
  1525. derBuf = *outBuf;
  1526. if (derBuf == NULL) {
  1527. /* Allocate buffer to hold DER encoded RSA key. */
  1528. derBuf = (byte*)XMALLOC((size_t)derSz, heap,
  1529. DYNAMIC_TYPE_TMP_BUFFER);
  1530. if (derBuf == NULL) {
  1531. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1532. ret = MEMORY_ERROR;
  1533. }
  1534. }
  1535. }
  1536. if ((ret == 1) && (outBuf != NULL)) {
  1537. if (publicKey > 0) {
  1538. /* RSA public key to DER. */
  1539. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf,
  1540. (word32)derSz);
  1541. }
  1542. else {
  1543. /* RSA private key to DER. */
  1544. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf,
  1545. (word32)derSz);
  1546. }
  1547. if (derSz < 0) {
  1548. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1549. ret = derSz;
  1550. }
  1551. else if ((*outBuf) != NULL) {
  1552. derBuf = NULL;
  1553. *outBuf += derSz;
  1554. }
  1555. else {
  1556. /* Return allocated buffer. */
  1557. *outBuf = derBuf;
  1558. }
  1559. }
  1560. if (ret == 1) {
  1561. /* Success - return DER encoding size. */
  1562. ret = derSz;
  1563. }
  1564. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1565. /* Not returning buffer, needs to be disposed of. */
  1566. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1567. }
  1568. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1569. return ret;
  1570. }
  1571. #endif /* OPENSSL_EXTRA */
  1572. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1573. /* Load the DER encoded private RSA key.
  1574. *
  1575. * Not OpenSSL API.
  1576. *
  1577. * @param [in] rsa RSA key.
  1578. * @param [in] derBuf Buffer holding DER encoding.
  1579. * @param [in] derSz Length of DER encoding.
  1580. * @return 1 on success.
  1581. * @return -1 on failure.
  1582. */
  1583. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1584. int derSz)
  1585. {
  1586. /* Call implementation that handles both private and public keys. */
  1587. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1588. }
  1589. /* Load the DER encoded public or private RSA key.
  1590. *
  1591. * Not OpenSSL API.
  1592. *
  1593. * @param [in] rsa RSA key.
  1594. * @param [in] derBuf Buffer holding DER encoding.
  1595. * @param [in] derSz Length of DER encoding.
  1596. * @param [in] opt Indicates public or private key.
  1597. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1598. * @return 1 on success.
  1599. * @return -1 on failure.
  1600. */
  1601. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1602. int derSz, int opt)
  1603. {
  1604. int ret = 1;
  1605. int res;
  1606. word32 idx = 0;
  1607. word32 algId;
  1608. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1609. /* Validate parameters. */
  1610. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1611. (derSz <= 0)) {
  1612. WOLFSSL_ERROR_MSG("Bad function arguments");
  1613. ret = -1;
  1614. }
  1615. if (ret == 1) {
  1616. rsa->pkcs8HeaderSz = 0;
  1617. /* Check if input buffer has PKCS8 header. In the case that it does not
  1618. * have a PKCS8 header then do not error out. */
  1619. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1620. &algId);
  1621. if (res > 0) {
  1622. /* Store size of PKCS#8 header for encoding. */
  1623. WOLFSSL_MSG("Found PKCS8 header");
  1624. rsa->pkcs8HeaderSz = (word16)idx;
  1625. }
  1626. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1627. else if (res != ASN_PARSE_E) {
  1628. /* Something went wrong while decoding. */
  1629. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1630. "header");
  1631. ret = -1;
  1632. }
  1633. }
  1634. if (ret == 1) {
  1635. /* Decode private or public key data. */
  1636. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1637. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1638. (word32)derSz);
  1639. }
  1640. else {
  1641. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1642. (word32)derSz);
  1643. }
  1644. /* Check for error. */
  1645. if (res < 0) {
  1646. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1647. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1648. }
  1649. else {
  1650. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1651. }
  1652. WOLFSSL_ERROR_VERBOSE(res);
  1653. ret = -1;
  1654. }
  1655. }
  1656. if (ret == 1) {
  1657. /* Set external RSA key data from wolfCrypt key. */
  1658. if (SetRsaExternal(rsa) != 1) {
  1659. ret = -1;
  1660. }
  1661. else {
  1662. rsa->inSet = 1;
  1663. }
  1664. }
  1665. return ret;
  1666. }
  1667. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1668. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1669. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1670. /* Load DER encoded data into WOLFSSL_RSA object.
  1671. *
  1672. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1673. *
  1674. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1675. * When rsa or *rsa is NULL a new object is created.
  1676. * When not NULL and *rsa is NULL then new object
  1677. * returned through pointer.
  1678. * @param [in] in DER encoded RSA key data.
  1679. * @param [in] inSz Size of DER encoded data in bytes.
  1680. * @param [in] opt Public or private key encoded in data. Valid values:
  1681. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1682. * @return NULL on failure.
  1683. * @return WOLFSSL_RSA object on success.
  1684. */
  1685. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1686. long inSz, int opt)
  1687. {
  1688. WOLFSSL_RSA* ret = NULL;
  1689. if ((rsa != NULL) && (*rsa != NULL)) {
  1690. ret = *rsa;
  1691. }
  1692. else {
  1693. ret = wolfSSL_RSA_new();
  1694. }
  1695. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1696. != 1)) {
  1697. if ((rsa == NULL) || (ret != *rsa)) {
  1698. wolfSSL_RSA_free(ret);
  1699. }
  1700. ret = NULL;
  1701. }
  1702. if ((rsa != NULL) && (*rsa == NULL)) {
  1703. *rsa = ret;
  1704. }
  1705. return ret;
  1706. }
  1707. #endif
  1708. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1709. /*
  1710. * RSA PEM APIs
  1711. */
  1712. #ifdef OPENSSL_EXTRA
  1713. #ifndef NO_BIO
  1714. #if defined(WOLFSSL_KEY_GEN)
  1715. /* Writes PEM encoding of an RSA public key to a BIO.
  1716. *
  1717. * @param [in] bio BIO object to write to.
  1718. * @param [in] rsa RSA key to write.
  1719. * @return 1 on success.
  1720. * @return 0 on failure.
  1721. */
  1722. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1723. {
  1724. int ret = 1;
  1725. int derSz = 0;
  1726. byte* derBuf = NULL;
  1727. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1728. /* Validate parameters. */
  1729. if ((bio == NULL) || (rsa == NULL)) {
  1730. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1731. return 0;
  1732. }
  1733. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1734. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1735. ret = 0;
  1736. }
  1737. if (derBuf == NULL) {
  1738. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1739. ret = 0;
  1740. }
  1741. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1742. PUBLICKEY_TYPE) != 1)) {
  1743. ret = 0;
  1744. }
  1745. /* Dispose of DER buffer. */
  1746. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1747. return ret;
  1748. }
  1749. #endif /* WOLFSSL_KEY_GEN */
  1750. #endif /* !NO_BIO */
  1751. #if defined(WOLFSSL_KEY_GEN)
  1752. #ifndef NO_FILESYSTEM
  1753. /* Writes PEM encoding of an RSA public key to a file pointer.
  1754. *
  1755. * @param [in] fp File pointer to write to.
  1756. * @param [in] rsa RSA key to write.
  1757. * @param [in] type PEM type to write out.
  1758. * @return 1 on success.
  1759. * @return 0 on failure.
  1760. */
  1761. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1762. int type)
  1763. {
  1764. int ret = 1;
  1765. int derSz;
  1766. byte* derBuf = NULL;
  1767. /* Validate parameters. */
  1768. if ((fp == XBADFILE) || (rsa == NULL)) {
  1769. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1770. return 0;
  1771. }
  1772. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1773. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1774. ret = 0;
  1775. }
  1776. if (derBuf == NULL) {
  1777. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1778. ret = 0;
  1779. }
  1780. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1781. rsa->heap) != 1)) {
  1782. ret = 0;
  1783. }
  1784. /* Dispose of DER buffer. */
  1785. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1786. return ret;
  1787. }
  1788. /* Writes PEM encoding of an RSA public key to a file pointer.
  1789. *
  1790. * Header/footer will contain: PUBLIC KEY
  1791. *
  1792. * @param [in] fp File pointer to write to.
  1793. * @param [in] rsa RSA key to write.
  1794. * @return 1 on success.
  1795. * @return 0 on failure.
  1796. */
  1797. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1798. {
  1799. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1800. }
  1801. /* Writes PEM encoding of an RSA public key to a file pointer.
  1802. *
  1803. * Header/footer will contain: RSA PUBLIC KEY
  1804. *
  1805. * @param [in] fp File pointer to write to.
  1806. * @param [in] rsa RSA key to write.
  1807. * @return 1 on success.
  1808. * @return 0 on failure.
  1809. */
  1810. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1811. {
  1812. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1813. }
  1814. #endif /* !NO_FILESYSTEM */
  1815. #endif /* WOLFSSL_KEY_GEN */
  1816. #ifndef NO_BIO
  1817. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1818. *
  1819. * @param [in] bio BIO object to read from.
  1820. * @param [out] out RSA key created.
  1821. * @param [in] cb Password callback when PEM encrypted.
  1822. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1823. * @return RSA key on success.
  1824. * @return NULL on failure.
  1825. */
  1826. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1827. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1828. {
  1829. WOLFSSL_RSA* rsa = NULL;
  1830. DerBuffer* der = NULL;
  1831. int keyFormat = 0;
  1832. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1833. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1834. &keyFormat, &der) >= 0)) {
  1835. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1836. WOLFSSL_RSA_LOAD_PUBLIC);
  1837. if (rsa == NULL) {
  1838. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1839. }
  1840. }
  1841. FreeDer(&der);
  1842. if ((out != NULL) && (rsa != NULL)) {
  1843. *out = rsa;
  1844. }
  1845. return rsa;
  1846. }
  1847. #endif /* !NO_BIO */
  1848. #ifndef NO_FILESYSTEM
  1849. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1850. *
  1851. * Header/footer should contain: PUBLIC KEY
  1852. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1853. *
  1854. * @param [in] fp File pointer to read from.
  1855. * @param [out] out RSA key created.
  1856. * @param [in] cb Password callback when PEM encrypted.
  1857. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1858. * @return RSA key on success.
  1859. * @return NULL on failure.
  1860. */
  1861. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1862. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1863. {
  1864. WOLFSSL_RSA* rsa = NULL;
  1865. DerBuffer* der = NULL;
  1866. int keyFormat = 0;
  1867. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1868. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1869. &keyFormat, &der) >= 0)) {
  1870. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1871. WOLFSSL_RSA_LOAD_PUBLIC);
  1872. if (rsa == NULL) {
  1873. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1874. }
  1875. }
  1876. FreeDer(&der);
  1877. if ((out != NULL) && (rsa != NULL)) {
  1878. *out = rsa;
  1879. }
  1880. return rsa;
  1881. }
  1882. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1883. *
  1884. * Header/footer should contain: RSA PUBLIC KEY
  1885. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1886. *
  1887. * @param [in] fp File pointer to read from.
  1888. * @param [out] rsa RSA key created.
  1889. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1890. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1891. * May be NULL.
  1892. * @return RSA key on success.
  1893. * @return NULL on failure.
  1894. */
  1895. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1896. wc_pem_password_cb* cb, void* pass)
  1897. {
  1898. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1899. }
  1900. #endif /* NO_FILESYSTEM */
  1901. #if defined(WOLFSSL_KEY_GEN) && \
  1902. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1903. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1904. *
  1905. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1906. *
  1907. * @param [in] rsa RSA key to write.
  1908. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1909. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1910. * @param [in] passwdSz Length of password string when PEM encrypted.
  1911. * @param [out] pem Allocated buffer with PEM encoding.
  1912. * @param [out] pLen Length of PEM encoding.
  1913. * @return 1 on success.
  1914. * @return 0 on failure.
  1915. */
  1916. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1917. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1918. {
  1919. int ret = 1;
  1920. byte* derBuf = NULL;
  1921. int derSz = 0;
  1922. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1923. /* Validate parameters. */
  1924. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1925. (rsa->internal == NULL)) {
  1926. WOLFSSL_ERROR_MSG("Bad function arguments");
  1927. ret = 0;
  1928. }
  1929. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1930. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1931. ret = 0;
  1932. }
  1933. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1934. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1935. rsa->heap)) < 0)) {
  1936. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1937. ret = 0;
  1938. }
  1939. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1940. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1941. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1942. ret = 0;
  1943. }
  1944. return ret;
  1945. }
  1946. #ifndef NO_BIO
  1947. /* Writes PEM encoding of an RSA private key to a BIO.
  1948. *
  1949. * @param [in] bio BIO object to write to.
  1950. * @param [in] rsa RSA key to write.
  1951. * @param [in] cipher Cipher to use when PEM encrypted.
  1952. * @param [in] passwd Password string when PEM encrypted.
  1953. * @param [in] len Length of password string when PEM encrypted.
  1954. * @param [in] cb Password callback to use when PEM encrypted.
  1955. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1956. * @return 1 on success.
  1957. * @return 0 on failure.
  1958. */
  1959. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1960. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1961. wc_pem_password_cb* cb, void* arg)
  1962. {
  1963. int ret = 1;
  1964. byte* pem = NULL;
  1965. int pLen = 0;
  1966. (void)cb;
  1967. (void)arg;
  1968. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1969. /* Validate parameters. */
  1970. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1971. WOLFSSL_ERROR_MSG("Bad function arguments");
  1972. ret = 0;
  1973. }
  1974. if (ret == 1) {
  1975. /* Write PEM to buffer that is allocated in the call. */
  1976. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1977. &pem, &pLen);
  1978. if (ret != 1) {
  1979. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1980. }
  1981. }
  1982. /* Write PEM to BIO. */
  1983. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  1984. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1985. ret = 0;
  1986. }
  1987. /* Dispose of any allocated PEM buffer. */
  1988. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1989. return ret;
  1990. }
  1991. #endif /* !NO_BIO */
  1992. #ifndef NO_FILESYSTEM
  1993. /* Writes PEM encoding of an RSA private key to a file pointer.
  1994. *
  1995. * TODO: Support use of the password callback and callback context.
  1996. *
  1997. * @param [in] fp File pointer to write to.
  1998. * @param [in] rsa RSA key to write.
  1999. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  2000. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  2001. * @param [in] passwdSz Length of password string when PEM encrypted.
  2002. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  2003. * @param [in] arg NUL terminated string for passphrase when PEM
  2004. * encrypted. Unused.
  2005. * @return 1 on success.
  2006. * @return 0 on failure.
  2007. */
  2008. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  2009. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  2010. wc_pem_password_cb *cb, void *arg)
  2011. {
  2012. int ret = 1;
  2013. byte* pem = NULL;
  2014. int pLen = 0;
  2015. (void)cb;
  2016. (void)arg;
  2017. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  2018. /* Validate parameters. */
  2019. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  2020. WOLFSSL_ERROR_MSG("Bad function arguments");
  2021. ret = 0;
  2022. }
  2023. if (ret == 1) {
  2024. /* Write PEM to buffer that is allocated in the call. */
  2025. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  2026. &pem, &pLen);
  2027. if (ret != 1) {
  2028. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  2029. }
  2030. }
  2031. /* Write PEM to file pointer. */
  2032. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  2033. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  2034. ret = 0;
  2035. }
  2036. /* Dispose of any allocated PEM buffer. */
  2037. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  2038. return ret;
  2039. }
  2040. #endif /* NO_FILESYSTEM */
  2041. #endif /* WOLFSSL_KEY_GEN && WOLFSSL_PEM_TO_DER */
  2042. #ifndef NO_BIO
  2043. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  2044. *
  2045. * @param [in] bio BIO object to read from.
  2046. * @param [out] out RSA key created.
  2047. * @param [in] cb Password callback when PEM encrypted.
  2048. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2049. * @return RSA key on success.
  2050. * @return NULL on failure.
  2051. */
  2052. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  2053. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  2054. {
  2055. WOLFSSL_RSA* rsa = NULL;
  2056. DerBuffer* der = NULL;
  2057. int keyFormat = 0;
  2058. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  2059. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  2060. &keyFormat, &der) >= 0)) {
  2061. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2062. WOLFSSL_RSA_LOAD_PRIVATE);
  2063. if (rsa == NULL) {
  2064. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2065. }
  2066. }
  2067. FreeDer(&der);
  2068. if ((out != NULL) && (rsa != NULL)) {
  2069. *out = rsa;
  2070. }
  2071. return rsa;
  2072. }
  2073. #endif /* !NO_BIO */
  2074. /* Create an RSA private key by reading the PEM encoded data from the file
  2075. * pointer.
  2076. *
  2077. * @param [in] fp File pointer to read from.
  2078. * @param [out] out RSA key created.
  2079. * @param [in] cb Password callback when PEM encrypted.
  2080. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2081. * @return RSA key on success.
  2082. * @return NULL on failure.
  2083. */
  2084. #ifndef NO_FILESYSTEM
  2085. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  2086. wc_pem_password_cb* cb, void* pass)
  2087. {
  2088. WOLFSSL_RSA* rsa = NULL;
  2089. DerBuffer* der = NULL;
  2090. int keyFormat = 0;
  2091. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  2092. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  2093. &keyFormat, &der) >= 0)) {
  2094. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2095. WOLFSSL_RSA_LOAD_PRIVATE);
  2096. if (rsa == NULL) {
  2097. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2098. }
  2099. }
  2100. FreeDer(&der);
  2101. if ((out != NULL) && (rsa != NULL)) {
  2102. *out = rsa;
  2103. }
  2104. return rsa;
  2105. }
  2106. #endif /* !NO_FILESYSTEM */
  2107. /*
  2108. * RSA print APIs
  2109. */
  2110. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  2111. !defined(NO_STDIO_FILESYSTEM)
  2112. /* Print an RSA key to a file pointer.
  2113. *
  2114. * @param [in] fp File pointer to write to.
  2115. * @param [in] rsa RSA key to write.
  2116. * @param [in] indent Number of spaces to prepend to each line.
  2117. * @return 1 on success.
  2118. * @return 0 on failure.
  2119. */
  2120. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2121. {
  2122. int ret = 1;
  2123. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2124. /* Validate parameters. */
  2125. if ((fp == XBADFILE) || (rsa == NULL)) {
  2126. ret = 0;
  2127. }
  2128. /* Set the external data from the wolfCrypt RSA key if not done. */
  2129. if ((ret == 1) && (!rsa->exSet)) {
  2130. ret = SetRsaExternal(rsa);
  2131. }
  2132. /* Get the key size from modulus if available. */
  2133. if ((ret == 1) && (rsa->n != NULL)) {
  2134. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2135. if (keySize == 0) {
  2136. ret = 0;
  2137. }
  2138. else {
  2139. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2140. ret = 0;
  2141. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2142. keySize) < 0)
  2143. ret = 0;
  2144. }
  2145. }
  2146. /* Print out any components available. */
  2147. if ((ret == 1) && (rsa->n != NULL)) {
  2148. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2149. }
  2150. if ((ret == 1) && (rsa->d != NULL)) {
  2151. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2152. }
  2153. if ((ret == 1) && (rsa->p != NULL)) {
  2154. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2155. }
  2156. if ((ret == 1) && (rsa->q != NULL)) {
  2157. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2158. }
  2159. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2160. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2161. }
  2162. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2163. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2164. }
  2165. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2166. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2167. }
  2168. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2169. return ret;
  2170. }
  2171. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2172. #if defined(XSNPRINTF) && !defined(NO_BIO)
  2173. /* snprintf() must be available */
  2174. /* Maximum size of a header line. */
  2175. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2176. /* Writes the human readable form of RSA to a BIO.
  2177. *
  2178. * @param [in] bio BIO object to write to.
  2179. * @param [in] rsa RSA key to write.
  2180. * @param [in] indent Number of spaces before each line.
  2181. * @return 1 on success.
  2182. * @return 0 on failure.
  2183. */
  2184. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2185. {
  2186. int ret = 1;
  2187. int sz = 0;
  2188. RsaKey* key = NULL;
  2189. char line[RSA_PRINT_MAX_HEADER_LINE];
  2190. int i = 0;
  2191. mp_int *num = NULL;
  2192. /* Header strings. */
  2193. const char *name[] = {
  2194. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2195. "Exponent1:", "Exponent2:", "Coefficient:"
  2196. };
  2197. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2198. /* Validate parameters. */
  2199. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2200. ret = -1;
  2201. }
  2202. if (ret == 1) {
  2203. key = (RsaKey*)rsa->internal;
  2204. /* Get size in bits of key for printing out. */
  2205. sz = wolfSSL_RSA_bits(rsa);
  2206. if (sz <= 0) {
  2207. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2208. ret = 0;
  2209. }
  2210. }
  2211. if (ret == 1) {
  2212. /* Print any indent spaces. */
  2213. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2214. }
  2215. if (ret == 1) {
  2216. /* Print header line. */
  2217. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2218. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2219. if (len >= (int)sizeof(line)) {
  2220. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2221. ret = 0;
  2222. }
  2223. else {
  2224. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2225. ret = 0;
  2226. }
  2227. }
  2228. }
  2229. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2230. /* Get mp_int for index. */
  2231. switch (i) {
  2232. case 0:
  2233. /* Print out modulus */
  2234. num = &key->n;
  2235. break;
  2236. case 1:
  2237. num = &key->e;
  2238. break;
  2239. case 2:
  2240. num = &key->d;
  2241. break;
  2242. case 3:
  2243. num = &key->p;
  2244. break;
  2245. case 4:
  2246. num = &key->q;
  2247. break;
  2248. case 5:
  2249. num = &key->dP;
  2250. break;
  2251. case 6:
  2252. num = &key->dQ;
  2253. break;
  2254. case 7:
  2255. num = &key->u;
  2256. break;
  2257. default:
  2258. WOLFSSL_ERROR_MSG("Bad index value");
  2259. }
  2260. if (i == 1) {
  2261. /* Print exponent as a 32-bit value. */
  2262. ret = wolfssl_print_value(bio, num, name[i], indent);
  2263. }
  2264. else if (!mp_iszero(num)) {
  2265. /* Print name and MP integer. */
  2266. ret = wolfssl_print_number(bio, num, name[i], indent);
  2267. }
  2268. }
  2269. return ret;
  2270. }
  2271. #endif /* XSNPRINTF && !NO_BIO */
  2272. #endif /* OPENSSL_EXTRA */
  2273. /*
  2274. * RSA get/set/test APIs
  2275. */
  2276. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2277. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2278. *
  2279. * @param [in, out] rsa RSA key.
  2280. * @return 1 on success.
  2281. * @return 0 on failure.
  2282. */
  2283. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2284. {
  2285. int ret = 1;
  2286. WOLFSSL_ENTER("SetRsaExternal");
  2287. /* Validate parameters. */
  2288. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2289. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2290. ret = -1;
  2291. }
  2292. if (ret == 1) {
  2293. RsaKey* key = (RsaKey*)rsa->internal;
  2294. /* Copy modulus. */
  2295. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2296. if (ret != 1) {
  2297. WOLFSSL_ERROR_MSG("rsa n error");
  2298. }
  2299. if (ret == 1) {
  2300. /* Copy public exponent. */
  2301. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2302. if (ret != 1) {
  2303. WOLFSSL_ERROR_MSG("rsa e error");
  2304. }
  2305. }
  2306. if (key->type == RSA_PRIVATE) {
  2307. if (ret == 1) {
  2308. /* Copy private exponent. */
  2309. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2310. if (ret != 1) {
  2311. WOLFSSL_ERROR_MSG("rsa d error");
  2312. }
  2313. }
  2314. if (ret == 1) {
  2315. /* Copy first prime. */
  2316. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2317. if (ret != 1) {
  2318. WOLFSSL_ERROR_MSG("rsa p error");
  2319. }
  2320. }
  2321. if (ret == 1) {
  2322. /* Copy second prime. */
  2323. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2324. if (ret != 1) {
  2325. WOLFSSL_ERROR_MSG("rsa q error");
  2326. }
  2327. }
  2328. #ifndef RSA_LOW_MEM
  2329. if (ret == 1) {
  2330. /* Copy d mod p-1. */
  2331. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2332. if (ret != 1) {
  2333. WOLFSSL_ERROR_MSG("rsa dP error");
  2334. }
  2335. }
  2336. if (ret == 1) {
  2337. /* Copy d mod q-1. */
  2338. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2339. if (ret != 1) {
  2340. WOLFSSL_ERROR_MSG("rsa dq error");
  2341. }
  2342. }
  2343. if (ret == 1) {
  2344. /* Copy 1/q mod p. */
  2345. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2346. if (ret != 1) {
  2347. WOLFSSL_ERROR_MSG("rsa u error");
  2348. }
  2349. }
  2350. #endif /* !RSA_LOW_MEM */
  2351. }
  2352. }
  2353. if (ret == 1) {
  2354. /* External values set. */
  2355. rsa->exSet = 1;
  2356. }
  2357. else {
  2358. /* Return 0 on failure. */
  2359. ret = 0;
  2360. }
  2361. return ret;
  2362. }
  2363. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2364. #ifdef OPENSSL_EXTRA
  2365. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2366. *
  2367. * @param [in, out] rsa RSA key.
  2368. * @return 1 on success.
  2369. * @return 0 on failure.
  2370. */
  2371. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2372. {
  2373. int ret = 1;
  2374. WOLFSSL_ENTER("SetRsaInternal");
  2375. /* Validate parameters. */
  2376. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2377. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2378. ret = -1;
  2379. }
  2380. if (ret == 1) {
  2381. RsaKey* key = (RsaKey*)rsa->internal;
  2382. /* Copy down modulus if available. */
  2383. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2384. WOLFSSL_ERROR_MSG("rsa n key error");
  2385. ret = -1;
  2386. }
  2387. /* Copy down public exponent if available. */
  2388. if ((ret == 1) && (rsa->e != NULL) &&
  2389. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2390. WOLFSSL_ERROR_MSG("rsa e key error");
  2391. ret = -1;
  2392. }
  2393. /* Enough numbers for public key */
  2394. key->type = RSA_PUBLIC;
  2395. /* Copy down private exponent if available. */
  2396. if ((ret == 1) && (rsa->d != NULL)) {
  2397. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2398. WOLFSSL_ERROR_MSG("rsa d key error");
  2399. ret = -1;
  2400. }
  2401. else {
  2402. /* Enough numbers for private key */
  2403. key->type = RSA_PRIVATE;
  2404. }
  2405. }
  2406. /* Copy down first prime if available. */
  2407. if ((ret == 1) && (rsa->p != NULL) &&
  2408. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2409. WOLFSSL_ERROR_MSG("rsa p key error");
  2410. ret = -1;
  2411. }
  2412. /* Copy down second prime if available. */
  2413. if ((ret == 1) && (rsa->q != NULL) &&
  2414. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2415. WOLFSSL_ERROR_MSG("rsa q key error");
  2416. ret = -1;
  2417. }
  2418. #ifndef RSA_LOW_MEM
  2419. /* Copy down d mod p-1 if available. */
  2420. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2421. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2422. WOLFSSL_ERROR_MSG("rsa dP key error");
  2423. ret = -1;
  2424. }
  2425. /* Copy down d mod q-1 if available. */
  2426. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2427. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2428. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2429. ret = -1;
  2430. }
  2431. /* Copy down 1/q mod p if available. */
  2432. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2433. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2434. WOLFSSL_ERROR_MSG("rsa u key error");
  2435. ret = -1;
  2436. }
  2437. #endif /* !RSA_LOW_MEM */
  2438. if (ret == 1) {
  2439. /* All available numbers have been set down. */
  2440. rsa->inSet = 1;
  2441. }
  2442. }
  2443. return ret;
  2444. }
  2445. /* Set the RSA method into object.
  2446. *
  2447. * @param [in, out] rsa RSA key.
  2448. * @param [in] meth RSA method.
  2449. * @return 1 always.
  2450. */
  2451. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2452. {
  2453. if (rsa != NULL) {
  2454. /* Store the method into object. */
  2455. rsa->meth = meth;
  2456. /* Copy over flags. */
  2457. rsa->flags = meth->flags;
  2458. }
  2459. /* OpenSSL always assumes it will work. */
  2460. return 1;
  2461. }
  2462. /* Get the RSA method from the RSA object.
  2463. *
  2464. * @param [in] rsa RSA key.
  2465. * @return RSA method on success.
  2466. * @return NULL when RSA is NULL or no method set.
  2467. */
  2468. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2469. {
  2470. return (rsa != NULL) ? rsa->meth : NULL;
  2471. }
  2472. /* Get the size in bytes of the RSA key.
  2473. *
  2474. * Return compliant with OpenSSL
  2475. *
  2476. * @param [in] rsa RSA key.
  2477. * @return RSA modulus size in bytes.
  2478. * @return 0 on error.
  2479. */
  2480. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2481. {
  2482. int ret = 0;
  2483. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2484. if (rsa != NULL) {
  2485. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2486. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2487. /* Get key size in bytes using wolfCrypt RSA key. */
  2488. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2489. }
  2490. }
  2491. return ret;
  2492. }
  2493. /* Get the size in bits of the RSA key.
  2494. *
  2495. * Uses external modulus field.
  2496. *
  2497. * @param [in] rsa RSA key.
  2498. * @return RSA modulus size in bits.
  2499. * @return 0 on error.
  2500. */
  2501. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2502. {
  2503. int ret = 0;
  2504. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2505. if (rsa != NULL) {
  2506. /* Get number of bits in external modulus. */
  2507. ret = wolfSSL_BN_num_bits(rsa->n);
  2508. }
  2509. return ret;
  2510. }
  2511. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2512. *
  2513. * Only for those that are not NULL parameters.
  2514. *
  2515. * @param [in] rsa RSA key.
  2516. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2517. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2518. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2519. */
  2520. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2521. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2522. const WOLFSSL_BIGNUM **iqmp)
  2523. {
  2524. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2525. /* For any parameters not NULL, return the BN from the key or NULL. */
  2526. if (dmp1 != NULL) {
  2527. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2528. }
  2529. if (dmq1 != NULL) {
  2530. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2531. }
  2532. if (iqmp != NULL) {
  2533. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2534. }
  2535. }
  2536. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2537. * into RSA key.
  2538. *
  2539. * If CRT parameter is NULL then there must be one in the RSA key already.
  2540. *
  2541. * @param [in, out] rsa RSA key.
  2542. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2543. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2544. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2545. * @return 1 on success.
  2546. * @return 0 on failure.
  2547. */
  2548. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2549. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2550. {
  2551. int ret = 1;
  2552. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2553. /* If a param is NULL in rsa then it must be non-NULL in the
  2554. * corresponding user input. */
  2555. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2556. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2557. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2558. WOLFSSL_ERROR_MSG("Bad parameters");
  2559. ret = 0;
  2560. }
  2561. if (ret == 1) {
  2562. /* Replace the BNs. */
  2563. if (dmp1 != NULL) {
  2564. wolfSSL_BN_clear_free(rsa->dmp1);
  2565. rsa->dmp1 = dmp1;
  2566. }
  2567. if (dmq1 != NULL) {
  2568. wolfSSL_BN_clear_free(rsa->dmq1);
  2569. rsa->dmq1 = dmq1;
  2570. }
  2571. if (iqmp != NULL) {
  2572. wolfSSL_BN_clear_free(rsa->iqmp);
  2573. rsa->iqmp = iqmp;
  2574. }
  2575. /* Set the values into the wolfCrypt RSA key. */
  2576. if (SetRsaInternal(rsa) != 1) {
  2577. if (dmp1 != NULL) {
  2578. rsa->dmp1 = NULL;
  2579. }
  2580. if (dmq1 != NULL) {
  2581. rsa->dmq1 = NULL;
  2582. }
  2583. if (iqmp != NULL) {
  2584. rsa->iqmp = NULL;
  2585. }
  2586. ret = 0;
  2587. }
  2588. }
  2589. return ret;
  2590. }
  2591. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2592. *
  2593. * @param [in] rsa RSA key.
  2594. * @param [out] p BN that is first prime. May be NULL.
  2595. * @param [out] q BN that is second prime. May be NULL.
  2596. */
  2597. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2598. const WOLFSSL_BIGNUM **q)
  2599. {
  2600. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2601. /* For any primes not NULL, return the BN from the key or NULL. */
  2602. if (p != NULL) {
  2603. *p = (rsa != NULL) ? rsa->p : NULL;
  2604. }
  2605. if (q != NULL) {
  2606. *q = (rsa != NULL) ? rsa->q : NULL;
  2607. }
  2608. }
  2609. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2610. *
  2611. * If factor parameter is NULL then there must be one in the RSA key already.
  2612. *
  2613. * @param [in, out] rsa RSA key.
  2614. * @param [in] p BN that is first prime. May be NULL.
  2615. * @param [in] q BN that is second prime. May be NULL.
  2616. * @return 1 on success.
  2617. * @return 0 on failure.
  2618. */
  2619. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2620. WOLFSSL_BIGNUM *q)
  2621. {
  2622. int ret = 1;
  2623. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2624. /* If a param is null in r then it must be non-null in the
  2625. * corresponding user input. */
  2626. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2627. ((rsa->q == NULL) && (q == NULL))) {
  2628. WOLFSSL_ERROR_MSG("Bad parameters");
  2629. ret = 0;
  2630. }
  2631. if (ret == 1) {
  2632. /* Replace the BNs. */
  2633. if (p != NULL) {
  2634. wolfSSL_BN_clear_free(rsa->p);
  2635. rsa->p = p;
  2636. }
  2637. if (q != NULL) {
  2638. wolfSSL_BN_clear_free(rsa->q);
  2639. rsa->q = q;
  2640. }
  2641. /* Set the values into the wolfCrypt RSA key. */
  2642. if (SetRsaInternal(rsa) != 1) {
  2643. if (p != NULL) {
  2644. rsa->p = NULL;
  2645. }
  2646. if (q != NULL) {
  2647. rsa->q = NULL;
  2648. }
  2649. ret = 0;
  2650. }
  2651. }
  2652. return ret;
  2653. }
  2654. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2655. * exponent, private exponent).
  2656. *
  2657. * @param [in] rsa RSA key.
  2658. * @param [out] n BN that is the modulus. May be NULL.
  2659. * @param [out] e BN that is the public exponent. May be NULL.
  2660. * @param [out] d BN that is the private exponent. May be NULL.
  2661. */
  2662. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2663. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2664. {
  2665. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2666. /* For any parameters not NULL, return the BN from the key or NULL. */
  2667. if (n != NULL) {
  2668. *n = (rsa != NULL) ? rsa->n : NULL;
  2669. }
  2670. if (e != NULL) {
  2671. *e = (rsa != NULL) ? rsa->e : NULL;
  2672. }
  2673. if (d != NULL) {
  2674. *d = (rsa != NULL) ? rsa->d : NULL;
  2675. }
  2676. }
  2677. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2678. * public exponent, private exponent).
  2679. *
  2680. * If BN parameter is NULL then there must be one in the RSA key already.
  2681. *
  2682. * @param [in,out] rsa RSA key.
  2683. * @param [in] n BN that is the modulus. May be NULL.
  2684. * @param [in] e BN that is the public exponent. May be NULL.
  2685. * @param [in] d BN that is the private exponent. May be NULL.
  2686. * @return 1 on success.
  2687. * @return 0 on failure.
  2688. */
  2689. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2690. WOLFSSL_BIGNUM *d)
  2691. {
  2692. int ret = 1;
  2693. /* If the fields n and e in r are NULL, the corresponding input
  2694. * parameters MUST be non-NULL for n and e. d may be
  2695. * left NULL (in case only the public key is used).
  2696. */
  2697. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2698. ((rsa->e == NULL) && (e == NULL))) {
  2699. ret = 0;
  2700. }
  2701. if (ret == 1) {
  2702. /* Replace the BNs. */
  2703. if (n != NULL) {
  2704. wolfSSL_BN_free(rsa->n);
  2705. rsa->n = n;
  2706. }
  2707. if (e != NULL) {
  2708. wolfSSL_BN_free(rsa->e);
  2709. rsa->e = e;
  2710. }
  2711. if (d != NULL) {
  2712. /* Private key is sensitive data. */
  2713. wolfSSL_BN_clear_free(rsa->d);
  2714. rsa->d = d;
  2715. }
  2716. /* Set the values into the wolfCrypt RSA key. */
  2717. if (SetRsaInternal(rsa) != 1) {
  2718. if (n != NULL) {
  2719. rsa->n = NULL;
  2720. }
  2721. if (e != NULL) {
  2722. rsa->e = NULL;
  2723. }
  2724. if (d != NULL) {
  2725. rsa->d = NULL;
  2726. }
  2727. ret = 0;
  2728. }
  2729. }
  2730. return ret;
  2731. }
  2732. /* Get the flags of the RSA key.
  2733. *
  2734. * @param [in] rsa RSA key.
  2735. * @return Flags set in RSA key on success.
  2736. * @return 0 when RSA key is NULL.
  2737. */
  2738. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2739. {
  2740. int ret = 0;
  2741. /* Get flags from the RSA key if available. */
  2742. if (rsa != NULL) {
  2743. ret = rsa->flags;
  2744. }
  2745. return ret;
  2746. }
  2747. /* Set the flags into the RSA key.
  2748. *
  2749. * @param [in, out] rsa RSA key.
  2750. * @param [in] flags Flags to set.
  2751. */
  2752. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2753. {
  2754. /* Add the flags into RSA key if available. */
  2755. if (rsa != NULL) {
  2756. rsa->flags |= flags;
  2757. }
  2758. }
  2759. /* Clear the flags in the RSA key.
  2760. *
  2761. * @param [in, out] rsa RSA key.
  2762. * @param [in] flags Flags to clear.
  2763. */
  2764. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2765. {
  2766. /* Clear the flags passed in that are on the RSA key if available. */
  2767. if (rsa != NULL) {
  2768. rsa->flags &= ~flags;
  2769. }
  2770. }
  2771. /* Test the flags in the RSA key.
  2772. *
  2773. * @param [in] rsa RSA key.
  2774. * @return Matching flags of RSA key on success.
  2775. * @return 0 when RSA key is NULL.
  2776. */
  2777. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2778. {
  2779. /* Return the flags passed in that are set on the RSA key if available. */
  2780. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2781. }
  2782. /* Get the extra data, by index, associated with the RSA key.
  2783. *
  2784. * @param [in] rsa RSA key.
  2785. * @param [in] idx Index of extra data.
  2786. * @return Extra data (anonymous type) on success.
  2787. * @return NULL on failure.
  2788. */
  2789. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2790. {
  2791. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2792. #ifdef HAVE_EX_DATA
  2793. return (rsa == NULL) ? NULL :
  2794. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2795. #else
  2796. (void)rsa;
  2797. (void)idx;
  2798. return NULL;
  2799. #endif
  2800. }
  2801. /* Set extra data against the RSA key at an index.
  2802. *
  2803. * @param [in, out] rsa RSA key.
  2804. * @param [in] idx Index set set extra data at.
  2805. * @param [in] data Extra data of anonymous type.
  2806. * @return 1 on success.
  2807. * @return 0 on failure.
  2808. */
  2809. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2810. {
  2811. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2812. #ifdef HAVE_EX_DATA
  2813. return (rsa == NULL) ? 0 :
  2814. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2815. #else
  2816. (void)rsa;
  2817. (void)idx;
  2818. (void)data;
  2819. return 0;
  2820. #endif
  2821. }
  2822. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2823. /* Set the extra data and cleanup callback against the RSA key at an index.
  2824. *
  2825. * Not OpenSSL API.
  2826. *
  2827. * @param [in, out] rsa RSA key.
  2828. * @param [in] idx Index set set extra data at.
  2829. * @param [in] data Extra data of anonymous type.
  2830. * @param [in] freeCb Callback function to free extra data.
  2831. * @return 1 on success.
  2832. * @return 0 on failure.
  2833. */
  2834. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2835. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2836. {
  2837. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2838. return (rsa == NULL) ? 0 :
  2839. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2840. freeCb);
  2841. }
  2842. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2843. /*
  2844. * RSA check key APIs
  2845. */
  2846. #ifdef WOLFSSL_RSA_KEY_CHECK
  2847. /* Check that the RSA key is valid using wolfCrypt.
  2848. *
  2849. * @param [in] rsa RSA key.
  2850. * @return 1 on success.
  2851. * @return 0 on failure.
  2852. */
  2853. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2854. {
  2855. int ret = 1;
  2856. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2857. /* Validate parameters. */
  2858. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2859. ret = 0;
  2860. }
  2861. /* Constant RSA - assume internal data has been set. */
  2862. /* Check wolfCrypt RSA key. */
  2863. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2864. ret = 0;
  2865. }
  2866. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2867. return ret;
  2868. }
  2869. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2870. /*
  2871. * RSA generate APIs
  2872. */
  2873. /* Get a random number generator associated with the RSA key.
  2874. *
  2875. * If not able, then get the global if possible.
  2876. * *tmpRng must not be an initialized RNG.
  2877. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2878. * associated with the wolfCrypt RSA key.
  2879. *
  2880. * @param [in] rsa RSA key.
  2881. * @param [out] tmpRng Temporary random number generator.
  2882. * @param [out] initTmpRng Temporary random number generator was initialized.
  2883. *
  2884. * @return A wolfCrypt RNG to use on success.
  2885. * @return NULL on error.
  2886. */
  2887. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2888. {
  2889. WC_RNG* rng = NULL;
  2890. int err = 0;
  2891. /* Check validity of parameters. */
  2892. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2893. err = 1;
  2894. }
  2895. if (!err) {
  2896. /* Haven't initialized any RNG passed through tmpRng. */
  2897. *initTmpRng = 0;
  2898. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2899. /* Use wolfCrypt RSA key's RNG if available/set. */
  2900. rng = ((RsaKey*)rsa->internal)->rng;
  2901. #endif
  2902. }
  2903. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2904. /* Make an RNG with tmpRng or get global. */
  2905. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2906. if ((rng != NULL) && *initTmpRng) {
  2907. *tmpRng = rng;
  2908. }
  2909. }
  2910. return rng;
  2911. }
  2912. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2913. *
  2914. * @param [in, out] rsa RSA key.
  2915. * @param [in] bits Number of bits that the modulus must have.
  2916. * @param [in] e A BN object holding the public exponent to use.
  2917. * @param [in] cb Status callback. Unused.
  2918. * @return 0 on success.
  2919. * @return wolfSSL native error code on error.
  2920. */
  2921. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2922. WOLFSSL_BIGNUM* e, void* cb)
  2923. {
  2924. #ifdef WOLFSSL_KEY_GEN
  2925. int ret = 0;
  2926. #ifdef WOLFSSL_SMALL_STACK
  2927. WC_RNG* tmpRng = NULL;
  2928. #else
  2929. WC_RNG _tmpRng[1];
  2930. WC_RNG* tmpRng = _tmpRng;
  2931. #endif
  2932. int initTmpRng = 0;
  2933. WC_RNG* rng = NULL;
  2934. #endif
  2935. (void)cb;
  2936. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2937. #ifdef WOLFSSL_KEY_GEN
  2938. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2939. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2940. if (rng == NULL) {
  2941. /* Something went wrong so return memory error. */
  2942. ret = MEMORY_E;
  2943. }
  2944. if (ret == 0) {
  2945. /* Generate an RSA key. */
  2946. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2947. (long)wolfSSL_BN_get_word(e), rng);
  2948. if (ret != MP_OKAY) {
  2949. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2950. }
  2951. }
  2952. if (ret == 0) {
  2953. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2954. ret = SetRsaExternal(rsa);
  2955. if (ret == 1) {
  2956. /* Internal matches external. */
  2957. rsa->inSet = 1;
  2958. /* Return success. */
  2959. ret = 0;
  2960. }
  2961. else {
  2962. /* Something went wrong so return memory error. */
  2963. ret = MEMORY_E;
  2964. }
  2965. }
  2966. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2967. if (initTmpRng) {
  2968. wc_FreeRng(tmpRng);
  2969. }
  2970. #ifdef WOLFSSL_SMALL_STACK
  2971. /* Dispose of any allocated RNG. */
  2972. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2973. #endif
  2974. return ret;
  2975. #else
  2976. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2977. (void)rsa;
  2978. (void)e;
  2979. (void)bits;
  2980. return NOT_COMPILED_IN;
  2981. #endif
  2982. }
  2983. /* Generate an RSA key that has the specified modulus size and public exponent.
  2984. *
  2985. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2986. * down to nearest multiple of 8. For example generating a key of size
  2987. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2988. *
  2989. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2990. * @param [in] e Public exponent to use i.e. 65537.
  2991. * @param [in] cb Status callback. Unused.
  2992. * @param [in] data Data to pass to status callback. Unused.
  2993. * @return A new RSA key on success.
  2994. * @return NULL on failure.
  2995. */
  2996. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2997. void(*cb)(int, int, void*), void* data)
  2998. {
  2999. WOLFSSL_RSA* rsa = NULL;
  3000. WOLFSSL_BIGNUM* bn = NULL;
  3001. int err = 0;
  3002. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  3003. (void)cb;
  3004. (void)data;
  3005. /* Validate bits. */
  3006. if (bits < 0) {
  3007. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  3008. err = 1;
  3009. }
  3010. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  3011. * longer values. */
  3012. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  3013. WOLFSSL_ERROR_MSG("Error creating big number");
  3014. err = 1;
  3015. }
  3016. /* Set public exponent. */
  3017. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  3018. WOLFSSL_ERROR_MSG("Error using e value");
  3019. err = 1;
  3020. }
  3021. /* Create an RSA key object to hold generated key. */
  3022. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  3023. WOLFSSL_ERROR_MSG("memory error");
  3024. err = 1;
  3025. }
  3026. while (!err) {
  3027. int ret;
  3028. /* Use wolfCrypt to generate RSA key. */
  3029. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  3030. #ifdef HAVE_FIPS
  3031. /* Keep trying if failed to find a prime. */
  3032. if (ret == PRIME_GEN_E) {
  3033. continue;
  3034. }
  3035. #endif
  3036. if (ret != WOLFSSL_ERROR_NONE) {
  3037. /* Unrecoverable error in generation. */
  3038. err = 1;
  3039. }
  3040. /* Done generating - unrecoverable error or success. */
  3041. break;
  3042. }
  3043. if (err) {
  3044. /* Dispose of RSA key object if generation didn't work. */
  3045. wolfSSL_RSA_free(rsa);
  3046. /* Returning NULL on error. */
  3047. rsa = NULL;
  3048. }
  3049. /* Dispose of the temporary BN used for the public exponent. */
  3050. wolfSSL_BN_free(bn);
  3051. return rsa;
  3052. }
  3053. /* Generate an RSA key that has the specified modulus size and public exponent.
  3054. *
  3055. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  3056. * down to nearest multiple of 8. For example generating a key of size
  3057. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  3058. *
  3059. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  3060. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  3061. * @param [in] cb Status callback. Unused.
  3062. * @return 1 on success.
  3063. * @return 0 on failure.
  3064. */
  3065. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  3066. void* cb)
  3067. {
  3068. int ret = 1;
  3069. /* Validate parameters. */
  3070. if ((rsa == NULL) || (rsa->internal == NULL)) {
  3071. WOLFSSL_ERROR_MSG("bad arguments");
  3072. ret = 0;
  3073. }
  3074. else {
  3075. for (;;) {
  3076. /* Use wolfCrypt to generate RSA key. */
  3077. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  3078. #ifdef HAVE_FIPS
  3079. /* Keep trying again if public key value didn't work. */
  3080. if (gen_ret == PRIME_GEN_E) {
  3081. continue;
  3082. }
  3083. #endif
  3084. if (gen_ret != WOLFSSL_ERROR_NONE) {
  3085. /* Unrecoverable error in generation. */
  3086. ret = 0;
  3087. }
  3088. /* Done generating - unrecoverable error or success. */
  3089. break;
  3090. }
  3091. }
  3092. return ret;
  3093. }
  3094. #endif /* OPENSSL_EXTRA */
  3095. /*
  3096. * RSA padding APIs
  3097. */
  3098. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  3099. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  3100. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  3101. /* Add PKCS#1 PSS padding to hash.
  3102. *
  3103. *
  3104. * +-----------+
  3105. * | M |
  3106. * +-----------+
  3107. * |
  3108. * V
  3109. * Hash
  3110. * |
  3111. * V
  3112. * +--------+----------+----------+
  3113. * M' = |Padding1| mHash | salt |
  3114. * +--------+----------+----------+
  3115. * |
  3116. * +--------+----------+ V
  3117. * DB = |Padding2|maskedseed| Hash
  3118. * +--------+----------+ |
  3119. * | |
  3120. * V | +--+
  3121. * xor <--- MGF <---| |bc|
  3122. * | | +--+
  3123. * | | |
  3124. * V V V
  3125. * +-------------------+----------+--+
  3126. * EM = | maskedDB |maskedseed|bc|
  3127. * +-------------------+----------+--+
  3128. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3129. *
  3130. * @param [in] rsa RSA key.
  3131. * @param [out] em Encoded message.
  3132. * @param [in[ mHash Message hash.
  3133. * @param [in] hashAlg Hash algorithm.
  3134. * @param [in] saltLen Length of salt to generate.
  3135. * @return 1 on success.
  3136. * @return 0 on failure.
  3137. */
  3138. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3139. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3140. {
  3141. int ret = 1;
  3142. enum wc_HashType hashType;
  3143. int hashLen = 0;
  3144. int emLen = 0;
  3145. int mgf = 0;
  3146. int initTmpRng = 0;
  3147. WC_RNG *rng = NULL;
  3148. #ifdef WOLFSSL_SMALL_STACK
  3149. WC_RNG* tmpRng = NULL;
  3150. #else
  3151. WC_RNG _tmpRng[1];
  3152. WC_RNG* tmpRng = _tmpRng;
  3153. #endif
  3154. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3155. /* Validate parameters. */
  3156. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3157. ret = 0;
  3158. }
  3159. if (ret == 1) {
  3160. /* Get/create an RNG. */
  3161. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3162. if (rng == NULL) {
  3163. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3164. ret = 0;
  3165. }
  3166. }
  3167. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3168. /* Set the external data from the wolfCrypt RSA key if not done. */
  3169. if ((ret == 1) && (!rsa->exSet)) {
  3170. ret = SetRsaExternal(rsa);
  3171. }
  3172. if (ret == 1) {
  3173. /* Get the wolfCrypt hash algorithm type. */
  3174. hashType = EvpMd2MacType(hashAlg);
  3175. if (hashType > WC_HASH_TYPE_MAX) {
  3176. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3177. ret = 0;
  3178. }
  3179. }
  3180. if (ret == 1) {
  3181. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3182. mgf = wc_hash2mgf(hashType);
  3183. if (mgf == WC_MGF1NONE) {
  3184. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3185. ret = 0;
  3186. }
  3187. }
  3188. if (ret == 1) {
  3189. /* Get the length of the hash output. */
  3190. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3191. if (hashLen < 0) {
  3192. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3193. ret = 0;
  3194. }
  3195. }
  3196. if (ret == 1) {
  3197. /* Get length of RSA key - encrypted message length. */
  3198. emLen = wolfSSL_RSA_size(rsa);
  3199. if (ret <= 0) {
  3200. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3201. ret = 0;
  3202. }
  3203. }
  3204. if (ret == 1) {
  3205. /* Calculate the salt length to use for special cases. */
  3206. /* TODO: use special case wolfCrypt values? */
  3207. switch (saltLen) {
  3208. /* Negative saltLen values are treated differently. */
  3209. case RSA_PSS_SALTLEN_DIGEST:
  3210. saltLen = hashLen;
  3211. break;
  3212. case RSA_PSS_SALTLEN_MAX_SIGN:
  3213. case RSA_PSS_SALTLEN_MAX:
  3214. #ifdef WOLFSSL_PSS_LONG_SALT
  3215. saltLen = emLen - hashLen - 2;
  3216. #else
  3217. saltLen = hashLen;
  3218. #endif
  3219. break;
  3220. default:
  3221. if (saltLen < 0) {
  3222. /* No other negative values implemented. */
  3223. WOLFSSL_ERROR_MSG("invalid saltLen");
  3224. ret = 0;
  3225. }
  3226. }
  3227. }
  3228. if (ret == 1) {
  3229. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3230. if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen,
  3231. RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0,
  3232. saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3233. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3234. ret = 0;
  3235. }
  3236. }
  3237. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3238. if (initTmpRng) {
  3239. wc_FreeRng(tmpRng);
  3240. }
  3241. #ifdef WOLFSSL_SMALL_STACK
  3242. /* Dispose of any allocated RNG. */
  3243. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3244. #endif
  3245. return ret;
  3246. }
  3247. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3248. *
  3249. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3250. *
  3251. * @param [in] rsa RSA key.
  3252. * @param [in[ mHash Message hash.
  3253. * @param [in] hashAlg Hash algorithm.
  3254. * @param [in] em Encoded message.
  3255. * @param [in] saltLen Length of salt to generate.
  3256. * @return 1 on success.
  3257. * @return 0 on failure.
  3258. */
  3259. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3260. const WOLFSSL_EVP_MD *hashAlg,
  3261. const unsigned char *em, int saltLen)
  3262. {
  3263. int ret = 1;
  3264. int hashLen = 0;
  3265. int mgf = 0;
  3266. int emLen = 0;
  3267. int mPrimeLen = 0;
  3268. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3269. byte *mPrime = NULL;
  3270. byte *buf = NULL;
  3271. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3272. /* Validate parameters. */
  3273. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3274. ret = 0;
  3275. }
  3276. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3277. /* Set the external data from the wolfCrypt RSA key if not done. */
  3278. if ((ret == 1) && (!rsa->exSet)) {
  3279. ret = SetRsaExternal(rsa);
  3280. }
  3281. if (ret == 1) {
  3282. /* Get hash length for hash algorithm. */
  3283. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3284. if (hashLen < 0) {
  3285. ret = 0;
  3286. }
  3287. }
  3288. if (ret == 1) {
  3289. /* Get length of RSA key - encrypted message length. */
  3290. emLen = wolfSSL_RSA_size(rsa);
  3291. if (emLen <= 0) {
  3292. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3293. ret = 0;
  3294. }
  3295. }
  3296. if (ret == 1) {
  3297. /* Calculate the salt length to use for special cases. */
  3298. switch (saltLen) {
  3299. /* Negative saltLen values are treated differently */
  3300. case RSA_PSS_SALTLEN_DIGEST:
  3301. saltLen = hashLen;
  3302. break;
  3303. case RSA_PSS_SALTLEN_AUTO:
  3304. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3305. saltLen = RSA_PSS_SALT_LEN_DISCOVER;
  3306. break;
  3307. #endif
  3308. case RSA_PSS_SALTLEN_MAX:
  3309. #ifdef WOLFSSL_PSS_LONG_SALT
  3310. saltLen = emLen - hashLen - 2;
  3311. #else
  3312. saltLen = hashLen;
  3313. #endif
  3314. break;
  3315. default:
  3316. if (saltLen < 0) {
  3317. /* No other negative values implemented. */
  3318. WOLFSSL_ERROR_MSG("invalid saltLen");
  3319. ret = 0;
  3320. }
  3321. }
  3322. }
  3323. if (ret == 1) {
  3324. /* Get the wolfCrypt hash algorithm type. */
  3325. hashType = EvpMd2MacType(hashAlg);
  3326. if (hashType > WC_HASH_TYPE_MAX) {
  3327. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3328. ret = 0;
  3329. }
  3330. }
  3331. if (ret == 1) {
  3332. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3333. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3334. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3335. ret = 0;
  3336. }
  3337. }
  3338. if (ret == 1) {
  3339. /* Allocate buffer to unpad inline with. */
  3340. buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3341. if (buf == NULL) {
  3342. WOLFSSL_ERROR_MSG("malloc error");
  3343. ret = 0;
  3344. }
  3345. }
  3346. if (ret == 1) {
  3347. /* Copy encrypted message to temp for inline unpadding. */
  3348. XMEMCPY(buf, em, (size_t)emLen);
  3349. /* Remove and verify the PSS padding. */
  3350. mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime,
  3351. RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3352. wolfSSL_BN_num_bits(rsa->n), NULL);
  3353. if (mPrimeLen < 0) {
  3354. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3355. ret = 0;
  3356. }
  3357. }
  3358. if (ret == 1) {
  3359. /* Verify the hash is correct. */
  3360. if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime,
  3361. (word32)mPrimeLen, hashType, saltLen,
  3362. wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3363. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3364. ret = 0;
  3365. }
  3366. }
  3367. /* Dispose of any allocated buffer. */
  3368. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3369. return ret;
  3370. }
  3371. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3372. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3373. * WOLFSSL_NGINX) */
  3374. /*
  3375. * RSA sign/verify APIs
  3376. */
  3377. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3378. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3379. #else
  3380. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3381. #endif
  3382. #if defined(OPENSSL_EXTRA)
  3383. /* Encode the message hash.
  3384. *
  3385. * Used by signing and verification.
  3386. *
  3387. * @param [in] hashAlg Hash algorithm OID.
  3388. * @param [in] hash Hash of message to encode for signing.
  3389. * @param [in] hLen Length of hash of message.
  3390. * @param [out] enc Encoded message hash.
  3391. * @param [out] encLen Length of encoded message hash.
  3392. * @param [in] padding Which padding scheme is being used.
  3393. * @return 1 on success.
  3394. * @return 0 on failure.
  3395. */
  3396. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3397. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3398. {
  3399. int ret = 1;
  3400. int hType = WC_HASH_TYPE_NONE;
  3401. /* Validate parameters. */
  3402. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3403. ret = 0;
  3404. }
  3405. if ((ret == 1) && (hashAlg != NID_undef) &&
  3406. (padding == RSA_PKCS1_PADDING)) {
  3407. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3408. hType = (int)nid2oid(hashAlg, oidHashType);
  3409. if (hType == -1) {
  3410. ret = 0;
  3411. }
  3412. }
  3413. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3414. /* PKCS#1.5 encoding. */
  3415. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3416. if (encSz == 0) {
  3417. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3418. ret = 0;
  3419. }
  3420. else {
  3421. *encLen = (unsigned int)encSz;
  3422. }
  3423. }
  3424. /* Other padding schemes require the hash as is. */
  3425. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3426. XMEMCPY(enc, hash, hLen);
  3427. *encLen = hLen;
  3428. }
  3429. return ret;
  3430. }
  3431. /* Sign the message hash using hash algorithm and RSA key.
  3432. *
  3433. * @param [in] hashAlg Hash algorithm OID.
  3434. * @param [in] hash Hash of message to encode for signing.
  3435. * @param [in] hLen Length of hash of message.
  3436. * @param [out] enc Encoded message hash.
  3437. * @param [out] encLen Length of encoded message hash.
  3438. * @param [in] rsa RSA key.
  3439. * @return 1 on success.
  3440. * @return 0 on failure.
  3441. */
  3442. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3443. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3444. {
  3445. if (sigLen != NULL) {
  3446. /* No size checking in this API */
  3447. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3448. }
  3449. /* flag is 1: output complete signature. */
  3450. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3451. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3452. }
  3453. /* Sign the message hash using hash algorithm and RSA key.
  3454. *
  3455. * Not OpenSSL API.
  3456. *
  3457. * @param [in] hashAlg Hash algorithm NID.
  3458. * @param [in] hash Hash of message to encode for signing.
  3459. * @param [in] hLen Length of hash of message.
  3460. * @param [out] enc Encoded message hash.
  3461. * @param [out] encLen Length of encoded message hash.
  3462. * @param [in] rsa RSA key.
  3463. * @param [in] flag When 1: Output encrypted signature.
  3464. * When 0: Output encoded hash.
  3465. * @return 1 on success.
  3466. * @return 0 on failure.
  3467. */
  3468. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3469. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3470. WOLFSSL_RSA* rsa, int flag)
  3471. {
  3472. int ret = 0;
  3473. if ((flag == 0) || (flag == 1)) {
  3474. if (sigLen != NULL) {
  3475. /* No size checking in this API */
  3476. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3477. }
  3478. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3479. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3480. }
  3481. return ret;
  3482. }
  3483. /**
  3484. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3485. *
  3486. * Not OpenSSL API.
  3487. *
  3488. * @param [in] hashAlg Hash NID
  3489. * @param [in] hash Message hash to sign.
  3490. * @param [in] mLen Length of message hash to sign.
  3491. * @param [out] sigRet Output buffer.
  3492. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3493. * On Output: length of data written to sigRet.
  3494. * @param [in] rsa RSA key used to sign the input.
  3495. * @param [in] flag 1: Output the signature.
  3496. * 0: Output the value that the unpadded signature
  3497. * should be compared to.
  3498. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3499. * RSA_PKCS1_PADDING are currently supported for
  3500. * signing.
  3501. * @return 1 on success.
  3502. * @return 0 on failure.
  3503. */
  3504. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3505. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3506. WOLFSSL_RSA* rsa, int flag, int padding)
  3507. {
  3508. int ret = 1;
  3509. word32 outLen = 0;
  3510. int signSz = 0;
  3511. WC_RNG* rng = NULL;
  3512. int initTmpRng = 0;
  3513. #ifdef WOLFSSL_SMALL_STACK
  3514. WC_RNG* tmpRng = NULL;
  3515. byte* encodedSig = NULL;
  3516. #else
  3517. WC_RNG _tmpRng[1];
  3518. WC_RNG* tmpRng = _tmpRng;
  3519. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3520. #endif
  3521. unsigned int encSz = 0;
  3522. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3523. if (flag == 0) {
  3524. /* Only encode message. */
  3525. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3526. padding);
  3527. }
  3528. /* Validate parameters. */
  3529. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3530. WOLFSSL_ERROR_MSG("Bad function arguments");
  3531. ret = 0;
  3532. }
  3533. /* Set wolfCrypt RSA key data from external if not already done. */
  3534. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3535. ret = 0;
  3536. }
  3537. if (ret == 1) {
  3538. /* Get the maximum signature length. */
  3539. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3540. /* Check not an error return. */
  3541. if (outLen == 0) {
  3542. WOLFSSL_ERROR_MSG("Bad RSA size");
  3543. ret = 0;
  3544. }
  3545. /* Check signature buffer is big enough. */
  3546. else if (outLen > *sigLen) {
  3547. WOLFSSL_ERROR_MSG("Output buffer too small");
  3548. ret = 0;
  3549. }
  3550. }
  3551. #ifdef WOLFSSL_SMALL_STACK
  3552. if (ret == 1) {
  3553. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3554. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3555. DYNAMIC_TYPE_SIGNATURE);
  3556. if (encodedSig == NULL) {
  3557. ret = 0;
  3558. }
  3559. }
  3560. #endif
  3561. if (ret == 1) {
  3562. /* Get/create an RNG. */
  3563. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3564. if (rng == NULL) {
  3565. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3566. ret = 0;
  3567. }
  3568. }
  3569. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3570. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3571. &encSz, padding) == 0)) {
  3572. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3573. ret = 0;
  3574. }
  3575. if (ret == 1) {
  3576. switch (padding) {
  3577. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3578. case RSA_NO_PADDING:
  3579. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3580. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3581. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3582. ret = 0;
  3583. }
  3584. break;
  3585. #endif
  3586. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3587. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3588. case RSA_PKCS1_PSS_PADDING:
  3589. {
  3590. enum wc_HashType hType =
  3591. wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3592. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3593. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3594. "OpenSSL uses max length by default.");
  3595. #endif
  3596. /* Create RSA PSS signature. */
  3597. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3598. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3599. (RsaKey*)rsa->internal, rng)) <= 0) {
  3600. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3601. ret = 0;
  3602. }
  3603. break;
  3604. }
  3605. #endif
  3606. #ifndef WC_NO_RSA_OAEP
  3607. case RSA_PKCS1_OAEP_PADDING:
  3608. /* Not a signature padding scheme. */
  3609. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3610. "signing");
  3611. ret = 0;
  3612. break;
  3613. #endif
  3614. case RSA_PKCS1_PADDING:
  3615. {
  3616. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3617. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3618. (RsaKey*)rsa->internal, rng)) <= 0) {
  3619. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3620. ret = 0;
  3621. }
  3622. break;
  3623. }
  3624. default:
  3625. WOLFSSL_ERROR_MSG("Unsupported padding");
  3626. ret = 0;
  3627. break;
  3628. }
  3629. }
  3630. if (ret == 1) {
  3631. /* Return the size of signature generated. */
  3632. *sigLen = (unsigned int)signSz;
  3633. }
  3634. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3635. if (initTmpRng) {
  3636. wc_FreeRng(tmpRng);
  3637. }
  3638. #ifdef WOLFSSL_SMALL_STACK
  3639. /* Dispose of any allocated RNG and encoded signature. */
  3640. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3641. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3642. #endif
  3643. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3644. return ret;
  3645. }
  3646. /**
  3647. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3648. *
  3649. * @param [in] hashAlg Hash NID
  3650. * @param [in] hash Message hash.
  3651. * @param [in] mLen Length of message hash.
  3652. * @param [in] sigRet Signature data.
  3653. * @param [in] sigLen Length of signature data.
  3654. * @param [in] rsa RSA key used to sign the input
  3655. * @return 1 on success.
  3656. * @return 0 on failure.
  3657. */
  3658. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3659. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3660. WOLFSSL_RSA* rsa)
  3661. {
  3662. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3663. RSA_PKCS1_PADDING);
  3664. }
  3665. /**
  3666. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3667. *
  3668. * Not OpenSSL API.
  3669. *
  3670. * @param [in] hashAlg Hash NID
  3671. * @param [in] hash Message hash.
  3672. * @param [in] mLen Length of message hash.
  3673. * @param [in] sigRet Signature data.
  3674. * @param [in] sigLen Length of signature data.
  3675. * @param [in] rsa RSA key used to sign the input
  3676. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3677. * RSA_PKCS1_PADDING are currently supported for
  3678. * signing.
  3679. * @return 1 on success.
  3680. * @return 0 on failure.
  3681. */
  3682. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3683. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3684. WOLFSSL_RSA* rsa, int padding)
  3685. {
  3686. int ret = 1;
  3687. #ifdef WOLFSSL_SMALL_STACK
  3688. unsigned char* encodedSig = NULL;
  3689. #else
  3690. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3691. #endif
  3692. unsigned char* sigDec = NULL;
  3693. unsigned int len = MAX_ENCODED_SIG_SZ;
  3694. int verLen = 0;
  3695. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3696. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3697. #endif
  3698. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3699. /* Validate parameters. */
  3700. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3701. WOLFSSL_ERROR_MSG("Bad function arguments");
  3702. ret = 0;
  3703. }
  3704. if (ret == 1) {
  3705. /* Allocate memory for decrypted signature. */
  3706. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3707. DYNAMIC_TYPE_TMP_BUFFER);
  3708. if (sigDec == NULL) {
  3709. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3710. ret = 0;
  3711. }
  3712. }
  3713. #ifdef WOLFSSL_SMALL_STACK
  3714. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3715. /* Allocate memory for encoded signature. */
  3716. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3717. DYNAMIC_TYPE_TMP_BUFFER);
  3718. if (encodedSig == NULL) {
  3719. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3720. ret = 0;
  3721. }
  3722. }
  3723. #endif
  3724. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3725. /* Make encoded signature to compare with decrypted signature. */
  3726. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3727. padding) <= 0) {
  3728. WOLFSSL_ERROR_MSG("Message Digest Error");
  3729. ret = 0;
  3730. }
  3731. }
  3732. if (ret == 1) {
  3733. /* Decrypt signature */
  3734. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3735. !defined(HAVE_SELFTEST)
  3736. hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3737. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3738. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3739. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3740. ret = 0;
  3741. }
  3742. #else
  3743. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3744. (RsaKey*)rsa->internal);
  3745. if (verLen < 0) {
  3746. ret = 0;
  3747. }
  3748. #endif
  3749. }
  3750. if (ret == 1) {
  3751. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3752. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3753. if (padding == RSA_PKCS1_PSS_PADDING) {
  3754. /* Check PSS padding is valid. */
  3755. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen,
  3756. hType, DEF_PSS_SALT_LEN,
  3757. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3758. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3759. ret = 0;
  3760. }
  3761. }
  3762. else
  3763. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3764. * FIPS_VERSION >= 5.1) */
  3765. /* Compare decrypted signature to encoded signature. */
  3766. if (((int)len != verLen) ||
  3767. (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) {
  3768. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3769. ret = 0;
  3770. }
  3771. }
  3772. /* Dispose of any allocated data. */
  3773. #ifdef WOLFSSL_SMALL_STACK
  3774. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3775. #endif
  3776. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3777. return ret;
  3778. }
  3779. /*
  3780. * RSA public/private encrypt/decrypt APIs
  3781. */
  3782. /* Encrypt with the RSA public key.
  3783. *
  3784. * Return compliant with OpenSSL.
  3785. *
  3786. * @param [in] len Length of data to encrypt.
  3787. * @param [in] from Data to encrypt.
  3788. * @param [out] to Encrypted data.
  3789. * @param [in] rsa RSA key.
  3790. * @param [in] padding Type of padding to place around plaintext.
  3791. * @return Size of encrypted data on success.
  3792. * @return -1 on failure.
  3793. */
  3794. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3795. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3796. {
  3797. int ret = 0;
  3798. int initTmpRng = 0;
  3799. WC_RNG *rng = NULL;
  3800. #ifdef WOLFSSL_SMALL_STACK
  3801. WC_RNG* tmpRng = NULL;
  3802. #else
  3803. WC_RNG _tmpRng[1];
  3804. WC_RNG* tmpRng = _tmpRng;
  3805. #endif
  3806. #if !defined(HAVE_FIPS)
  3807. int mgf = WC_MGF1NONE;
  3808. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3809. int pad_type = WC_RSA_NO_PAD;
  3810. #endif
  3811. int outLen = 0;
  3812. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3813. /* Validate parameters. */
  3814. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3815. (from == NULL)) {
  3816. WOLFSSL_ERROR_MSG("Bad function arguments");
  3817. ret = -1;
  3818. }
  3819. if (ret == 0) {
  3820. #if !defined(HAVE_FIPS)
  3821. /* Convert to wolfCrypt padding, hash and MGF. */
  3822. switch (padding) {
  3823. case RSA_PKCS1_PADDING:
  3824. pad_type = WC_RSA_PKCSV15_PAD;
  3825. break;
  3826. case RSA_PKCS1_OAEP_PADDING:
  3827. pad_type = WC_RSA_OAEP_PAD;
  3828. hash = WC_HASH_TYPE_SHA;
  3829. mgf = WC_MGF1SHA1;
  3830. break;
  3831. case RSA_NO_PADDING:
  3832. pad_type = WC_RSA_NO_PAD;
  3833. break;
  3834. default:
  3835. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3836. "scheme");
  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 encrypted 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. /* Get an RNG. */
  3863. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3864. if (rng == NULL) {
  3865. ret = -1;
  3866. }
  3867. }
  3868. if (ret == 0) {
  3869. /* Use wolfCrypt to public-encrypt with RSA key. */
  3870. #if !defined(HAVE_FIPS)
  3871. ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen,
  3872. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3873. #else
  3874. ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen,
  3875. (RsaKey*)rsa->internal, rng);
  3876. #endif
  3877. }
  3878. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3879. if (initTmpRng) {
  3880. wc_FreeRng(tmpRng);
  3881. }
  3882. #ifdef WOLFSSL_SMALL_STACK
  3883. /* Dispose of any allocated RNG. */
  3884. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3885. #endif
  3886. /* wolfCrypt error means return -1. */
  3887. if (ret <= 0) {
  3888. ret = -1;
  3889. }
  3890. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3891. return ret;
  3892. }
  3893. /* Decrypt with the RSA public key.
  3894. *
  3895. * Return compliant with OpenSSL.
  3896. *
  3897. * @param [in] len Length of encrypted data.
  3898. * @param [in] from Encrypted data.
  3899. * @param [out] to Decrypted data.
  3900. * @param [in] rsa RSA key.
  3901. * @param [in] padding Type of padding to around plaintext to remove.
  3902. * @return Size of decrypted data on success.
  3903. * @return -1 on failure.
  3904. */
  3905. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3906. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3907. {
  3908. int ret = 0;
  3909. #if !defined(HAVE_FIPS)
  3910. int mgf = WC_MGF1NONE;
  3911. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3912. int pad_type = WC_RSA_NO_PAD;
  3913. #endif
  3914. int outLen = 0;
  3915. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3916. /* Validate parameters. */
  3917. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3918. (from == NULL)) {
  3919. WOLFSSL_ERROR_MSG("Bad function arguments");
  3920. ret = -1;
  3921. }
  3922. if (ret == 0) {
  3923. #if !defined(HAVE_FIPS)
  3924. switch (padding) {
  3925. case RSA_PKCS1_PADDING:
  3926. pad_type = WC_RSA_PKCSV15_PAD;
  3927. break;
  3928. case RSA_PKCS1_OAEP_PADDING:
  3929. pad_type = WC_RSA_OAEP_PAD;
  3930. hash = WC_HASH_TYPE_SHA;
  3931. mgf = WC_MGF1SHA1;
  3932. break;
  3933. case RSA_NO_PADDING:
  3934. pad_type = WC_RSA_NO_PAD;
  3935. break;
  3936. default:
  3937. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3938. ret = -1;
  3939. }
  3940. #else
  3941. /* Check for supported padding schemes in FIPS. */
  3942. /* TODO: Do we support more schemes in later versions of FIPS? */
  3943. if (padding != RSA_PKCS1_PADDING) {
  3944. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3945. "FIPS");
  3946. ret = -1;
  3947. }
  3948. #endif
  3949. }
  3950. /* Set wolfCrypt RSA key data from external if not already done. */
  3951. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3952. ret = -1;
  3953. }
  3954. if (ret == 0) {
  3955. /* Calculate maximum length of decrypted data. */
  3956. outLen = wolfSSL_RSA_size(rsa);
  3957. if (outLen == 0) {
  3958. WOLFSSL_ERROR_MSG("Bad RSA size");
  3959. ret = -1;
  3960. }
  3961. }
  3962. if (ret == 0) {
  3963. /* Use wolfCrypt to private-decrypt with RSA key.
  3964. * Size of 'to' buffer must be size of RSA key */
  3965. #if !defined(HAVE_FIPS)
  3966. ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen,
  3967. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3968. #else
  3969. ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen,
  3970. (RsaKey*)rsa->internal);
  3971. #endif
  3972. }
  3973. /* wolfCrypt error means return -1. */
  3974. if (ret <= 0) {
  3975. ret = -1;
  3976. }
  3977. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  3978. return ret;
  3979. }
  3980. /* Decrypt with the RSA public key.
  3981. *
  3982. * @param [in] len Length of encrypted data.
  3983. * @param [in] from Encrypted data.
  3984. * @param [out] to Decrypted data.
  3985. * @param [in] rsa RSA key.
  3986. * @param [in] padding Type of padding to around plaintext to remove.
  3987. * @return Size of decrypted data on success.
  3988. * @return -1 on failure.
  3989. */
  3990. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3991. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3992. {
  3993. int ret = 0;
  3994. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3995. int pad_type = WC_RSA_NO_PAD;
  3996. #endif
  3997. int outLen = 0;
  3998. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  3999. /* Validate parameters. */
  4000. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4001. (from == NULL)) {
  4002. WOLFSSL_ERROR_MSG("Bad function arguments");
  4003. ret = -1;
  4004. }
  4005. if (ret == 0) {
  4006. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4007. switch (padding) {
  4008. case RSA_PKCS1_PADDING:
  4009. pad_type = WC_RSA_PKCSV15_PAD;
  4010. break;
  4011. case RSA_NO_PADDING:
  4012. pad_type = WC_RSA_NO_PAD;
  4013. break;
  4014. /* TODO: RSA_X931_PADDING not supported */
  4015. default:
  4016. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  4017. ret = -1;
  4018. }
  4019. #else
  4020. if (padding != RSA_PKCS1_PADDING) {
  4021. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  4022. "FIPS");
  4023. ret = -1;
  4024. }
  4025. #endif
  4026. }
  4027. /* Set wolfCrypt RSA key data from external if not already done. */
  4028. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4029. ret = -1;
  4030. }
  4031. if (ret == 0) {
  4032. /* Calculate maximum length of encrypted data. */
  4033. outLen = wolfSSL_RSA_size(rsa);
  4034. if (outLen == 0) {
  4035. WOLFSSL_ERROR_MSG("Bad RSA size");
  4036. ret = -1;
  4037. }
  4038. }
  4039. if (ret == 0) {
  4040. /* Use wolfCrypt to public-decrypt with RSA key. */
  4041. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4042. /* Size of 'to' buffer must be size of RSA key. */
  4043. ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen,
  4044. (RsaKey*)rsa->internal, pad_type);
  4045. #else
  4046. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  4047. ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen,
  4048. (RsaKey*)rsa->internal);
  4049. #endif
  4050. }
  4051. /* wolfCrypt error means return -1. */
  4052. if (ret <= 0) {
  4053. ret = -1;
  4054. }
  4055. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  4056. return ret;
  4057. }
  4058. /* Encrypt with the RSA private key.
  4059. *
  4060. * Calls wc_RsaSSL_Sign.
  4061. *
  4062. * @param [in] len Length of data to encrypt.
  4063. * @param [in] from Data to encrypt.
  4064. * @param [out] to Encrypted data.
  4065. * @param [in] rsa RSA key.
  4066. * @param [in] padding Type of padding to place around plaintext.
  4067. * @return Size of encrypted data on success.
  4068. * @return -1 on failure.
  4069. */
  4070. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  4071. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  4072. {
  4073. int ret = 0;
  4074. int initTmpRng = 0;
  4075. WC_RNG *rng = NULL;
  4076. #ifdef WOLFSSL_SMALL_STACK
  4077. WC_RNG* tmpRng = NULL;
  4078. #else
  4079. WC_RNG _tmpRng[1];
  4080. WC_RNG* tmpRng = _tmpRng;
  4081. #endif
  4082. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  4083. /* Validate parameters. */
  4084. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4085. (from == NULL)) {
  4086. WOLFSSL_ERROR_MSG("Bad function arguments");
  4087. ret = -1;
  4088. }
  4089. if (ret == 0) {
  4090. switch (padding) {
  4091. case RSA_PKCS1_PADDING:
  4092. #ifdef WC_RSA_NO_PADDING
  4093. case RSA_NO_PADDING:
  4094. #endif
  4095. break;
  4096. /* TODO: RSA_X931_PADDING not supported */
  4097. default:
  4098. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  4099. ret = -1;
  4100. }
  4101. }
  4102. /* Set wolfCrypt RSA key data from external if not already done. */
  4103. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4104. ret = -1;
  4105. }
  4106. if (ret == 0) {
  4107. /* Get an RNG. */
  4108. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  4109. if (rng == NULL) {
  4110. ret = -1;
  4111. }
  4112. }
  4113. if (ret == 0) {
  4114. /* Use wolfCrypt to private-encrypt with RSA key.
  4115. * Size of output buffer must be size of RSA key. */
  4116. if (padding == RSA_PKCS1_PADDING) {
  4117. ret = wc_RsaSSL_Sign(from, (word32)len, to,
  4118. (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng);
  4119. }
  4120. #ifdef WC_RSA_NO_PADDING
  4121. else if (padding == RSA_NO_PADDING) {
  4122. word32 outLen = (word32)wolfSSL_RSA_size(rsa);
  4123. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  4124. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  4125. if (ret == 0)
  4126. ret = (int)outLen;
  4127. }
  4128. #endif
  4129. }
  4130. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4131. if (initTmpRng) {
  4132. wc_FreeRng(tmpRng);
  4133. }
  4134. #ifdef WOLFSSL_SMALL_STACK
  4135. /* Dispose of any allocated RNG. */
  4136. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4137. #endif
  4138. /* wolfCrypt error means return -1. */
  4139. if (ret <= 0) {
  4140. ret = -1;
  4141. }
  4142. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4143. return ret;
  4144. }
  4145. /*
  4146. * RSA misc operation APIs
  4147. */
  4148. /* Calculate d mod p-1 and q-1 into BNs.
  4149. *
  4150. * Not OpenSSL API.
  4151. *
  4152. * @param [in, out] rsa RSA key.
  4153. * @return 1 on success.
  4154. * @return -1 on failure.
  4155. */
  4156. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4157. {
  4158. int ret = 1;
  4159. int err;
  4160. mp_int* t = NULL;
  4161. #ifdef WOLFSSL_SMALL_STACK
  4162. mp_int *tmp = NULL;
  4163. #else
  4164. mp_int tmp[1];
  4165. #endif
  4166. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4167. /* Validate parameters. */
  4168. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4169. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4170. WOLFSSL_ERROR_MSG("rsa no init error");
  4171. ret = -1;
  4172. }
  4173. #ifdef WOLFSSL_SMALL_STACK
  4174. if (ret == 1) {
  4175. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4176. DYNAMIC_TYPE_TMP_BUFFER);
  4177. if (tmp == NULL) {
  4178. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4179. ret = -1;
  4180. }
  4181. }
  4182. #endif
  4183. if (ret == 1) {
  4184. /* Initialize temp MP integer. */
  4185. if (mp_init(tmp) != MP_OKAY) {
  4186. WOLFSSL_ERROR_MSG("mp_init error");
  4187. ret = -1;
  4188. }
  4189. }
  4190. if (ret == 1) {
  4191. t = tmp;
  4192. /* Sub 1 from p into temp. */
  4193. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4194. if (err != MP_OKAY) {
  4195. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4196. ret = -1;
  4197. }
  4198. }
  4199. if (ret == 1) {
  4200. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4201. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4202. (mp_int*)rsa->dmp1->internal);
  4203. if (err != MP_OKAY) {
  4204. WOLFSSL_ERROR_MSG("mp_mod error");
  4205. ret = -1;
  4206. }
  4207. }
  4208. if (ret == 1) {
  4209. /* Sub 1 from q into temp. */
  4210. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4211. if (err != MP_OKAY) {
  4212. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4213. ret = -1;
  4214. }
  4215. }
  4216. if (ret == 1) {
  4217. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4218. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4219. (mp_int*)rsa->dmq1->internal);
  4220. if (err != MP_OKAY) {
  4221. WOLFSSL_ERROR_MSG("mp_mod error");
  4222. ret = -1;
  4223. }
  4224. }
  4225. mp_clear(t);
  4226. #ifdef WOLFSSL_SMALL_STACK
  4227. if (tmp != NULL)
  4228. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4229. #endif
  4230. return ret;
  4231. }
  4232. #ifndef NO_WOLFSSL_STUB
  4233. /* Enable blinding for RSA key operations.
  4234. *
  4235. * Blinding is a compile time option in wolfCrypt.
  4236. *
  4237. * @param [in] rsa RSA key. Unused.
  4238. * @param [in] bnCtx BN context to use for blinding. Unused.
  4239. * @return 1 always.
  4240. */
  4241. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4242. {
  4243. WOLFSSL_STUB("RSA_blinding_on");
  4244. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4245. (void)rsa;
  4246. (void)bnCtx;
  4247. return 1; /* on by default */
  4248. }
  4249. #endif
  4250. #endif /* OPENSSL_EXTRA */
  4251. #endif /* !NO_RSA */
  4252. /*******************************************************************************
  4253. * END OF RSA API
  4254. ******************************************************************************/
  4255. /*******************************************************************************
  4256. * START OF DSA API
  4257. ******************************************************************************/
  4258. #ifndef NO_DSA
  4259. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4260. !defined(NO_STDIO_FILESYSTEM)
  4261. /* return code compliant with OpenSSL :
  4262. * 1 if success, 0 if error
  4263. */
  4264. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4265. {
  4266. int ret = 1;
  4267. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4268. if (fp == XBADFILE || dsa == NULL) {
  4269. ret = 0;
  4270. }
  4271. if (ret == 1 && dsa->p != NULL) {
  4272. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4273. if (pBits == 0) {
  4274. ret = 0;
  4275. }
  4276. else {
  4277. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4278. ret = 0;
  4279. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4280. ret = 0;
  4281. }
  4282. }
  4283. if (ret == 1 && dsa->priv_key != NULL) {
  4284. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4285. }
  4286. if (ret == 1 && dsa->pub_key != NULL) {
  4287. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4288. }
  4289. if (ret == 1 && dsa->p != NULL) {
  4290. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4291. }
  4292. if (ret == 1 && dsa->q != NULL) {
  4293. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4294. }
  4295. if (ret == 1 && dsa->g != NULL) {
  4296. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4297. }
  4298. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4299. return ret;
  4300. }
  4301. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4302. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4303. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4304. {
  4305. if (dsa) {
  4306. dsa->p = NULL;
  4307. dsa->q = NULL;
  4308. dsa->g = NULL;
  4309. dsa->pub_key = NULL;
  4310. dsa->priv_key = NULL;
  4311. dsa->internal = NULL;
  4312. dsa->inSet = 0;
  4313. dsa->exSet = 0;
  4314. }
  4315. }
  4316. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4317. {
  4318. WOLFSSL_DSA* external;
  4319. DsaKey* key;
  4320. WOLFSSL_MSG("wolfSSL_DSA_new");
  4321. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4322. if (key == NULL) {
  4323. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4324. return NULL;
  4325. }
  4326. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4327. DYNAMIC_TYPE_DSA);
  4328. if (external == NULL) {
  4329. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4330. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4331. return NULL;
  4332. }
  4333. InitwolfSSL_DSA(external);
  4334. if (wc_InitDsaKey(key) != 0) {
  4335. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4336. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4337. wolfSSL_DSA_free(external);
  4338. return NULL;
  4339. }
  4340. external->internal = key;
  4341. return external;
  4342. }
  4343. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4344. {
  4345. WOLFSSL_MSG("wolfSSL_DSA_free");
  4346. if (dsa) {
  4347. if (dsa->internal) {
  4348. FreeDsaKey((DsaKey*)dsa->internal);
  4349. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4350. dsa->internal = NULL;
  4351. }
  4352. wolfSSL_BN_free(dsa->priv_key);
  4353. wolfSSL_BN_free(dsa->pub_key);
  4354. wolfSSL_BN_free(dsa->g);
  4355. wolfSSL_BN_free(dsa->q);
  4356. wolfSSL_BN_free(dsa->p);
  4357. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4358. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4359. /* dsa = NULL, don't try to access or double free it */
  4360. }
  4361. }
  4362. /* wolfSSL -> OpenSSL */
  4363. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4364. {
  4365. DsaKey* key;
  4366. WOLFSSL_MSG("Entering SetDsaExternal");
  4367. if (dsa == NULL || dsa->internal == NULL) {
  4368. WOLFSSL_MSG("dsa key NULL error");
  4369. return -1;
  4370. }
  4371. key = (DsaKey*)dsa->internal;
  4372. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4373. WOLFSSL_MSG("dsa p key error");
  4374. return -1;
  4375. }
  4376. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4377. WOLFSSL_MSG("dsa q key error");
  4378. return -1;
  4379. }
  4380. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4381. WOLFSSL_MSG("dsa g key error");
  4382. return -1;
  4383. }
  4384. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4385. WOLFSSL_MSG("dsa y key error");
  4386. return -1;
  4387. }
  4388. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4389. WOLFSSL_MSG("dsa x key error");
  4390. return -1;
  4391. }
  4392. dsa->exSet = 1;
  4393. return 1;
  4394. }
  4395. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4396. #ifdef OPENSSL_EXTRA
  4397. /* Openssl -> WolfSSL */
  4398. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4399. {
  4400. DsaKey* key;
  4401. WOLFSSL_MSG("Entering SetDsaInternal");
  4402. if (dsa == NULL || dsa->internal == NULL) {
  4403. WOLFSSL_MSG("dsa key NULL error");
  4404. return -1;
  4405. }
  4406. key = (DsaKey*)dsa->internal;
  4407. if (dsa->p != NULL &&
  4408. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4409. WOLFSSL_MSG("rsa p key error");
  4410. return -1;
  4411. }
  4412. if (dsa->q != NULL &&
  4413. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4414. WOLFSSL_MSG("rsa q key error");
  4415. return -1;
  4416. }
  4417. if (dsa->g != NULL &&
  4418. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4419. WOLFSSL_MSG("rsa g key error");
  4420. return -1;
  4421. }
  4422. if (dsa->pub_key != NULL) {
  4423. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4424. WOLFSSL_MSG("rsa pub_key error");
  4425. return -1;
  4426. }
  4427. /* public key */
  4428. key->type = DSA_PUBLIC;
  4429. }
  4430. if (dsa->priv_key != NULL) {
  4431. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4432. WOLFSSL_MSG("rsa priv_key error");
  4433. return -1;
  4434. }
  4435. /* private key */
  4436. key->type = DSA_PRIVATE;
  4437. }
  4438. dsa->inSet = 1;
  4439. return 1;
  4440. }
  4441. /* return code compliant with OpenSSL :
  4442. * 1 if success, 0 if error
  4443. */
  4444. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4445. {
  4446. int ret = 0;
  4447. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4448. if (dsa == NULL || dsa->internal == NULL) {
  4449. WOLFSSL_MSG("Bad arguments");
  4450. return 0;
  4451. }
  4452. if (dsa->inSet == 0) {
  4453. WOLFSSL_MSG("No DSA internal set, do it");
  4454. if (SetDsaInternal(dsa) != 1) {
  4455. WOLFSSL_MSG("SetDsaInternal failed");
  4456. return ret;
  4457. }
  4458. }
  4459. #ifdef WOLFSSL_KEY_GEN
  4460. {
  4461. int initTmpRng = 0;
  4462. WC_RNG *rng = NULL;
  4463. #ifdef WOLFSSL_SMALL_STACK
  4464. WC_RNG *tmpRng;
  4465. #else
  4466. WC_RNG tmpRng[1];
  4467. #endif
  4468. #ifdef WOLFSSL_SMALL_STACK
  4469. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4470. if (tmpRng == NULL)
  4471. return -1;
  4472. #endif
  4473. if (wc_InitRng(tmpRng) == 0) {
  4474. rng = tmpRng;
  4475. initTmpRng = 1;
  4476. }
  4477. else {
  4478. WOLFSSL_MSG("Bad RNG Init, trying global");
  4479. rng = wolfssl_get_global_rng();
  4480. }
  4481. if (rng) {
  4482. /* These were allocated above by SetDsaInternal(). They should
  4483. * be cleared before wc_MakeDsaKey() which reinitializes
  4484. * x and y. */
  4485. mp_clear(&((DsaKey*)dsa->internal)->x);
  4486. mp_clear(&((DsaKey*)dsa->internal)->y);
  4487. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4488. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4489. else if (SetDsaExternal(dsa) != 1)
  4490. WOLFSSL_MSG("SetDsaExternal failed");
  4491. else
  4492. ret = 1;
  4493. }
  4494. if (initTmpRng)
  4495. wc_FreeRng(tmpRng);
  4496. #ifdef WOLFSSL_SMALL_STACK
  4497. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4498. #endif
  4499. }
  4500. #else /* WOLFSSL_KEY_GEN */
  4501. WOLFSSL_MSG("No Key Gen built in");
  4502. #endif
  4503. return ret;
  4504. }
  4505. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4506. */
  4507. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4508. int seedLen, int* counterRet, unsigned long* hRet,
  4509. WOLFSSL_BN_CB cb, void* CBArg)
  4510. {
  4511. WOLFSSL_DSA* dsa;
  4512. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4513. (void)cb;
  4514. (void)CBArg;
  4515. dsa = wolfSSL_DSA_new();
  4516. if (dsa == NULL) {
  4517. return NULL;
  4518. }
  4519. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4520. counterRet, hRet, NULL) != 1) {
  4521. wolfSSL_DSA_free(dsa);
  4522. return NULL;
  4523. }
  4524. return dsa;
  4525. }
  4526. /* return code compliant with OpenSSL :
  4527. * 1 if success, 0 if error
  4528. */
  4529. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4530. unsigned char* seed, int seedLen,
  4531. int* counterRet,
  4532. unsigned long* hRet, void* cb)
  4533. {
  4534. int ret = 0;
  4535. (void)bits;
  4536. (void)seed;
  4537. (void)seedLen;
  4538. (void)counterRet;
  4539. (void)hRet;
  4540. (void)cb;
  4541. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4542. if (dsa == NULL || dsa->internal == NULL) {
  4543. WOLFSSL_MSG("Bad arguments");
  4544. return 0;
  4545. }
  4546. #ifdef WOLFSSL_KEY_GEN
  4547. {
  4548. int initTmpRng = 0;
  4549. WC_RNG *rng = NULL;
  4550. #ifdef WOLFSSL_SMALL_STACK
  4551. WC_RNG *tmpRng;
  4552. #else
  4553. WC_RNG tmpRng[1];
  4554. #endif
  4555. #ifdef WOLFSSL_SMALL_STACK
  4556. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4557. if (tmpRng == NULL)
  4558. return -1;
  4559. #endif
  4560. if (wc_InitRng(tmpRng) == 0) {
  4561. rng = tmpRng;
  4562. initTmpRng = 1;
  4563. }
  4564. else {
  4565. WOLFSSL_MSG("Bad RNG Init, trying global");
  4566. rng = wolfssl_get_global_rng();
  4567. }
  4568. if (rng) {
  4569. if (wc_MakeDsaParameters(rng, bits,
  4570. (DsaKey*)dsa->internal) != MP_OKAY)
  4571. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4572. else if (SetDsaExternal(dsa) != 1)
  4573. WOLFSSL_MSG("SetDsaExternal failed");
  4574. else
  4575. ret = 1;
  4576. }
  4577. if (initTmpRng)
  4578. wc_FreeRng(tmpRng);
  4579. #ifdef WOLFSSL_SMALL_STACK
  4580. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4581. #endif
  4582. }
  4583. #else /* WOLFSSL_KEY_GEN */
  4584. WOLFSSL_MSG("No Key Gen built in");
  4585. #endif
  4586. return ret;
  4587. }
  4588. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4589. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4590. {
  4591. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4592. if (d != NULL) {
  4593. if (p != NULL)
  4594. *p = d->p;
  4595. if (q != NULL)
  4596. *q = d->q;
  4597. if (g != NULL)
  4598. *g = d->g;
  4599. }
  4600. }
  4601. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4602. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4603. {
  4604. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4605. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4606. WOLFSSL_MSG("Bad parameter");
  4607. return 0;
  4608. }
  4609. wolfSSL_BN_free(d->p);
  4610. wolfSSL_BN_free(d->q);
  4611. wolfSSL_BN_free(d->g);
  4612. d->p = p;
  4613. d->q = q;
  4614. d->g = g;
  4615. return 1;
  4616. }
  4617. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4618. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4619. {
  4620. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4621. if (d != NULL) {
  4622. if (pub_key != NULL)
  4623. *pub_key = d->pub_key;
  4624. if (priv_key != NULL)
  4625. *priv_key = d->priv_key;
  4626. }
  4627. }
  4628. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4629. WOLFSSL_BIGNUM *priv_key)
  4630. {
  4631. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4632. /* The private key may be NULL */
  4633. if (d->pub_key == NULL && pub_key == NULL) {
  4634. WOLFSSL_MSG("Bad parameter");
  4635. return 0;
  4636. }
  4637. if (pub_key != NULL) {
  4638. wolfSSL_BN_free(d->pub_key);
  4639. d->pub_key = pub_key;
  4640. }
  4641. if (priv_key != NULL) {
  4642. wolfSSL_BN_free(d->priv_key);
  4643. d->priv_key = priv_key;
  4644. }
  4645. return 1;
  4646. }
  4647. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4648. {
  4649. WOLFSSL_DSA_SIG* sig;
  4650. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4651. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4652. DYNAMIC_TYPE_OPENSSL);
  4653. if (sig)
  4654. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4655. return sig;
  4656. }
  4657. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4658. {
  4659. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4660. if (sig) {
  4661. if (sig->r) {
  4662. wolfSSL_BN_free(sig->r);
  4663. }
  4664. if (sig->s) {
  4665. wolfSSL_BN_free(sig->s);
  4666. }
  4667. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4668. }
  4669. }
  4670. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4671. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4672. {
  4673. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4674. if (sig != NULL) {
  4675. *r = sig->r;
  4676. *s = sig->s;
  4677. }
  4678. }
  4679. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4680. WOLFSSL_BIGNUM *s)
  4681. {
  4682. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4683. if (r == NULL || s == NULL) {
  4684. WOLFSSL_MSG("Bad parameter");
  4685. return 0;
  4686. }
  4687. wolfSSL_BN_clear_free(sig->r);
  4688. wolfSSL_BN_clear_free(sig->s);
  4689. sig->r = r;
  4690. sig->s = s;
  4691. return 1;
  4692. }
  4693. #ifndef HAVE_SELFTEST
  4694. /**
  4695. *
  4696. * @param sig The input signature to encode
  4697. * @param out The output buffer. If *out is NULL then a new buffer is
  4698. * allocated. Otherwise the output is written to the buffer.
  4699. * @return length on success and -1 on error
  4700. */
  4701. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4702. {
  4703. /* Space for sequence + two asn ints */
  4704. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4705. word32 bufLen = sizeof(buf);
  4706. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4707. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4708. out == NULL) {
  4709. WOLFSSL_MSG("Bad function arguments");
  4710. return -1;
  4711. }
  4712. if (StoreECC_DSA_Sig(buf, &bufLen,
  4713. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4714. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4715. return -1;
  4716. }
  4717. if (*out == NULL) {
  4718. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4719. if (tmp == NULL) {
  4720. WOLFSSL_MSG("malloc error");
  4721. return -1;
  4722. }
  4723. *out = tmp;
  4724. }
  4725. XMEMCPY(*out, buf, bufLen);
  4726. return (int)bufLen;
  4727. }
  4728. /**
  4729. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4730. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4731. */
  4732. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4733. {
  4734. WOLFSSL_DSA_SIG* ret;
  4735. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4736. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4737. return NULL;
  4738. }
  4739. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4740. WOLFSSL_MSG("wolfSSL_BN_new error");
  4741. wolfSSL_DSA_SIG_free(ret);
  4742. return NULL;
  4743. }
  4744. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4745. WOLFSSL_MSG("wolfSSL_BN_new error");
  4746. wolfSSL_DSA_SIG_free(ret);
  4747. return NULL;
  4748. }
  4749. return ret;
  4750. }
  4751. /**
  4752. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4753. * ASN1_SEQUENCE
  4754. * ASN1_INTEGER (DSA r)
  4755. * ASN1_INTEGER (DSA s)
  4756. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4757. * length then this API interprets this as two unsigned binary numbers.
  4758. * @param sig If non-null then free'd first and then newly created
  4759. * WOLFSSL_DSA_SIG is assigned
  4760. * @param pp Input buffer that is moved forward on success
  4761. * @param length Length of input buffer
  4762. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4763. */
  4764. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4765. const unsigned char **pp, long length)
  4766. {
  4767. WOLFSSL_DSA_SIG* ret;
  4768. mp_int* r;
  4769. mp_int* s;
  4770. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4771. if (pp == NULL || *pp == NULL || length < 0) {
  4772. WOLFSSL_MSG("Bad function arguments");
  4773. return NULL;
  4774. }
  4775. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4776. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4777. return NULL;
  4778. }
  4779. r = (mp_int*)ret->r->internal;
  4780. s = (mp_int*)ret->s->internal;
  4781. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4782. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4783. /* Two raw numbers of length/2 size each */
  4784. if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) {
  4785. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4786. wolfSSL_DSA_SIG_free(ret);
  4787. return NULL;
  4788. }
  4789. if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) !=
  4790. 0) {
  4791. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4792. wolfSSL_DSA_SIG_free(ret);
  4793. return NULL;
  4794. }
  4795. *pp += length;
  4796. }
  4797. else {
  4798. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4799. wolfSSL_DSA_SIG_free(ret);
  4800. return NULL;
  4801. }
  4802. }
  4803. else {
  4804. /* DecodeECC_DSA_Sig success move pointer forward */
  4805. #ifndef NO_STRICT_ECDSA_LEN
  4806. *pp += length;
  4807. #else
  4808. {
  4809. /* We need to figure out how much to move by ourselves */
  4810. word32 idx = 0;
  4811. int len = 0;
  4812. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4813. WOLFSSL_MSG("GetSequence error");
  4814. wolfSSL_DSA_SIG_free(ret);
  4815. return NULL;
  4816. }
  4817. *pp += len;
  4818. }
  4819. #endif
  4820. }
  4821. if (sig != NULL) {
  4822. if (*sig != NULL)
  4823. wolfSSL_DSA_SIG_free(*sig);
  4824. *sig = ret;
  4825. }
  4826. return ret;
  4827. }
  4828. #endif /* HAVE_SELFTEST */
  4829. /* return 1 on success, < 0 otherwise */
  4830. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4831. WOLFSSL_DSA* dsa)
  4832. {
  4833. int ret = -1;
  4834. int initTmpRng = 0;
  4835. WC_RNG* rng = NULL;
  4836. #ifdef WOLFSSL_SMALL_STACK
  4837. WC_RNG* tmpRng = NULL;
  4838. #else
  4839. WC_RNG tmpRng[1];
  4840. #endif
  4841. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4842. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4843. WOLFSSL_MSG("Bad function arguments");
  4844. return ret;
  4845. }
  4846. if (dsa->inSet == 0) {
  4847. WOLFSSL_MSG("No DSA internal set, do it");
  4848. if (SetDsaInternal(dsa) != 1) {
  4849. WOLFSSL_MSG("SetDsaInternal failed");
  4850. return ret;
  4851. }
  4852. }
  4853. #ifdef WOLFSSL_SMALL_STACK
  4854. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4855. if (tmpRng == NULL)
  4856. return -1;
  4857. #endif
  4858. if (wc_InitRng(tmpRng) == 0) {
  4859. rng = tmpRng;
  4860. initTmpRng = 1;
  4861. }
  4862. else {
  4863. WOLFSSL_MSG("Bad RNG Init, trying global");
  4864. rng = wolfssl_get_global_rng();
  4865. }
  4866. if (rng) {
  4867. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4868. WOLFSSL_MSG("DsaSign failed");
  4869. else
  4870. ret = 1;
  4871. }
  4872. if (initTmpRng)
  4873. wc_FreeRng(tmpRng);
  4874. #ifdef WOLFSSL_SMALL_STACK
  4875. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4876. #endif
  4877. return ret;
  4878. }
  4879. #ifndef HAVE_SELFTEST
  4880. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4881. int inLen, WOLFSSL_DSA* dsa)
  4882. {
  4883. byte sigBin[DSA_MAX_SIG_SIZE];
  4884. const byte *tmp = sigBin;
  4885. int sigLen;
  4886. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4887. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4888. WOLFSSL_MSG("Bad function arguments");
  4889. return NULL;
  4890. }
  4891. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4892. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4893. return NULL;
  4894. }
  4895. if (dsa->internal == NULL) {
  4896. WOLFSSL_MSG("dsa->internal is null");
  4897. return NULL;
  4898. }
  4899. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4900. if (sigLen <= 0) {
  4901. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4902. return NULL;
  4903. }
  4904. /* 2 * sigLen for the two points r and s */
  4905. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4906. }
  4907. #endif /* !HAVE_SELFTEST */
  4908. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4909. WOLFSSL_DSA* dsa, int *dsacheck)
  4910. {
  4911. int ret = -1;
  4912. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4913. if (d == NULL || sig == NULL || dsa == NULL) {
  4914. WOLFSSL_MSG("Bad function arguments");
  4915. return -1;
  4916. }
  4917. if (dsa->inSet == 0)
  4918. {
  4919. WOLFSSL_MSG("No DSA internal set, do it");
  4920. if (SetDsaInternal(dsa) != 1) {
  4921. WOLFSSL_MSG("SetDsaInternal failed");
  4922. return -1;
  4923. }
  4924. }
  4925. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4926. if (ret != 0 || *dsacheck != 1) {
  4927. WOLFSSL_MSG("DsaVerify failed");
  4928. return ret;
  4929. }
  4930. return 1;
  4931. }
  4932. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4933. {
  4934. if (!d)
  4935. return 0;
  4936. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4937. return 0;
  4938. return wolfSSL_BN_num_bits(d->p);
  4939. }
  4940. #ifndef HAVE_SELFTEST
  4941. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4942. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4943. {
  4944. int dsacheck, sz;
  4945. byte sigBin[DSA_MAX_SIG_SIZE];
  4946. byte* sigBinPtr = sigBin;
  4947. DsaKey* key;
  4948. int qSz;
  4949. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4950. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4951. WOLFSSL_MSG("Bad function arguments");
  4952. return 0;
  4953. }
  4954. if (!sig->r || !sig->s) {
  4955. WOLFSSL_MSG("No signature found in DSA_SIG");
  4956. return 0;
  4957. }
  4958. if (dsa->inSet == 0) {
  4959. WOLFSSL_MSG("No DSA internal set, do it");
  4960. if (SetDsaInternal(dsa) != 1) {
  4961. WOLFSSL_MSG("SetDsaInternal failed");
  4962. return 0;
  4963. }
  4964. }
  4965. key = (DsaKey*)dsa->internal;
  4966. if (key == NULL) {
  4967. WOLFSSL_MSG("dsa->internal is null");
  4968. return 0;
  4969. }
  4970. qSz = mp_unsigned_bin_size(&key->q);
  4971. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4972. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4973. return 0;
  4974. }
  4975. /* read r */
  4976. /* front pad with zeros */
  4977. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4978. return 0;
  4979. while (sz++ < qSz)
  4980. *sigBinPtr++ = 0;
  4981. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4982. return 0;
  4983. /* Move to s */
  4984. sigBinPtr = sigBin + qSz;
  4985. /* read s */
  4986. /* front pad with zeros */
  4987. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4988. return 0;
  4989. while (sz++ < qSz)
  4990. *sigBinPtr++ = 0;
  4991. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4992. return 0;
  4993. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4994. != 1) || dsacheck != 1) {
  4995. return 0;
  4996. }
  4997. return 1;
  4998. }
  4999. #endif /* !HAVE_SELFTEST */
  5000. int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  5001. unsigned char** out)
  5002. {
  5003. int ret = 0;
  5004. word32 derLen = 0;
  5005. int preAllocated = 1;
  5006. DsaKey* key = NULL;
  5007. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  5008. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  5009. ret = BAD_FUNC_ARG;
  5010. }
  5011. if (ret == 0) {
  5012. key = (DsaKey*)dsa->internal;
  5013. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  5014. if (ret == LENGTH_ONLY_E) {
  5015. ret = 0;
  5016. }
  5017. }
  5018. if (ret == 0 && *out == NULL) {
  5019. /* If we're allocating out for the caller, we don't increment out just
  5020. past the end of the DER buffer. If out is already allocated, we do.
  5021. (OpenSSL convention) */
  5022. preAllocated = 0;
  5023. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  5024. if (*out == NULL) {
  5025. ret = MEMORY_E;
  5026. }
  5027. }
  5028. if (ret == 0) {
  5029. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  5030. }
  5031. if (ret >= 0 && preAllocated == 1) {
  5032. *out += derLen;
  5033. }
  5034. if (ret < 0 && preAllocated == 0) {
  5035. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  5036. }
  5037. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  5038. return ret;
  5039. }
  5040. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  5041. long derLen)
  5042. {
  5043. WOLFSSL_DSA* ret = NULL;
  5044. int err = 0;
  5045. word32 idx = 0;
  5046. int asnLen;
  5047. DsaKey* internalKey = NULL;
  5048. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  5049. if (der == NULL || *der == NULL || derLen <= 0) {
  5050. err = 1;
  5051. }
  5052. if (err == 0) {
  5053. ret = wolfSSL_DSA_new();
  5054. err = ret == NULL;
  5055. }
  5056. if (err == 0) {
  5057. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  5058. }
  5059. if (err == 0) {
  5060. internalKey = (DsaKey*)ret->internal;
  5061. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  5062. }
  5063. if (err == 0) {
  5064. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  5065. }
  5066. if (err == 0) {
  5067. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  5068. }
  5069. if (err == 0) {
  5070. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  5071. != 1;
  5072. }
  5073. if (err == 0) {
  5074. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  5075. != 1;
  5076. }
  5077. if (err == 0) {
  5078. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  5079. != 1;
  5080. }
  5081. if (err == 0 && dsa != NULL) {
  5082. *dsa = ret;
  5083. }
  5084. if (err != 0 && ret != NULL) {
  5085. wolfSSL_DSA_free(ret);
  5086. ret = NULL;
  5087. }
  5088. return ret;
  5089. }
  5090. #if defined(WOLFSSL_KEY_GEN)
  5091. #ifndef NO_BIO
  5092. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  5093. * Returns 1 or 0
  5094. */
  5095. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  5096. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  5097. wc_pem_password_cb* cb, void* arg)
  5098. {
  5099. int ret = 1;
  5100. byte *pem = NULL;
  5101. int pLen = 0;
  5102. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  5103. (void)cb;
  5104. (void)arg;
  5105. /* Validate parameters. */
  5106. if ((bio == NULL) || (dsa == NULL)) {
  5107. WOLFSSL_MSG("Bad Function Arguments");
  5108. ret = 0;
  5109. }
  5110. if (ret == 1) {
  5111. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, cipher, passwd, passwdSz,
  5112. &pem, &pLen);
  5113. }
  5114. /* Write PEM to BIO. */
  5115. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  5116. WOLFSSL_ERROR_MSG("DSA private key BIO write failed");
  5117. ret = 0;
  5118. }
  5119. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5120. return ret;
  5121. }
  5122. #ifndef HAVE_SELFTEST
  5123. /* Encode the DSA public key as DER.
  5124. *
  5125. * @param [in] key DSA key to encode.
  5126. * @param [out] der Pointer through which buffer is returned.
  5127. * @param [in] heap Heap hint.
  5128. * @return Size of encoding on success.
  5129. * @return 0 on error.
  5130. */
  5131. static int wolfssl_dsa_key_to_pubkey_der(WOLFSSL_DSA* key, unsigned char** der,
  5132. void* heap)
  5133. {
  5134. int sz;
  5135. unsigned char* buf = NULL;
  5136. /* Use maximum encoded size to allocate. */
  5137. sz = MAX_DSA_PUBKEY_SZ;
  5138. /* Allocate memory to hold encoding. */
  5139. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5140. if (buf == NULL) {
  5141. WOLFSSL_MSG("malloc failed");
  5142. sz = 0;
  5143. }
  5144. if (sz > 0) {
  5145. /* Encode public key to DER using wolfSSL. */
  5146. sz = wc_DsaKeyToPublicDer((DsaKey*)key->internal, buf, (word32)sz);
  5147. if (sz < 0) {
  5148. WOLFSSL_MSG("wc_DsaKeyToPublicDer failed");
  5149. sz = 0;
  5150. }
  5151. }
  5152. /* Return buffer on success. */
  5153. if (sz > 0) {
  5154. *der = buf;
  5155. }
  5156. else {
  5157. /* Dispose of any dynamically allocated data not returned. */
  5158. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5159. }
  5160. return sz;
  5161. }
  5162. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5163. * Returns 1 or 0
  5164. */
  5165. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5166. {
  5167. int ret = 1;
  5168. unsigned char* derBuf = NULL;
  5169. int derSz = 0;
  5170. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5171. /* Validate parameters. */
  5172. if ((bio == NULL) || (dsa == NULL)) {
  5173. WOLFSSL_MSG("Bad Function Arguments");
  5174. return 0;
  5175. }
  5176. /* Encode public key in EC key as DER. */
  5177. derSz = wolfssl_dsa_key_to_pubkey_der(dsa, &derBuf, bio->heap);
  5178. if (derSz == 0) {
  5179. ret = 0;
  5180. }
  5181. /* Write out to BIO the PEM encoding of the DSA public key. */
  5182. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  5183. PUBLICKEY_TYPE) != 1)) {
  5184. ret = 0;
  5185. }
  5186. /* Dispose of any dynamically allocated data. */
  5187. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5188. return ret;
  5189. }
  5190. #endif /* HAVE_SELFTEST */
  5191. #endif /* !NO_BIO */
  5192. /* return code compliant with OpenSSL :
  5193. * 1 if success, 0 if error
  5194. */
  5195. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5196. const EVP_CIPHER* cipher,
  5197. unsigned char* passwd, int passwdSz,
  5198. unsigned char **pem, int *pLen)
  5199. {
  5200. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5201. byte *derBuf, *tmp, *cipherInfo = NULL;
  5202. int der_max_len = 0, derSz = 0;
  5203. const int type = DSA_PRIVATEKEY_TYPE;
  5204. const char* header = NULL;
  5205. const char* footer = NULL;
  5206. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5207. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5208. WOLFSSL_MSG("Bad function arguments");
  5209. return 0;
  5210. }
  5211. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5212. return 0;
  5213. if (dsa->inSet == 0) {
  5214. WOLFSSL_MSG("No DSA internal set, do it");
  5215. if (SetDsaInternal(dsa) != 1) {
  5216. WOLFSSL_MSG("SetDsaInternal failed");
  5217. return 0;
  5218. }
  5219. }
  5220. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5221. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER);
  5222. if (derBuf == NULL) {
  5223. WOLFSSL_MSG("malloc failed");
  5224. return 0;
  5225. }
  5226. /* Key to DER */
  5227. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5228. if (derSz < 0) {
  5229. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5230. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5231. return 0;
  5232. }
  5233. /* encrypt DER buffer if required */
  5234. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5235. int ret;
  5236. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5237. passwd, passwdSz, &cipherInfo, der_max_len);
  5238. if (ret != 1) {
  5239. WOLFSSL_MSG("EncryptDerKey failed");
  5240. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5241. return ret;
  5242. }
  5243. /* tmp buffer with a max size */
  5244. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5245. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5246. }
  5247. else { /* tmp buffer with a max size */
  5248. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5249. (int)XSTRLEN(footer) + 1;
  5250. }
  5251. tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM);
  5252. if (tmp == NULL) {
  5253. WOLFSSL_MSG("malloc failed");
  5254. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5255. if (cipherInfo != NULL)
  5256. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5257. return 0;
  5258. }
  5259. /* DER to PEM */
  5260. *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo,
  5261. type);
  5262. if (*pLen <= 0) {
  5263. WOLFSSL_MSG("wc_DerToPemEx failed");
  5264. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5265. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5266. if (cipherInfo != NULL)
  5267. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5268. return 0;
  5269. }
  5270. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5271. if (cipherInfo != NULL)
  5272. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5273. *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY);
  5274. if (*pem == NULL) {
  5275. WOLFSSL_MSG("malloc failed");
  5276. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5277. return 0;
  5278. }
  5279. XMEMSET(*pem, 0, (size_t)((*pLen)+1));
  5280. if (XMEMCPY(*pem, tmp, (size_t)*pLen) == NULL) {
  5281. WOLFSSL_MSG("XMEMCPY failed");
  5282. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5283. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5284. return 0;
  5285. }
  5286. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5287. return 1;
  5288. #else
  5289. (void)dsa;
  5290. (void)cipher;
  5291. (void)passwd;
  5292. (void)passwdSz;
  5293. (void)pem;
  5294. (void)pLen;
  5295. return 0;
  5296. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5297. }
  5298. #ifndef NO_FILESYSTEM
  5299. /* return code compliant with OpenSSL :
  5300. * 1 if success, 0 if error
  5301. */
  5302. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5303. const EVP_CIPHER *enc,
  5304. unsigned char *kstr, int klen,
  5305. wc_pem_password_cb *cb, void *u)
  5306. {
  5307. byte *pem;
  5308. int pLen, ret;
  5309. (void)cb;
  5310. (void)u;
  5311. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5312. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5313. WOLFSSL_MSG("Bad function arguments");
  5314. return 0;
  5315. }
  5316. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5317. &pLen);
  5318. if (ret != 1) {
  5319. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5320. return 0;
  5321. }
  5322. ret = (int)XFWRITE(pem, (size_t)pLen, 1, fp);
  5323. if (ret != 1) {
  5324. WOLFSSL_MSG("DSA private key file write failed");
  5325. return 0;
  5326. }
  5327. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5328. return 1;
  5329. }
  5330. #endif /* NO_FILESYSTEM */
  5331. #endif /* defined(WOLFSSL_KEY_GEN) */
  5332. #ifndef NO_FILESYSTEM
  5333. /* return code compliant with OpenSSL :
  5334. * 1 if success, 0 if error
  5335. */
  5336. #ifndef NO_WOLFSSL_STUB
  5337. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5338. {
  5339. (void)fp;
  5340. (void)x;
  5341. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5342. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5343. return 0;
  5344. }
  5345. #endif
  5346. #endif /* NO_FILESYSTEM */
  5347. #ifndef NO_BIO
  5348. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5349. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5350. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5351. * the results to be an DSA key.
  5352. *
  5353. * bio structure to read DSA private key from
  5354. * dsa if not null is then set to the result
  5355. * cb password callback for reading PEM
  5356. * pass password string
  5357. *
  5358. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5359. */
  5360. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5361. WOLFSSL_DSA** dsa,
  5362. wc_pem_password_cb* cb,
  5363. void* pass)
  5364. {
  5365. WOLFSSL_EVP_PKEY* pkey = NULL;
  5366. WOLFSSL_DSA* local;
  5367. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5368. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5369. if (pkey == NULL) {
  5370. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5371. return NULL;
  5372. }
  5373. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5374. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5375. * to avoid having it free'd */
  5376. pkey->ownDsa = 0;
  5377. local = pkey->dsa;
  5378. if (dsa != NULL) {
  5379. *dsa = local;
  5380. }
  5381. wolfSSL_EVP_PKEY_free(pkey);
  5382. return local;
  5383. }
  5384. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5385. * Returns 1 or 0
  5386. */
  5387. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5388. wc_pem_password_cb* cb, void* pass)
  5389. {
  5390. WOLFSSL_EVP_PKEY* pkey;
  5391. WOLFSSL_DSA* local;
  5392. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5393. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5394. if (pkey == NULL) {
  5395. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5396. return NULL;
  5397. }
  5398. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5399. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5400. * to avoid having it free'd */
  5401. pkey->ownDsa = 0;
  5402. local = pkey->dsa;
  5403. if (dsa != NULL) {
  5404. *dsa = local;
  5405. }
  5406. wolfSSL_EVP_PKEY_free(pkey);
  5407. return local;
  5408. }
  5409. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5410. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5411. #endif /* NO_BIO */
  5412. #endif /* OPENSSL_EXTRA */
  5413. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5414. /* return 1 if success, -1 if error */
  5415. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5416. {
  5417. word32 idx = 0;
  5418. int ret;
  5419. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5420. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5421. WOLFSSL_MSG("Bad function arguments");
  5422. return -1;
  5423. }
  5424. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5425. (word32)derSz);
  5426. if (ret < 0) {
  5427. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5428. return -1;
  5429. }
  5430. if (SetDsaExternal(dsa) != 1) {
  5431. WOLFSSL_MSG("SetDsaExternal failed");
  5432. return -1;
  5433. }
  5434. dsa->inSet = 1;
  5435. return 1;
  5436. }
  5437. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5438. returns 1 on success, or 0 on failure. */
  5439. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5440. int derSz, int opt)
  5441. {
  5442. word32 idx = 0;
  5443. int ret;
  5444. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5445. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5446. WOLFSSL_MSG("Bad function arguments");
  5447. return -1;
  5448. }
  5449. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5450. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5451. (word32)derSz);
  5452. }
  5453. else {
  5454. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5455. (word32)derSz);
  5456. }
  5457. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5458. WOLFSSL_ERROR_VERBOSE(ret);
  5459. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5460. return -1;
  5461. }
  5462. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5463. WOLFSSL_ERROR_VERBOSE(ret);
  5464. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5465. return -1;
  5466. }
  5467. if (SetDsaExternal(dsa) != 1) {
  5468. WOLFSSL_MSG("SetDsaExternal failed");
  5469. return -1;
  5470. }
  5471. dsa->inSet = 1;
  5472. return 1;
  5473. }
  5474. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5475. #ifdef OPENSSL_EXTRA
  5476. #ifndef NO_BIO
  5477. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5478. wc_pem_password_cb *cb, void *u)
  5479. {
  5480. WOLFSSL_DSA* dsa;
  5481. DsaKey* key;
  5482. int length;
  5483. unsigned char* buf;
  5484. word32 bufSz;
  5485. int ret;
  5486. word32 idx = 0;
  5487. DerBuffer* pDer;
  5488. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5489. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5490. if (ret <= 0) {
  5491. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5492. return NULL;
  5493. }
  5494. bufSz = (word32)ret;
  5495. if (cb != NULL || u != NULL) {
  5496. /*
  5497. * cb is for a call back when encountering encrypted PEM files
  5498. * if cb == NULL and u != NULL then u = null terminated password string
  5499. */
  5500. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5501. }
  5502. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5503. NULL) < 0 ) {
  5504. WOLFSSL_MSG("Issue converting from PEM to DER");
  5505. return NULL;
  5506. }
  5507. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5508. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5509. FreeDer(&pDer);
  5510. return NULL;
  5511. }
  5512. dsa = wolfSSL_DSA_new();
  5513. if (dsa == NULL) {
  5514. FreeDer(&pDer);
  5515. WOLFSSL_MSG("Error creating DSA struct");
  5516. return NULL;
  5517. }
  5518. key = (DsaKey*)dsa->internal;
  5519. if (key == NULL) {
  5520. FreeDer(&pDer);
  5521. wolfSSL_DSA_free(dsa);
  5522. WOLFSSL_MSG("Error finding DSA key struct");
  5523. return NULL;
  5524. }
  5525. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5526. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5527. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5528. WOLFSSL_MSG("dsa key error");
  5529. FreeDer(&pDer);
  5530. wolfSSL_DSA_free(dsa);
  5531. return NULL;
  5532. }
  5533. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5534. WOLFSSL_MSG("dsa p key error");
  5535. FreeDer(&pDer);
  5536. wolfSSL_DSA_free(dsa);
  5537. return NULL;
  5538. }
  5539. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5540. WOLFSSL_MSG("dsa q key error");
  5541. FreeDer(&pDer);
  5542. wolfSSL_DSA_free(dsa);
  5543. return NULL;
  5544. }
  5545. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5546. WOLFSSL_MSG("dsa g key error");
  5547. FreeDer(&pDer);
  5548. wolfSSL_DSA_free(dsa);
  5549. return NULL;
  5550. }
  5551. if (x != NULL) {
  5552. *x = dsa;
  5553. }
  5554. FreeDer(&pDer);
  5555. return dsa;
  5556. }
  5557. #endif /* !NO_BIO */
  5558. #if !defined(NO_DH)
  5559. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5560. {
  5561. WOLFSSL_DH* dh;
  5562. DhKey* key;
  5563. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5564. if (dsa == NULL) {
  5565. return NULL;
  5566. }
  5567. dh = wolfSSL_DH_new();
  5568. if (dh == NULL) {
  5569. return NULL;
  5570. }
  5571. key = (DhKey*)dh->internal;
  5572. if (dsa->p != NULL &&
  5573. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5574. != 1) {
  5575. WOLFSSL_MSG("rsa p key error");
  5576. wolfSSL_DH_free(dh);
  5577. return NULL;
  5578. }
  5579. if (dsa->g != NULL &&
  5580. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5581. != 1) {
  5582. WOLFSSL_MSG("rsa g key error");
  5583. wolfSSL_DH_free(dh);
  5584. return NULL;
  5585. }
  5586. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5587. WOLFSSL_MSG("dsa p key error");
  5588. wolfSSL_DH_free(dh);
  5589. return NULL;
  5590. }
  5591. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5592. WOLFSSL_MSG("dsa g key error");
  5593. wolfSSL_DH_free(dh);
  5594. return NULL;
  5595. }
  5596. return dh;
  5597. }
  5598. #endif /* !NO_DH */
  5599. #endif /* OPENSSL_EXTRA */
  5600. #endif /* !NO_DSA */
  5601. /*******************************************************************************
  5602. * END OF DSA API
  5603. ******************************************************************************/
  5604. /*******************************************************************************
  5605. * START OF DH API
  5606. ******************************************************************************/
  5607. #ifndef NO_DH
  5608. #ifdef OPENSSL_EXTRA
  5609. /*
  5610. * DH constructor/deconstructor APIs
  5611. */
  5612. /* Allocate and initialize a new DH key.
  5613. *
  5614. * @return DH key on success.
  5615. * @return NULL on failure.
  5616. */
  5617. WOLFSSL_DH* wolfSSL_DH_new(void)
  5618. {
  5619. int err = 0;
  5620. WOLFSSL_DH* dh = NULL;
  5621. DhKey* key = NULL;
  5622. WOLFSSL_ENTER("wolfSSL_DH_new");
  5623. /* Allocate OpenSSL DH key. */
  5624. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5625. if (dh == NULL) {
  5626. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5627. err = 1;
  5628. }
  5629. if (!err) {
  5630. /* Clear key data. */
  5631. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5632. /* Initialize reference counting. */
  5633. wolfSSL_RefInit(&dh->ref, &err);
  5634. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5635. }
  5636. if (!err) {
  5637. #endif
  5638. /* Allocate wolfSSL DH key. */
  5639. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5640. if (key == NULL) {
  5641. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5642. err = 1;
  5643. }
  5644. }
  5645. if (!err) {
  5646. /* Set and initialize wolfSSL DH key. */
  5647. dh->internal = key;
  5648. if (wc_InitDhKey(key) != 0) {
  5649. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5650. err = 1;
  5651. }
  5652. }
  5653. if (err && (dh != NULL)) {
  5654. /* Dispose of the allocated memory. */
  5655. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5656. wolfSSL_RefFree(&dh->ref);
  5657. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5658. dh = NULL;
  5659. }
  5660. return dh;
  5661. }
  5662. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5663. /* Set the DH parameters based on the NID.
  5664. *
  5665. * @param [in, out] dh DH key to set.
  5666. * @param [in] nid Numeric ID of predefined DH parameters.
  5667. * @return 0 on success.
  5668. * @return 1 on failure.
  5669. */
  5670. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5671. {
  5672. int err = 0;
  5673. const DhParams* params = NULL;
  5674. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5675. * FIPS v2 module */
  5676. switch (nid) {
  5677. #ifdef HAVE_FFDHE_2048
  5678. case NID_ffdhe2048:
  5679. params = wc_Dh_ffdhe2048_Get();
  5680. break;
  5681. #endif /* HAVE_FFDHE_2048 */
  5682. #ifdef HAVE_FFDHE_3072
  5683. case NID_ffdhe3072:
  5684. params = wc_Dh_ffdhe3072_Get();
  5685. break;
  5686. #endif /* HAVE_FFDHE_3072 */
  5687. #ifdef HAVE_FFDHE_4096
  5688. case NID_ffdhe4096:
  5689. params = wc_Dh_ffdhe4096_Get();
  5690. break;
  5691. #endif /* HAVE_FFDHE_4096 */
  5692. default:
  5693. break;
  5694. }
  5695. if (params == NULL) {
  5696. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5697. err = 1;
  5698. }
  5699. if (!err) {
  5700. /* Set prime from data retrieved. */
  5701. dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL);
  5702. if (dh->p == NULL) {
  5703. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5704. err = 1;
  5705. }
  5706. }
  5707. if (!err) {
  5708. /* Set generator from data retrieved. */
  5709. dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL);
  5710. if (dh->g == NULL) {
  5711. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5712. err = 1;
  5713. }
  5714. }
  5715. #ifdef HAVE_FFDHE_Q
  5716. if (!err) {
  5717. /* Set order from data retrieved. */
  5718. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5719. if (dh->q == NULL) {
  5720. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5721. err = 1;
  5722. }
  5723. }
  5724. #endif
  5725. /* Synchronize the external into internal DH key's parameters. */
  5726. if ((!err) && (SetDhInternal(dh) != 1)) {
  5727. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5728. err = 1;
  5729. }
  5730. if (!err) {
  5731. /* External DH key parameters were set. */
  5732. dh->exSet = 1;
  5733. }
  5734. if (err == 1) {
  5735. /* Dispose of any external parameters. */
  5736. #ifdef HAVE_FFDHE_Q
  5737. wolfSSL_BN_free(dh->q);
  5738. dh->q = NULL;
  5739. #endif
  5740. wolfSSL_BN_free(dh->p);
  5741. dh->p = NULL;
  5742. wolfSSL_BN_free(dh->g);
  5743. dh->g = NULL;
  5744. }
  5745. return err;
  5746. }
  5747. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5748. FIPS_VERSION_GT(2,0))
  5749. /* Set the DH parameters based on the NID.
  5750. *
  5751. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5752. *
  5753. * @param [in, out] dh DH key to set.
  5754. * @param [in] nid Numeric ID of predefined DH parameters.
  5755. * @return 0 on success.
  5756. * @return 1 on failure.
  5757. */
  5758. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5759. {
  5760. int err = 0;
  5761. int name = 0;
  5762. #ifdef HAVE_FFDHE_Q
  5763. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5764. #else
  5765. int elements = ELEMENT_P | ELEMENT_G;
  5766. #endif /* HAVE_FFDHE_Q */
  5767. switch (nid) {
  5768. #ifdef HAVE_FFDHE_2048
  5769. case NID_ffdhe2048:
  5770. name = WC_FFDHE_2048;
  5771. break;
  5772. #endif /* HAVE_FFDHE_2048 */
  5773. #ifdef HAVE_FFDHE_3072
  5774. case NID_ffdhe3072:
  5775. name = WC_FFDHE_3072;
  5776. break;
  5777. #endif /* HAVE_FFDHE_3072 */
  5778. #ifdef HAVE_FFDHE_4096
  5779. case NID_ffdhe4096:
  5780. name = WC_FFDHE_4096;
  5781. break;
  5782. #endif /* HAVE_FFDHE_4096 */
  5783. default:
  5784. err = 1;
  5785. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5786. break;
  5787. }
  5788. /* Set the internal DH key's parameters based on name. */
  5789. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5790. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5791. err = 1;
  5792. }
  5793. /* Synchronize the internal into external DH key's parameters. */
  5794. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5795. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5796. err = 1;
  5797. }
  5798. return err;
  5799. }
  5800. #else
  5801. /* Set the DH parameters based on the NID.
  5802. *
  5803. * Pre-defined DH parameters not available.
  5804. *
  5805. * @param [in, out] dh DH key to set.
  5806. * @param [in] nid Numeric ID of predefined DH parameters.
  5807. * @return 1 for failure.
  5808. */
  5809. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5810. {
  5811. return 1;
  5812. }
  5813. #endif
  5814. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5815. *
  5816. * @param [in] nid Numeric ID of DH parameters.
  5817. *
  5818. * @return DH key on success.
  5819. * @return NULL on failure.
  5820. */
  5821. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5822. {
  5823. WOLFSSL_DH* dh = NULL;
  5824. int err = 0;
  5825. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5826. /* Allocate a new DH key. */
  5827. dh = wolfSSL_DH_new();
  5828. if (dh == NULL) {
  5829. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5830. err = 1;
  5831. }
  5832. if (!err) {
  5833. /* Set the parameters based on NID. */
  5834. err = wolfssl_dh_set_nid(dh, nid);
  5835. }
  5836. if (err && (dh != NULL)) {
  5837. /* Dispose of the key on failure to set. */
  5838. wolfSSL_DH_free(dh);
  5839. dh = NULL;
  5840. }
  5841. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5842. return dh;
  5843. }
  5844. /* Dispose of DH key and allocated data.
  5845. *
  5846. * Cannot use dh after this call.
  5847. *
  5848. * @param [in] dh DH key to free.
  5849. */
  5850. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5851. {
  5852. int doFree = 0;
  5853. WOLFSSL_ENTER("wolfSSL_DH_free");
  5854. if (dh != NULL) {
  5855. int err;
  5856. /* Only free if all references to it are done */
  5857. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5858. /* Ignore errors - doFree will be 0 on error. */
  5859. (void)err;
  5860. }
  5861. if (doFree) {
  5862. /* Dispose of allocated reference counting data. */
  5863. wolfSSL_RefFree(&dh->ref);
  5864. /* Dispose of wolfSSL DH key. */
  5865. if (dh->internal) {
  5866. wc_FreeDhKey((DhKey*)dh->internal);
  5867. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5868. dh->internal = NULL;
  5869. }
  5870. /* Dispose of any allocated BNs. */
  5871. wolfSSL_BN_free(dh->priv_key);
  5872. wolfSSL_BN_free(dh->pub_key);
  5873. wolfSSL_BN_free(dh->g);
  5874. wolfSSL_BN_free(dh->p);
  5875. wolfSSL_BN_free(dh->q);
  5876. /* Set back to NULLs for safety. */
  5877. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5878. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5879. }
  5880. }
  5881. /* Increments ref count of DH key.
  5882. *
  5883. * @param [in, out] dh DH key.
  5884. * @return 1 on success
  5885. * @return 0 on error
  5886. */
  5887. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5888. {
  5889. int err = 1;
  5890. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5891. if (dh != NULL) {
  5892. wolfSSL_RefInc(&dh->ref, &err);
  5893. }
  5894. return !err;
  5895. }
  5896. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5897. defined(OPENSSL_EXTRA)
  5898. #ifdef WOLFSSL_DH_EXTRA
  5899. /* Duplicate the DH key.
  5900. *
  5901. * Internal DH key in 'dh' is updated if necessary.
  5902. *
  5903. * @param [in, out] dh DH key to duplicate.
  5904. * @return NULL on failure.
  5905. * @return DH key on success.
  5906. */
  5907. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5908. {
  5909. WOLFSSL_DH* ret = NULL;
  5910. int err = 0;
  5911. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5912. /* Validate parameters. */
  5913. if (dh == NULL) {
  5914. WOLFSSL_ERROR_MSG("Bad parameter");
  5915. err = 1;
  5916. }
  5917. /* Ensure internal DH key is set. */
  5918. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5919. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5920. err = 1;
  5921. }
  5922. /* Create a new DH key object. */
  5923. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5924. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5925. err = 1;
  5926. }
  5927. /* Copy internal DH key from original to new. */
  5928. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5929. MP_OKAY)) {
  5930. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5931. err = 1;
  5932. }
  5933. if (!err) {
  5934. ret->inSet = 1;
  5935. /* Synchronize the internal into external DH key's parameters. */
  5936. if (SetDhExternal(ret) != 1) {
  5937. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5938. err = 1;
  5939. }
  5940. }
  5941. /* Dispose of any allocated DH key on error. */
  5942. if (err && (ret != NULL)) {
  5943. wolfSSL_DH_free(ret);
  5944. ret = NULL;
  5945. }
  5946. return ret;
  5947. }
  5948. #endif /* WOLFSSL_DH_EXTRA */
  5949. #endif
  5950. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5951. *
  5952. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5953. * Subgroup."
  5954. *
  5955. * @return NULL on failure.
  5956. * @return DH Key on success.
  5957. */
  5958. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5959. {
  5960. WOLFSSL_DH* dh;
  5961. int err = 0;
  5962. static const byte pHex[] = {
  5963. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5964. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5965. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5966. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5967. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5968. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5969. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5970. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5971. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5972. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5973. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5974. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5975. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5976. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5977. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5978. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5979. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5980. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5981. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5982. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5983. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5984. 0x1E, 0x1A, 0x15, 0x97
  5985. };
  5986. static const byte gHex[] = {
  5987. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5988. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5989. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5990. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5991. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5992. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5993. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5994. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5995. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5996. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5997. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5998. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5999. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  6000. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  6001. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  6002. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  6003. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  6004. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  6005. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  6006. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  6007. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  6008. 0x6C, 0xC4, 0x16, 0x59
  6009. };
  6010. static const byte qHex[] = {
  6011. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  6012. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  6013. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  6014. };
  6015. /* Create a new DH key to return. */
  6016. dh = wolfSSL_DH_new();
  6017. if (dh == NULL) {
  6018. err = 1;
  6019. }
  6020. if (!err) {
  6021. /* Set prime. */
  6022. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  6023. if (dh->p == NULL) {
  6024. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  6025. err = 1;
  6026. }
  6027. }
  6028. if (!err) {
  6029. /* Set generator. */
  6030. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  6031. if (dh->g == NULL) {
  6032. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  6033. err = 1;
  6034. }
  6035. }
  6036. if (!err) {
  6037. /* Set order. */
  6038. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  6039. if (dh->q == NULL) {
  6040. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  6041. err = 1;
  6042. }
  6043. }
  6044. /* Set values into wolfSSL DH key. */
  6045. if ((!err) && (SetDhInternal(dh) != 1)) {
  6046. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  6047. err = 1;
  6048. }
  6049. if (!err) {
  6050. /* External DH key parameters were set. */
  6051. dh->exSet = 1;
  6052. }
  6053. /* Dispose of any allocated DH key on error. */
  6054. if (err && (dh != NULL)) {
  6055. wolfSSL_DH_free(dh);
  6056. dh = NULL;
  6057. }
  6058. return dh;
  6059. }
  6060. /* TODO: consider changing strings to byte arrays. */
  6061. /* Returns a big number with the 768-bit prime from RFC 2409.
  6062. *
  6063. * @param [in, out] bn If not NULL then this BN is set and returned.
  6064. * If NULL then a new BN is created, set and returned.
  6065. *
  6066. * @return NULL on failure.
  6067. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  6068. */
  6069. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  6070. {
  6071. #if WOLFSSL_MAX_BN_BITS >= 768
  6072. static const char prm[] = {
  6073. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6074. "C4C6628B80DC1CD129024E088A67CC74"
  6075. "020BBEA63B139B22514A08798E3404DD"
  6076. "EF9519B3CD3A431B302B0A6DF25F1437"
  6077. "4FE1356D6D51C245E485B576625E7EC6"
  6078. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  6079. };
  6080. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  6081. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6082. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6083. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  6084. bn = NULL;
  6085. }
  6086. return bn;
  6087. #else
  6088. (void)bn;
  6089. return NULL;
  6090. #endif
  6091. }
  6092. /* Returns a big number with the 1024-bit prime from RFC 2409.
  6093. *
  6094. * @param [in, out] bn If not NULL then this BN is set and returned.
  6095. * If NULL then a new BN is created, set and returned.
  6096. *
  6097. * @return NULL on failure.
  6098. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  6099. */
  6100. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  6101. {
  6102. #if WOLFSSL_MAX_BN_BITS >= 1024
  6103. static const char prm[] = {
  6104. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6105. "C4C6628B80DC1CD129024E088A67CC74"
  6106. "020BBEA63B139B22514A08798E3404DD"
  6107. "EF9519B3CD3A431B302B0A6DF25F1437"
  6108. "4FE1356D6D51C245E485B576625E7EC6"
  6109. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6110. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6111. "49286651ECE65381FFFFFFFFFFFFFFFF"
  6112. };
  6113. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  6114. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6115. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6116. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  6117. bn = NULL;
  6118. }
  6119. return bn;
  6120. #else
  6121. (void)bn;
  6122. return NULL;
  6123. #endif
  6124. }
  6125. /* Returns a big number with the 1536-bit prime from RFC 3526.
  6126. *
  6127. * @param [in, out] bn If not NULL then this BN is set and returned.
  6128. * If NULL then a new BN is created, set and returned.
  6129. *
  6130. * @return NULL on failure.
  6131. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  6132. */
  6133. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  6134. {
  6135. #if WOLFSSL_MAX_BN_BITS >= 1536
  6136. static const char prm[] = {
  6137. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6138. "C4C6628B80DC1CD129024E088A67CC74"
  6139. "020BBEA63B139B22514A08798E3404DD"
  6140. "EF9519B3CD3A431B302B0A6DF25F1437"
  6141. "4FE1356D6D51C245E485B576625E7EC6"
  6142. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6143. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6144. "49286651ECE45B3DC2007CB8A163BF05"
  6145. "98DA48361C55D39A69163FA8FD24CF5F"
  6146. "83655D23DCA3AD961C62F356208552BB"
  6147. "9ED529077096966D670C354E4ABC9804"
  6148. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6149. };
  6150. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6151. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6152. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6153. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6154. bn = NULL;
  6155. }
  6156. return bn;
  6157. #else
  6158. (void)bn;
  6159. return NULL;
  6160. #endif
  6161. }
  6162. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6163. *
  6164. * @param [in, out] bn If not NULL then this BN is set and returned.
  6165. * If NULL then a new BN is created, set and returned.
  6166. *
  6167. * @return NULL on failure.
  6168. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6169. */
  6170. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6171. {
  6172. #if WOLFSSL_MAX_BN_BITS >= 2048
  6173. static const char prm[] = {
  6174. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6175. "C4C6628B80DC1CD129024E088A67CC74"
  6176. "020BBEA63B139B22514A08798E3404DD"
  6177. "EF9519B3CD3A431B302B0A6DF25F1437"
  6178. "4FE1356D6D51C245E485B576625E7EC6"
  6179. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6180. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6181. "49286651ECE45B3DC2007CB8A163BF05"
  6182. "98DA48361C55D39A69163FA8FD24CF5F"
  6183. "83655D23DCA3AD961C62F356208552BB"
  6184. "9ED529077096966D670C354E4ABC9804"
  6185. "F1746C08CA18217C32905E462E36CE3B"
  6186. "E39E772C180E86039B2783A2EC07A28F"
  6187. "B5C55DF06F4C52C9DE2BCBF695581718"
  6188. "3995497CEA956AE515D2261898FA0510"
  6189. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6190. };
  6191. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6192. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6193. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6194. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6195. bn = NULL;
  6196. }
  6197. return bn;
  6198. #else
  6199. (void)bn;
  6200. return NULL;
  6201. #endif
  6202. }
  6203. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6204. *
  6205. * @param [in, out] bn If not NULL then this BN is set and returned.
  6206. * If NULL then a new BN is created, set and returned.
  6207. *
  6208. * @return NULL on failure.
  6209. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6210. */
  6211. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6212. {
  6213. #if WOLFSSL_MAX_BN_BITS >= 3072
  6214. static const char prm[] = {
  6215. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6216. "C4C6628B80DC1CD129024E088A67CC74"
  6217. "020BBEA63B139B22514A08798E3404DD"
  6218. "EF9519B3CD3A431B302B0A6DF25F1437"
  6219. "4FE1356D6D51C245E485B576625E7EC6"
  6220. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6221. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6222. "49286651ECE45B3DC2007CB8A163BF05"
  6223. "98DA48361C55D39A69163FA8FD24CF5F"
  6224. "83655D23DCA3AD961C62F356208552BB"
  6225. "9ED529077096966D670C354E4ABC9804"
  6226. "F1746C08CA18217C32905E462E36CE3B"
  6227. "E39E772C180E86039B2783A2EC07A28F"
  6228. "B5C55DF06F4C52C9DE2BCBF695581718"
  6229. "3995497CEA956AE515D2261898FA0510"
  6230. "15728E5A8AAAC42DAD33170D04507A33"
  6231. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6232. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6233. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6234. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6235. "D87602733EC86A64521F2B18177B200C"
  6236. "BBE117577A615D6C770988C0BAD946E2"
  6237. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6238. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6239. };
  6240. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6241. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6242. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6243. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6244. bn = NULL;
  6245. }
  6246. return bn;
  6247. #else
  6248. (void)bn;
  6249. return NULL;
  6250. #endif
  6251. }
  6252. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6253. *
  6254. * @param [in, out] bn If not NULL then this BN is set and returned.
  6255. * If NULL then a new BN is created, set and returned.
  6256. *
  6257. * @return NULL on failure.
  6258. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6259. */
  6260. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6261. {
  6262. #if WOLFSSL_MAX_BN_BITS >= 4096
  6263. static const char prm[] = {
  6264. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6265. "C4C6628B80DC1CD129024E088A67CC74"
  6266. "020BBEA63B139B22514A08798E3404DD"
  6267. "EF9519B3CD3A431B302B0A6DF25F1437"
  6268. "4FE1356D6D51C245E485B576625E7EC6"
  6269. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6270. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6271. "49286651ECE45B3DC2007CB8A163BF05"
  6272. "98DA48361C55D39A69163FA8FD24CF5F"
  6273. "83655D23DCA3AD961C62F356208552BB"
  6274. "9ED529077096966D670C354E4ABC9804"
  6275. "F1746C08CA18217C32905E462E36CE3B"
  6276. "E39E772C180E86039B2783A2EC07A28F"
  6277. "B5C55DF06F4C52C9DE2BCBF695581718"
  6278. "3995497CEA956AE515D2261898FA0510"
  6279. "15728E5A8AAAC42DAD33170D04507A33"
  6280. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6281. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6282. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6283. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6284. "D87602733EC86A64521F2B18177B200C"
  6285. "BBE117577A615D6C770988C0BAD946E2"
  6286. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6287. "4B82D120A92108011A723C12A787E6D7"
  6288. "88719A10BDBA5B2699C327186AF4E23C"
  6289. "1A946834B6150BDA2583E9CA2AD44CE8"
  6290. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6291. "287C59474E6BC05D99B2964FA090C3A2"
  6292. "233BA186515BE7ED1F612970CEE2D7AF"
  6293. "B81BDD762170481CD0069127D5B05AA9"
  6294. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6295. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6296. };
  6297. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6298. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6299. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6300. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6301. bn = NULL;
  6302. }
  6303. return bn;
  6304. #else
  6305. (void)bn;
  6306. return NULL;
  6307. #endif
  6308. }
  6309. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6310. *
  6311. * @param [in, out] bn If not NULL then this BN is set and returned.
  6312. * If NULL then a new BN is created, set and returned.
  6313. *
  6314. * @return NULL on failure.
  6315. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6316. */
  6317. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6318. {
  6319. #if WOLFSSL_MAX_BN_BITS >= 6144
  6320. static const char prm[] = {
  6321. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6322. "C4C6628B80DC1CD129024E088A67CC74"
  6323. "020BBEA63B139B22514A08798E3404DD"
  6324. "EF9519B3CD3A431B302B0A6DF25F1437"
  6325. "4FE1356D6D51C245E485B576625E7EC6"
  6326. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6327. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6328. "49286651ECE45B3DC2007CB8A163BF05"
  6329. "98DA48361C55D39A69163FA8FD24CF5F"
  6330. "83655D23DCA3AD961C62F356208552BB"
  6331. "9ED529077096966D670C354E4ABC9804"
  6332. "F1746C08CA18217C32905E462E36CE3B"
  6333. "E39E772C180E86039B2783A2EC07A28F"
  6334. "B5C55DF06F4C52C9DE2BCBF695581718"
  6335. "3995497CEA956AE515D2261898FA0510"
  6336. "15728E5A8AAAC42DAD33170D04507A33"
  6337. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6338. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6339. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6340. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6341. "D87602733EC86A64521F2B18177B200C"
  6342. "BBE117577A615D6C770988C0BAD946E2"
  6343. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6344. "4B82D120A92108011A723C12A787E6D7"
  6345. "88719A10BDBA5B2699C327186AF4E23C"
  6346. "1A946834B6150BDA2583E9CA2AD44CE8"
  6347. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6348. "287C59474E6BC05D99B2964FA090C3A2"
  6349. "233BA186515BE7ED1F612970CEE2D7AF"
  6350. "B81BDD762170481CD0069127D5B05AA9"
  6351. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6352. "4DF435C93402849236C3FAB4D27C7026"
  6353. "C1D4DCB2602646DEC9751E763DBA37BD"
  6354. "F8FF9406AD9E530EE5DB382F413001AE"
  6355. "B06A53ED9027D831179727B0865A8918"
  6356. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6357. "DB7F1447E6CC254B332051512BD7AF42"
  6358. "6FB8F401378CD2BF5983CA01C64B92EC"
  6359. "F032EA15D1721D03F482D7CE6E74FEF6"
  6360. "D55E702F46980C82B5A84031900B1C9E"
  6361. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6362. "0F1D45B7FF585AC54BD407B22B4154AA"
  6363. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6364. "A79715EEF29BE32806A1D58BB7C5DA76"
  6365. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6366. "DA56C9EC2EF29632387FE8D76E3C0468"
  6367. "043E8F663F4860EE12BF2D5B0B7474D6"
  6368. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6369. };
  6370. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6371. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6372. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6373. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6374. bn = NULL;
  6375. }
  6376. return bn;
  6377. #else
  6378. (void)bn;
  6379. return NULL;
  6380. #endif
  6381. }
  6382. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6383. *
  6384. * @param [in, out] bn If not NULL then this BN is set and returned.
  6385. * If NULL then a new BN is created, set and returned.
  6386. *
  6387. * @return NULL on failure.
  6388. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6389. */
  6390. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6391. {
  6392. #if WOLFSSL_MAX_BN_BITS >= 8192
  6393. static const char prm[] = {
  6394. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6395. "C4C6628B80DC1CD129024E088A67CC74"
  6396. "020BBEA63B139B22514A08798E3404DD"
  6397. "EF9519B3CD3A431B302B0A6DF25F1437"
  6398. "4FE1356D6D51C245E485B576625E7EC6"
  6399. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6400. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6401. "49286651ECE45B3DC2007CB8A163BF05"
  6402. "98DA48361C55D39A69163FA8FD24CF5F"
  6403. "83655D23DCA3AD961C62F356208552BB"
  6404. "9ED529077096966D670C354E4ABC9804"
  6405. "F1746C08CA18217C32905E462E36CE3B"
  6406. "E39E772C180E86039B2783A2EC07A28F"
  6407. "B5C55DF06F4C52C9DE2BCBF695581718"
  6408. "3995497CEA956AE515D2261898FA0510"
  6409. "15728E5A8AAAC42DAD33170D04507A33"
  6410. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6411. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6412. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6413. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6414. "D87602733EC86A64521F2B18177B200C"
  6415. "BBE117577A615D6C770988C0BAD946E2"
  6416. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6417. "4B82D120A92108011A723C12A787E6D7"
  6418. "88719A10BDBA5B2699C327186AF4E23C"
  6419. "1A946834B6150BDA2583E9CA2AD44CE8"
  6420. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6421. "287C59474E6BC05D99B2964FA090C3A2"
  6422. "233BA186515BE7ED1F612970CEE2D7AF"
  6423. "B81BDD762170481CD0069127D5B05AA9"
  6424. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6425. "4DF435C93402849236C3FAB4D27C7026"
  6426. "C1D4DCB2602646DEC9751E763DBA37BD"
  6427. "F8FF9406AD9E530EE5DB382F413001AE"
  6428. "B06A53ED9027D831179727B0865A8918"
  6429. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6430. "DB7F1447E6CC254B332051512BD7AF42"
  6431. "6FB8F401378CD2BF5983CA01C64B92EC"
  6432. "F032EA15D1721D03F482D7CE6E74FEF6"
  6433. "D55E702F46980C82B5A84031900B1C9E"
  6434. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6435. "0F1D45B7FF585AC54BD407B22B4154AA"
  6436. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6437. "A79715EEF29BE32806A1D58BB7C5DA76"
  6438. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6439. "DA56C9EC2EF29632387FE8D76E3C0468"
  6440. "043E8F663F4860EE12BF2D5B0B7474D6"
  6441. "E694F91E6DBE115974A3926F12FEE5E4"
  6442. "38777CB6A932DF8CD8BEC4D073B931BA"
  6443. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6444. "2576F6936BA424663AAB639C5AE4F568"
  6445. "3423B4742BF1C978238F16CBE39D652D"
  6446. "E3FDB8BEFC848AD922222E04A4037C07"
  6447. "13EB57A81A23F0C73473FC646CEA306B"
  6448. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6449. "79683303ED5BDD3A062B3CF5B3A278A6"
  6450. "6D2A13F83F44F82DDF310EE074AB6A36"
  6451. "4597E899A0255DC164F31CC50846851D"
  6452. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6453. "FAF36BC31ECFA268359046F4EB879F92"
  6454. "4009438B481C6CD7889A002ED5EE382B"
  6455. "C9190DA6FC026E479558E4475677E9AA"
  6456. "9E3050E2765694DFC81F56E880B96E71"
  6457. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6458. };
  6459. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6460. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6461. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6462. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6463. bn = NULL;
  6464. }
  6465. return bn;
  6466. #else
  6467. (void)bn;
  6468. return NULL;
  6469. #endif
  6470. }
  6471. /*
  6472. * DH to/from bin APIs
  6473. */
  6474. #ifndef NO_CERTS
  6475. /* Load the DER encoded DH parameters/key into DH key.
  6476. *
  6477. * @param [in, out] dh DH key to load parameters into.
  6478. * @param [in] der Buffer holding DER encoded parameters data.
  6479. * @param [in, out] idx On in, index at which DH key DER data starts.
  6480. * On out, index after DH key DER data.
  6481. * @param [in] derSz Size of DER buffer in bytes.
  6482. *
  6483. * @return 0 on success.
  6484. * @return 1 when decoding DER or setting the external key fails.
  6485. */
  6486. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6487. word32* idx, word32 derSz)
  6488. {
  6489. int err = 0;
  6490. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6491. int ret;
  6492. /* Decode DH parameters/key from DER. */
  6493. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6494. if (ret != 0) {
  6495. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6496. err = 1;
  6497. }
  6498. if (!err) {
  6499. /* wolfSSL DH key set. */
  6500. dh->inSet = 1;
  6501. /* Set the external DH key based on wolfSSL DH key. */
  6502. if (SetDhExternal(dh) != 1) {
  6503. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6504. err = 1;
  6505. }
  6506. }
  6507. #else
  6508. byte* p;
  6509. byte* g;
  6510. word32 pSz = MAX_DH_SIZE;
  6511. word32 gSz = MAX_DH_SIZE;
  6512. /* Only DH parameters supported. */
  6513. /* Load external and set internal. */
  6514. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6515. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6516. if ((p == NULL) || (g == NULL)) {
  6517. err = 1;
  6518. }
  6519. /* Extract the p and g as data from the DER encoded DH parameters. */
  6520. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6521. &gSz) < 0)) {
  6522. err = 1;
  6523. }
  6524. if (!err) {
  6525. /* Put p and g in as big numbers - free existing BNs. */
  6526. if (dh->p != NULL) {
  6527. wolfSSL_BN_free(dh->p);
  6528. dh->p = NULL;
  6529. }
  6530. if (dh->g != NULL) {
  6531. wolfSSL_BN_free(dh->g);
  6532. dh->g = NULL;
  6533. }
  6534. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6535. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6536. if (dh->p == NULL || dh->g == NULL) {
  6537. err = 1;
  6538. }
  6539. else {
  6540. /* External DH key parameters were set. */
  6541. dh->exSet = 1;
  6542. }
  6543. }
  6544. /* Set internal as the outside has been updated. */
  6545. if ((!err) && (SetDhInternal(dh) != 1)) {
  6546. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6547. err = 1;
  6548. }
  6549. if (!err) {
  6550. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6551. }
  6552. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6553. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6554. #endif
  6555. return err;
  6556. }
  6557. #ifdef OPENSSL_ALL
  6558. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6559. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6560. *
  6561. * @param [out] dh DH key to put parameters into. May be NULL.
  6562. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6563. * Value updated to end of data when dh is not NULL.
  6564. * @param [in] length Length of data available in bytes.
  6565. *
  6566. * @return DH key on success.
  6567. * @return NULL on failure.
  6568. */
  6569. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6570. long length)
  6571. {
  6572. WOLFSSL_DH *newDh = NULL;
  6573. word32 idx = 0;
  6574. int err = 0;
  6575. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6576. /* Validate parameters. */
  6577. if ((pp == NULL) || (length <= 0)) {
  6578. WOLFSSL_ERROR_MSG("bad argument");
  6579. err = 1;
  6580. }
  6581. /* Create new DH key to return. */
  6582. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6583. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6584. err = 1;
  6585. }
  6586. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6587. (word32)length) != 0)) {
  6588. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6589. err = 1;
  6590. }
  6591. if ((!err) && (dh != NULL)) {
  6592. /* Return through parameter too. */
  6593. *dh = newDh;
  6594. /* Move buffer on by the used amount. */
  6595. *pp += idx;
  6596. }
  6597. if (err && (newDh != NULL)) {
  6598. /* Dispose of any created DH key. */
  6599. wolfSSL_DH_free(newDh);
  6600. newDh = NULL;
  6601. }
  6602. return newDh;
  6603. }
  6604. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6605. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6606. *
  6607. * @params [in] dh DH key with parameters to encode.
  6608. * @params [in, out] out Pointer to buffer to encode into.
  6609. * When NULL or pointer to NULL, only length returned.
  6610. * @return 0 on error.
  6611. * @return Size of DER encoding in bytes on success.
  6612. */
  6613. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6614. {
  6615. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6616. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6617. word32 len = (word32)-1;
  6618. int err = 0;
  6619. /* Validate parameters. */
  6620. if (dh == NULL) {
  6621. WOLFSSL_ERROR_MSG("Bad parameters");
  6622. err = 1;
  6623. }
  6624. /* Push external DH data into internal DH key if not set. */
  6625. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6626. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6627. err = 1;
  6628. }
  6629. if (!err) {
  6630. int ret;
  6631. unsigned char* der = NULL;
  6632. /* Use *out when available otherwise NULL. */
  6633. if (out != NULL) {
  6634. der = *out;
  6635. }
  6636. /* Get length and/or encode. */
  6637. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6638. /* Length of encoded data is returned on success. */
  6639. if (ret > 0) {
  6640. *out += len;
  6641. }
  6642. /* An error occurred unless only length returned. */
  6643. else if (ret != LENGTH_ONLY_E) {
  6644. err = 1;
  6645. }
  6646. }
  6647. /* Set return to 0 on error. */
  6648. if (err) {
  6649. len = 0;
  6650. }
  6651. return (int)len;
  6652. #else
  6653. word32 len;
  6654. int ret = 0;
  6655. int pSz;
  6656. int gSz;
  6657. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6658. /* Validate parameters. */
  6659. if (dh == NULL) {
  6660. WOLFSSL_ERROR_MSG("Bad parameters");
  6661. len = 0;
  6662. }
  6663. else {
  6664. /* SEQ <len>
  6665. * INT <len> [0x00] <prime>
  6666. * INT <len> [0x00] <generator>
  6667. * Integers have 0x00 prepended if the top bit of positive number is
  6668. * set.
  6669. */
  6670. /* Get total length of prime including any prepended zeros. */
  6671. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6672. mp_leading_bit((mp_int*)dh->p->internal);
  6673. /* Get total length of generator including any prepended zeros. */
  6674. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6675. mp_leading_bit((mp_int*)dh->g->internal);
  6676. /* Calculate length of data in sequence. */
  6677. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6678. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6679. /* Add in the length of the SEQUENCE. */
  6680. len += 1 + ASN_LEN_SIZE(len);
  6681. if ((out != NULL) && (*out != NULL)) {
  6682. /* Encode parameters. */
  6683. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6684. (mp_int*)dh->g->internal);
  6685. if (ret != MP_OKAY) {
  6686. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6687. len = 0;
  6688. }
  6689. else {
  6690. /* Move pointer on if encoded. */
  6691. *out += len;
  6692. }
  6693. }
  6694. }
  6695. return (int)len;
  6696. #endif
  6697. }
  6698. #endif /* OPENSSL_ALL */
  6699. #endif /* !NO_CERTS */
  6700. #endif /* OPENSSL_EXTRA */
  6701. #if defined(OPENSSL_EXTRA) || \
  6702. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6703. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6704. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6705. /* Load the DER encoded DH parameters into DH key.
  6706. *
  6707. * @param [in, out] dh DH key to load parameters into.
  6708. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6709. * @param [in] derSz Size of DER data in buffer in bytes.
  6710. *
  6711. * @return 1 on success.
  6712. * @return -1 when DH or derBuf is NULL,
  6713. * internal DH key in DH is NULL,
  6714. * derSz is 0 or less,
  6715. * error decoding DER data or
  6716. * setting external parameter values fails.
  6717. */
  6718. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6719. {
  6720. int ret = 1;
  6721. word32 idx = 0;
  6722. /* Validate parameters. */
  6723. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6724. (derSz <= 0)) {
  6725. WOLFSSL_ERROR_MSG("Bad function arguments");
  6726. ret = -1;
  6727. }
  6728. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6729. (word32)derSz) != 0)) {
  6730. WOLFSSL_ERROR_MSG("DH key decode failed");
  6731. ret = -1;
  6732. }
  6733. return ret;
  6734. }
  6735. #endif
  6736. /*
  6737. * DH PEM APIs
  6738. */
  6739. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6740. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6741. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6742. /* Create a DH key by reading the PEM encoded data from the BIO.
  6743. *
  6744. * @param [in] bio BIO object to read from.
  6745. * @param [in, out] dh DH key to use. May be NULL.
  6746. * @param [in] pem PEM data to decode.
  6747. * @param [in] pemSz Size of PEM data in bytes.
  6748. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6749. * freed after use.
  6750. * @return DH key on success.
  6751. * @return NULL on failure.
  6752. */
  6753. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6754. unsigned char* pem, int pemSz, int memAlloced)
  6755. {
  6756. WOLFSSL_DH* localDh = NULL;
  6757. DerBuffer *der = NULL;
  6758. int err = 0;
  6759. /* Convert PEM to DER assuming DH Parameter format. */
  6760. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6761. NULL) < 0)) {
  6762. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6763. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6764. != 0) {
  6765. err = 1;
  6766. }
  6767. /* If Success on X9.42 DH format, clear error from failed DH format */
  6768. else {
  6769. unsigned long error;
  6770. CLEAR_ASN_NO_PEM_HEADER_ERROR(error);
  6771. }
  6772. }
  6773. if (memAlloced) {
  6774. /* PEM data no longer needed. */
  6775. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6776. }
  6777. if (!err) {
  6778. /* Use the DH key passed in or allocate a new one. */
  6779. if (dh != NULL) {
  6780. localDh = *dh;
  6781. }
  6782. if (localDh == NULL) {
  6783. localDh = wolfSSL_DH_new();
  6784. if (localDh == NULL) {
  6785. err = 1;
  6786. }
  6787. }
  6788. }
  6789. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6790. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length)
  6791. != 1)) {
  6792. /* Free an allocated DH key. */
  6793. if ((dh == NULL) || (localDh != *dh)) {
  6794. wolfSSL_DH_free(localDh);
  6795. }
  6796. localDh = NULL;
  6797. err = 1;
  6798. }
  6799. /* Return the DH key on success. */
  6800. if ((!err) && (dh != NULL)) {
  6801. *dh = localDh;
  6802. }
  6803. /* Dispose of DER data. */
  6804. if (der != NULL) {
  6805. FreeDer(&der);
  6806. }
  6807. return localDh;
  6808. }
  6809. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6810. #ifndef NO_BIO
  6811. /* Create a DH key by reading the PEM encoded data from the BIO.
  6812. *
  6813. * DH parameters are public data and are not expected to be encrypted.
  6814. *
  6815. * @param [in] bio BIO object to read from.
  6816. * @param [in, out] dh DH key to When pointer to
  6817. * NULL, a new DH key is created.
  6818. * @param [in] cb Password callback when PEM encrypted. Not used.
  6819. * @param [in] pass NUL terminated string for passphrase when PEM
  6820. * encrypted. Not used.
  6821. * @return DH key on success.
  6822. * @return NULL on failure.
  6823. */
  6824. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6825. wc_pem_password_cb *cb, void *pass)
  6826. {
  6827. WOLFSSL_DH* localDh = NULL;
  6828. int err = 0;
  6829. unsigned char* mem = NULL;
  6830. int size = 0;
  6831. int memAlloced = 0;
  6832. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6833. (void)cb;
  6834. (void)pass;
  6835. /* Validate parameters. */
  6836. if (bio == NULL) {
  6837. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6838. err = 1;
  6839. }
  6840. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6841. */
  6842. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6843. != 0)) {
  6844. err = 1;
  6845. }
  6846. if (!err) {
  6847. /* Create a DH key from the PEM - try two different headers. */
  6848. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6849. }
  6850. return localDh;
  6851. }
  6852. #endif /* !NO_BIO */
  6853. #ifndef NO_FILESYSTEM
  6854. /* Read DH parameters from a file pointer into DH key.
  6855. *
  6856. * DH parameters are public data and are not expected to be encrypted.
  6857. *
  6858. * @param [in] fp File pointer to read DH parameter file from.
  6859. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6860. * NULL, a new DH key is created.
  6861. * @param [in] cb Password callback when PEM encrypted. Not used.
  6862. * @param [in] pass NUL terminated string for passphrase when PEM
  6863. * encrypted. Not used.
  6864. *
  6865. * @return NULL on failure.
  6866. * @return DH key with parameters set on success.
  6867. */
  6868. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6869. wc_pem_password_cb* cb, void* pass)
  6870. {
  6871. WOLFSSL_DH* localDh = NULL;
  6872. int err = 0;
  6873. unsigned char* mem = NULL;
  6874. int size = 0;
  6875. (void)cb;
  6876. (void)pass;
  6877. /* Read data from file pointer. */
  6878. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6879. err = 1;
  6880. }
  6881. if (!err) {
  6882. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6883. }
  6884. return localDh;
  6885. }
  6886. #endif /* !NO_FILESYSTEM */
  6887. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6888. /* Encoded parameter data in DH key as DER.
  6889. *
  6890. * @param [in, out] dh DH key object to encode.
  6891. * @param [out] out Buffer containing DER encoding.
  6892. * @param [in] heap Heap hint.
  6893. * @return <0 on error.
  6894. * @return Length of DER encoded DH parameters in bytes.
  6895. */
  6896. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6897. void* heap)
  6898. {
  6899. int ret = -1;
  6900. int err = 0;
  6901. byte* der = NULL;
  6902. word32 derSz;
  6903. DhKey* key = NULL;
  6904. (void)heap;
  6905. /* Set internal parameters based on external parameters. */
  6906. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6907. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6908. err = 1;
  6909. }
  6910. if (!err) {
  6911. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6912. key = (DhKey*)dh->internal;
  6913. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6914. if (ret != LENGTH_ONLY_E) {
  6915. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6916. err = 1;
  6917. }
  6918. }
  6919. if (!err) {
  6920. /* Allocate memory for DER encoding. */
  6921. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6922. if (der == NULL) {
  6923. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6924. err = 1;
  6925. }
  6926. }
  6927. if (!err) {
  6928. /* Encode DH parameters into DER buffer. */
  6929. ret = wc_DhParamsToDer(key, der, &derSz);
  6930. if (ret < 0) {
  6931. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6932. err = 1;
  6933. }
  6934. }
  6935. if (!err) {
  6936. *out = der;
  6937. der = NULL;
  6938. }
  6939. if (der != NULL) {
  6940. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6941. }
  6942. return ret;
  6943. }
  6944. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6945. * passed in.
  6946. *
  6947. * @param [in] fp File pointer to write to.
  6948. * @param [in] dh DH key to write.
  6949. * @return 1 on success.
  6950. * @return 0 on failure.
  6951. */
  6952. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6953. {
  6954. int ret = 1;
  6955. int derSz;
  6956. byte* derBuf = NULL;
  6957. void* heap = NULL;
  6958. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6959. /* Validate parameters. */
  6960. if ((fp == XBADFILE) || (dh == NULL)) {
  6961. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6962. ret = 0;
  6963. }
  6964. if (ret == 1) {
  6965. DhKey* key = (DhKey*)dh->internal;
  6966. if (key)
  6967. heap = key->heap;
  6968. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6969. WOLFSSL_ERROR_MSG("DER encoding failed");
  6970. ret = 0;
  6971. }
  6972. if (derBuf == NULL) {
  6973. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6974. ret = 0;
  6975. }
  6976. }
  6977. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6978. DH_PARAM_TYPE, NULL) != 1)) {
  6979. ret = 0;
  6980. }
  6981. /* Dispose of DER buffer. */
  6982. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6983. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6984. return ret;
  6985. }
  6986. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6987. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6988. * OPENSSL_EXTRA */
  6989. /*
  6990. * DH get/set APIs
  6991. */
  6992. #ifdef OPENSSL_EXTRA
  6993. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6994. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6995. /* Set the members of DhKey into WOLFSSL_DH
  6996. * Specify elements to set via the 2nd parameter
  6997. *
  6998. * @param [in, out] dh DH key to synchronize.
  6999. * @param [in] elm Elements to synchronize.
  7000. * @return 1 on success.
  7001. * @return -1 on failure.
  7002. */
  7003. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  7004. {
  7005. int ret = 1;
  7006. DhKey *key = NULL;
  7007. WOLFSSL_ENTER("SetDhExternal_ex");
  7008. /* Validate parameters. */
  7009. if ((dh == NULL) || (dh->internal == NULL)) {
  7010. WOLFSSL_ERROR_MSG("dh key NULL error");
  7011. ret = -1;
  7012. }
  7013. if (ret == 1) {
  7014. /* Get the wolfSSL DH key. */
  7015. key = (DhKey*)dh->internal;
  7016. }
  7017. if ((ret == 1) && (elm & ELEMENT_P)) {
  7018. /* Set the prime. */
  7019. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  7020. WOLFSSL_ERROR_MSG("dh param p error");
  7021. ret = -1;
  7022. }
  7023. }
  7024. if ((ret == 1) && (elm & ELEMENT_G)) {
  7025. /* Set the generator. */
  7026. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  7027. WOLFSSL_ERROR_MSG("dh param g error");
  7028. ret = -1;
  7029. }
  7030. }
  7031. if ((ret == 1) && (elm & ELEMENT_Q)) {
  7032. /* Set the order. */
  7033. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  7034. WOLFSSL_ERROR_MSG("dh param q error");
  7035. ret = -1;
  7036. }
  7037. }
  7038. #ifdef WOLFSSL_DH_EXTRA
  7039. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  7040. /* Set the private key. */
  7041. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  7042. WOLFSSL_ERROR_MSG("No DH Private Key");
  7043. ret = -1;
  7044. }
  7045. }
  7046. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  7047. /* Set the public key. */
  7048. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  7049. WOLFSSL_ERROR_MSG("No DH Public Key");
  7050. ret = -1;
  7051. }
  7052. }
  7053. #endif /* WOLFSSL_DH_EXTRA */
  7054. if (ret == 1) {
  7055. /* On success record that the external values have been set. */
  7056. dh->exSet = 1;
  7057. }
  7058. return ret;
  7059. }
  7060. /* Set the members of DhKey into WOLFSSL_DH
  7061. * DhKey was populated from wc_DhKeyDecode
  7062. * p, g, pub_key and priv_key are set.
  7063. *
  7064. * @param [in, out] dh DH key to synchronize.
  7065. * @return 1 on success.
  7066. * @return -1 on failure.
  7067. */
  7068. int SetDhExternal(WOLFSSL_DH *dh)
  7069. {
  7070. /* Assuming Q not required when using this API. */
  7071. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  7072. WOLFSSL_ENTER("SetDhExternal");
  7073. return SetDhExternal_ex(dh, elements);
  7074. }
  7075. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  7076. /* Set the internal/wolfSSL DH key with data from the external parts.
  7077. *
  7078. * @param [in, out] dh DH key to synchronize.
  7079. * @return 1 on success.
  7080. * @return -1 on failure.
  7081. */
  7082. int SetDhInternal(WOLFSSL_DH* dh)
  7083. {
  7084. int ret = 1;
  7085. DhKey *key = NULL;
  7086. WOLFSSL_ENTER("SetDhInternal");
  7087. /* Validate parameters. */
  7088. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7089. WOLFSSL_ERROR_MSG("Bad function arguments");
  7090. ret = -1;
  7091. }
  7092. if (ret == 1) {
  7093. /* Get the wolfSSL DH key. */
  7094. key = (DhKey*)dh->internal;
  7095. /* Clear out key and initialize. */
  7096. wc_FreeDhKey(key);
  7097. if (wc_InitDhKey(key) != 0) {
  7098. ret = -1;
  7099. }
  7100. }
  7101. if (ret == 1) {
  7102. /* Transfer prime. */
  7103. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  7104. ret = -1;
  7105. }
  7106. }
  7107. if (ret == 1) {
  7108. /* Transfer generator. */
  7109. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  7110. ret = -1;
  7111. }
  7112. }
  7113. #ifdef HAVE_FFDHE_Q
  7114. /* Transfer order if available. */
  7115. if ((ret == 1) && (dh->q != NULL)) {
  7116. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  7117. ret = -1;
  7118. }
  7119. }
  7120. #endif
  7121. #ifdef WOLFSSL_DH_EXTRA
  7122. /* Transfer private key if available. */
  7123. if ((ret == 1) && (dh->priv_key != NULL) &&
  7124. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  7125. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7126. ret = -1;
  7127. }
  7128. }
  7129. /* Transfer public key if available. */
  7130. if ((ret == 1) && (dh->pub_key != NULL) &&
  7131. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  7132. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7133. ret = -1;
  7134. }
  7135. }
  7136. #endif /* WOLFSSL_DH_EXTRA */
  7137. if (ret == 1) {
  7138. /* On success record that the internal values have been set. */
  7139. dh->inSet = 1;
  7140. }
  7141. return ret;
  7142. }
  7143. /* Get the size, in bytes, of the DH key.
  7144. *
  7145. * Return code compliant with OpenSSL.
  7146. *
  7147. * @param [in] dh DH key.
  7148. * @return -1 on error.
  7149. * @return Size of DH key in bytes on success.
  7150. */
  7151. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7152. {
  7153. int ret = -1;
  7154. WOLFSSL_ENTER("wolfSSL_DH_size");
  7155. /* Validate parameter. */
  7156. if (dh != NULL) {
  7157. /* Size of key is size of prime in bytes. */
  7158. ret = wolfSSL_BN_num_bytes(dh->p);
  7159. }
  7160. return ret;
  7161. }
  7162. /**
  7163. * Return parameters p, q and/or g of the DH key.
  7164. *
  7165. * @param [in] dh DH key to retrieve parameters from.
  7166. * @param [out] p Pointer to return prime in. May be NULL.
  7167. * @param [out] q Pointer to return order in. May be NULL.
  7168. * @param [out] g Pointer to return generator in. May be NULL.
  7169. */
  7170. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7171. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7172. {
  7173. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7174. if (dh != NULL) {
  7175. /* Return prime if required. */
  7176. if (p != NULL) {
  7177. *p = dh->p;
  7178. }
  7179. /* Return order if required. */
  7180. if (q != NULL) {
  7181. *q = dh->q;
  7182. }
  7183. /* Return generator if required. */
  7184. if (g != NULL) {
  7185. *g = dh->g;
  7186. }
  7187. }
  7188. }
  7189. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7190. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7191. #if defined(OPENSSL_ALL) || \
  7192. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7193. /* Sets the parameters p, g and optionally q into the DH key.
  7194. *
  7195. * Ownership of p, q and g get taken over by "dh" on success and should be
  7196. * free'd with a call to wolfSSL_DH_free -- not individually.
  7197. *
  7198. * @param [in, out] dh DH key to set.
  7199. * @param [in] p Prime value to set. May be NULL when value already
  7200. * present.
  7201. * @param [in] q Order value to set. May be NULL.
  7202. * @param [in] g Generator value to set. May be NULL when value already
  7203. * present.
  7204. * @return 1 on success.
  7205. * @return 0 on failure.
  7206. */
  7207. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7208. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7209. {
  7210. int ret = 1;
  7211. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7212. /* Validate parameters - q is optional. */
  7213. if (dh == NULL) {
  7214. WOLFSSL_ERROR_MSG("Bad function arguments");
  7215. ret = 0;
  7216. }
  7217. /* p can be NULL if we already have one set. */
  7218. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7219. WOLFSSL_ERROR_MSG("Bad function arguments");
  7220. ret = 0;
  7221. }
  7222. /* g can be NULL if we already have one set. */
  7223. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7224. WOLFSSL_ERROR_MSG("Bad function arguments");
  7225. ret = 0;
  7226. }
  7227. if (ret == 1) {
  7228. /* Invalidate internal key. */
  7229. dh->inSet = 0;
  7230. /* Free external representation of parameters and set with those passed
  7231. * in. */
  7232. if (p != NULL) {
  7233. wolfSSL_BN_free(dh->p);
  7234. dh->p = p;
  7235. }
  7236. if (q != NULL) {
  7237. wolfSSL_BN_free(dh->q);
  7238. dh->q = q;
  7239. }
  7240. if (g != NULL) {
  7241. wolfSSL_BN_free(dh->g);
  7242. dh->g = g;
  7243. }
  7244. /* External DH key parameters were set. */
  7245. dh->exSet = 1;
  7246. /* Set internal/wolfSSL DH key as well. */
  7247. if (SetDhInternal(dh) != 1) {
  7248. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7249. /* Don't keep parameters on failure. */
  7250. dh->p = NULL;
  7251. dh->q = NULL;
  7252. dh->g = NULL;
  7253. /* Internal and external DH key not set. */
  7254. dh->inSet = 0;
  7255. dh->exSet = 0;
  7256. ret = 0;
  7257. }
  7258. }
  7259. return ret;
  7260. }
  7261. /* Set the length of the DH private key in bits.
  7262. *
  7263. * Length field is checked at generation.
  7264. *
  7265. * @param [in, out] dh DH key to set.
  7266. * @param [in] len Length of DH private key in bytes.
  7267. * @return 0 on failure.
  7268. * @return 1 on success.
  7269. */
  7270. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7271. {
  7272. int ret = 1;
  7273. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7274. /* Validate parameter. */
  7275. if (dh == NULL) {
  7276. WOLFSSL_ERROR_MSG("Bad function arguments");
  7277. ret = 0;
  7278. }
  7279. else {
  7280. /* Store length. */
  7281. dh->length = (int)len;
  7282. }
  7283. return ret;
  7284. }
  7285. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7286. #endif
  7287. /* Get the public and private keys requested.
  7288. *
  7289. * @param [in] dh DH key to get keys from.
  7290. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7291. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7292. */
  7293. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7294. const WOLFSSL_BIGNUM **priv_key)
  7295. {
  7296. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7297. /* Get only when valid DH passed in. */
  7298. if (dh != NULL) {
  7299. /* Return public key if required and available. */
  7300. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7301. *pub_key = dh->pub_key;
  7302. }
  7303. /* Return private key if required and available. */
  7304. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7305. *priv_key = dh->priv_key;
  7306. }
  7307. }
  7308. }
  7309. /* Set the public and/or private key.
  7310. *
  7311. * @param [in, out] dh DH key to have keys set into.
  7312. * @param [in] pub_key Public key to set. May be NULL.
  7313. * @param [in] priv_key Private key to set. May be NULL.
  7314. * @return 0 on failure.
  7315. * @return 1 on success.
  7316. */
  7317. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7318. WOLFSSL_BIGNUM *priv_key)
  7319. {
  7320. int ret = 1;
  7321. #ifdef WOLFSSL_DH_EXTRA
  7322. DhKey *key = NULL;
  7323. #endif
  7324. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7325. /* Validate parameters. */
  7326. if (dh == NULL) {
  7327. ret = 0;
  7328. }
  7329. #ifdef WOLFSSL_DH_EXTRA
  7330. else {
  7331. key = (DhKey*)dh->internal;
  7332. }
  7333. #endif
  7334. /* Replace public key when one passed in. */
  7335. if ((ret == 1) && (pub_key != NULL)) {
  7336. wolfSSL_BN_free(dh->pub_key);
  7337. dh->pub_key = pub_key;
  7338. #ifdef WOLFSSL_DH_EXTRA
  7339. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7340. ret = 0;
  7341. }
  7342. #endif
  7343. }
  7344. /* Replace private key when one passed in. */
  7345. if ((ret == 1) && (priv_key != NULL)) {
  7346. wolfSSL_BN_clear_free(dh->priv_key);
  7347. dh->priv_key = priv_key;
  7348. #ifdef WOLFSSL_DH_EXTRA
  7349. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7350. ret = 0;
  7351. }
  7352. #endif
  7353. }
  7354. return ret;
  7355. }
  7356. #endif /* OPENSSL_EXTRA */
  7357. /*
  7358. * DH check APIs
  7359. */
  7360. #ifdef OPENSSL_EXTRA
  7361. #ifndef NO_CERTS
  7362. #ifdef OPENSSL_ALL
  7363. /* Check whether BN number is a prime.
  7364. *
  7365. * @param [in] n Number to check.
  7366. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7367. * @return 1 on success.
  7368. * @return 0 on error.
  7369. */
  7370. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7371. {
  7372. int ret = 1;
  7373. #ifdef WOLFSSL_SMALL_STACK
  7374. WC_RNG* tmpRng = NULL;
  7375. #else
  7376. WC_RNG tmpRng[1];
  7377. #endif
  7378. WC_RNG* rng;
  7379. int localRng;
  7380. /* Make an RNG with tmpRng or get global. */
  7381. rng = wolfssl_make_rng(tmpRng, &localRng);
  7382. if (rng == NULL) {
  7383. ret = 0;
  7384. }
  7385. if (ret == 1) {
  7386. mp_int* prime = (mp_int*)n->internal;
  7387. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7388. ret = 0;
  7389. }
  7390. /* Free local random number generator if created. */
  7391. if (localRng) {
  7392. wc_FreeRng(rng);
  7393. #ifdef WOLFSSL_SMALL_STACK
  7394. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7395. #endif
  7396. }
  7397. }
  7398. return ret;
  7399. }
  7400. /* Checks the Diffie-Hellman parameters.
  7401. *
  7402. * Checks that the generator and prime are available.
  7403. * Checks that the prime is prime.
  7404. * OpenSSL expects codes to be non-NULL.
  7405. *
  7406. * @param [in] dh DH key to check.
  7407. * @param [out] codes Codes of checks that failed.
  7408. * @return 1 on success.
  7409. * @return 0 when DH is NULL, there were errors or failed to create a random
  7410. * number generator.
  7411. */
  7412. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7413. {
  7414. int ret = 1;
  7415. int errors = 0;
  7416. WOLFSSL_ENTER("wolfSSL_DH_check");
  7417. /* Validate parameters. */
  7418. if (dh == NULL) {
  7419. ret = 0;
  7420. }
  7421. /* Check generator available. */
  7422. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7423. errors |= DH_NOT_SUITABLE_GENERATOR;
  7424. }
  7425. if (ret == 1) {
  7426. /* Check prime available. */
  7427. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7428. errors |= DH_CHECK_P_NOT_PRIME;
  7429. }
  7430. else {
  7431. /* Test if dh->p is prime. */
  7432. int isPrime = MP_NO;
  7433. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7434. /* Set error code if parameter p is not prime. */
  7435. if ((ret == 1) && (isPrime != MP_YES)) {
  7436. errors |= DH_CHECK_P_NOT_PRIME;
  7437. }
  7438. }
  7439. }
  7440. /* Return errors when user wants exact issues. */
  7441. if (codes != NULL) {
  7442. *codes = errors;
  7443. }
  7444. else if (errors) {
  7445. ret = 0;
  7446. }
  7447. return ret;
  7448. }
  7449. #endif /* OPENSSL_ALL */
  7450. #endif /* !NO_CERTS */
  7451. #endif /* OPENSSL_EXTRA */
  7452. /*
  7453. * DH generate APIs
  7454. */
  7455. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7456. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7457. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7458. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7459. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7460. /* Generate DH parameters.
  7461. *
  7462. * @param [in] prime_len Length of prime in bits.
  7463. * @param [in] generator Generator value to use.
  7464. * @param [in] callback Called with progress information. Unused.
  7465. * @param [in] cb_arg User callback argument. Unused.
  7466. * @return NULL on failure.
  7467. * @return DH key on success.
  7468. */
  7469. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7470. void (*callback) (int, int, void *), void *cb_arg)
  7471. {
  7472. WOLFSSL_DH* dh = NULL;
  7473. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7474. /* Not supported by wolfSSl APIs. */
  7475. (void)callback;
  7476. (void)cb_arg;
  7477. /* Create an empty DH key. */
  7478. if ((dh = wolfSSL_DH_new()) == NULL) {
  7479. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7480. }
  7481. /* Generate parameters into DH key. */
  7482. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7483. != 1) {
  7484. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7485. wolfSSL_DH_free(dh);
  7486. dh = NULL;
  7487. }
  7488. return dh;
  7489. }
  7490. /* Generate DH parameters.
  7491. *
  7492. * @param [in] dh DH key to generate parameters into.
  7493. * @param [in] prime_len Length of prime in bits.
  7494. * @param [in] generator Generator value to use.
  7495. * @param [in] callback Called with progress information. Unused.
  7496. * @param [in] cb_arg User callback argument. Unused.
  7497. * @return 0 on failure.
  7498. * @return 1 on success.
  7499. */
  7500. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7501. int generator, void (*callback) (int, int, void *))
  7502. {
  7503. int ret = 1;
  7504. DhKey* key = NULL;
  7505. #ifdef WOLFSSL_SMALL_STACK
  7506. WC_RNG* tmpRng = NULL;
  7507. #else
  7508. WC_RNG tmpRng[1];
  7509. #endif
  7510. WC_RNG* rng = NULL;
  7511. int localRng = 0;
  7512. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7513. /* Not supported by wolfSSL APIs. */
  7514. (void)callback;
  7515. (void)generator;
  7516. /* Validate parameters. */
  7517. if (dh == NULL) {
  7518. WOLFSSL_ERROR_MSG("Bad parameter");
  7519. ret = 0;
  7520. }
  7521. if (ret == 1) {
  7522. /* Make an RNG with tmpRng or get global. */
  7523. rng = wolfssl_make_rng(tmpRng, &localRng);
  7524. if (rng == NULL) {
  7525. WOLFSSL_ERROR_MSG("No RNG to use");
  7526. ret = 0;
  7527. }
  7528. }
  7529. if (ret == 1) {
  7530. /* Get internal/wolfSSL DH key. */
  7531. key = (DhKey*)dh->internal;
  7532. /* Clear out data from internal DH key. */
  7533. wc_FreeDhKey(key);
  7534. /* Re-initialize internal DH key. */
  7535. if (wc_InitDhKey(key) != 0) {
  7536. ret = 0;
  7537. }
  7538. }
  7539. if (ret == 1) {
  7540. /* Generate parameters into internal DH key. */
  7541. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7542. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7543. ret = 0;
  7544. }
  7545. }
  7546. /* Free local random number generator if created. */
  7547. if (localRng) {
  7548. wc_FreeRng(rng);
  7549. #ifdef WOLFSSL_SMALL_STACK
  7550. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7551. #endif
  7552. }
  7553. if (ret == 1) {
  7554. /* Internal parameters set by generation. */
  7555. dh->inSet = 1;
  7556. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7557. /* Synchronize the external to the internal parameters. */
  7558. if (SetDhExternal(dh) != 1) {
  7559. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7560. ret = 0;
  7561. }
  7562. }
  7563. return ret;
  7564. }
  7565. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7566. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7567. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7568. * HAVE_SBLIM_SFCB)) */
  7569. #ifdef OPENSSL_EXTRA
  7570. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7571. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7572. /* Generate a public/private key pair base on parameters.
  7573. *
  7574. * @param [in, out] dh DH key to generate keys into.
  7575. * @return 1 on success.
  7576. * @return 0 on error.
  7577. */
  7578. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7579. {
  7580. int ret = 1;
  7581. word32 pubSz = 0;
  7582. word32 privSz = 0;
  7583. int localRng = 0;
  7584. WC_RNG* rng = NULL;
  7585. #ifdef WOLFSSL_SMALL_STACK
  7586. WC_RNG* tmpRng = NULL;
  7587. #else
  7588. WC_RNG tmpRng[1];
  7589. #endif
  7590. unsigned char* pub = NULL;
  7591. unsigned char* priv = NULL;
  7592. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7593. /* Validate parameters. */
  7594. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7595. WOLFSSL_ERROR_MSG("Bad function arguments");
  7596. ret = 0;
  7597. }
  7598. /* Synchronize the external and internal parameters. */
  7599. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7600. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7601. ret = 0;
  7602. }
  7603. if (ret == 1) {
  7604. /* Make a new RNG or use global. */
  7605. rng = wolfssl_make_rng(tmpRng, &localRng);
  7606. /* Check we have a random number generator. */
  7607. if (rng == NULL) {
  7608. ret = 0;
  7609. }
  7610. }
  7611. if (ret == 1) {
  7612. /* Get the size of the prime in bytes. */
  7613. pubSz = (word32)wolfSSL_BN_num_bytes(dh->p);
  7614. if (pubSz == 0) {
  7615. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7616. ret = 0;
  7617. }
  7618. }
  7619. if (ret == 1) {
  7620. /* Private key size can be as much as the size of the prime. */
  7621. if (dh->length) {
  7622. privSz = (word32)(dh->length / 8); /* to bytes */
  7623. }
  7624. else {
  7625. privSz = pubSz;
  7626. }
  7627. /* Allocate public and private key arrays. */
  7628. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7629. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7630. if (pub == NULL || priv == NULL) {
  7631. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7632. ret = 0;
  7633. }
  7634. }
  7635. if (ret == 1) {
  7636. /* Dispose of old public and private keys. */
  7637. wolfSSL_BN_free(dh->pub_key);
  7638. wolfSSL_BN_free(dh->priv_key);
  7639. /* Allocate new public and private keys. */
  7640. dh->pub_key = wolfSSL_BN_new();
  7641. dh->priv_key = wolfSSL_BN_new();
  7642. if (dh->pub_key == NULL) {
  7643. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7644. ret = 0;
  7645. }
  7646. if (dh->priv_key == NULL) {
  7647. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7648. ret = 0;
  7649. }
  7650. }
  7651. PRIVATE_KEY_UNLOCK();
  7652. /* Generate public and private keys into arrays. */
  7653. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7654. &privSz, pub, &pubSz) < 0)) {
  7655. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7656. ret = 0;
  7657. }
  7658. /* Set public key from array. */
  7659. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) ==
  7660. NULL)) {
  7661. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7662. ret = 0;
  7663. }
  7664. /* Set private key from array. */
  7665. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) ==
  7666. NULL)) {
  7667. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7668. ret = 0;
  7669. }
  7670. PRIVATE_KEY_LOCK();
  7671. if (localRng) {
  7672. /* Free an initialized local random number generator. */
  7673. wc_FreeRng(rng);
  7674. #ifdef WOLFSSL_SMALL_STACK
  7675. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7676. #endif
  7677. }
  7678. /* Dispose of allocated data. */
  7679. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7680. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7681. return ret;
  7682. }
  7683. /* Compute the shared key from the private key and peer's public key.
  7684. *
  7685. * Return code compliant with OpenSSL.
  7686. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7687. * supported.
  7688. *
  7689. * @param [out] key Buffer to place shared key.
  7690. * @param [in] otherPub Peer's public key.
  7691. * @param [in] dh DH key containing private key.
  7692. * @return -1 on error.
  7693. * @return Size of shared secret in bytes on success.
  7694. */
  7695. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7696. WOLFSSL_DH* dh)
  7697. {
  7698. int ret = 0;
  7699. word32 keySz = 0;
  7700. int pubSz = MAX_DHKEY_SZ;
  7701. int privSz = MAX_DHKEY_SZ;
  7702. int sz = 0;
  7703. #ifdef WOLFSSL_SMALL_STACK
  7704. unsigned char* pub = NULL;
  7705. unsigned char* priv = NULL;
  7706. #else
  7707. unsigned char pub [MAX_DHKEY_SZ];
  7708. unsigned char priv[MAX_DHKEY_SZ];
  7709. #endif
  7710. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7711. /* Validate parameters. */
  7712. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7713. WOLFSSL_ERROR_MSG("Bad function arguments");
  7714. ret = -1;
  7715. }
  7716. /* Get the maximum size of computed DH key. */
  7717. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7718. WOLFSSL_ERROR_MSG("Bad DH_size");
  7719. ret = -1;
  7720. }
  7721. if (ret == 0) {
  7722. /* Validate the size of the private key. */
  7723. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7724. if (sz > (int)privSz) {
  7725. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7726. ret = -1;
  7727. }
  7728. }
  7729. if (ret == 0) {
  7730. #ifdef WOLFSSL_SMALL_STACK
  7731. /* Keep real private key size to minimize amount allocated. */
  7732. privSz = sz;
  7733. #endif
  7734. /* Validate the size of the public key. */
  7735. sz = wolfSSL_BN_num_bytes(otherPub);
  7736. if (sz > pubSz) {
  7737. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7738. ret = -1;
  7739. }
  7740. }
  7741. if (ret == 0) {
  7742. #ifdef WOLFSSL_SMALL_STACK
  7743. /* Allocate memory for the public key array. */
  7744. pub = (unsigned char*)XMALLOC((size_t)sz, NULL,
  7745. DYNAMIC_TYPE_PUBLIC_KEY);
  7746. if (pub == NULL)
  7747. ret = -1;
  7748. }
  7749. if (ret == 0) {
  7750. /* Allocate memory for the private key array. */
  7751. priv = (unsigned char*)XMALLOC((size_t)privSz, NULL,
  7752. DYNAMIC_TYPE_PRIVATE_KEY);
  7753. if (priv == NULL) {
  7754. ret = -1;
  7755. }
  7756. }
  7757. if (ret == 0) {
  7758. #endif
  7759. /* Get the private key into the array. */
  7760. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7761. if (privSz <= 0) {
  7762. ret = -1;
  7763. }
  7764. }
  7765. if (ret == 0) {
  7766. /* Get the public key into the array. */
  7767. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7768. if (privSz <= 0) {
  7769. ret = -1;
  7770. }
  7771. }
  7772. /* Synchronize the external into the internal parameters. */
  7773. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7774. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7775. ret = -1;
  7776. }
  7777. PRIVATE_KEY_UNLOCK();
  7778. /* Calculate shared secret from private and public keys. */
  7779. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7780. (word32)privSz, pub, (word32)pubSz) < 0)) {
  7781. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7782. ret = -1;
  7783. }
  7784. if (ret == 0) {
  7785. /* Return actual length. */
  7786. ret = (int)keySz;
  7787. }
  7788. PRIVATE_KEY_LOCK();
  7789. #ifdef WOLFSSL_SMALL_STACK
  7790. if (priv != NULL)
  7791. #endif
  7792. {
  7793. /* Zeroize sensitive data. */
  7794. ForceZero(priv, (word32)privSz);
  7795. }
  7796. #ifdef WOLFSSL_SMALL_STACK
  7797. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7798. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7799. #endif
  7800. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7801. return ret;
  7802. }
  7803. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7804. * HAVE_FIPS_VERSION > 2 */
  7805. #endif /* OPENSSL_EXTRA */
  7806. #endif /* NO_DH */
  7807. /*******************************************************************************
  7808. * END OF DH API
  7809. ******************************************************************************/
  7810. /*******************************************************************************
  7811. * START OF EC API
  7812. ******************************************************************************/
  7813. #ifdef HAVE_ECC
  7814. #if defined(OPENSSL_EXTRA)
  7815. /* Start EC_curve */
  7816. /* Get the NIST name for the numeric ID.
  7817. *
  7818. * @param [in] nid Numeric ID of an EC curve.
  7819. * @return String representing NIST name of EC curve on success.
  7820. * @return NULL on error.
  7821. */
  7822. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7823. {
  7824. const char* name = NULL;
  7825. const WOLF_EC_NIST_NAME* nist_name;
  7826. /* Attempt to find the curve info matching the NID passed in. */
  7827. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7828. if (nist_name->nid == nid) {
  7829. /* NID found - return name. */
  7830. name = nist_name->name;
  7831. break;
  7832. }
  7833. }
  7834. return name;
  7835. }
  7836. /* Get the numeric ID for the NIST name.
  7837. *
  7838. * @param [in] name NIST name of EC curve.
  7839. * @return NID matching NIST name on success.
  7840. * @return 0 on error.
  7841. */
  7842. int wolfSSL_EC_curve_nist2nid(const char* name)
  7843. {
  7844. int nid = 0;
  7845. const WOLF_EC_NIST_NAME* nist_name;
  7846. /* Attempt to find the curve info matching the NIST name passed in. */
  7847. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7848. if (XSTRCMP(nist_name->name, name) == 0) {
  7849. /* Name found - return NID. */
  7850. nid = nist_name->nid;
  7851. break;
  7852. }
  7853. }
  7854. return nid;
  7855. }
  7856. #endif /* OPENSSL_EXTRA */
  7857. /* End EC_curve */
  7858. /* Start EC_METHOD */
  7859. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7860. /* Get the EC method of the EC group object.
  7861. *
  7862. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7863. * the NID.
  7864. *
  7865. * @param [in] group EC group object.
  7866. * @return EC method.
  7867. */
  7868. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7869. const WOLFSSL_EC_GROUP *group)
  7870. {
  7871. /* No method table used so just return the same object. */
  7872. return group;
  7873. }
  7874. /* Get field type for method.
  7875. *
  7876. * Only prime fields are supported.
  7877. *
  7878. * @param [in] meth EC method.
  7879. * @return X9.63 prime field NID on success.
  7880. * @return 0 on error.
  7881. */
  7882. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7883. {
  7884. int nid = 0;
  7885. if (meth != NULL) {
  7886. /* Only field type supported by code base. */
  7887. nid = NID_X9_62_prime_field;
  7888. }
  7889. return nid;
  7890. }
  7891. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7892. /* End EC_METHOD */
  7893. /* Start EC_GROUP */
  7894. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7895. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7896. * value.
  7897. *
  7898. * @param [in] n ECC curve id.
  7899. * @return ECC curve NID (OpenSSL compatible value).
  7900. */
  7901. int EccEnumToNID(int n)
  7902. {
  7903. WOLFSSL_ENTER("EccEnumToNID");
  7904. switch(n) {
  7905. case ECC_SECP192R1:
  7906. return NID_X9_62_prime192v1;
  7907. case ECC_PRIME192V2:
  7908. return NID_X9_62_prime192v2;
  7909. case ECC_PRIME192V3:
  7910. return NID_X9_62_prime192v3;
  7911. case ECC_PRIME239V1:
  7912. return NID_X9_62_prime239v1;
  7913. case ECC_PRIME239V2:
  7914. return NID_X9_62_prime239v2;
  7915. case ECC_PRIME239V3:
  7916. return NID_X9_62_prime239v3;
  7917. case ECC_SECP256R1:
  7918. return NID_X9_62_prime256v1;
  7919. case ECC_SECP112R1:
  7920. return NID_secp112r1;
  7921. case ECC_SECP112R2:
  7922. return NID_secp112r2;
  7923. case ECC_SECP128R1:
  7924. return NID_secp128r1;
  7925. case ECC_SECP128R2:
  7926. return NID_secp128r2;
  7927. case ECC_SECP160R1:
  7928. return NID_secp160r1;
  7929. case ECC_SECP160R2:
  7930. return NID_secp160r2;
  7931. case ECC_SECP224R1:
  7932. return NID_secp224r1;
  7933. case ECC_SECP384R1:
  7934. return NID_secp384r1;
  7935. case ECC_SECP521R1:
  7936. return NID_secp521r1;
  7937. case ECC_SECP160K1:
  7938. return NID_secp160k1;
  7939. case ECC_SECP192K1:
  7940. return NID_secp192k1;
  7941. case ECC_SECP224K1:
  7942. return NID_secp224k1;
  7943. case ECC_SECP256K1:
  7944. return NID_secp256k1;
  7945. case ECC_BRAINPOOLP160R1:
  7946. return NID_brainpoolP160r1;
  7947. case ECC_BRAINPOOLP192R1:
  7948. return NID_brainpoolP192r1;
  7949. case ECC_BRAINPOOLP224R1:
  7950. return NID_brainpoolP224r1;
  7951. case ECC_BRAINPOOLP256R1:
  7952. return NID_brainpoolP256r1;
  7953. case ECC_BRAINPOOLP320R1:
  7954. return NID_brainpoolP320r1;
  7955. case ECC_BRAINPOOLP384R1:
  7956. return NID_brainpoolP384r1;
  7957. case ECC_BRAINPOOLP512R1:
  7958. return NID_brainpoolP512r1;
  7959. #ifdef WOLFSSL_SM2
  7960. case ECC_SM2P256V1:
  7961. return NID_sm2;
  7962. #endif
  7963. default:
  7964. WOLFSSL_MSG("NID not found");
  7965. return -1;
  7966. }
  7967. }
  7968. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7969. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7970. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  7971. *
  7972. * Used by ecc_sets[].
  7973. *
  7974. * @param [in] n OpenSSL NID of EC curve.
  7975. * @return wolfCrypt EC curve id.
  7976. * @return -1 on error.
  7977. */
  7978. int NIDToEccEnum(int nid)
  7979. {
  7980. /* -1 on error. */
  7981. int id = -1;
  7982. WOLFSSL_ENTER("NIDToEccEnum");
  7983. switch (nid) {
  7984. case NID_X9_62_prime192v1:
  7985. id = ECC_SECP192R1;
  7986. break;
  7987. case NID_X9_62_prime192v2:
  7988. id = ECC_PRIME192V2;
  7989. break;
  7990. case NID_X9_62_prime192v3:
  7991. id = ECC_PRIME192V3;
  7992. break;
  7993. case NID_X9_62_prime239v1:
  7994. id = ECC_PRIME239V1;
  7995. break;
  7996. case NID_X9_62_prime239v2:
  7997. id = ECC_PRIME239V2;
  7998. break;
  7999. case NID_X9_62_prime239v3:
  8000. id = ECC_PRIME239V3;
  8001. break;
  8002. case NID_X9_62_prime256v1:
  8003. id = ECC_SECP256R1;
  8004. break;
  8005. case NID_secp112r1:
  8006. id = ECC_SECP112R1;
  8007. break;
  8008. case NID_secp112r2:
  8009. id = ECC_SECP112R2;
  8010. break;
  8011. case NID_secp128r1:
  8012. id = ECC_SECP128R1;
  8013. break;
  8014. case NID_secp128r2:
  8015. id = ECC_SECP128R2;
  8016. break;
  8017. case NID_secp160r1:
  8018. id = ECC_SECP160R1;
  8019. break;
  8020. case NID_secp160r2:
  8021. id = ECC_SECP160R2;
  8022. break;
  8023. case NID_secp224r1:
  8024. id = ECC_SECP224R1;
  8025. break;
  8026. case NID_secp384r1:
  8027. id = ECC_SECP384R1;
  8028. break;
  8029. case NID_secp521r1:
  8030. id = ECC_SECP521R1;
  8031. break;
  8032. case NID_secp160k1:
  8033. id = ECC_SECP160K1;
  8034. break;
  8035. case NID_secp192k1:
  8036. id = ECC_SECP192K1;
  8037. break;
  8038. case NID_secp224k1:
  8039. id = ECC_SECP224K1;
  8040. break;
  8041. case NID_secp256k1:
  8042. id = ECC_SECP256K1;
  8043. break;
  8044. case NID_brainpoolP160r1:
  8045. id = ECC_BRAINPOOLP160R1;
  8046. break;
  8047. case NID_brainpoolP192r1:
  8048. id = ECC_BRAINPOOLP192R1;
  8049. break;
  8050. case NID_brainpoolP224r1:
  8051. id = ECC_BRAINPOOLP224R1;
  8052. break;
  8053. case NID_brainpoolP256r1:
  8054. id = ECC_BRAINPOOLP256R1;
  8055. break;
  8056. case NID_brainpoolP320r1:
  8057. id = ECC_BRAINPOOLP320R1;
  8058. break;
  8059. case NID_brainpoolP384r1:
  8060. id = ECC_BRAINPOOLP384R1;
  8061. break;
  8062. case NID_brainpoolP512r1:
  8063. id = ECC_BRAINPOOLP512R1;
  8064. break;
  8065. default:
  8066. WOLFSSL_MSG("NID not found");
  8067. }
  8068. return id;
  8069. }
  8070. /* Set the fields of the EC group based on numeric ID.
  8071. *
  8072. * @param [in, out] group EC group.
  8073. * @param [in] nid Numeric ID of an EC curve.
  8074. */
  8075. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  8076. {
  8077. int eccEnum;
  8078. int realNid;
  8079. /* Convert ecc_curve_id enum to NID. */
  8080. if ((realNid = EccEnumToNID(nid)) != -1) {
  8081. /* ecc_curve_id enum passed in - have real NID value set. */
  8082. eccEnum = nid;
  8083. }
  8084. else {
  8085. /* NID passed in is OpenSSL type. */
  8086. realNid = nid;
  8087. /* Convert NID to ecc_curve_id enum. */
  8088. eccEnum = NIDToEccEnum(nid);
  8089. }
  8090. /* Set the numeric ID of the curve */
  8091. group->curve_nid = realNid;
  8092. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  8093. group->curve_idx = -1;
  8094. /* Find index and OID sum for curve if wolfCrypt supports it. */
  8095. if (eccEnum != -1) {
  8096. int i;
  8097. /* Find id and set the internal curve idx and OID sum. */
  8098. for (i = 0; ecc_sets[i].size != 0; i++) {
  8099. if (ecc_sets[i].id == eccEnum) {
  8100. /* Found id in wolfCrypt supported EC curves. */
  8101. group->curve_idx = i;
  8102. group->curve_oid = (int)ecc_sets[i].oidSum;
  8103. break;
  8104. }
  8105. }
  8106. }
  8107. }
  8108. /* Create a new EC group with the numeric ID for an EC curve.
  8109. *
  8110. * @param [in] nid Numeric ID of an EC curve.
  8111. * @return New, allocated EC group on success.
  8112. * @return NULL on error.
  8113. */
  8114. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  8115. {
  8116. int err = 0;
  8117. WOLFSSL_EC_GROUP* group;
  8118. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  8119. /* Allocate EC group. */
  8120. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  8121. DYNAMIC_TYPE_ECC);
  8122. if (group == NULL) {
  8123. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  8124. err = 1;
  8125. }
  8126. if (!err) {
  8127. /* Reset all fields. */
  8128. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  8129. /* Set the fields of group based on the numeric ID. */
  8130. ec_group_set_nid(group, nid);
  8131. }
  8132. return group;
  8133. }
  8134. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8135. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8136. /* Dispose of the EC group.
  8137. *
  8138. * Cannot use group after this call.
  8139. *
  8140. * @param [in] group EC group to free.
  8141. */
  8142. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8143. {
  8144. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8145. /* Dispose of EC group. */
  8146. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8147. }
  8148. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8149. #ifdef OPENSSL_EXTRA
  8150. #ifndef NO_BIO
  8151. /* Creates an EC group from the DER encoding.
  8152. *
  8153. * Only named curves supported.
  8154. *
  8155. * @param [out] group Reference to EC group object.
  8156. * @param [in] in Buffer holding DER encoding of curve.
  8157. * @param [in] inSz Length of data in buffer.
  8158. * @return EC group on success.
  8159. * @return NULL on error.
  8160. */
  8161. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  8162. const unsigned char* in, long inSz)
  8163. {
  8164. int err = 0;
  8165. WOLFSSL_EC_GROUP* ret = NULL;
  8166. word32 idx = 0;
  8167. word32 oid = 0;
  8168. int id = 0;
  8169. /* Use the group passed in. */
  8170. if ((group != NULL) && (*group != NULL)) {
  8171. ret = *group;
  8172. }
  8173. /* Only support named curves. */
  8174. if (in[0] != ASN_OBJECT_ID) {
  8175. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8176. err = 1;
  8177. }
  8178. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8179. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8180. 0)) {
  8181. err = 1;
  8182. }
  8183. if (!err) {
  8184. /* Get the internal ID for OID. */
  8185. id = wc_ecc_get_oid(oid, NULL, NULL);
  8186. if (id < 0) {
  8187. err = 1;
  8188. }
  8189. }
  8190. if (!err) {
  8191. /* Get the NID for the internal ID. */
  8192. int nid = EccEnumToNID(id);
  8193. if (ret == NULL) {
  8194. /* Create a new EC group with the numeric ID. */
  8195. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8196. if (ret == NULL) {
  8197. err = 1;
  8198. }
  8199. }
  8200. else {
  8201. ec_group_set_nid(ret, nid);
  8202. }
  8203. }
  8204. if ((!err) && (group != NULL)) {
  8205. /* Return the EC group through reference. */
  8206. *group = ret;
  8207. }
  8208. if (err) {
  8209. if ((ret != NULL) && (ret != *group)) {
  8210. wolfSSL_EC_GROUP_free(ret);
  8211. }
  8212. ret = NULL;
  8213. }
  8214. return ret;
  8215. }
  8216. /* Creates a new EC group from the PEM encoding in the BIO.
  8217. *
  8218. * @param [in] bio BIO to read PEM encoding from.
  8219. * @param [out] group Reference to EC group object.
  8220. * @param [in] cb Password callback when PEM encrypted.
  8221. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8222. * @return EC group on success.
  8223. * @return NULL on error.
  8224. */
  8225. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8226. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8227. {
  8228. int err = 0;
  8229. WOLFSSL_EC_GROUP* ret = NULL;
  8230. DerBuffer* der = NULL;
  8231. int keyFormat = 0;
  8232. if (bio == NULL) {
  8233. err = 1;
  8234. }
  8235. /* Read parameters from BIO and convert PEM to DER. */
  8236. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8237. &keyFormat, &der) < 0)) {
  8238. err = 1;
  8239. }
  8240. if (!err) {
  8241. /* Create EC group from DER encoding. */
  8242. ret = wolfssl_ec_group_d2i(group, der->buffer, der->length);
  8243. if (ret == NULL) {
  8244. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8245. }
  8246. }
  8247. /* Dispose of any allocated data. */
  8248. FreeDer(&der);
  8249. return ret;
  8250. }
  8251. #endif /* !NO_BIO */
  8252. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8253. /* Copy an EC group.
  8254. *
  8255. * Only used by wolfSSL_EC_KEY_dup at this time.
  8256. *
  8257. * @param [in, out] dst Destination EC group.
  8258. * @param [in] src Source EC group.
  8259. * @return 0 on success.
  8260. */
  8261. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8262. const WOLFSSL_EC_GROUP* src)
  8263. {
  8264. /* Copy the fields. */
  8265. dst->curve_idx = src->curve_idx;
  8266. dst->curve_nid = src->curve_nid;
  8267. dst->curve_oid = src->curve_oid;
  8268. return 0;
  8269. }
  8270. #endif /* OPENSSL_ALL && !NO_CERTS */
  8271. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8272. *
  8273. * @param [in] src EC group to duplicate.
  8274. *
  8275. * @return EC group on success.
  8276. * @return NULL on error.
  8277. */
  8278. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8279. {
  8280. WOLFSSL_EC_GROUP* newGroup = NULL;
  8281. if (src != NULL) {
  8282. /* Create new group base on NID in original EC group. */
  8283. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8284. }
  8285. return newGroup;
  8286. }
  8287. /* Compare two EC groups.
  8288. *
  8289. * Return code compliant with OpenSSL.
  8290. *
  8291. * @param [in] a First EC group.
  8292. * @param [in] b Second EC group.
  8293. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8294. *
  8295. * @return 0 if equal.
  8296. * @return 1 if not equal.
  8297. * @return -1 on error.
  8298. */
  8299. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8300. WOLFSSL_BN_CTX *ctx)
  8301. {
  8302. int ret;
  8303. /* No BN operations performed. */
  8304. (void)ctx;
  8305. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8306. /* Validate parameters. */
  8307. if ((a == NULL) || (b == NULL)) {
  8308. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8309. /* Return error value. */
  8310. ret = -1;
  8311. }
  8312. /* Compare NID and wolfSSL curve index. */
  8313. else {
  8314. /* 0 when same, 1 when not. */
  8315. ret = ((a->curve_nid == b->curve_nid) &&
  8316. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8317. }
  8318. return ret;
  8319. }
  8320. #ifndef NO_WOLFSSL_STUB
  8321. /* Set the ASN.1 flag that indicate encoding of curve.
  8322. *
  8323. * Stub function - flag not used elsewhere.
  8324. * Always encoded as named curve.
  8325. *
  8326. * @param [in] group EC group to modify.
  8327. * @param [in] flag ASN.1 flag to set. Valid values:
  8328. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8329. */
  8330. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8331. {
  8332. (void)group;
  8333. (void)flag;
  8334. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8335. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8336. }
  8337. #endif
  8338. /* Get the curve NID of the group.
  8339. *
  8340. * Return code compliant with OpenSSL.
  8341. *
  8342. * @param [in] group EC group.
  8343. * @return Curve NID on success.
  8344. * @return 0 on error.
  8345. */
  8346. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8347. {
  8348. int nid = 0;
  8349. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8350. if (group == NULL) {
  8351. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8352. }
  8353. else {
  8354. nid = group->curve_nid;
  8355. }
  8356. return nid;
  8357. }
  8358. /* Get the degree (curve size in bits) of the EC group.
  8359. *
  8360. * Return code compliant with OpenSSL.
  8361. *
  8362. * @return Degree of the curve on success.
  8363. * @return 0 on error.
  8364. */
  8365. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8366. {
  8367. int degree = 0;
  8368. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8369. if (group == NULL) {
  8370. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8371. }
  8372. else {
  8373. switch (group->curve_nid) {
  8374. case NID_secp112r1:
  8375. case NID_secp112r2:
  8376. degree = 112;
  8377. break;
  8378. case NID_secp128r1:
  8379. case NID_secp128r2:
  8380. degree = 128;
  8381. break;
  8382. case NID_secp160k1:
  8383. case NID_secp160r1:
  8384. case NID_secp160r2:
  8385. case NID_brainpoolP160r1:
  8386. degree = 160;
  8387. break;
  8388. case NID_secp192k1:
  8389. case NID_brainpoolP192r1:
  8390. case NID_X9_62_prime192v1:
  8391. case NID_X9_62_prime192v2:
  8392. case NID_X9_62_prime192v3:
  8393. degree = 192;
  8394. break;
  8395. case NID_secp224k1:
  8396. case NID_secp224r1:
  8397. case NID_brainpoolP224r1:
  8398. degree = 224;
  8399. break;
  8400. case NID_X9_62_prime239v1:
  8401. case NID_X9_62_prime239v2:
  8402. case NID_X9_62_prime239v3:
  8403. degree = 239;
  8404. break;
  8405. case NID_secp256k1:
  8406. case NID_brainpoolP256r1:
  8407. case NID_X9_62_prime256v1:
  8408. degree = 256;
  8409. break;
  8410. case NID_brainpoolP320r1:
  8411. degree = 320;
  8412. break;
  8413. case NID_secp384r1:
  8414. case NID_brainpoolP384r1:
  8415. degree = 384;
  8416. break;
  8417. case NID_brainpoolP512r1:
  8418. degree = 512;
  8419. break;
  8420. case NID_secp521r1:
  8421. degree = 521;
  8422. break;
  8423. }
  8424. }
  8425. return degree;
  8426. }
  8427. #endif /* OPENSSL_EXTRA */
  8428. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8429. /* Get the length of the order in bits of the EC group.
  8430. *
  8431. * TODO: consider switch statement or calculating directly from hex string
  8432. * array instead of using mp_int.
  8433. *
  8434. * @param [in] group EC group.
  8435. * @return Length of order in bits on success.
  8436. * @return 0 on error.
  8437. */
  8438. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8439. {
  8440. int ret = 0;
  8441. #ifdef WOLFSSL_SMALL_STACK
  8442. mp_int *order = NULL;
  8443. #else
  8444. mp_int order[1];
  8445. #endif
  8446. /* Validate parameter. */
  8447. if ((group == NULL) || (group->curve_idx < 0)) {
  8448. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8449. ret = -1;
  8450. }
  8451. #ifdef WOLFSSL_SMALL_STACK
  8452. if (ret == 0) {
  8453. /* Allocate memory for mp_int that will hold order value. */
  8454. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8455. DYNAMIC_TYPE_TMP_BUFFER);
  8456. if (order == NULL) {
  8457. ret = -1;
  8458. }
  8459. }
  8460. #endif
  8461. if (ret == 0) {
  8462. /* Initialize mp_int. */
  8463. ret = mp_init(order);
  8464. }
  8465. if (ret == 0) {
  8466. /* Read hex string of order from wolfCrypt array of curves. */
  8467. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8468. MP_RADIX_HEX);
  8469. if (ret == 0) {
  8470. /* Get bits of order. */
  8471. ret = mp_count_bits(order);
  8472. }
  8473. /* Clear and free mp_int. */
  8474. mp_clear(order);
  8475. }
  8476. #ifdef WOLFSSL_SMALL_STACK
  8477. /* Deallocate order. */
  8478. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8479. #endif
  8480. /* Convert error code to length of 0. */
  8481. if (ret < 0) {
  8482. ret = 0;
  8483. }
  8484. return ret;
  8485. }
  8486. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8487. #if defined(OPENSSL_EXTRA)
  8488. /* Get the order of the group as a BN.
  8489. *
  8490. * Return code compliant with OpenSSL.
  8491. *
  8492. * @param [in] group EC group.
  8493. * @param [in, out] order BN to hold order value.
  8494. * @param [in] ctx Context to use for BN operations. Unused.
  8495. * @return 1 on success.
  8496. * @return 0 on error.
  8497. */
  8498. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8499. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8500. {
  8501. int ret = 1;
  8502. mp_int* mp = NULL;
  8503. /* No BN operations performed - done with mp_int in BN. */
  8504. (void)ctx;
  8505. /* Validate parameters. */
  8506. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8507. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8508. ret = 0;
  8509. }
  8510. if (ret == 1) {
  8511. mp = (mp_int*)order->internal;
  8512. }
  8513. /* Initialize */
  8514. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8515. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8516. ret = 0;
  8517. }
  8518. /* Read hex string of order from wolfCrypt array of curves. */
  8519. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8520. MP_RADIX_HEX) != MP_OKAY)) {
  8521. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8522. /* Zero out any partial value but don't free. */
  8523. mp_zero(mp);
  8524. ret = 0;
  8525. }
  8526. return ret;
  8527. }
  8528. #endif /* OPENSSL_EXTRA */
  8529. /* End EC_GROUP */
  8530. /* Start EC_POINT */
  8531. #if defined(OPENSSL_EXTRA)
  8532. /* Set data of EC point into internal, wolfCrypt EC point object.
  8533. *
  8534. * EC_POINT Openssl -> WolfSSL
  8535. *
  8536. * @param [in, out] p EC point to update.
  8537. * @return 1 on success.
  8538. * @return -1 on failure.
  8539. */
  8540. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8541. {
  8542. int ret = 1;
  8543. WOLFSSL_ENTER("ec_point_internal_set");
  8544. /* Validate parameter. */
  8545. if ((p == NULL) || (p->internal == NULL)) {
  8546. WOLFSSL_MSG("ECPoint NULL error");
  8547. ret = -1;
  8548. }
  8549. else {
  8550. /* Get internal point as a wolfCrypt EC point. */
  8551. ecc_point* point = (ecc_point*)p->internal;
  8552. /* Set X ordinate if available. */
  8553. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8554. WOLFSSL_MSG("ecc point X error");
  8555. ret = -1;
  8556. }
  8557. /* Set Y ordinate if available. */
  8558. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8559. point->y) != 1)) {
  8560. WOLFSSL_MSG("ecc point Y error");
  8561. ret = -1;
  8562. }
  8563. /* Set Z ordinate if available. */
  8564. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8565. point->z) != 1)) {
  8566. WOLFSSL_MSG("ecc point Z error");
  8567. ret = -1;
  8568. }
  8569. /* Internal values set when operations succeeded. */
  8570. p->inSet = (ret == 1);
  8571. }
  8572. return ret;
  8573. }
  8574. /* Set data of internal, wolfCrypt EC point object into EC point.
  8575. *
  8576. * EC_POINT WolfSSL -> OpenSSL
  8577. *
  8578. * @param [in, out] p EC point to update.
  8579. * @return 1 on success.
  8580. * @return -1 on failure.
  8581. */
  8582. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8583. {
  8584. int ret = 1;
  8585. WOLFSSL_ENTER("ec_point_external_set");
  8586. /* Validate parameter. */
  8587. if ((p == NULL) || (p->internal == NULL)) {
  8588. WOLFSSL_MSG("ECPoint NULL error");
  8589. ret = -1;
  8590. }
  8591. else {
  8592. /* Get internal point as a wolfCrypt EC point. */
  8593. ecc_point* point = (ecc_point*)p->internal;
  8594. /* Set X ordinate. */
  8595. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8596. WOLFSSL_MSG("ecc point X error");
  8597. ret = -1;
  8598. }
  8599. /* Set Y ordinate. */
  8600. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8601. WOLFSSL_MSG("ecc point Y error");
  8602. ret = -1;
  8603. }
  8604. /* Set Z ordinate. */
  8605. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8606. WOLFSSL_MSG("ecc point Z error");
  8607. ret = -1;
  8608. }
  8609. /* External values set when operations succeeded. */
  8610. p->exSet = (ret == 1);
  8611. }
  8612. return ret;
  8613. }
  8614. /* Setup internals of EC point.
  8615. *
  8616. * Assumes point is not NULL.
  8617. *
  8618. * @param [in, out] point EC point to update.
  8619. * @return 1 on success.
  8620. * @return 0 on failure.
  8621. */
  8622. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8623. int ret = 1;
  8624. /* Check if internal values need setting. */
  8625. if (!point->inSet) {
  8626. WOLFSSL_MSG("No ECPoint internal set, do it");
  8627. /* Forcing to non-constant type to update internals. */
  8628. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8629. WOLFSSL_MSG("ec_point_internal_set failed");
  8630. ret = 0;
  8631. }
  8632. }
  8633. return ret;
  8634. }
  8635. /* Create a new EC point from the group.
  8636. *
  8637. * @param [in] group EC group.
  8638. * @return EC point on success.
  8639. * @return NULL on error.
  8640. */
  8641. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8642. {
  8643. int err = 0;
  8644. WOLFSSL_EC_POINT* point = NULL;
  8645. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8646. /* Validate parameter. */
  8647. if (group == NULL) {
  8648. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8649. err = 1;
  8650. }
  8651. if (!err) {
  8652. /* Allocate memory for new EC point. */
  8653. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8654. DYNAMIC_TYPE_ECC);
  8655. if (point == NULL) {
  8656. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8657. err = 1;
  8658. }
  8659. }
  8660. if (!err) {
  8661. /* Clear fields of EC point. */
  8662. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8663. /* Allocate internal EC point. */
  8664. point->internal = wc_ecc_new_point();
  8665. if (point->internal == NULL) {
  8666. WOLFSSL_MSG("ecc_new_point failure");
  8667. err = 1;
  8668. }
  8669. }
  8670. if (err) {
  8671. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8672. point = NULL;
  8673. }
  8674. return point;
  8675. }
  8676. #endif /* OPENSSL_EXTRA */
  8677. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8678. /* Dispose of the EC point.
  8679. *
  8680. * Cannot use point after this call.
  8681. *
  8682. * @param [in, out] point EC point to free.
  8683. */
  8684. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8685. {
  8686. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8687. if (point != NULL) {
  8688. if (point->internal != NULL) {
  8689. wc_ecc_del_point((ecc_point*)point->internal);
  8690. point->internal = NULL;
  8691. }
  8692. /* Free ordinates. */
  8693. wolfSSL_BN_free(point->X);
  8694. wolfSSL_BN_free(point->Y);
  8695. wolfSSL_BN_free(point->Z);
  8696. /* Clear fields. */
  8697. point->X = NULL;
  8698. point->Y = NULL;
  8699. point->Z = NULL;
  8700. point->inSet = 0;
  8701. point->exSet = 0;
  8702. /* Dispose of EC point. */
  8703. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8704. }
  8705. }
  8706. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8707. #ifdef OPENSSL_EXTRA
  8708. /* Clear and dispose of the EC point.
  8709. *
  8710. * Cannot use point after this call.
  8711. *
  8712. * @param [in, out] point EC point to free.
  8713. */
  8714. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8715. {
  8716. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8717. if (point != NULL) {
  8718. if (point->internal != NULL) {
  8719. /* Force internal point to be zeros. */
  8720. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8721. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8722. #else
  8723. ecc_point* p = (ecc_point*)point->internal;
  8724. mp_forcezero(p->x);
  8725. mp_forcezero(p->y);
  8726. mp_forcezero(p->z);
  8727. #endif
  8728. wc_ecc_del_point((ecc_point*)point->internal);
  8729. point->internal = NULL;
  8730. }
  8731. /* Clear the ordinates before freeing. */
  8732. wolfSSL_BN_clear_free(point->X);
  8733. wolfSSL_BN_clear_free(point->Y);
  8734. wolfSSL_BN_clear_free(point->Z);
  8735. /* Clear fields. */
  8736. point->X = NULL;
  8737. point->Y = NULL;
  8738. point->Z = NULL;
  8739. point->inSet = 0;
  8740. point->exSet = 0;
  8741. /* Dispose of EC point. */
  8742. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8743. }
  8744. }
  8745. /* Print out the internals of EC point in debug and when logging callback set.
  8746. *
  8747. * Not an OpenSSL API.
  8748. *
  8749. * TODO: Use WOLFSSL_MSG_EX()?
  8750. *
  8751. * @param [in] msg Message to prepend.
  8752. * @param [in] point EC point to print.
  8753. */
  8754. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8755. {
  8756. #if defined(DEBUG_WOLFSSL)
  8757. char *num;
  8758. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8759. /* Only print when debugging on. */
  8760. if (WOLFSSL_IS_DEBUG_ON()) {
  8761. if (point == NULL) {
  8762. /* No point passed in so just put out "NULL". */
  8763. WOLFSSL_MSG_EX("%s = NULL\n", msg);
  8764. }
  8765. else {
  8766. /* Put out message and status of internal/external data set. */
  8767. WOLFSSL_MSG_EX("%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8768. point->exSet);
  8769. /* Get x-ordinate as a hex string and print. */
  8770. num = wolfSSL_BN_bn2hex(point->X);
  8771. WOLFSSL_MSG_EX("\tX = %s\n", num);
  8772. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8773. /* Get x-ordinate as a hex string and print. */
  8774. num = wolfSSL_BN_bn2hex(point->Y);
  8775. WOLFSSL_MSG_EX("\tY = %s\n", num);
  8776. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8777. /* Get z-ordinate as a hex string and print. */
  8778. num = wolfSSL_BN_bn2hex(point->Z);
  8779. WOLFSSL_MSG_EX("\tZ = %s\n", num);
  8780. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8781. }
  8782. }
  8783. #else
  8784. (void)msg;
  8785. (void)point;
  8786. #endif
  8787. }
  8788. #ifndef HAVE_SELFTEST
  8789. /* Convert EC point to hex string that as either uncompressed or compressed.
  8790. *
  8791. * ECC point compression types were not included in selftest ecc.h
  8792. *
  8793. * @param [in] group EC group for point.
  8794. * @param [in] point EC point to encode.
  8795. * @param [in] form Format of encoding. Valid values:
  8796. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8797. * @param [in] ctx Context to use for BN operations. Unused.
  8798. * @return Allocated hex string on success.
  8799. * @return NULL on error.
  8800. */
  8801. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8802. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8803. {
  8804. static const char* hexDigit = "0123456789ABCDEF";
  8805. char* hex = NULL;
  8806. int i;
  8807. int sz = 0;
  8808. int len = 0;
  8809. int err = 0;
  8810. /* No BN operations performed. */
  8811. (void)ctx;
  8812. /* Validate parameters. */
  8813. if ((group == NULL) || (point == NULL)) {
  8814. err = 1;
  8815. }
  8816. /* Get curve id expects a positive index. */
  8817. if ((!err) && (group->curve_idx < 0)) {
  8818. err = 1;
  8819. }
  8820. if (!err) {
  8821. /* Get curve id to look up ordinate size. */
  8822. int id = wc_ecc_get_curve_id(group->curve_idx);
  8823. /* Get size of ordinate. */
  8824. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8825. err = 1;
  8826. }
  8827. }
  8828. if (!err) {
  8829. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8830. len = sz + 1;
  8831. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8832. /* Include y ordinate when uncompressed. */
  8833. len += sz;
  8834. }
  8835. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8836. */
  8837. hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC);
  8838. if (hex == NULL) {
  8839. err = 1;
  8840. }
  8841. }
  8842. if (!err) {
  8843. /* Make bytes all zeros to allow for ordinate values less than max size.
  8844. */
  8845. XMEMSET(hex, 0, (size_t)(2 * len + 1));
  8846. /* Calculate offset as leading zeros not encoded. */
  8847. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8848. /* Put in x-ordinate after format byte. */
  8849. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8850. 0) {
  8851. err = 1;
  8852. }
  8853. }
  8854. if (!err) {
  8855. if (form == POINT_CONVERSION_COMPRESSED) {
  8856. /* Compressed format byte value dependent on whether y-ordinate is
  8857. * odd.
  8858. */
  8859. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8860. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8861. /* No y-ordinate. */
  8862. }
  8863. else {
  8864. /* Put in uncompressed format byte. */
  8865. hex[0] = ECC_POINT_UNCOMP;
  8866. /* Calculate offset as leading zeros not encoded. */
  8867. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8868. /* Put in y-ordinate after x-ordinate. */
  8869. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8870. (byte*)(hex + i)) < 0) {
  8871. err = 1;
  8872. }
  8873. }
  8874. }
  8875. if (!err) {
  8876. /* Convert binary encoding to hex string. */
  8877. /* Start at end so as not to overwrite. */
  8878. for (i = len-1; i >= 0; i--) {
  8879. /* Get byte value and store has hex string. */
  8880. byte b = (byte)hex[i];
  8881. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8882. hex[i * 2 ] = hexDigit[b >> 4];
  8883. }
  8884. /* Memset put trailing zero or '\0' on end of string. */
  8885. }
  8886. if (err && (hex != NULL)) {
  8887. /* Dispose of allocated data not being returned. */
  8888. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8889. hex = NULL;
  8890. }
  8891. /* Return hex string encoding. */
  8892. return hex;
  8893. }
  8894. #endif /* HAVE_SELFTEST */
  8895. /* Encode the EC point as an uncompressed point in DER.
  8896. *
  8897. * Return code compliant with OpenSSL.
  8898. * Not OpenSSL API.
  8899. *
  8900. * @param [in] group EC group point belongs to.
  8901. * @param [in] point EC point to encode.
  8902. * @param [out] out Buffer to encode into. May be NULL.
  8903. * @param [in, out] len On in, length of buffer in bytes.
  8904. * On out, length of encoding in bytes.
  8905. * @return 1 on success.
  8906. * @return 0 on error.
  8907. */
  8908. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8909. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  8910. {
  8911. int res = 1;
  8912. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8913. /* Validate parameters. */
  8914. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  8915. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8916. res = 0;
  8917. }
  8918. /* Ensure points internals are set up. */
  8919. if ((res == 1) && (ec_point_setup(point) != 1)) {
  8920. res = 0;
  8921. }
  8922. /* Dump the point if encoding. */
  8923. if ((res == 1) && (out != NULL)) {
  8924. wolfSSL_EC_POINT_dump("i2d p", point);
  8925. }
  8926. if (res == 1) {
  8927. /* DER encode point in uncompressed format. */
  8928. int ret = wc_ecc_export_point_der(group->curve_idx,
  8929. (ecc_point*)point->internal, out, len);
  8930. /* Check return. When out is NULL, return will be length only error. */
  8931. if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) {
  8932. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8933. res = 0;
  8934. }
  8935. }
  8936. return res;
  8937. }
  8938. /* Decode the uncompressed point in DER into EC point.
  8939. *
  8940. * Return code compliant with OpenSSL.
  8941. * Not OpenSSL API.
  8942. *
  8943. * @param [in] in Buffer containing DER encoded point.
  8944. * @param [in] len Length of data in bytes.
  8945. * @param [in] group EC group associated with point.
  8946. * @param [in, out] point EC point to set data into.
  8947. * @return 1 on success.
  8948. * @return 0 on error.
  8949. */
  8950. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  8951. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  8952. {
  8953. int ret = 1;
  8954. WOLFSSL_BIGNUM* x = NULL;
  8955. WOLFSSL_BIGNUM* y = NULL;
  8956. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8957. /* Validate parameters. */
  8958. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  8959. (point->internal == NULL)) {
  8960. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8961. ret = 0;
  8962. }
  8963. if (ret == 1) {
  8964. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8965. /* Import point into internal EC point. */
  8966. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8967. (ecc_point*)point->internal, 0) != MP_OKAY) {
  8968. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8969. ret = 0;
  8970. }
  8971. #else
  8972. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8973. if (in[0] == 0x04) {
  8974. /* Import point into internal EC point. */
  8975. if (wc_ecc_import_point_der((unsigned char *)in, len,
  8976. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  8977. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8978. ret = 0;
  8979. }
  8980. }
  8981. else {
  8982. WOLFSSL_MSG("Only uncompressed points supported with "
  8983. "HAVE_SELFTEST");
  8984. ret = 0;
  8985. }
  8986. #endif
  8987. }
  8988. if (ret == 1)
  8989. point->inSet = 1;
  8990. /* Set new external point. */
  8991. if (ret == 1 && ec_point_external_set(point) != 1) {
  8992. WOLFSSL_MSG("ec_point_external_set failed");
  8993. ret = 0;
  8994. }
  8995. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  8996. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  8997. x = wolfSSL_BN_new();
  8998. y = wolfSSL_BN_new();
  8999. if (x == NULL || y == NULL)
  9000. ret = 0;
  9001. if (ret == 1 && wolfSSL_EC_POINT_get_affine_coordinates_GFp(group,
  9002. point, x, y, NULL) != 1) {
  9003. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp failed");
  9004. ret = 0;
  9005. }
  9006. /* wolfSSL_EC_POINT_set_affine_coordinates_GFp check that the point is
  9007. * on the curve. */
  9008. if (ret == 1 && wolfSSL_EC_POINT_set_affine_coordinates_GFp(group,
  9009. point, x, y, NULL) != 1) {
  9010. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp failed");
  9011. ret = 0;
  9012. }
  9013. #else
  9014. WOLFSSL_MSG("Importing non-affine point. This may cause issues in math "
  9015. "operations later on.");
  9016. #endif
  9017. }
  9018. if (ret == 1) {
  9019. /* Dump new point. */
  9020. wolfSSL_EC_POINT_dump("d2i p", point);
  9021. }
  9022. wolfSSL_BN_free(x);
  9023. wolfSSL_BN_free(y);
  9024. return ret;
  9025. }
  9026. /* Encode point as octet string.
  9027. *
  9028. * HYBRID not supported.
  9029. *
  9030. * @param [in] group EC group that point belongs to.
  9031. * @param [in] point EC point to encode.
  9032. * @param [in] form Format of encoding. Valid values:
  9033. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  9034. * @param [out] buf Buffer to write encoding into.
  9035. * @param [in] len Length of buffer.
  9036. * @param [in] ctx Context to use for BN operations. Unused.
  9037. * @return Length of encoded data on success.
  9038. * @return 0 on error.
  9039. */
  9040. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  9041. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  9042. WOLFSSL_BN_CTX *ctx)
  9043. {
  9044. int err = 0;
  9045. word32 enc_len = (word32)len;
  9046. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9047. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  9048. #endif /* !HAVE_SELFTEST */
  9049. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  9050. /* No BN operations performed. */
  9051. (void)ctx;
  9052. /* Validate parameters. */
  9053. if ((group == NULL) || (point == NULL)) {
  9054. err = 1;
  9055. }
  9056. /* Ensure points internals are set up. */
  9057. if ((!err) && (ec_point_setup(point) != 1)) {
  9058. err = 1;
  9059. }
  9060. /* Special case when point is infinity. */
  9061. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9062. /* Encoding is a single octet: 0x00. */
  9063. enc_len = 1;
  9064. if (buf != NULL) {
  9065. /* Check whether buffer has space. */
  9066. if (len < 1) {
  9067. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  9068. err = 1;
  9069. }
  9070. else {
  9071. /* Put in encoding of infinity. */
  9072. buf[0] = 0x00;
  9073. }
  9074. }
  9075. }
  9076. /* Not infinity. */
  9077. else if (!err) {
  9078. /* Validate format. */
  9079. if (form != POINT_CONVERSION_UNCOMPRESSED
  9080. #ifndef HAVE_SELFTEST
  9081. && form != POINT_CONVERSION_COMPRESSED
  9082. #endif /* !HAVE_SELFTEST */
  9083. ) {
  9084. WOLFSSL_MSG("Unsupported point form");
  9085. err = 1;
  9086. }
  9087. if (!err) {
  9088. int ret;
  9089. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9090. /* Encode as compressed or uncompressed. */
  9091. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  9092. (ecc_point*)point->internal, buf, &enc_len, compressed);
  9093. #else
  9094. /* Encode uncompressed point in DER format. */
  9095. ret = wc_ecc_export_point_der(group->curve_idx,
  9096. (ecc_point*)point->internal, buf, &enc_len);
  9097. #endif /* !HAVE_SELFTEST */
  9098. /* Check return. When buf is NULL, return will be length only
  9099. * error.
  9100. */
  9101. if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) {
  9102. err = 1;
  9103. }
  9104. }
  9105. }
  9106. #if defined(DEBUG_WOLFSSL)
  9107. if (!err) {
  9108. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_point2oct point", point);
  9109. WOLFSSL_MSG("\twolfSSL_EC_POINT_point2oct output:");
  9110. WOLFSSL_BUFFER(buf, enc_len);
  9111. }
  9112. #endif
  9113. /* On error, return encoding length of 0. */
  9114. if (err) {
  9115. enc_len = 0;
  9116. }
  9117. return (size_t)enc_len;
  9118. }
  9119. /* Convert octet string to EC point.
  9120. *
  9121. * @param [in] group EC group.
  9122. * @param [in, out] point EC point to set data into.
  9123. * @param [in] buf Buffer holding octet string.
  9124. * @param [in] len Length of data in buffer in bytes.
  9125. * @param [in] ctx Context to use for BN operations. Unused.
  9126. */
  9127. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  9128. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  9129. WOLFSSL_BN_CTX *ctx)
  9130. {
  9131. int ret;
  9132. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9133. /* No BN operations performed. */
  9134. (void)ctx;
  9135. /* Validate parameters. */
  9136. if ((group == NULL) || (point == NULL)) {
  9137. ret = 0;
  9138. }
  9139. else {
  9140. /* Decode DER encoding into EC point. */
  9141. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  9142. point);
  9143. }
  9144. return ret;
  9145. }
  9146. /* Convert an EC point to a single BN.
  9147. *
  9148. * @param [in] group EC group.
  9149. * @param [in] point EC point.
  9150. * @param [in] form Format of encoding. Valid values:
  9151. * POINT_CONVERSION_UNCOMPRESSED,
  9152. * POINT_CONVERSION_COMPRESSED.
  9153. * @param [in, out] bn BN to hold point value.
  9154. * When NULL a new BN is allocated otherwise this is
  9155. * returned on success.
  9156. * @param [in] ctx Context to use for BN operations. Unused.
  9157. * @return BN object with point as a value on success.
  9158. * @return NULL on error.
  9159. */
  9160. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  9161. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  9162. WOLFSSL_BN_CTX* ctx)
  9163. {
  9164. int err = 0;
  9165. size_t len = 0;
  9166. byte *buf = NULL;
  9167. WOLFSSL_BIGNUM *ret = NULL;
  9168. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9169. /* Validate parameters. */
  9170. if ((group == NULL) || (point == NULL)) {
  9171. err = 1;
  9172. }
  9173. /* Calculate length of octet encoding. */
  9174. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  9175. 0, ctx)) == 0)) {
  9176. err = 1;
  9177. }
  9178. /* Allocate buffer to hold octet encoding. */
  9179. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  9180. NULL)) {
  9181. WOLFSSL_MSG("malloc failed");
  9182. err = 1;
  9183. }
  9184. /* Encode EC point as an octet string. */
  9185. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  9186. ctx) != len)) {
  9187. err = 1;
  9188. }
  9189. /* Load BN with octet string data. */
  9190. if (!err) {
  9191. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  9192. }
  9193. /* Dispose of any allocated data. */
  9194. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9195. return ret;
  9196. }
  9197. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9198. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9199. /* Check if EC point is on the the curve defined by the EC group.
  9200. *
  9201. * @param [in] group EC group defining curve.
  9202. * @param [in] point EC point to check.
  9203. * @param [in] ctx Context to use for BN operations. Unused.
  9204. * @return 1 when point is on curve.
  9205. * @return 0 when point is not on curve or error.
  9206. */
  9207. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9208. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9209. {
  9210. int err = 0;
  9211. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9212. /* No BN operations performed. */
  9213. (void)ctx;
  9214. /* Validate parameters. */
  9215. if ((group == NULL) || (point == NULL)) {
  9216. WOLFSSL_MSG("Invalid arguments");
  9217. err = 1;
  9218. }
  9219. /* Ensure internal EC point set. */
  9220. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9221. (WOLFSSL_EC_POINT*)point) != 1) {
  9222. WOLFSSL_MSG("ec_point_internal_set error");
  9223. err = 1;
  9224. }
  9225. /* Check point is on curve from group. */
  9226. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9227. group->curve_idx) != MP_OKAY)) {
  9228. err = 1;
  9229. }
  9230. /* Return boolean of on curve. No error means on curve. */
  9231. return !err;
  9232. }
  9233. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9234. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9235. /* Convert Jacobian ordinates to affine.
  9236. *
  9237. * @param [in] group EC group.
  9238. * @param [in] point EC point to get coordinates from.
  9239. * @return 1 on success.
  9240. * @return 0 on error.
  9241. */
  9242. int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9243. WOLFSSL_EC_POINT *point)
  9244. {
  9245. int err = 0;
  9246. mp_digit mp = 0;
  9247. #ifdef WOLFSSL_SMALL_STACK
  9248. mp_int* modulus;
  9249. #else
  9250. mp_int modulus[1];
  9251. #endif
  9252. #ifdef WOLFSSL_SMALL_STACK
  9253. /* Allocate memory for curve's prime modulus. */
  9254. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9255. if (modulus == NULL) {
  9256. err = 1;
  9257. }
  9258. #endif
  9259. /* Initialize the MP integer. */
  9260. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9261. WOLFSSL_MSG("mp_init failed");
  9262. err = 1;
  9263. }
  9264. if (!err) {
  9265. /* Get the modulus from the hex string in the EC curve set. */
  9266. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9267. MP_RADIX_HEX) != MP_OKAY) {
  9268. WOLFSSL_MSG("mp_read_radix failed");
  9269. err = 1;
  9270. }
  9271. /* Get Montgomery multiplier for the modulus as ordinates in
  9272. * Montgomery form.
  9273. */
  9274. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9275. WOLFSSL_MSG("mp_montgomery_setup failed");
  9276. err = 1;
  9277. }
  9278. /* Map internal EC point from Jacobian to affine. */
  9279. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9280. MP_OKAY)) {
  9281. WOLFSSL_MSG("ecc_map failed");
  9282. err = 1;
  9283. }
  9284. /* Set new ordinates into external EC point. */
  9285. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9286. WOLFSSL_MSG("ec_point_external_set failed");
  9287. err = 1;
  9288. }
  9289. point->exSet = !err;
  9290. mp_clear(modulus);
  9291. }
  9292. #ifdef WOLFSSL_SMALL_STACK
  9293. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9294. #endif
  9295. return err;
  9296. }
  9297. /* Get the affine coordinates of the EC point on a Prime curve.
  9298. *
  9299. * When z-ordinate is not one then coordinates are Jacobian and need to be
  9300. * converted to affine before storing in BNs.
  9301. *
  9302. * Return code compliant with OpenSSL.
  9303. *
  9304. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9305. *
  9306. * @param [in] group EC group.
  9307. * @param [in] point EC point to get coordinates from.
  9308. * @param [in, out] x BN to hold x-ordinate.
  9309. * @param [in, out] y BN to hold y-ordinate.
  9310. * @param [in] ctx Context to use for BN operations. Unused.
  9311. * @return 1 on success.
  9312. * @return 0 on error.
  9313. */
  9314. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9315. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9316. WOLFSSL_BN_CTX* ctx)
  9317. {
  9318. int ret = 1;
  9319. /* BN operations don't need context. */
  9320. (void)ctx;
  9321. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9322. /* Validate parameters. */
  9323. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9324. (x == NULL) || (y == NULL)) {
  9325. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9326. ret = 0;
  9327. }
  9328. /* Don't return point at infinity. */
  9329. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9330. ret = 0;
  9331. }
  9332. /* Ensure internal EC point has values of external EC point. */
  9333. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9334. ret = 0;
  9335. }
  9336. /* Check whether ordinates are in Jacobian form. */
  9337. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9338. /* Convert from Jacobian to affine. */
  9339. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9340. ret = 0;
  9341. }
  9342. }
  9343. /* Copy the externally set x and y ordinates. */
  9344. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9345. ret = 0;
  9346. }
  9347. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9348. ret = 0;
  9349. }
  9350. return ret;
  9351. }
  9352. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9353. /* Sets the affine coordinates that belong on a prime curve.
  9354. *
  9355. * @param [in] group EC group.
  9356. * @param [in, out] point EC point to set coordinates into.
  9357. * @param [in] x BN holding x-ordinate.
  9358. * @param [in] y BN holding y-ordinate.
  9359. * @param [in] ctx Context to use for BN operations. Unused.
  9360. * @return 1 on success.
  9361. * @return 0 on error.
  9362. */
  9363. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9364. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9365. WOLFSSL_BN_CTX* ctx)
  9366. {
  9367. int ret = 1;
  9368. /* BN operations don't need context. */
  9369. (void)ctx;
  9370. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9371. /* Validate parameters. */
  9372. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9373. (x == NULL) || (y == NULL)) {
  9374. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9375. ret = 0;
  9376. }
  9377. /* Ensure we have a object for x-ordinate. */
  9378. if ((ret == 1) && (point->X == NULL) &&
  9379. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9380. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9381. ret = 0;
  9382. }
  9383. /* Ensure we have a object for y-ordinate. */
  9384. if ((ret == 1) && (point->Y == NULL) &&
  9385. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9386. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9387. ret = 0;
  9388. }
  9389. /* Ensure we have a object for z-ordinate. */
  9390. if ((ret == 1) && (point->Z == NULL) &&
  9391. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9392. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9393. ret = 0;
  9394. }
  9395. /* Copy the x-ordinate. */
  9396. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9397. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9398. ret = 0;
  9399. }
  9400. /* Copy the y-ordinate. */
  9401. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9402. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9403. ret = 0;
  9404. }
  9405. /* z-ordinate is one for affine coordinates. */
  9406. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9407. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9408. ret = 0;
  9409. }
  9410. /* Copy the new point data to internal object. */
  9411. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9412. WOLFSSL_MSG("ec_point_internal_set failed");
  9413. ret = 0;
  9414. }
  9415. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9416. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9417. /* Check that the point is valid. */
  9418. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9419. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9420. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9421. ret = 0;
  9422. }
  9423. #endif
  9424. return ret;
  9425. }
  9426. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9427. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9428. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9429. /* Add two points on the same together.
  9430. *
  9431. * @param [in] curveIdx Index of curve in ecc_set.
  9432. * @param [out] r Result point.
  9433. * @param [in] p1 First point to add.
  9434. * @param [in] p2 Second point to add.
  9435. * @return 1 on success.
  9436. * @return 0 on error.
  9437. */
  9438. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9439. ecc_point* p2)
  9440. {
  9441. int ret = 1;
  9442. #ifdef WOLFSSL_SMALL_STACK
  9443. mp_int* a = NULL;
  9444. mp_int* prime = NULL;
  9445. mp_int* mu = NULL;
  9446. #else
  9447. mp_int a[1];
  9448. mp_int prime[1];
  9449. mp_int mu[1];
  9450. #endif
  9451. mp_digit mp = 0;
  9452. ecc_point* montP1 = NULL;
  9453. ecc_point* montP2 = NULL;
  9454. #ifdef WOLFSSL_SMALL_STACK
  9455. if (ret == 1) {
  9456. /* Allocate memory for curve parameter: a. */
  9457. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9458. if (a == NULL) {
  9459. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9460. ret = 0;
  9461. }
  9462. }
  9463. if (ret == 1) {
  9464. /* Allocate memory for curve parameter: prime. */
  9465. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9466. if (prime == NULL) {
  9467. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9468. ret = 0;
  9469. }
  9470. }
  9471. if (ret == 1) {
  9472. /* Allocate memory for mu (Montgomery normalizer). */
  9473. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9474. if (mu == NULL) {
  9475. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9476. ret = 0;
  9477. }
  9478. }
  9479. if (ret == 1) {
  9480. /* Zero out all MP int data in case initialization fails. */
  9481. XMEMSET(a, 0, sizeof(mp_int));
  9482. XMEMSET(prime, 0, sizeof(mp_int));
  9483. XMEMSET(mu, 0, sizeof(mp_int));
  9484. }
  9485. #endif
  9486. /* Initialize the MP ints. */
  9487. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9488. MP_OKAY)) {
  9489. WOLFSSL_MSG("mp_init_multi error");
  9490. ret = 0;
  9491. }
  9492. /* Read the curve parameter: a. */
  9493. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9494. MP_OKAY)) {
  9495. WOLFSSL_MSG("mp_read_radix a error");
  9496. ret = 0;
  9497. }
  9498. /* Read the curve parameter: prime. */
  9499. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9500. MP_RADIX_HEX) != MP_OKAY)) {
  9501. WOLFSSL_MSG("mp_read_radix prime error");
  9502. ret = 0;
  9503. }
  9504. /* Calculate the Montgomery product. */
  9505. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9506. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9507. ret = 0;
  9508. }
  9509. /* TODO: use the heap filed of one of the points? */
  9510. /* Allocate new points to hold the Montgomery form values. */
  9511. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9512. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9513. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9514. ret = 0;
  9515. }
  9516. /* Calculate the Montgomery normalizer. */
  9517. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9518. MP_OKAY)) {
  9519. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9520. ret = 0;
  9521. }
  9522. /* Convert to Montgomery form. */
  9523. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9524. /* Copy the points if the normalizer is 1. */
  9525. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9526. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9527. WOLFSSL_MSG("wc_ecc_copy_point error");
  9528. ret = 0;
  9529. }
  9530. }
  9531. else if (ret == 1) {
  9532. /* Multiply each ordinate by the Montgomery normalizer. */
  9533. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9534. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9535. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9536. WOLFSSL_MSG("mp_mulmod error");
  9537. ret = 0;
  9538. }
  9539. /* Multiply each ordinate by the Montgomery normalizer. */
  9540. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9541. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9542. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9543. WOLFSSL_MSG("mp_mulmod error");
  9544. ret = 0;
  9545. }
  9546. }
  9547. /* Perform point addition with internal EC point objects - Jacobian form
  9548. * result.
  9549. */
  9550. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9551. mp) != MP_OKAY)) {
  9552. WOLFSSL_MSG("ecc_projective_add_point error");
  9553. ret = 0;
  9554. }
  9555. /* Map point back to affine coordinates. Converts from Montogomery form. */
  9556. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9557. WOLFSSL_MSG("ecc_map error");
  9558. ret = 0;
  9559. }
  9560. /* Dispose of allocated memory. */
  9561. mp_clear(a);
  9562. mp_clear(prime);
  9563. mp_clear(mu);
  9564. wc_ecc_del_point_h(montP1, NULL);
  9565. wc_ecc_del_point_h(montP2, NULL);
  9566. #ifdef WOLFSSL_SMALL_STACK
  9567. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9568. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9569. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9570. #endif
  9571. return ret;
  9572. }
  9573. /* Add two points on the same curve together.
  9574. *
  9575. * @param [in] group EC group.
  9576. * @param [out] r EC point that is result of point addition.
  9577. * @param [in] p1 First EC point to add.
  9578. * @param [in] p2 Second EC point to add.
  9579. * @param [in] ctx Context to use for BN operations. Unused.
  9580. * @return 1 on success.
  9581. * @return 0 on error.
  9582. */
  9583. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9584. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9585. {
  9586. int ret = 1;
  9587. /* No BN operations performed. */
  9588. (void)ctx;
  9589. /* Validate parameters. */
  9590. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9591. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9592. ret = 0;
  9593. }
  9594. /* Ensure the internal objects of the EC points are setup. */
  9595. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9596. (ec_point_setup(p2) != 1))) {
  9597. WOLFSSL_MSG("ec_point_setup error");
  9598. ret = 0;
  9599. }
  9600. #ifdef DEBUG_WOLFSSL
  9601. if (ret == 1) {
  9602. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9603. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9604. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9605. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p1", p1);
  9606. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p2", p2);
  9607. if (curve != NULL)
  9608. WOLFSSL_MSG_EX("curve name: %s", curve);
  9609. if (nistName != NULL)
  9610. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9611. }
  9612. #endif
  9613. if (ret == 1) {
  9614. /* Add points using wolfCrypt objects. */
  9615. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9616. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9617. }
  9618. /* Copy internal EC point values out to external EC point. */
  9619. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9620. WOLFSSL_MSG("ec_point_external_set error");
  9621. ret = 0;
  9622. }
  9623. #ifdef DEBUG_WOLFSSL
  9624. if (ret == 1) {
  9625. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add result", r);
  9626. }
  9627. #endif
  9628. return ret;
  9629. }
  9630. /* Sum the scalar multiplications of the base point and n, and q and m.
  9631. *
  9632. * r = base point * n + q * m
  9633. *
  9634. * @param [out] r EC point that is result of operation.
  9635. * @param [in] b Base point of curve.
  9636. * @param [in] n Scalar to multiply by base point.
  9637. * @param [in] q EC point to be scalar multiplied.
  9638. * @param [in] m Scalar to multiply q by.
  9639. * @param [in] a Parameter A of curve.
  9640. * @param [in] prime Prime (modulus) of curve.
  9641. * @return 1 on success.
  9642. * @return 0 on error.
  9643. */
  9644. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9645. mp_int* m, mp_int* a, mp_int* prime)
  9646. {
  9647. int ret = 1;
  9648. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9649. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9650. WOLFSSL_MSG("ecc_mul2add error");
  9651. ret = 0;
  9652. }
  9653. #else
  9654. ecc_point* tmp = NULL;
  9655. mp_digit mp = 0;
  9656. /* Calculate Montgomery product. */
  9657. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9658. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9659. ret = 0;
  9660. }
  9661. /* Create temporary point to hold: q * m */
  9662. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9663. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9664. ret = 0;
  9665. }
  9666. /* r = base point * n */
  9667. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9668. MP_OKAY)) {
  9669. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9670. ret = 0;
  9671. }
  9672. /* tmp = q * m */
  9673. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9674. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9675. ret = 0;
  9676. }
  9677. /* r = r + tmp */
  9678. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9679. MP_OKAY)) {
  9680. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9681. ret = 0;
  9682. }
  9683. /* Map point back to affine coordinates. Converts from Montogomery
  9684. * form. */
  9685. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9686. WOLFSSL_MSG("ecc_map nqm error");
  9687. ret = 0;
  9688. }
  9689. /* Dispose of allocated temporary point. */
  9690. wc_ecc_del_point(tmp);
  9691. #endif
  9692. return ret;
  9693. }
  9694. /* Sum the scalar multiplications of the base point and n, and q and m.
  9695. *
  9696. * r = base point * n + q * m
  9697. *
  9698. * @param [in] curveIdx Index of curve in ecc_set.
  9699. * @param [out] r EC point that is result of operation.
  9700. * @param [in] n Scalar to multiply by base point. May be NULL.
  9701. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9702. * @param [in] m Scalar to multiply q by. May be NULL.
  9703. * @return 1 on success.
  9704. * @return 0 on error.
  9705. */
  9706. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9707. ecc_point* q, mp_int* m)
  9708. {
  9709. int ret = 1;
  9710. #ifdef WOLFSSL_SMALL_STACK
  9711. mp_int* a = NULL;
  9712. mp_int* prime = NULL;
  9713. #else
  9714. mp_int a[1], prime[1];
  9715. #endif
  9716. #ifdef WOLFSSL_SMALL_STACK
  9717. /* Allocate MP integer for curve parameter: a. */
  9718. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9719. if (a == NULL) {
  9720. ret = 0;
  9721. }
  9722. if (ret == 1) {
  9723. /* Allocate MP integer for curve parameter: prime. */
  9724. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9725. if (prime == NULL) {
  9726. ret = 0;
  9727. }
  9728. }
  9729. #endif
  9730. /* Initialize the MP ints. */
  9731. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9732. MP_OKAY)) {
  9733. WOLFSSL_MSG("mp_init_multi error");
  9734. ret = 0;
  9735. }
  9736. /* Read the curve parameter: prime. */
  9737. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9738. MP_RADIX_HEX) != MP_OKAY)) {
  9739. WOLFSSL_MSG("mp_read_radix prime error");
  9740. ret = 0;
  9741. }
  9742. /* Read the curve parameter: a. */
  9743. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9744. MP_RADIX_HEX) != MP_OKAY)) {
  9745. WOLFSSL_MSG("mp_read_radix a error");
  9746. ret = 0;
  9747. }
  9748. if ((ret == 1) && (n != NULL)) {
  9749. /* Get generator - base point. */
  9750. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9751. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9752. WOLFSSL_MSG("wc_ecc_get_generator error");
  9753. ret = 0;
  9754. }
  9755. #else
  9756. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9757. /* Read generator (base point) x-ordinate. */
  9758. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9759. MP_RADIX_HEX) != MP_OKAY)) {
  9760. WOLFSSL_MSG("mp_read_radix Gx error");
  9761. ret = 0;
  9762. }
  9763. /* Read generator (base point) y-ordinate. */
  9764. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9765. MP_RADIX_HEX) != MP_OKAY)) {
  9766. WOLFSSL_MSG("mp_read_radix Gy error");
  9767. ret = 0;
  9768. }
  9769. /* z-ordinate is one as point is affine. */
  9770. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9771. WOLFSSL_MSG("mp_set Gz error");
  9772. ret = 0;
  9773. }
  9774. #endif /* NOPT_FIPS_VERSION == 2 */
  9775. }
  9776. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9777. /* r = base point * n + q * m */
  9778. ret = ec_mul2add(r, r, n, q, m, a, prime);
  9779. }
  9780. /* Not all values present, see if we are only doing base point * n. */
  9781. else if ((ret == 1) && (n != NULL)) {
  9782. /* r = base point * n */
  9783. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9784. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9785. ret = 0;
  9786. }
  9787. }
  9788. /* Not all values present, see if we are only doing q * m. */
  9789. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9790. /* r = q * m */
  9791. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9792. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9793. ret = 0;
  9794. }
  9795. }
  9796. /* No values to use. */
  9797. else if (ret == 1) {
  9798. /* Set result to infinity as no values passed in. */
  9799. mp_zero(r->x);
  9800. mp_zero(r->y);
  9801. mp_zero(r->z);
  9802. }
  9803. mp_clear(a);
  9804. mp_clear(prime);
  9805. #ifdef WOLFSSL_SMALL_STACK
  9806. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9807. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9808. #endif
  9809. return ret;
  9810. }
  9811. /* Sum the scalar multiplications of the base point and n, and q and m.
  9812. *
  9813. * r = base point * n + q * m
  9814. *
  9815. * Return code compliant with OpenSSL.
  9816. *
  9817. * @param [in] group EC group.
  9818. * @param [out] r EC point that is result of operation.
  9819. * @param [in] n Scalar to multiply by base point. May be NULL.
  9820. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9821. * @param [in] m Scalar to multiply q by. May be NULL.
  9822. * @param [in] ctx Context to use for BN operations. Unused.
  9823. * @return 1 on success.
  9824. * @return 0 on error.
  9825. */
  9826. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9827. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  9828. WOLFSSL_BN_CTX *ctx)
  9829. {
  9830. int ret = 1;
  9831. /* No BN operations performed. */
  9832. (void)ctx;
  9833. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9834. /* Validate parameters. */
  9835. if ((group == NULL) || (r == NULL)) {
  9836. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9837. ret = 0;
  9838. }
  9839. /* Ensure the internal representation of the EC point q is setup. */
  9840. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  9841. WOLFSSL_MSG("ec_point_setup error");
  9842. ret = 0;
  9843. }
  9844. #ifdef DEBUG_WOLFSSL
  9845. if (ret == 1) {
  9846. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9847. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9848. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9849. char* num;
  9850. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul input q", q);
  9851. num = wolfSSL_BN_bn2hex(n);
  9852. WOLFSSL_MSG_EX("\tn = %s", num);
  9853. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9854. num = wolfSSL_BN_bn2hex(m);
  9855. WOLFSSL_MSG_EX("\tm = %s", num);
  9856. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9857. if (curve != NULL)
  9858. WOLFSSL_MSG_EX("curve name: %s", curve);
  9859. if (nistName != NULL)
  9860. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9861. }
  9862. #endif
  9863. if (ret == 1) {
  9864. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  9865. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  9866. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  9867. /* Perform multiplication with wolfCrypt objects. */
  9868. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  9869. ni, qi, mi);
  9870. }
  9871. /* Only on success is the internal point guaranteed to be set. */
  9872. if (r != NULL) {
  9873. r->inSet = (ret == 1);
  9874. }
  9875. /* Copy internal EC point values out to external EC point. */
  9876. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9877. WOLFSSL_MSG("ec_point_external_set error");
  9878. ret = 0;
  9879. }
  9880. #ifdef DEBUG_WOLFSSL
  9881. if (ret == 1) {
  9882. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul result", r);
  9883. }
  9884. #endif
  9885. return ret;
  9886. }
  9887. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9888. * !WOLFSSL_SP_MATH */
  9889. /* Invert the point on the curve.
  9890. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9891. *
  9892. * @param [in] curveIdx Index of curve in ecc_set.
  9893. * @param [in, out] point EC point to invert.
  9894. * @return 1 on success.
  9895. * @return 0 on error.
  9896. */
  9897. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  9898. {
  9899. int ret = 1;
  9900. #ifdef WOLFSSL_SMALL_STACK
  9901. mp_int* prime = NULL;
  9902. #else
  9903. mp_int prime[1];
  9904. #endif
  9905. #ifdef WOLFSSL_SMALL_STACK
  9906. /* Allocate memory for an MP int to hold the prime of the curve. */
  9907. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9908. if (prime == NULL) {
  9909. ret = 0;
  9910. }
  9911. #endif
  9912. /* Initialize MP int. */
  9913. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  9914. WOLFSSL_MSG("mp_init_multi error");
  9915. ret = 0;
  9916. }
  9917. /* Read the curve parameter: prime. */
  9918. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9919. MP_RADIX_HEX) != MP_OKAY)) {
  9920. WOLFSSL_MSG("mp_read_radix prime error");
  9921. ret = 0;
  9922. }
  9923. /* y = (prime - y) mod prime. */
  9924. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  9925. point->y) != MP_OKAY)) {
  9926. WOLFSSL_MSG("mp_sub error");
  9927. ret = 0;
  9928. }
  9929. /* Dispose of memory associated with MP. */
  9930. mp_free(prime);
  9931. #ifdef WOLFSSL_SMALL_STACK
  9932. /* Dispose of dynamically allocated temporaries. */
  9933. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9934. #endif
  9935. return ret;
  9936. }
  9937. /* Invert the point on the curve.
  9938. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9939. *
  9940. * @param [in] group EC group.
  9941. * @param [in, out] point EC point to invert.
  9942. * @param [in] ctx Context to use for BN operations. Unused.
  9943. * @return 1 on success.
  9944. * @return 0 on error.
  9945. */
  9946. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  9947. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9948. {
  9949. int ret = 1;
  9950. /* No BN operations performed. */
  9951. (void)ctx;
  9952. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9953. /* Validate parameters. */
  9954. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9955. ret = 0;
  9956. }
  9957. /* Ensure internal representation of point is setup. */
  9958. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9959. ret = 0;
  9960. }
  9961. #ifdef DEBUG_WOLFSSL
  9962. if (ret == 1) {
  9963. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9964. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9965. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9966. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert input", point);
  9967. if (curve != NULL)
  9968. WOLFSSL_MSG_EX("curve name: %s", curve);
  9969. if (nistName != NULL)
  9970. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9971. }
  9972. #endif
  9973. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  9974. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9975. if (ec_point_convert_to_affine(group, point) != 0)
  9976. ret = 0;
  9977. #else
  9978. WOLFSSL_MSG("wolfSSL_EC_POINT_invert called on non-affine point");
  9979. ret = 0;
  9980. #endif
  9981. }
  9982. if (ret == 1) {
  9983. /* Perform inversion using wolfCrypt objects. */
  9984. ret = wolfssl_ec_point_invert(group->curve_idx,
  9985. (ecc_point*)point->internal);
  9986. }
  9987. /* Set the external EC point representation based on internal. */
  9988. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  9989. WOLFSSL_MSG("ec_point_external_set error");
  9990. ret = 0;
  9991. }
  9992. #ifdef DEBUG_WOLFSSL
  9993. if (ret == 1) {
  9994. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert result", point);
  9995. }
  9996. #endif
  9997. return ret;
  9998. }
  9999. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10000. /* Compare two points on a the same curve.
  10001. *
  10002. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  10003. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10004. * When equal:
  10005. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10006. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  10007. *
  10008. * @param [in] group EC group.
  10009. * @param [in] a EC point to compare.
  10010. * @param [in] b EC point to compare.
  10011. * @return 0 when equal.
  10012. * @return 1 when different.
  10013. * @return -1 on error.
  10014. */
  10015. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  10016. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10017. {
  10018. int ret = 0;
  10019. BIGNUM* at = BN_new();
  10020. BIGNUM* bt = BN_new();
  10021. BIGNUM* az = BN_new();
  10022. BIGNUM* bz = BN_new();
  10023. BIGNUM* mod = BN_new();
  10024. /* Check that the big numbers were allocated. */
  10025. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  10026. (mod == NULL)) {
  10027. ret = -1;
  10028. }
  10029. /* Get the modulus for the curve. */
  10030. if ((ret == 0) &&
  10031. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  10032. ret = -1;
  10033. }
  10034. if (ret == 0) {
  10035. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  10036. if (BN_is_one(a->Z)) {
  10037. if (BN_copy(bt, b->X) == NULL) {
  10038. ret = -1;
  10039. }
  10040. }
  10041. /* az = Az ^ 2 */
  10042. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  10043. ret = -1;
  10044. }
  10045. /* bt = Bx * az = Bx * (Az ^ 2) */
  10046. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  10047. ret = -1;
  10048. }
  10049. }
  10050. if (ret == 0) {
  10051. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  10052. if (BN_is_one(b->Z)) {
  10053. if (BN_copy(at, a->X) == NULL) {
  10054. ret = -1;
  10055. }
  10056. }
  10057. /* bz = Bz ^ 2 */
  10058. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  10059. ret = -1;
  10060. }
  10061. /* at = Ax * bz = Ax * (Bz ^ 2) */
  10062. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  10063. ret = -1;
  10064. }
  10065. }
  10066. /* Compare x-ordinates. */
  10067. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10068. ret = 1;
  10069. }
  10070. if (ret == 0) {
  10071. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  10072. if (BN_is_one(a->Z)) {
  10073. if (BN_copy(bt, b->Y) == NULL) {
  10074. ret = -1;
  10075. }
  10076. }
  10077. /* az = az * Az = Az ^ 3 */
  10078. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  10079. ret = -1;
  10080. }
  10081. /* bt = By * az = By * (Az ^ 3) */
  10082. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  10083. ret = -1;
  10084. }
  10085. }
  10086. if (ret == 0) {
  10087. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  10088. if (BN_is_one(b->Z)) {
  10089. if (BN_copy(at, a->Y) == NULL) {
  10090. ret = -1;
  10091. }
  10092. }
  10093. /* bz = bz * Bz = Bz ^ 3 */
  10094. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  10095. ret = -1;
  10096. }
  10097. /* at = Ay * bz = Ay * (Bz ^ 3) */
  10098. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  10099. ret = -1;
  10100. }
  10101. }
  10102. /* Compare y-ordinates. */
  10103. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10104. ret = 1;
  10105. }
  10106. BN_free(mod);
  10107. BN_free(bz);
  10108. BN_free(az);
  10109. BN_free(bt);
  10110. BN_free(at);
  10111. return ret;
  10112. }
  10113. #endif
  10114. /* Compare two points on a the same curve.
  10115. *
  10116. * Return code compliant with OpenSSL.
  10117. *
  10118. * @param [in] group EC group.
  10119. * @param [in] a EC point to compare.
  10120. * @param [in] b EC point to compare.
  10121. * @param [in] ctx Context to use for BN operations. Unused.
  10122. * @return 0 when equal.
  10123. * @return 1 when different.
  10124. * @return -1 on error.
  10125. */
  10126. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  10127. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10128. {
  10129. int ret = 0;
  10130. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  10131. /* Validate parameters. */
  10132. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  10133. (b == NULL) || (b->internal == NULL)) {
  10134. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  10135. ret = -1;
  10136. }
  10137. if (ret != -1) {
  10138. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10139. /* If same Z ordinate then no need to convert to affine. */
  10140. if (BN_cmp(a->Z, b->Z) == 0) {
  10141. /* Compare */
  10142. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  10143. }
  10144. else {
  10145. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  10146. }
  10147. #else
  10148. /* No BN operations performed. */
  10149. (void)ctx;
  10150. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  10151. (ecc_point*)b->internal) != MP_EQ);
  10152. #endif
  10153. }
  10154. return ret;
  10155. }
  10156. /* Copy EC point.
  10157. *
  10158. * @param [out] dest EC point to copy into.
  10159. * @param [in] src EC point to copy.
  10160. * @return 1 on success.
  10161. * @return 0 on error.
  10162. */
  10163. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  10164. {
  10165. int ret = 1;
  10166. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  10167. /* Validate parameters. */
  10168. if ((dest == NULL) || (src == NULL)) {
  10169. ret = 0;
  10170. }
  10171. /* Ensure internal EC point of src is setup. */
  10172. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  10173. ret = 0;
  10174. }
  10175. /* Copy internal EC points. */
  10176. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  10177. (ecc_point*)dest->internal) != MP_OKAY)) {
  10178. ret = 0;
  10179. }
  10180. if (ret == 1) {
  10181. /* Destinatation internal point is set. */
  10182. dest->inSet = 1;
  10183. /* Set the external EC point of dest based on internal. */
  10184. if (ec_point_external_set(dest) != 1) {
  10185. ret = 0;
  10186. }
  10187. }
  10188. return ret;
  10189. }
  10190. /* Checks whether point is at infinity.
  10191. *
  10192. * Return code compliant with OpenSSL.
  10193. *
  10194. * @param [in] group EC group.
  10195. * @param [in] point EC point to check.
  10196. * @return 1 when at infinity.
  10197. * @return 0 when not at infinity.
  10198. */
  10199. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  10200. const WOLFSSL_EC_POINT *point)
  10201. {
  10202. int ret = 1;
  10203. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  10204. /* Validate parameters. */
  10205. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10206. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  10207. ret = 0;
  10208. }
  10209. /* Ensure internal EC point is setup. */
  10210. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10211. ret = 0;
  10212. }
  10213. if (ret == 1) {
  10214. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10215. /* Check for infinity. */
  10216. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  10217. if (ret < 0) {
  10218. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  10219. /* Error return is 0 by OpenSSL. */
  10220. ret = 0;
  10221. }
  10222. #else
  10223. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  10224. ret = 0;
  10225. #endif
  10226. }
  10227. return ret;
  10228. }
  10229. #endif /* OPENSSL_EXTRA */
  10230. /* End EC_POINT */
  10231. /* Start EC_KEY */
  10232. #ifdef OPENSSL_EXTRA
  10233. /*
  10234. * EC key constructor/deconstructor APIs
  10235. */
  10236. /* Allocate a new EC key.
  10237. *
  10238. * Not OpenSSL API.
  10239. *
  10240. * @param [in] heap Heap hint for dynamic memory allocation.
  10241. * @param [in] devId Device identifier value.
  10242. * @return New, allocated EC key on success.
  10243. * @return NULL on error.
  10244. */
  10245. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  10246. {
  10247. WOLFSSL_EC_KEY *key = NULL;
  10248. int err = 0;
  10249. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  10250. /* Allocate memory for EC key. */
  10251. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  10252. DYNAMIC_TYPE_ECC);
  10253. if (key == NULL) {
  10254. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  10255. err = 1;
  10256. }
  10257. if (!err) {
  10258. /* Reset all fields to 0. */
  10259. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  10260. /* Cache heap hint. */
  10261. key->heap = heap;
  10262. /* Initialize fields to defaults. */
  10263. key->form = POINT_CONVERSION_UNCOMPRESSED;
  10264. /* Initialize reference count. */
  10265. wolfSSL_RefInit(&key->ref, &err);
  10266. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  10267. }
  10268. if (!err) {
  10269. #endif
  10270. /* Allocate memory for internal EC key representation. */
  10271. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  10272. DYNAMIC_TYPE_ECC);
  10273. if (key->internal == NULL) {
  10274. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10275. err = 1;
  10276. }
  10277. }
  10278. if (!err) {
  10279. /* Initialize wolfCrypt EC key. */
  10280. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10281. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10282. err = 1;
  10283. }
  10284. }
  10285. if (!err) {
  10286. /* Group unknown at creation */
  10287. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10288. if (key->group == NULL) {
  10289. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10290. err = 1;
  10291. }
  10292. }
  10293. if (!err) {
  10294. /* Allocate a point as public key. */
  10295. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10296. if (key->pub_key == NULL) {
  10297. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10298. err = 1;
  10299. }
  10300. }
  10301. if (!err) {
  10302. /* Allocate a BN as private key. */
  10303. key->priv_key = wolfSSL_BN_new();
  10304. if (key->priv_key == NULL) {
  10305. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10306. err = 1;
  10307. }
  10308. }
  10309. if (err) {
  10310. /* Dispose of EC key on error. */
  10311. wolfSSL_EC_KEY_free(key);
  10312. key = NULL;
  10313. }
  10314. /* Return new EC key object. */
  10315. return key;
  10316. }
  10317. /* Allocate a new EC key.
  10318. *
  10319. * @return New, allocated EC key on success.
  10320. * @return NULL on error.
  10321. */
  10322. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10323. {
  10324. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10325. }
  10326. /* Create new EC key with the group having the specified numeric ID.
  10327. *
  10328. * @param [in] nid Numeric ID.
  10329. * @return New, allocated EC key on success.
  10330. * @return NULL on error.
  10331. */
  10332. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10333. {
  10334. WOLFSSL_EC_KEY *key;
  10335. int err = 0;
  10336. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10337. /* Allocate empty, EC key. */
  10338. key = wolfSSL_EC_KEY_new();
  10339. if (key == NULL) {
  10340. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10341. err = 1;
  10342. }
  10343. if (!err) {
  10344. /* Set group to be nid. */
  10345. ec_group_set_nid(key->group, nid);
  10346. if (key->group->curve_idx == -1) {
  10347. wolfSSL_EC_KEY_free(key);
  10348. key = NULL;
  10349. }
  10350. }
  10351. /* Return the new EC key object. */
  10352. return key;
  10353. }
  10354. /* Dispose of the EC key and allocated data.
  10355. *
  10356. * Cannot use key after this call.
  10357. *
  10358. * @param [in] key EC key to free.
  10359. */
  10360. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10361. {
  10362. int doFree = 0;
  10363. int err;
  10364. (void)err;
  10365. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10366. if (key != NULL) {
  10367. void* heap = key->heap;
  10368. /* Decrement reference count. */
  10369. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10370. if (doFree) {
  10371. /* Dispose of allocated reference counting data. */
  10372. wolfSSL_RefFree(&key->ref);
  10373. /* Dispose of private key. */
  10374. wolfSSL_BN_free(key->priv_key);
  10375. wolfSSL_EC_POINT_free(key->pub_key);
  10376. wolfSSL_EC_GROUP_free(key->group);
  10377. if (key->internal != NULL) {
  10378. /* Dispose of wolfCrypt representation of EC key. */
  10379. wc_ecc_free((ecc_key*)key->internal);
  10380. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10381. }
  10382. /* Set back to NULLs for safety. */
  10383. ForceZero(key, sizeof(*key));
  10384. /* Dispose of the memory associated with the EC key. */
  10385. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10386. (void)heap;
  10387. }
  10388. }
  10389. }
  10390. /* Increments ref count of EC key.
  10391. *
  10392. * @param [in, out] key EC key.
  10393. * @return 1 on success
  10394. * @return 0 on error
  10395. */
  10396. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10397. {
  10398. int err = 1;
  10399. if (key != NULL) {
  10400. wolfSSL_RefInc(&key->ref, &err);
  10401. }
  10402. return !err;
  10403. }
  10404. #ifndef NO_CERTS
  10405. #if defined(OPENSSL_ALL)
  10406. /* Copy the internal, wolfCrypt EC key.
  10407. *
  10408. * @param [in, out] dst Destination wolfCrypt EC key.
  10409. * @param [in] src Source wolfCrypt EC key.
  10410. * @return 0 on success.
  10411. * @return Negative on error.
  10412. */
  10413. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10414. {
  10415. int ret;
  10416. /* Copy public key. */
  10417. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10418. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10419. #else
  10420. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10421. #endif
  10422. if (ret != MP_OKAY) {
  10423. WOLFSSL_MSG("wc_ecc_copy_point error");
  10424. }
  10425. if (ret == 0) {
  10426. /* Copy private key. */
  10427. ret = mp_copy(wc_ecc_key_get_priv((ecc_key*)src),
  10428. wc_ecc_key_get_priv(dst));
  10429. if (ret != MP_OKAY) {
  10430. WOLFSSL_MSG("mp_copy error");
  10431. }
  10432. }
  10433. if (ret == 0) {
  10434. /* Copy domain parameters. */
  10435. if (src->dp) {
  10436. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10437. if (ret != 0) {
  10438. WOLFSSL_MSG("wc_ecc_set_curve error");
  10439. }
  10440. }
  10441. }
  10442. if (ret == 0) {
  10443. /* Copy the other components. */
  10444. dst->type = src->type;
  10445. dst->idx = src->idx;
  10446. dst->state = src->state;
  10447. dst->flags = src->flags;
  10448. }
  10449. return ret;
  10450. }
  10451. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10452. *
  10453. * Copies the internal representation as well.
  10454. *
  10455. * @param [in] src EC key to duplicate.
  10456. *
  10457. * @return EC key on success.
  10458. * @return NULL on error.
  10459. */
  10460. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10461. {
  10462. int err = 0;
  10463. WOLFSSL_EC_KEY* newKey = NULL;
  10464. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10465. /* Validate EC key. */
  10466. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10467. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10468. WOLFSSL_MSG("src NULL error");
  10469. err = 1;
  10470. }
  10471. if (!err) {
  10472. /* Create a new, empty key. */
  10473. newKey = wolfSSL_EC_KEY_new();
  10474. if (newKey == NULL) {
  10475. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10476. err = 1;
  10477. }
  10478. }
  10479. if (!err) {
  10480. /* Copy internal EC key. */
  10481. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10482. (ecc_key*)src->internal) != 0) {
  10483. WOLFSSL_MSG("Copying internal EC key error");
  10484. err = 1;
  10485. }
  10486. }
  10487. if (!err) {
  10488. /* Internal key set. */
  10489. newKey->inSet = 1;
  10490. /* Copy group */
  10491. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10492. }
  10493. /* Copy public key. */
  10494. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10495. WOLFSSL_MSG("Copying EC public key error");
  10496. err = 1;
  10497. }
  10498. if (!err) {
  10499. /* Set header size of private key in PKCS#8 format.*/
  10500. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10501. /* Copy private key. */
  10502. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10503. WOLFSSL_MSG("Copying EC private key error");
  10504. err = 1;
  10505. }
  10506. }
  10507. if (err) {
  10508. /* Dispose of EC key on error. */
  10509. wolfSSL_EC_KEY_free(newKey);
  10510. newKey = NULL;
  10511. }
  10512. /* Return the new EC key. */
  10513. return newKey;
  10514. }
  10515. #endif /* OPENSSL_ALL */
  10516. #endif /* !NO_CERTS */
  10517. /*
  10518. * EC key to/from bin/octet APIs
  10519. */
  10520. /* Create an EC key from the octet encoded public key.
  10521. *
  10522. * Behaviour checked against OpenSSL.
  10523. *
  10524. * @param [out] key Reference to EC key. Must pass in a valid object with
  10525. * group set.
  10526. * @param [in, out] in On in, reference to buffer that contains data.
  10527. * On out, reference to buffer after public key data.
  10528. * @param [in] len Length of data in the buffer. Must be length of the
  10529. * encoded public key.
  10530. * @return Allocated EC key on success.
  10531. * @return NULL on error.
  10532. */
  10533. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10534. const unsigned char **in, long len)
  10535. {
  10536. int err = 0;
  10537. WOLFSSL_EC_KEY* ret = NULL;
  10538. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10539. /* Validate parameters: EC group needed to perform import. */
  10540. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10541. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10542. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10543. err = 1;
  10544. }
  10545. if (!err) {
  10546. /* Return the EC key object passed in. */
  10547. ret = *key;
  10548. /* Import point into public key field. */
  10549. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in,
  10550. (size_t)len, NULL) != 1) {
  10551. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10552. ret = NULL;
  10553. err = 1;
  10554. }
  10555. }
  10556. if (!err) {
  10557. /* Assumed length passed in is all the data. */
  10558. *in += len;
  10559. }
  10560. return ret;
  10561. }
  10562. /* Puts the encoded public key into out.
  10563. *
  10564. * Passing in NULL for out returns length only.
  10565. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10566. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10567. *
  10568. * @param [in] key EC key to encode.
  10569. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10570. * point to NULL.
  10571. * @return Length of encoding in bytes on success.
  10572. * @return 0 on error.
  10573. */
  10574. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10575. {
  10576. int ret = 1;
  10577. size_t len = 0;
  10578. int form = POINT_CONVERSION_UNCOMPRESSED;
  10579. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10580. /* Validate parameters. */
  10581. if (key == NULL) {
  10582. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10583. ret = 0;
  10584. }
  10585. /* Ensure the external key data is set from the internal EC key. */
  10586. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10587. key) != 1)) {
  10588. WOLFSSL_MSG("SetECKeyExternal failure");
  10589. ret = 0;
  10590. }
  10591. if (ret == 1) {
  10592. #ifdef HAVE_COMP_KEY
  10593. /* Default to compressed form if not set */
  10594. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10595. POINT_CONVERSION_UNCOMPRESSED :
  10596. POINT_CONVERSION_COMPRESSED;
  10597. #endif
  10598. /* Calculate length of point encoding. */
  10599. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10600. 0, NULL);
  10601. }
  10602. /* Encode if length calculated and pointer supplied to update. */
  10603. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10604. unsigned char *tmp = NULL;
  10605. /* Allocate buffer for encoding if no buffer supplied. */
  10606. if (*out == NULL) {
  10607. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10608. if (tmp == NULL) {
  10609. WOLFSSL_MSG("malloc failed");
  10610. ret = 0;
  10611. }
  10612. }
  10613. else {
  10614. /* Get buffer to encode into. */
  10615. tmp = *out;
  10616. }
  10617. /* Encode public key into buffer. */
  10618. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10619. form, tmp, len, NULL) == 0)) {
  10620. ret = 0;
  10621. }
  10622. if (ret == 1) {
  10623. /* Return buffer if allocated. */
  10624. if (*out == NULL) {
  10625. *out = tmp;
  10626. }
  10627. else {
  10628. /* Step over encoded data if not allocated. */
  10629. *out += len;
  10630. }
  10631. }
  10632. else if (*out == NULL) {
  10633. /* Dispose of allocated buffer. */
  10634. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10635. }
  10636. }
  10637. if (ret == 1) {
  10638. /* Return length on success. */
  10639. ret = (int)len;
  10640. }
  10641. return ret;
  10642. }
  10643. #ifdef HAVE_ECC_KEY_IMPORT
  10644. /* Create a EC key from the DER encoded private key.
  10645. *
  10646. * @param [out] key Reference to EC key.
  10647. * @param [in, out] in On in, reference to buffer that contains DER data.
  10648. * On out, reference to buffer after private key data.
  10649. * @param [in] long Length of data in the buffer. May be larger than the
  10650. * length of the encoded private key.
  10651. * @return Allocated EC key on success.
  10652. * @return NULL on error.
  10653. */
  10654. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10655. const unsigned char** in, long len)
  10656. {
  10657. int err = 0;
  10658. word32 idx = 0;
  10659. WOLFSSL_EC_KEY* ret = NULL;
  10660. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10661. /* Validate parameters. */
  10662. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10663. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10664. err = 1;
  10665. }
  10666. /* Create a new, empty EC key. */
  10667. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10668. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10669. err = 1;
  10670. }
  10671. /* Decode the private key DER data into internal EC key. */
  10672. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10673. (word32)len) != 0)) {
  10674. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10675. err = 1;
  10676. }
  10677. if (!err) {
  10678. /* Internal EC key setup. */
  10679. ret->inSet = 1;
  10680. /* Set the EC key from the internal values. */
  10681. if (SetECKeyExternal(ret) != 1) {
  10682. WOLFSSL_MSG("SetECKeyExternal error");
  10683. err = 1;
  10684. }
  10685. }
  10686. if (!err) {
  10687. /* Move buffer on to next byte after data used. */
  10688. *in += idx;
  10689. if (key) {
  10690. /* Return new EC key through reference. */
  10691. *key = ret;
  10692. }
  10693. }
  10694. if (err && (ret != NULL)) {
  10695. /* Dispose of allocated EC key. */
  10696. wolfSSL_EC_KEY_free(ret);
  10697. ret = NULL;
  10698. }
  10699. return ret;
  10700. }
  10701. #endif /* HAVE_ECC_KEY_IMPORT */
  10702. /* Enecode the private key of the EC key into the buffer as DER.
  10703. *
  10704. * @param [in] key EC key to encode.
  10705. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10706. * On out, reference to buffer adter the encoding.
  10707. * May be NULL.
  10708. * @return Length of DER encoding on success.
  10709. * @return 0 on error.
  10710. */
  10711. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10712. {
  10713. int err = 0;
  10714. word32 len = 0;
  10715. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10716. /* Validate parameters. */
  10717. if (key == NULL) {
  10718. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10719. err = 1;
  10720. }
  10721. /* Update the internal EC key if not set. */
  10722. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10723. 1)) {
  10724. WOLFSSL_MSG("SetECKeyInternal error");
  10725. err = 1;
  10726. }
  10727. /* Calculate the length of the private key DER encoding using internal EC
  10728. * key. */
  10729. if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal,
  10730. 0)) <= 0)) {
  10731. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10732. err = 1;
  10733. }
  10734. /* Only return length when out is NULL. */
  10735. if ((!err) && (out != NULL)) {
  10736. unsigned char* buf = NULL;
  10737. /* Must have a buffer to encode into. */
  10738. if (*out == NULL) {
  10739. /* Allocate a new buffer of appropriate length. */
  10740. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10741. if (buf == NULL) {
  10742. /* Error and return 0. */
  10743. err = 1;
  10744. len = 0;
  10745. }
  10746. else {
  10747. /* Return the allocated buffer. */
  10748. *out = buf;
  10749. }
  10750. }
  10751. /* Encode the internal EC key as a private key in DER format. */
  10752. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10753. len) < 0) {
  10754. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10755. err = 1;
  10756. }
  10757. else if (buf != *out) {
  10758. /* Move the reference to byte past encoded private key. */
  10759. *out += len;
  10760. }
  10761. /* Dispose of any allocated buffer on error. */
  10762. if (err && (*out == buf)) {
  10763. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10764. *out = NULL;
  10765. }
  10766. }
  10767. return (int)len;
  10768. }
  10769. /* Load private key into EC key from DER encoding.
  10770. *
  10771. * Not an OpenSSL compatibility API.
  10772. *
  10773. * @param [in, out] key EC key to put private key values into.
  10774. * @param [in] derBuf Buffer holding DER encoding.
  10775. * @param [in] derSz Size of DER encoding in bytes.
  10776. * @return 1 on success.
  10777. * @return -1 on error.
  10778. */
  10779. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10780. int derSz)
  10781. {
  10782. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10783. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10784. }
  10785. /* Load private/public key into EC key from DER encoding.
  10786. *
  10787. * Not an OpenSSL compatibility API.
  10788. *
  10789. * @param [in, out] key EC key to put private/public key values into.
  10790. * @param [in] derBuf Buffer holding DER encoding.
  10791. * @param [in] derSz Size of DER encoding in bytes.
  10792. * @param [in] opt Key type option. Valid values:
  10793. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10794. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10795. * @return 1 on success.
  10796. * @return -1 on error.
  10797. */
  10798. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10799. int derSz, int opt)
  10800. {
  10801. int res = 1;
  10802. int ret;
  10803. word32 idx = 0;
  10804. word32 algId;
  10805. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10806. /* Validate parameters. */
  10807. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10808. (derSz <= 0)) {
  10809. WOLFSSL_MSG("Bad function arguments");
  10810. res = -1;
  10811. }
  10812. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10813. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10814. res = -1;
  10815. }
  10816. if (res == 1) {
  10817. /* Assume no PKCS#8 header. */
  10818. key->pkcs8HeaderSz = 0;
  10819. /* Check if input buffer has PKCS8 header. In the case that it does not
  10820. * have a PKCS8 header then do not error out.
  10821. */
  10822. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10823. (word32)derSz, &algId)) > 0) {
  10824. WOLFSSL_MSG("Found PKCS8 header");
  10825. key->pkcs8HeaderSz = (word16)idx;
  10826. res = 1;
  10827. }
  10828. /* Error out on parsing error. */
  10829. else if (ret != ASN_PARSE_E) {
  10830. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10831. res = -1;
  10832. }
  10833. }
  10834. if (res == 1) {
  10835. /* Load into internal EC key based on key type option. */
  10836. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10837. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10838. (word32)derSz);
  10839. }
  10840. else {
  10841. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10842. (word32)derSz);
  10843. if (ret < 0) {
  10844. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  10845. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  10846. if (tmp == NULL) {
  10847. ret = -1;
  10848. }
  10849. else {
  10850. /* We now try again as x.963 [point type][x][opt y]. */
  10851. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  10852. INVALID_DEVID);
  10853. if (ret == 0) {
  10854. ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp);
  10855. if (ret == 0) {
  10856. /* Take ownership of new key - set tmp to the old
  10857. * key which will then be freed below. */
  10858. ecc_key *old = (ecc_key *)key->internal;
  10859. key->internal = tmp;
  10860. tmp = old;
  10861. idx = (word32)derSz;
  10862. }
  10863. wc_ecc_free(tmp);
  10864. }
  10865. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  10866. DYNAMIC_TYPE_ECC);
  10867. }
  10868. }
  10869. }
  10870. if (ret < 0) {
  10871. /* Error returned from wolfSSL. */
  10872. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10873. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10874. }
  10875. else {
  10876. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10877. }
  10878. res = -1;
  10879. }
  10880. /* Internal key updated - update whether it is a valid key. */
  10881. key->inSet = (res == 1);
  10882. }
  10883. /* Set the external EC key based on value in internal. */
  10884. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  10885. WOLFSSL_MSG("SetECKeyExternal failed");
  10886. res = -1;
  10887. }
  10888. return res;
  10889. }
  10890. /*
  10891. * EC key PEM APIs
  10892. */
  10893. #ifdef HAVE_ECC_KEY_EXPORT
  10894. #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_FILESYSTEM) || !defined(NO_BIO))
  10895. /* Encode the EC public key as DER.
  10896. *
  10897. * @param [in] key EC key to encode.
  10898. * @param [out] der Pointer through which buffer is returned.
  10899. * @param [in] heap Heap hint.
  10900. * @return Size of encoding on success.
  10901. * @return 0 on error.
  10902. */
  10903. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  10904. unsigned char** der, void* heap)
  10905. {
  10906. int sz;
  10907. unsigned char* buf = NULL;
  10908. (void)heap;
  10909. /* Calculate encoded size to allocate. */
  10910. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  10911. if (sz <= 0) {
  10912. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  10913. sz = 0;
  10914. }
  10915. if (sz > 0) {
  10916. /* Allocate memory to hold encoding. */
  10917. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10918. if (buf == NULL) {
  10919. WOLFSSL_MSG("malloc failed");
  10920. sz = 0;
  10921. }
  10922. }
  10923. if (sz > 0) {
  10924. /* Encode public key to DER using wolfSSL. */
  10925. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1);
  10926. if (sz < 0) {
  10927. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  10928. sz = 0;
  10929. }
  10930. }
  10931. /* Return buffer on success. */
  10932. if (sz > 0) {
  10933. *der = buf;
  10934. }
  10935. else {
  10936. /* Dispose of any dynamically allocated data not returned. */
  10937. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10938. }
  10939. return sz;
  10940. }
  10941. #endif
  10942. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  10943. /*
  10944. * Return code compliant with OpenSSL.
  10945. *
  10946. * @param [in] fp File pointer to write PEM encoding to.
  10947. * @param [in] key EC key to encode and write.
  10948. * @return 1 on success.
  10949. * @return 0 on error.
  10950. */
  10951. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10952. {
  10953. int ret = 1;
  10954. unsigned char* derBuf = NULL;
  10955. int derSz = 0;
  10956. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10957. /* Validate parameters. */
  10958. if ((fp == XBADFILE) || (key == NULL)) {
  10959. WOLFSSL_MSG("Bad argument.");
  10960. return 0;
  10961. }
  10962. /* Encode public key in EC key as DER. */
  10963. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  10964. if (derSz == 0) {
  10965. ret = 0;
  10966. }
  10967. /* Write out to file the PEM encoding of the DER. */
  10968. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  10969. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  10970. ret = 0;
  10971. }
  10972. /* Dispose of any dynamically allocated data. */
  10973. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10974. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10975. return ret;
  10976. }
  10977. #endif
  10978. #endif
  10979. #ifndef NO_BIO
  10980. /* Read a PEM encoded EC public key from a BIO.
  10981. *
  10982. * @param [in] bio BIO to read EC public key from.
  10983. * @param [out] out Pointer to return EC key object through. May be NULL.
  10984. * @param [in] cb Password callback when PEM encrypted.
  10985. * @param [in] pass NUL terminated string for passphrase when PEM
  10986. * encrypted.
  10987. * @return New EC key object on success.
  10988. * @return NULL on error.
  10989. */
  10990. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10991. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10992. {
  10993. int err = 0;
  10994. WOLFSSL_EC_KEY* ec = NULL;
  10995. DerBuffer* der = NULL;
  10996. int keyFormat = 0;
  10997. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10998. /* Validate parameters. */
  10999. if (bio == NULL) {
  11000. err = 1;
  11001. }
  11002. if (!err) {
  11003. /* Create an empty EC key. */
  11004. ec = wolfSSL_EC_KEY_new();
  11005. if (ec == NULL) {
  11006. err = 1;
  11007. }
  11008. }
  11009. /* Read a PEM key in to a new DER buffer. */
  11010. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  11011. &keyFormat, &der) <= 0)) {
  11012. err = 1;
  11013. }
  11014. /* Load the EC key with the public key from the DER encoding. */
  11015. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11016. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  11017. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11018. err = 1;
  11019. }
  11020. /* Dispose of dynamically allocated data not needed anymore. */
  11021. FreeDer(&der);
  11022. if (err) {
  11023. wolfSSL_EC_KEY_free(ec);
  11024. ec = NULL;
  11025. }
  11026. /* Return EC key through out if required. */
  11027. if ((out != NULL) && (ec != NULL)) {
  11028. *out = ec;
  11029. }
  11030. return ec;
  11031. }
  11032. /* Read a PEM encoded EC private key from a BIO.
  11033. *
  11034. * @param [in] bio BIO to read EC private key from.
  11035. * @param [out] out Pointer to return EC key object through. May be NULL.
  11036. * @param [in] cb Password callback when PEM encrypted.
  11037. * @param [in] pass NUL terminated string for passphrase when PEM
  11038. * encrypted.
  11039. * @return New EC key object on success.
  11040. * @return NULL on error.
  11041. */
  11042. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  11043. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  11044. {
  11045. int err = 0;
  11046. WOLFSSL_EC_KEY* ec = NULL;
  11047. DerBuffer* der = NULL;
  11048. int keyFormat = 0;
  11049. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  11050. /* Validate parameters. */
  11051. if (bio == NULL) {
  11052. err = 1;
  11053. }
  11054. if (!err) {
  11055. /* Create an empty EC key. */
  11056. ec = wolfSSL_EC_KEY_new();
  11057. if (ec == NULL) {
  11058. err = 1;
  11059. }
  11060. }
  11061. /* Read a PEM key in to a new DER buffer.
  11062. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  11063. * pem_read_bio_key(), and then check key format if it is EC.
  11064. */
  11065. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  11066. &keyFormat, &der) <= 0)) {
  11067. err = 1;
  11068. }
  11069. if (keyFormat != ECDSAk) {
  11070. WOLFSSL_ERROR_MSG("Error not EC key format");
  11071. err = 1;
  11072. }
  11073. /* Load the EC key with the private key from the DER encoding. */
  11074. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11075. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  11076. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11077. err = 1;
  11078. }
  11079. /* Dispose of dynamically allocated data not needed anymore. */
  11080. FreeDer(&der);
  11081. if (err) {
  11082. wolfSSL_EC_KEY_free(ec);
  11083. ec = NULL;
  11084. }
  11085. /* Return EC key through out if required. */
  11086. if ((out != NULL) && (ec != NULL)) {
  11087. *out = ec;
  11088. }
  11089. return ec;
  11090. }
  11091. #endif /* !NO_BIO */
  11092. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC_KEY_EXPORT)
  11093. #ifndef NO_BIO
  11094. /* Write out the EC public key as PEM to the BIO.
  11095. *
  11096. * @param [in] bio BIO to write PEM encoding to.
  11097. * @param [in] ec EC public key to encode.
  11098. * @return 1 on success.
  11099. * @return 0 on error.
  11100. */
  11101. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  11102. {
  11103. int ret = 1;
  11104. unsigned char* derBuf = NULL;
  11105. int derSz = 0;
  11106. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  11107. /* Validate parameters. */
  11108. if ((bio == NULL) || (ec == NULL)) {
  11109. WOLFSSL_MSG("Bad Function Arguments");
  11110. return 0;
  11111. }
  11112. /* Encode public key in EC key as DER. */
  11113. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  11114. if (derSz == 0) {
  11115. ret = 0;
  11116. }
  11117. /* Write out to BIO the PEM encoding of the EC public key. */
  11118. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  11119. ECC_PUBLICKEY_TYPE) != 1)) {
  11120. ret = 0;
  11121. }
  11122. /* Dispose of any dynamically allocated data. */
  11123. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11124. return ret;
  11125. }
  11126. /* Write out the EC private key as PEM to the BIO.
  11127. *
  11128. * Return code compliant with OpenSSL.
  11129. *
  11130. * @param [in] bio BIO to write PEM encoding to.
  11131. * @param [in] ec EC private key to encode.
  11132. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11133. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11134. * @param [in] passwdSz Length of password string when PEM encrypted.
  11135. * @param [in] cb Password callback when PEM encrypted. Unused.
  11136. * @param [in] pass NUL terminated string for passphrase when PEM
  11137. * encrypted. Unused.
  11138. * @return 1 on success.
  11139. * @return 0 on error.
  11140. */
  11141. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  11142. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11143. wc_pem_password_cb* cb, void* arg)
  11144. {
  11145. int ret = 1;
  11146. unsigned char* pem = NULL;
  11147. int pLen = 0;
  11148. (void)cb;
  11149. (void)arg;
  11150. /* Validate parameters. */
  11151. if ((bio == NULL) || (ec == NULL)) {
  11152. ret = 0;
  11153. }
  11154. /* Write EC private key to PEM. */
  11155. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11156. passwdSz, &pem, &pLen) != 1)) {
  11157. ret = 0;
  11158. }
  11159. /* Write PEM to BIO. */
  11160. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  11161. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  11162. ret = 0;
  11163. }
  11164. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11165. return ret;
  11166. }
  11167. #endif /* !NO_BIO */
  11168. /* Encode the EC private key as PEM into buffer.
  11169. *
  11170. * Return code compliant with OpenSSL.
  11171. * Not an OpenSSL API.
  11172. *
  11173. * @param [in] ec EC private key to encode.
  11174. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11175. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11176. * @param [in] passwdSz Length of password string when PEM encrypted.
  11177. * @param [out] pem Newly allocated buffer holding PEM encoding.
  11178. * @param [out] pLen Length of PEM encoding in bytes.
  11179. * @return 1 on success.
  11180. * @return 0 on error.
  11181. */
  11182. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  11183. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11184. unsigned char **pem, int *pLen)
  11185. {
  11186. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  11187. int ret = 1;
  11188. byte* derBuf = NULL;
  11189. word32 der_max_len = 0;
  11190. int derSz = 0;
  11191. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  11192. /* Validate parameters. */
  11193. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  11194. (ec->internal == NULL)) {
  11195. WOLFSSL_MSG("Bad function arguments");
  11196. ret = 0;
  11197. }
  11198. /* Ensure internal EC key is set from external. */
  11199. if ((ret == 1) && (ec->inSet == 0)) {
  11200. WOLFSSL_MSG("No ECC internal set, do it");
  11201. if (SetECKeyInternal(ec) != 1) {
  11202. WOLFSSL_MSG("SetECKeyInternal failed");
  11203. ret = 0;
  11204. }
  11205. }
  11206. if (ret == 1) {
  11207. /* Calculate maximum size of DER encoding.
  11208. * 4 > size of pub, priv + ASN.1 additional information */
  11209. der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) +
  11210. AES_BLOCK_SIZE;
  11211. /* Allocate buffer big enough to hold encoding. */
  11212. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL,
  11213. DYNAMIC_TYPE_TMP_BUFFER);
  11214. if (derBuf == NULL) {
  11215. WOLFSSL_MSG("malloc failed");
  11216. ret = 0;
  11217. }
  11218. }
  11219. if (ret == 1) {
  11220. /* Encode EC private key as DER. */
  11221. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  11222. if (derSz < 0) {
  11223. WOLFSSL_MSG("wc_EccKeyToDer failed");
  11224. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  11225. ret = 0;
  11226. }
  11227. }
  11228. /* Convert DER to PEM - possibly encrypting. */
  11229. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  11230. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  11231. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  11232. ret = 0;
  11233. }
  11234. return ret;
  11235. #else
  11236. (void)ec;
  11237. (void)cipher;
  11238. (void)passwd;
  11239. (void)passwdSz;
  11240. (void)pem;
  11241. (void)pLen;
  11242. return 0;
  11243. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  11244. }
  11245. #ifndef NO_FILESYSTEM
  11246. /* Write out the EC private key as PEM to file.
  11247. *
  11248. * Return code compliant with OpenSSL.
  11249. *
  11250. * @param [in] fp File pointer to write PEM encoding to.
  11251. * @param [in] ec EC private key to encode.
  11252. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11253. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11254. * @param [in] passwdSz Length of password string when PEM encrypted.
  11255. * @param [in] cb Password callback when PEM encrypted. Unused.
  11256. * @param [in] pass NUL terminated string for passphrase when PEM
  11257. * encrypted. Unused.
  11258. * @return 1 on success.
  11259. * @return 0 on error.
  11260. */
  11261. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  11262. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  11263. wc_pem_password_cb *cb, void *pass)
  11264. {
  11265. int ret = 1;
  11266. byte *pem = NULL;
  11267. int pLen = 0;
  11268. (void)cb;
  11269. (void)pass;
  11270. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  11271. /* Validate parameters. */
  11272. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  11273. WOLFSSL_MSG("Bad function arguments");
  11274. ret = 0;
  11275. }
  11276. /* Write EC private key to PEM. */
  11277. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11278. passwdSz, &pem, &pLen) != 1)) {
  11279. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11280. ret = 0;
  11281. }
  11282. /* Write out to file the PEM encoding of the EC private key. */
  11283. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  11284. WOLFSSL_MSG("ECC private key file write failed");
  11285. ret = 0;
  11286. }
  11287. /* Dispose of any dynamically allocated data. */
  11288. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11289. return ret;
  11290. }
  11291. #endif /* NO_FILESYSTEM */
  11292. #endif /* WOLFSSL_KEY_GEN && HAVE_ECC_KEY_EXPORT */
  11293. /*
  11294. * EC key print APIs
  11295. */
  11296. #ifndef NO_CERTS
  11297. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11298. !defined(NO_STDIO_FILESYSTEM)
  11299. /* Print the EC key to a file pointer as text.
  11300. *
  11301. * @param [in] fp File pointer.
  11302. * @param [in] key EC key to print.
  11303. * @param [in] indent Number of spaces to place before each line printed.
  11304. * @return 1 on success.
  11305. * @return 0 on failure.
  11306. */
  11307. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11308. {
  11309. int ret = 1;
  11310. int bits = 0;
  11311. int priv = 0;
  11312. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11313. /* Validate parameters. */
  11314. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11315. (indent < 0)) {
  11316. ret = 0;
  11317. }
  11318. if (ret == 1) {
  11319. /* Get EC groups order size in bits. */
  11320. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11321. if (bits <= 0) {
  11322. WOLFSSL_MSG("Failed to get group order bits.");
  11323. ret = 0;
  11324. }
  11325. }
  11326. if (ret == 1) {
  11327. const char* keyType;
  11328. /* Determine whether this is a private or public key. */
  11329. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11330. keyType = "Private-Key";
  11331. priv = 1;
  11332. }
  11333. else {
  11334. keyType = "Public-Key";
  11335. }
  11336. /* Print key header. */
  11337. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11338. ret = 0;
  11339. }
  11340. }
  11341. if ((ret == 1) && priv) {
  11342. /* Print the private key BN. */
  11343. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11344. }
  11345. /* Check for public key data in EC key. */
  11346. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11347. /* Get the public key point as one BN. */
  11348. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11349. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11350. if (pubBn == NULL) {
  11351. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11352. ret = 0;
  11353. }
  11354. else {
  11355. /* Print the public key in a BN. */
  11356. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11357. wolfSSL_BN_free(pubBn);
  11358. }
  11359. }
  11360. if (ret == 1) {
  11361. /* Get the NID of the group. */
  11362. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11363. if (nid > 0) {
  11364. /* Convert the NID into a long name and NIST name. */
  11365. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11366. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11367. /* Print OID name if known. */
  11368. if ((curve != NULL) &&
  11369. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11370. ret = 0;
  11371. }
  11372. /* Print NIST curve name if known. */
  11373. if ((nistName != NULL) &&
  11374. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11375. nistName) < 0)) {
  11376. ret = 0;
  11377. }
  11378. }
  11379. }
  11380. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11381. return ret;
  11382. }
  11383. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11384. #endif /* !NO_CERTS */
  11385. /*
  11386. * EC_KEY get/set/test APIs
  11387. */
  11388. /* Set data of internal, wolfCrypt EC key object into EC key.
  11389. *
  11390. * EC_KEY wolfSSL -> OpenSSL
  11391. *
  11392. * @param [in, out] p EC key to update.
  11393. * @return 1 on success.
  11394. * @return -1 on failure.
  11395. */
  11396. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11397. {
  11398. int ret = 1;
  11399. WOLFSSL_ENTER("SetECKeyExternal");
  11400. /* Validate parameter. */
  11401. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11402. WOLFSSL_MSG("ec key NULL error");
  11403. ret = -1;
  11404. }
  11405. else {
  11406. ecc_key* key = (ecc_key*)eckey->internal;
  11407. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11408. eckey->group->curve_oid = (int)key->dp->oidSum;
  11409. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11410. eckey->group->curve_idx = key->idx;
  11411. if (eckey->pub_key->internal != NULL) {
  11412. /* Copy internal public point from internal key's public point. */
  11413. if (wc_ecc_copy_point(&key->pubkey,
  11414. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11415. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11416. ret = -1;
  11417. }
  11418. /* Set external public key from internal wolfCrypt, public key. */
  11419. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11420. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11421. ret = -1;
  11422. }
  11423. }
  11424. /* set the external privkey */
  11425. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11426. (wolfssl_bn_set_value(&eckey->priv_key,
  11427. wc_ecc_key_get_priv(key)) != 1)) {
  11428. WOLFSSL_MSG("ec priv key error");
  11429. ret = -1;
  11430. }
  11431. /* External values set when operations succeeded. */
  11432. eckey->exSet = (ret == 1);
  11433. }
  11434. return ret;
  11435. }
  11436. /* Set data of EC key into internal, wolfCrypt EC key object.
  11437. *
  11438. * EC_KEY Openssl -> WolfSSL
  11439. *
  11440. * @param [in, out] p EC key to update.
  11441. * @return 1 on success.
  11442. * @return -1 on failure.
  11443. */
  11444. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11445. {
  11446. int ret = 1;
  11447. WOLFSSL_ENTER("SetECKeyInternal");
  11448. /* Validate parameter. */
  11449. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11450. (eckey->group == NULL)) {
  11451. WOLFSSL_MSG("ec key NULL error");
  11452. ret = -1;
  11453. }
  11454. else {
  11455. ecc_key* key = (ecc_key*)eckey->internal;
  11456. int pubSet = 0;
  11457. /* Validate group. */
  11458. if ((eckey->group->curve_idx < 0) ||
  11459. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11460. WOLFSSL_MSG("invalid curve idx");
  11461. ret = -1;
  11462. }
  11463. if (ret == 1) {
  11464. /* Set group (idx of curve and corresponding domain parameters). */
  11465. key->idx = eckey->group->curve_idx;
  11466. key->dp = &ecc_sets[key->idx];
  11467. pubSet = (eckey->pub_key != NULL);
  11468. }
  11469. /* Set public key (point). */
  11470. if ((ret == 1) && pubSet) {
  11471. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11472. WOLFSSL_MSG("ec key pub error");
  11473. ret = -1;
  11474. }
  11475. /* Copy public point to key. */
  11476. if ((ret == 1) && (wc_ecc_copy_point(
  11477. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11478. MP_OKAY)) {
  11479. WOLFSSL_MSG("wc_ecc_copy_point error");
  11480. ret = -1;
  11481. }
  11482. if (ret == 1) {
  11483. /* Set that the internal key is a public key */
  11484. key->type = ECC_PUBLICKEY;
  11485. }
  11486. }
  11487. /* set privkey */
  11488. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11489. if (wolfssl_bn_get_value(eckey->priv_key,
  11490. wc_ecc_key_get_priv(key)) != 1) {
  11491. WOLFSSL_MSG("ec key priv error");
  11492. ret = -1;
  11493. }
  11494. /* private key */
  11495. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11496. if (pubSet) {
  11497. key->type = ECC_PRIVATEKEY;
  11498. }
  11499. else {
  11500. key->type = ECC_PRIVATEKEY_ONLY;
  11501. }
  11502. }
  11503. }
  11504. /* Internal values set when operations succeeded. */
  11505. eckey->inSet = (ret == 1);
  11506. }
  11507. return ret;
  11508. }
  11509. /* Get point conversion format of EC key.
  11510. *
  11511. * @param [in] key EC key.
  11512. * @return Point conversion format on success.
  11513. * @return -1 on error.
  11514. */
  11515. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11516. {
  11517. int ret = -1;
  11518. if (key != NULL) {
  11519. ret = key->form;
  11520. }
  11521. return ret;
  11522. }
  11523. /* Set point conversion format into EC key.
  11524. *
  11525. * @param [in, out] key EC key to set format into.
  11526. * @param [in] form Point conversion format. Valid values:
  11527. * POINT_CONVERSION_UNCOMPRESSED,
  11528. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11529. */
  11530. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11531. {
  11532. if (key == NULL) {
  11533. WOLFSSL_MSG("Key passed in NULL");
  11534. }
  11535. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11536. #ifdef HAVE_COMP_KEY
  11537. || form == POINT_CONVERSION_COMPRESSED
  11538. #endif
  11539. ) {
  11540. key->form = (unsigned char)form;
  11541. }
  11542. else {
  11543. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11544. }
  11545. }
  11546. /* Get the EC group object that is in EC key.
  11547. *
  11548. * @param [in] key EC key.
  11549. * @return EC group object on success.
  11550. * @return NULL when key is NULL.
  11551. */
  11552. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11553. {
  11554. WOLFSSL_EC_GROUP* group = NULL;
  11555. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11556. if (key != NULL) {
  11557. group = key->group;
  11558. }
  11559. return group;
  11560. }
  11561. /* Set the group in WOLFSSL_EC_KEY
  11562. *
  11563. * @param [in, out] key EC key to update.
  11564. * @param [in] group EC group to copy.
  11565. * @return 1 on success
  11566. * @return 0 on failure.
  11567. */
  11568. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11569. {
  11570. int ret = 1;
  11571. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11572. /* Validate parameters. */
  11573. if ((key == NULL) || (group == NULL)) {
  11574. ret = 0;
  11575. }
  11576. if (ret == 1) {
  11577. /* Dispose of the current group. */
  11578. if (key->group != NULL) {
  11579. wolfSSL_EC_GROUP_free(key->group);
  11580. }
  11581. /* Duplicate the passed in group into EC key. */
  11582. key->group = wolfSSL_EC_GROUP_dup(group);
  11583. if (key->group == NULL) {
  11584. ret = 0;
  11585. }
  11586. }
  11587. return ret;
  11588. }
  11589. /* Get the BN object that is the private key in the EC key.
  11590. *
  11591. * @param [in] key EC key.
  11592. * @return BN object on success.
  11593. * @return NULL when key is NULL or private key is not set.
  11594. */
  11595. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11596. {
  11597. WOLFSSL_BIGNUM* priv_key = NULL;
  11598. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11599. /* Validate parameter. */
  11600. if (key == NULL) {
  11601. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11602. }
  11603. /* Only return private key if it is not 0. */
  11604. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11605. priv_key = key->priv_key;
  11606. }
  11607. return priv_key;
  11608. }
  11609. /* Sets the private key value into EC key.
  11610. *
  11611. * Return code compliant with OpenSSL.
  11612. *
  11613. * @param [in, out] key EC key to set.
  11614. * @param [in] priv_key Private key value in a BN.
  11615. * @return 1 on success
  11616. * @return 0 on failure.
  11617. */
  11618. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11619. const WOLFSSL_BIGNUM *priv_key)
  11620. {
  11621. int ret = 1;
  11622. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11623. /* Validate parameters. */
  11624. if ((key == NULL) || (priv_key == NULL)) {
  11625. WOLFSSL_MSG("Bad arguments");
  11626. ret = 0;
  11627. }
  11628. /* Check for obvious invalid values. */
  11629. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11630. wolfSSL_BN_is_one(priv_key)) {
  11631. WOLFSSL_MSG("Invalid private key value");
  11632. ret = 0;
  11633. }
  11634. if (ret == 1) {
  11635. /* Free key if previously set. */
  11636. if (key->priv_key != NULL) {
  11637. wolfSSL_BN_free(key->priv_key);
  11638. }
  11639. /* Duplicate the BN passed in. */
  11640. key->priv_key = wolfSSL_BN_dup(priv_key);
  11641. if (key->priv_key == NULL) {
  11642. WOLFSSL_MSG("key ecc priv key NULL");
  11643. ret = 0;
  11644. }
  11645. }
  11646. /* Set the external values into internal EC key. */
  11647. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11648. WOLFSSL_MSG("SetECKeyInternal failed");
  11649. /* Dispose of new private key on error. */
  11650. wolfSSL_BN_free(key->priv_key);
  11651. key->priv_key = NULL;
  11652. ret = 0;
  11653. }
  11654. return ret;
  11655. }
  11656. /* Get the public key EC point object that is in EC key.
  11657. *
  11658. * @param [in] key EC key.
  11659. * @return EC point object that is the public key on success.
  11660. * @return NULL when key is NULL.
  11661. */
  11662. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11663. {
  11664. WOLFSSL_EC_POINT* pub_key = NULL;
  11665. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11666. if (key != NULL) {
  11667. pub_key = key->pub_key;
  11668. }
  11669. return pub_key;
  11670. }
  11671. /*
  11672. * Return code compliant with OpenSSL.
  11673. *
  11674. * @param [in, out] key EC key.
  11675. * @param [in] pub Public key as an EC point.
  11676. * @return 1 on success
  11677. * @return 0 on failure.
  11678. */
  11679. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11680. const WOLFSSL_EC_POINT *pub)
  11681. {
  11682. int ret = 1;
  11683. ecc_point *pub_p = NULL;
  11684. ecc_point *key_p = NULL;
  11685. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11686. /* Validate parameters. */
  11687. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11688. (pub->internal == NULL)) {
  11689. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11690. ret = 0;
  11691. }
  11692. /* Ensure the internal EC key is set. */
  11693. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11694. WOLFSSL_MSG("SetECKeyInternal failed");
  11695. ret = 0;
  11696. }
  11697. /* Ensure the internal EC point of pub is setup. */
  11698. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11699. ret = 0;
  11700. }
  11701. if (ret == 1) {
  11702. /* Get the internal point of pub and the public key in key. */
  11703. pub_p = (ecc_point*)pub->internal;
  11704. key_p = (ecc_point*)key->pub_key->internal;
  11705. /* Create new point if required. */
  11706. if (key_p == NULL) {
  11707. key_p = wc_ecc_new_point();
  11708. key->pub_key->internal = (void*)key_p;
  11709. }
  11710. /* Check point available. */
  11711. if (key_p == NULL) {
  11712. WOLFSSL_MSG("key ecc point NULL");
  11713. ret = 0;
  11714. }
  11715. }
  11716. /* Copy the internal pub point into internal key point. */
  11717. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11718. WOLFSSL_MSG("ecc_copy_point failure");
  11719. ret = 0;
  11720. }
  11721. /* Copy the internal point data into external. */
  11722. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11723. WOLFSSL_MSG("SetECKeyInternal failed");
  11724. ret = 0;
  11725. }
  11726. /* Copy the internal key into external. */
  11727. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11728. WOLFSSL_MSG("SetECKeyInternal failed");
  11729. ret = 0;
  11730. }
  11731. if (ret == 1) {
  11732. /* Dump out the point and the key's public key for debug. */
  11733. wolfSSL_EC_POINT_dump("pub", pub);
  11734. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11735. }
  11736. return ret;
  11737. }
  11738. #ifndef NO_WOLFSSL_STUB
  11739. /* Set the ASN.1 encoding flag against the EC key.
  11740. *
  11741. * No implementation as only named curves supported for encoding.
  11742. *
  11743. * @param [in, out] key EC key.
  11744. * @param [in] flag ASN.1 flag to set. Valid values:
  11745. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11746. */
  11747. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11748. {
  11749. (void)key;
  11750. (void)asn1_flag;
  11751. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11752. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11753. }
  11754. #endif
  11755. /*
  11756. * EC key generate key APIs
  11757. */
  11758. /* Generate an EC key.
  11759. *
  11760. * Uses the internal curve index set in the EC key or the default.
  11761. *
  11762. * @param [in, out] key EC key.
  11763. * @return 1 on success
  11764. * @return 0 on failure.
  11765. */
  11766. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11767. {
  11768. int res = 1;
  11769. int initTmpRng = 0;
  11770. WC_RNG* rng = NULL;
  11771. #ifdef WOLFSSL_SMALL_STACK
  11772. WC_RNG* tmpRng = NULL;
  11773. #else
  11774. WC_RNG tmpRng[1];
  11775. #endif
  11776. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11777. /* Validate parameters. */
  11778. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11779. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11780. res = 0;
  11781. }
  11782. if (res == 1) {
  11783. /* Check if we know which internal curve index to use. */
  11784. if (key->group->curve_idx < 0) {
  11785. /* Generate key using the default curve. */
  11786. #if FIPS_VERSION3_GE(6,0,0)
  11787. key->group->curve_idx = ECC_SECP256R1; /* FIPS default to 256 */
  11788. #else
  11789. key->group->curve_idx = ECC_CURVE_DEF;
  11790. #endif
  11791. }
  11792. /* Create a random number generator. */
  11793. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  11794. if (rng == NULL) {
  11795. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  11796. res = 0;
  11797. }
  11798. }
  11799. if (res == 1) {
  11800. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  11801. * is 0 then pass ECC_CURVE_DEF as arg */
  11802. int eccEnum = key->group->curve_nid ?
  11803. #if FIPS_VERSION3_GE(6,0,0)
  11804. NIDToEccEnum(key->group->curve_nid) : ECC_SECP256R1;
  11805. #else
  11806. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  11807. #endif
  11808. /* Get the internal EC key. */
  11809. ecc_key* ecKey = (ecc_key*)key->internal;
  11810. /* Make the key using internal API. */
  11811. int ret = 0;
  11812. #if FIPS_VERSION3_GE(6,0,0)
  11813. /* In the case of FIPS only allow key generation with approved curves */
  11814. if (eccEnum != ECC_SECP256R1 && eccEnum != ECC_SECP224R1 &&
  11815. eccEnum != ECC_SECP384R1 && eccEnum != ECC_SECP521R1) {
  11816. WOLFSSL_MSG("Unsupported curve selected in FIPS mode");
  11817. res = 0;
  11818. }
  11819. if (res == 1) {
  11820. #endif
  11821. ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  11822. #if FIPS_VERSION3_GE(6,0,0)
  11823. }
  11824. #endif
  11825. #if defined(WOLFSSL_ASYNC_CRYPT)
  11826. /* Wait on asynchronouse operation. */
  11827. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  11828. #endif
  11829. if (ret != 0) {
  11830. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  11831. res = 0;
  11832. }
  11833. }
  11834. /* Dispose of local random number generator if initialized. */
  11835. if (initTmpRng) {
  11836. wc_FreeRng(rng);
  11837. #ifdef WOLFSSL_SMALL_STACK
  11838. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  11839. #endif
  11840. }
  11841. /* Set the external key from new internal key values. */
  11842. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11843. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  11844. res = 0;
  11845. }
  11846. return res;
  11847. }
  11848. /*
  11849. * EC key check key APIs
  11850. */
  11851. /* Check that the EC key is valid.
  11852. *
  11853. * @param [in] key EC key.
  11854. * @return 1 on valid.
  11855. * @return 0 on invalid or error.
  11856. */
  11857. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  11858. {
  11859. int ret = 1;
  11860. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  11861. /* Validate parameter. */
  11862. if ((key == NULL) || (key->internal == NULL)) {
  11863. WOLFSSL_MSG("Bad parameter");
  11864. ret = 0;
  11865. }
  11866. /* Set the external EC key values into internal if not already. */
  11867. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  11868. (WOLFSSL_EC_KEY*)key) != 1)) {
  11869. WOLFSSL_MSG("SetECKeyInternal failed");
  11870. ret = 0;
  11871. }
  11872. if (ret == 1) {
  11873. /* Have internal EC implementation check key. */
  11874. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  11875. }
  11876. return ret;
  11877. }
  11878. /* End EC_KEY */
  11879. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  11880. /* Get the supported, built-in EC curves
  11881. *
  11882. * @param [in, out] curves Pre-allocated list to put supported curves into.
  11883. * @param [in] len Maximum number of items to place in list.
  11884. * @return Number of built-in EC curves when curves is NULL or len is 0.
  11885. * @return Number of items placed in list otherwise.
  11886. */
  11887. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  11888. size_t len)
  11889. {
  11890. size_t i;
  11891. size_t cnt;
  11892. #ifdef HAVE_SELFTEST
  11893. /* Defined in ecc.h when available. */
  11894. size_t ecc_sets_count;
  11895. /* Count the pre-defined curves since global not available. */
  11896. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  11897. /* Do nothing. */
  11898. }
  11899. ecc_sets_count = i;
  11900. #endif
  11901. /* Assume we are going to return total count. */
  11902. cnt = ecc_sets_count;
  11903. /* Check we have a list that can hold data. */
  11904. if ((curves != NULL) && (len != 0)) {
  11905. /* Limit count to length of list. */
  11906. if (cnt > len) {
  11907. cnt = len;
  11908. }
  11909. /* Put in built-in EC curve nid and short name. */
  11910. for (i = 0; i < cnt; i++) {
  11911. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  11912. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  11913. }
  11914. }
  11915. return cnt;
  11916. }
  11917. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  11918. /* Start ECDSA_SIG */
  11919. /* Allocate a new ECDSA signature object.
  11920. *
  11921. * @return New, allocated ECDSA signature object on success.
  11922. * @return NULL on error.
  11923. */
  11924. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  11925. {
  11926. int err = 0;
  11927. WOLFSSL_ECDSA_SIG *sig;
  11928. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  11929. /* Allocate memory for ECDSA signature object. */
  11930. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  11931. DYNAMIC_TYPE_ECC);
  11932. if (sig == NULL) {
  11933. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  11934. err = 1;
  11935. }
  11936. if (!err) {
  11937. /* Set s to NULL in case of error. */
  11938. sig->s = NULL;
  11939. /* Allocate BN into r. */
  11940. sig->r = wolfSSL_BN_new();
  11941. if (sig->r == NULL) {
  11942. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  11943. err = 1;
  11944. }
  11945. }
  11946. if (!err) {
  11947. /* Allocate BN into s. */
  11948. sig->s = wolfSSL_BN_new();
  11949. if (sig->s == NULL) {
  11950. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  11951. err = 1;
  11952. }
  11953. }
  11954. if (err && (sig != NULL)) {
  11955. /* Dispose of allocated memory. */
  11956. wolfSSL_ECDSA_SIG_free(sig);
  11957. sig = NULL;
  11958. }
  11959. return sig;
  11960. }
  11961. /* Dispose of ECDSA signature object.
  11962. *
  11963. * Cannot use object after this call.
  11964. *
  11965. * @param [in] sig ECDSA signature object to free.
  11966. */
  11967. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  11968. {
  11969. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  11970. if (sig != NULL) {
  11971. /* Dispose of BNs allocated for r and s. */
  11972. wolfSSL_BN_free(sig->r);
  11973. wolfSSL_BN_free(sig->s);
  11974. /* Dispose of memory associated with ECDSA signature object. */
  11975. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  11976. }
  11977. }
  11978. /* Create an ECDSA signature from the DER encoding.
  11979. *
  11980. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  11981. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  11982. * On out, reference to buffer after signature data.
  11983. * @param [in] len Length of the data in the buffer. May be more than
  11984. * the length of the signature.
  11985. * @return ECDSA signature object on success.
  11986. * @return NULL on error.
  11987. */
  11988. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  11989. const unsigned char** pp, long len)
  11990. {
  11991. int err = 0;
  11992. /* ECDSA signature object to return. */
  11993. WOLFSSL_ECDSA_SIG *s = NULL;
  11994. /* Validate parameter. */
  11995. if (pp == NULL) {
  11996. err = 1;
  11997. }
  11998. if (!err) {
  11999. if (sig != NULL) {
  12000. /* Use the ECDSA signature object passed in. */
  12001. s = *sig;
  12002. }
  12003. if (s == NULL) {
  12004. /* No ECDSA signature object passed in - create a new one. */
  12005. s = wolfSSL_ECDSA_SIG_new();
  12006. if (s == NULL) {
  12007. err = 1;
  12008. }
  12009. }
  12010. }
  12011. if (!err) {
  12012. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  12013. mp_free((mp_int*)s->r->internal);
  12014. mp_free((mp_int*)s->s->internal);
  12015. /* Decode the signature into internal r and s fields. */
  12016. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  12017. (mp_int*)s->s->internal) != MP_OKAY) {
  12018. err = 1;
  12019. }
  12020. }
  12021. if (!err) {
  12022. /* Move pointer passed signature data successfully decoded. */
  12023. *pp += wolfssl_der_length(*pp, (int)len);
  12024. if (sig != NULL) {
  12025. /* Update reference to ECDSA signature object. */
  12026. *sig = s;
  12027. }
  12028. }
  12029. /* Dispose of newly allocated object on error. */
  12030. if (err) {
  12031. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  12032. wolfSSL_ECDSA_SIG_free(s);
  12033. }
  12034. /* Return NULL for object on error. */
  12035. s = NULL;
  12036. }
  12037. return s;
  12038. }
  12039. /* Encode the ECDSA signature as DER.
  12040. *
  12041. * @param [in] sig ECDSA signature object.
  12042. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  12043. * On out, reference to buffer after encoding.
  12044. * May be NULL or point to NULL in which case no encoding
  12045. * is done.
  12046. * @return Length of encoding on success.
  12047. * @return 0 on error.
  12048. */
  12049. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  12050. {
  12051. word32 len = 0;
  12052. /* Validate parameter. */
  12053. if (sig != NULL) {
  12054. /* ASN.1: SEQ + INT + INT
  12055. * ASN.1 Integer must be a positive value - prepend zero if number has
  12056. * top bit set.
  12057. */
  12058. /* Get total length of r including any prepended zero. */
  12059. word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) +
  12060. mp_unsigned_bin_size((mp_int*)sig->r->internal));
  12061. /* Get total length of s including any prepended zero. */
  12062. word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) +
  12063. mp_unsigned_bin_size((mp_int*)sig->s->internal));
  12064. /* Calculate length of data in sequence. */
  12065. len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen +
  12066. (word32)1 + ASN_LEN_SIZE(sLen) + sLen;
  12067. /* Add in the length of the SEQUENCE. */
  12068. len += (word32)1 + ASN_LEN_SIZE(len);
  12069. /* Encode only if there is a buffer to encode into. */
  12070. if ((pp != NULL) && (*pp != NULL)) {
  12071. /* Encode using the internal representations of r and s. */
  12072. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  12073. (mp_int*)sig->s->internal) != MP_OKAY) {
  12074. /* No bytes encoded. */
  12075. len = 0;
  12076. }
  12077. else {
  12078. /* Update pointer to after encoding. */
  12079. *pp += len;
  12080. }
  12081. }
  12082. }
  12083. return (int)len;
  12084. }
  12085. /* Get the pointer to the fields of the ECDSA signature.
  12086. *
  12087. * r and s untouched when sig is NULL.
  12088. *
  12089. * @param [in] sig ECDSA signature object.
  12090. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  12091. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  12092. */
  12093. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  12094. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  12095. {
  12096. /* Validate parameter. */
  12097. if (sig != NULL) {
  12098. /* Return the r BN when pointer to return through. */
  12099. if (r != NULL) {
  12100. *r = sig->r;
  12101. }
  12102. /* Return the s BN when pointer to return through. */
  12103. if (s != NULL) {
  12104. *s = sig->s;
  12105. }
  12106. }
  12107. }
  12108. /* Set the pointers to the fields of the ECDSA signature.
  12109. *
  12110. * @param [in, out] sig ECDSA signature object to update.
  12111. * @param [in] r R field of ECDSA signature as a BN.
  12112. * @param [in] s S field of ECDSA signature as a BN.
  12113. * @return 1 on success.
  12114. * @return 0 on error.
  12115. */
  12116. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  12117. WOLFSSL_BIGNUM* s)
  12118. {
  12119. int ret = 1;
  12120. /* Validate parameters. */
  12121. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  12122. ret = 0;
  12123. }
  12124. if (ret == 1) {
  12125. /* Dispose of old BN objects. */
  12126. wolfSSL_BN_free(sig->r);
  12127. wolfSSL_BN_free(sig->s);
  12128. /* Assign new BN objects. */
  12129. sig->r = r;
  12130. sig->s = s;
  12131. }
  12132. return ret;
  12133. }
  12134. /* End ECDSA_SIG */
  12135. /* Start ECDSA */
  12136. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  12137. *
  12138. * @param [in] key EC key.
  12139. * @return Size of DER encoded signature on success.
  12140. * @return 0 on error.
  12141. */
  12142. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  12143. {
  12144. int err = 0;
  12145. int len = 0;
  12146. const EC_GROUP *group = NULL;
  12147. int bits = 0;
  12148. /* Validate parameter. */
  12149. if (key == NULL) {
  12150. err = 1;
  12151. }
  12152. /* Get group from key to get order bits. */
  12153. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  12154. err = 1;
  12155. }
  12156. /* Get order bits of group. */
  12157. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  12158. /* Group is not set. */
  12159. err = 1;
  12160. }
  12161. if (!err) {
  12162. /* r and s are mod order. */
  12163. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  12164. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  12165. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  12166. bytes + bytes; /* max r and s in bytes */
  12167. }
  12168. return len;
  12169. }
  12170. /* Create ECDSA signature by signing digest with key.
  12171. *
  12172. * @param [in] dgst Digest to sign.
  12173. * @param [in] dLen Length of digest in bytes.
  12174. * @param [in] key EC key to sign with.
  12175. * @return ECDSA signature object on success.
  12176. * @return NULL on error.
  12177. */
  12178. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  12179. WOLFSSL_EC_KEY *key)
  12180. {
  12181. int err = 0;
  12182. WOLFSSL_ECDSA_SIG *sig = NULL;
  12183. #ifdef WOLFSSL_SMALL_STACK
  12184. byte* out = NULL;
  12185. #else
  12186. byte out[ECC_BUFSIZE];
  12187. #endif
  12188. unsigned int outLen = ECC_BUFSIZE;
  12189. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  12190. /* Validate parameters. */
  12191. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  12192. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  12193. err = 1;
  12194. }
  12195. /* Ensure internal EC key is set from external. */
  12196. if ((!err) && (key->inSet == 0)) {
  12197. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  12198. if (SetECKeyInternal(key) != 1) {
  12199. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  12200. err = 1;
  12201. }
  12202. }
  12203. #ifdef WOLFSSL_SMALL_STACK
  12204. if (!err) {
  12205. /* Allocate buffer to hold encoded signature. */
  12206. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12207. if (out == NULL) {
  12208. err = 1;
  12209. }
  12210. }
  12211. #endif
  12212. /* Sign the digest with the key to create encoded ECDSA signature. */
  12213. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  12214. err = 1;
  12215. }
  12216. if (!err) {
  12217. const byte* p = out;
  12218. /* Decode the ECDSA signature into a new object. */
  12219. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  12220. }
  12221. #ifdef WOLFSSL_SMALL_STACK
  12222. /* Dispose of any temporary dynamically allocated data. */
  12223. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12224. #endif
  12225. return sig;
  12226. }
  12227. /* Verify ECDSA signature in the object using digest and key.
  12228. *
  12229. * Return code compliant with OpenSSL.
  12230. *
  12231. * @param [in] dgst Digest to verify.
  12232. * @param [in] dLen Length of the digest in bytes.
  12233. * @param [in] sig ECDSA signature object.
  12234. * @param [in] key EC key containing public key.
  12235. * @return 1 when signature is valid.
  12236. * @return 0 when signature is invalid.
  12237. * @return -1 on error.
  12238. */
  12239. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  12240. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  12241. {
  12242. int ret = 1;
  12243. int verified = 0;
  12244. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  12245. byte signature[ECC_MAX_SIG_SIZE];
  12246. int signatureLen;
  12247. byte* p = signature;
  12248. #endif
  12249. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  12250. /* Validate parameters. */
  12251. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  12252. (key->internal == NULL)) {
  12253. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  12254. ret = -1;
  12255. }
  12256. /* Ensure internal EC key is set from external. */
  12257. if ((ret == 1) && (key->inSet == 0)) {
  12258. WOLFSSL_MSG("No EC key internal set, do it");
  12259. if (SetECKeyInternal(key) != 1) {
  12260. WOLFSSL_MSG("SetECKeyInternal failed");
  12261. ret = -1;
  12262. }
  12263. }
  12264. if (ret == 1) {
  12265. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12266. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  12267. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  12268. (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified,
  12269. (ecc_key *)key->internal) != MP_OKAY) {
  12270. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12271. ret = -1;
  12272. }
  12273. else if (verified == 0) {
  12274. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12275. ret = 0;
  12276. }
  12277. #else
  12278. signatureLen = i2d_ECDSA_SIG(sig, &p);
  12279. if (signatureLen > 0) {
  12280. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  12281. ret = wc_ecc_verify_hash(signature, signatureLen, dgst,
  12282. (word32)dLen, &verified, (ecc_key*)key->internal);
  12283. if (ret != MP_OKAY) {
  12284. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12285. ret = -1;
  12286. }
  12287. else if (verified == 0) {
  12288. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12289. ret = 0;
  12290. }
  12291. }
  12292. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12293. }
  12294. return ret;
  12295. }
  12296. /* Sign the digest with the key to produce a DER encode signature.
  12297. *
  12298. * @param [in] type Digest algorithm used to create digest. Unused.
  12299. * @param [in] digest Digest of the message to sign.
  12300. * @param [in] digestSz Size of the digest in bytes.
  12301. * @param [out] sig Buffer to hold signature.
  12302. * @param [in, out] sigSz On in, size of buffer in bytes.
  12303. * On out, size of signatre in bytes.
  12304. * @param [in] key EC key containing private key.
  12305. * @return 1 on success.
  12306. * @return 0 on error.
  12307. */
  12308. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12309. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12310. {
  12311. int ret = 1;
  12312. WC_RNG* rng = NULL;
  12313. #ifdef WOLFSSL_SMALL_STACK
  12314. WC_RNG* tmpRng = NULL;
  12315. #else
  12316. WC_RNG tmpRng[1];
  12317. #endif
  12318. int initTmpRng = 0;
  12319. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12320. /* Digest algorithm not used in DER encoding. */
  12321. (void)type;
  12322. /* Validate parameters. */
  12323. if (key == NULL) {
  12324. ret = 0;
  12325. }
  12326. if (ret == 1) {
  12327. /* Make an RNG - create local or get global. */
  12328. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12329. if (rng == NULL) {
  12330. ret = 0;
  12331. }
  12332. }
  12333. /* Sign the digest with the key using the RNG and put signature into buffer
  12334. * update sigSz to be actual length.
  12335. */
  12336. if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz,
  12337. rng, (ecc_key*)key->internal) != 0)) {
  12338. ret = 0;
  12339. }
  12340. if (initTmpRng) {
  12341. wc_FreeRng(rng);
  12342. #ifdef WOLFSSL_SMALL_STACK
  12343. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12344. #endif
  12345. }
  12346. return ret;
  12347. }
  12348. /* Verify the signature with the digest and key.
  12349. *
  12350. * @param [in] type Digest algorithm used to create digest. Unused.
  12351. * @param [in] digest Digest of the message to verify.
  12352. * @param [in] digestSz Size of the digest in bytes.
  12353. * @param [in] sig Buffer holding signature.
  12354. * @param [in] sigSz Size of signature data in bytes.
  12355. * @param [in] key EC key containing public key.
  12356. * @return 1 when signature is valid.
  12357. * @return 0 when signature is invalid or error.
  12358. */
  12359. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12360. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12361. {
  12362. int ret = 1;
  12363. int verify = 0;
  12364. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12365. /* Digest algorithm not used in DER encoding. */
  12366. (void)type;
  12367. /* Validate parameters. */
  12368. if (key == NULL) {
  12369. ret = 0;
  12370. }
  12371. /* Verify signature using digest and key. */
  12372. if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest,
  12373. (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) {
  12374. ret = 0;
  12375. }
  12376. /* When no error, verification may still have failed - check now. */
  12377. if ((ret == 1) && (verify != 1)) {
  12378. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12379. ret = 0;
  12380. }
  12381. return ret;
  12382. }
  12383. /* End ECDSA */
  12384. /* Start ECDH */
  12385. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12386. /* Compute the shared secret (key) using ECDH.
  12387. *
  12388. * KDF not supported.
  12389. *
  12390. * Return code compliant with OpenSSL.
  12391. *
  12392. * @param [out] out Buffer to hold key.
  12393. * @param [in] outLen Length of buffer in bytes.
  12394. * @param [in] pubKey Public key as an EC point.
  12395. * @param [in] privKey EC key holding a private key.
  12396. * @param [in] kdf Key derivation function to apply to secret.
  12397. * @return Length of computed key on success
  12398. * @return 0 on error.
  12399. */
  12400. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12401. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12402. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12403. {
  12404. int err = 0;
  12405. word32 len = 0;
  12406. ecc_key* key = NULL;
  12407. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12408. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12409. int setGlobalRNG = 0;
  12410. #endif
  12411. /* TODO: support using the KDF. */
  12412. (void)kdf;
  12413. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12414. /* Validate parameters. */
  12415. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12416. (privKey == NULL) || (privKey->internal == NULL)) {
  12417. WOLFSSL_MSG("Bad function arguments");
  12418. err = 1;
  12419. }
  12420. /* Ensure internal EC key is set from external. */
  12421. if ((!err) && (privKey->inSet == 0)) {
  12422. WOLFSSL_MSG("No EC key internal set, do it");
  12423. if (SetECKeyInternal(privKey) != 1) {
  12424. WOLFSSL_MSG("SetECKeyInternal failed");
  12425. err = 1;
  12426. }
  12427. }
  12428. if (!err) {
  12429. int ret;
  12430. /* Get the internal key. */
  12431. key = (ecc_key*)privKey->internal;
  12432. /* Set length into variable of type suitable for wolfSSL API. */
  12433. len = (word32)outLen;
  12434. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12435. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12436. /* An RNG is needed. */
  12437. if (key->rng == NULL) {
  12438. key->rng = wolfssl_make_global_rng();
  12439. /* RNG set and needs to be unset. */
  12440. setGlobalRNG = 1;
  12441. }
  12442. #endif
  12443. PRIVATE_KEY_UNLOCK();
  12444. /* Create secret using wolfSSL. */
  12445. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12446. (byte *)out, &len);
  12447. PRIVATE_KEY_LOCK();
  12448. if (ret != MP_OKAY) {
  12449. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12450. err = 1;
  12451. }
  12452. }
  12453. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12454. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12455. /* Remove global from key. */
  12456. if (setGlobalRNG) {
  12457. key->rng = NULL;
  12458. }
  12459. #endif
  12460. if (err) {
  12461. /* Make returned value zero. */
  12462. len = 0;
  12463. }
  12464. return (int)len;
  12465. }
  12466. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12467. /* End ECDH */
  12468. #ifndef NO_WOLFSSL_STUB
  12469. const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_OpenSSL(void)
  12470. {
  12471. WOLFSSL_STUB("wolfSSL_EC_KEY_OpenSSL");
  12472. return NULL;
  12473. }
  12474. WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_METHOD_new(
  12475. const WOLFSSL_EC_KEY_METHOD *meth)
  12476. {
  12477. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_new");
  12478. (void)meth;
  12479. return NULL;
  12480. }
  12481. void wolfSSL_EC_KEY_METHOD_free(WOLFSSL_EC_KEY_METHOD *meth)
  12482. {
  12483. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_free");
  12484. (void)meth;
  12485. }
  12486. void wolfSSL_EC_KEY_METHOD_set_init(WOLFSSL_EC_KEY_METHOD *meth,
  12487. void* a1, void* a2, void* a3, void* a4, void* a5, void* a6)
  12488. {
  12489. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_init");
  12490. (void)meth;
  12491. (void)a1;
  12492. (void)a2;
  12493. (void)a3;
  12494. (void)a4;
  12495. (void)a5;
  12496. (void)a6;
  12497. }
  12498. void wolfSSL_EC_KEY_METHOD_set_sign(WOLFSSL_EC_KEY_METHOD *meth,
  12499. void* a1, void* a2, void* a3)
  12500. {
  12501. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_sign");
  12502. (void)meth;
  12503. (void)a1;
  12504. (void)a2;
  12505. (void)a3;
  12506. }
  12507. const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_get_method(
  12508. const WOLFSSL_EC_KEY *key)
  12509. {
  12510. WOLFSSL_STUB("wolfSSL_EC_KEY_get_method");
  12511. (void)key;
  12512. return NULL;
  12513. }
  12514. int wolfSSL_EC_KEY_set_method(WOLFSSL_EC_KEY *key,
  12515. const WOLFSSL_EC_KEY_METHOD *meth)
  12516. {
  12517. WOLFSSL_STUB("wolfSSL_EC_KEY_set_method");
  12518. (void)key;
  12519. (void)meth;
  12520. return 0;
  12521. }
  12522. #endif /* !NO_WOLFSSL_STUB */
  12523. #endif /* OPENSSL_EXTRA */
  12524. #endif /* HAVE_ECC */
  12525. /*******************************************************************************
  12526. * END OF EC API
  12527. ******************************************************************************/
  12528. /*******************************************************************************
  12529. * START OF EC25519 API
  12530. ******************************************************************************/
  12531. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519)
  12532. /* Generate an EC25519 key pair.
  12533. *
  12534. * Output keys are in little endian format.
  12535. *
  12536. * @param [out] priv EC25519 private key data.
  12537. * @param [in, out] privSz On in, the size of priv in bytes.
  12538. * On out, the length of the private key data in bytes.
  12539. * @param [out] pub EC25519 public key data.
  12540. * @param [in, out] pubSz On in, the size of pub in bytes.
  12541. * On out, the length of the public key data in bytes.
  12542. * @return 1 on success
  12543. * @return 0 on failure.
  12544. */
  12545. int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12546. unsigned char *pub, unsigned int *pubSz)
  12547. {
  12548. #ifdef WOLFSSL_KEY_GEN
  12549. int res = 1;
  12550. int initTmpRng = 0;
  12551. WC_RNG *rng = NULL;
  12552. #ifdef WOLFSSL_SMALL_STACK
  12553. WC_RNG *tmpRng = NULL;
  12554. #else
  12555. WC_RNG tmpRng[1];
  12556. #endif
  12557. curve25519_key key;
  12558. WOLFSSL_ENTER("wolfSSL_EC25519_generate_key");
  12559. /* Validate parameters. */
  12560. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE25519_KEYSIZE) ||
  12561. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE25519_KEYSIZE)) {
  12562. WOLFSSL_MSG("Bad arguments");
  12563. res = 0;
  12564. }
  12565. if (res) {
  12566. /* Create a random number generator. */
  12567. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12568. if (rng == NULL) {
  12569. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12570. res = 0;
  12571. }
  12572. }
  12573. /* Initialize a Curve25519 key. */
  12574. if (res && (wc_curve25519_init(&key) != 0)) {
  12575. WOLFSSL_MSG("wc_curve25519_init failed");
  12576. res = 0;
  12577. }
  12578. if (res) {
  12579. /* Make a Curve25519 key pair. */
  12580. int ret = wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key);
  12581. if (ret != MP_OKAY) {
  12582. WOLFSSL_MSG("wc_curve25519_make_key failed");
  12583. res = 0;
  12584. }
  12585. if (res) {
  12586. /* Export Curve25519 key pair to buffers. */
  12587. ret = wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub,
  12588. pubSz, EC25519_LITTLE_ENDIAN);
  12589. if (ret != MP_OKAY) {
  12590. WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed");
  12591. res = 0;
  12592. }
  12593. }
  12594. /* Dispose of key. */
  12595. wc_curve25519_free(&key);
  12596. }
  12597. if (initTmpRng) {
  12598. wc_FreeRng(rng);
  12599. #ifdef WOLFSSL_SMALL_STACK
  12600. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12601. #endif
  12602. }
  12603. return res;
  12604. #else
  12605. WOLFSSL_MSG("No Key Gen built in");
  12606. (void)priv;
  12607. (void)privSz;
  12608. (void)pub;
  12609. (void)pubSz;
  12610. return 0;
  12611. #endif /* WOLFSSL_KEY_GEN */
  12612. }
  12613. /* Compute a shared secret from private and public EC25519 keys.
  12614. *
  12615. * Input and output keys are in little endian format
  12616. *
  12617. * @param [out] shared Shared secret buffer.
  12618. * @param [in, out] sharedSz On in, the size of shared in bytes.
  12619. * On out, the length of the secret in bytes.
  12620. * @param [in] priv EC25519 private key data.
  12621. * @param [in] privSz Length of the private key data in bytes.
  12622. * @param [in] pub EC25519 public key data.
  12623. * @param [in] pubSz Length of the public key data in bytes.
  12624. * @return 1 on success
  12625. * @return 0 on failure.
  12626. */
  12627. int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz,
  12628. const unsigned char *priv, unsigned int privSz, const unsigned char *pub,
  12629. unsigned int pubSz)
  12630. {
  12631. #ifdef WOLFSSL_KEY_GEN
  12632. int res = 1;
  12633. curve25519_key privkey;
  12634. curve25519_key pubkey;
  12635. WOLFSSL_ENTER("wolfSSL_EC25519_shared_key");
  12636. /* Validate parameters. */
  12637. if ((shared == NULL) || (sharedSz == NULL) ||
  12638. (*sharedSz < CURVE25519_KEYSIZE) || (priv == NULL) ||
  12639. (privSz < CURVE25519_KEYSIZE) || (pub == NULL) ||
  12640. (pubSz < CURVE25519_KEYSIZE)) {
  12641. WOLFSSL_MSG("Bad arguments");
  12642. res = 0;
  12643. }
  12644. /* Initialize private key object. */
  12645. if (res && (wc_curve25519_init(&privkey) != 0)) {
  12646. WOLFSSL_MSG("wc_curve25519_init privkey failed");
  12647. res = 0;
  12648. }
  12649. if (res) {
  12650. /* Initialize public key object. */
  12651. if (wc_curve25519_init(&pubkey) != MP_OKAY) {
  12652. WOLFSSL_MSG("wc_curve25519_init pubkey failed");
  12653. res = 0;
  12654. }
  12655. if (res) {
  12656. /* Import our private key. */
  12657. int ret = wc_curve25519_import_private_ex(priv, privSz, &privkey,
  12658. EC25519_LITTLE_ENDIAN);
  12659. if (ret != 0) {
  12660. WOLFSSL_MSG("wc_curve25519_import_private_ex failed");
  12661. res = 0;
  12662. }
  12663. if (res) {
  12664. /* Import peer's public key. */
  12665. ret = wc_curve25519_import_public_ex(pub, pubSz, &pubkey,
  12666. EC25519_LITTLE_ENDIAN);
  12667. if (ret != 0) {
  12668. WOLFSSL_MSG("wc_curve25519_import_public_ex failed");
  12669. res = 0;
  12670. }
  12671. }
  12672. if (res) {
  12673. /* Compute shared secret. */
  12674. ret = wc_curve25519_shared_secret_ex(&privkey, &pubkey, shared,
  12675. sharedSz, EC25519_LITTLE_ENDIAN);
  12676. if (ret != 0) {
  12677. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  12678. res = 0;
  12679. }
  12680. }
  12681. wc_curve25519_free(&pubkey);
  12682. }
  12683. wc_curve25519_free(&privkey);
  12684. }
  12685. return res;
  12686. #else
  12687. WOLFSSL_MSG("No Key Gen built in");
  12688. (void)shared;
  12689. (void)sharedSz;
  12690. (void)priv;
  12691. (void)privSz;
  12692. (void)pub;
  12693. (void)pubSz;
  12694. return 0;
  12695. #endif /* WOLFSSL_KEY_GEN */
  12696. }
  12697. #endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */
  12698. /*******************************************************************************
  12699. * END OF EC25519 API
  12700. ******************************************************************************/
  12701. /*******************************************************************************
  12702. * START OF ED25519 API
  12703. ******************************************************************************/
  12704. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519)
  12705. /* Generate an ED25519 key pair.
  12706. *
  12707. * Output keys are in little endian format.
  12708. *
  12709. * @param [out] priv ED25519 private key data.
  12710. * @param [in, out] privSz On in, the size of priv in bytes.
  12711. * On out, the length of the private key data in bytes.
  12712. * @param [out] pub ED25519 public key data.
  12713. * @param [in, out] pubSz On in, the size of pub in bytes.
  12714. * On out, the length of the public key data in bytes.
  12715. * @return 1 on success
  12716. * @return 0 on failure.
  12717. */
  12718. int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12719. unsigned char *pub, unsigned int *pubSz)
  12720. {
  12721. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED25519_KEY_EXPORT)
  12722. int res = 1;
  12723. int initTmpRng = 0;
  12724. WC_RNG *rng = NULL;
  12725. #ifdef WOLFSSL_SMALL_STACK
  12726. WC_RNG *tmpRng = NULL;
  12727. #else
  12728. WC_RNG tmpRng[1];
  12729. #endif
  12730. ed25519_key key;
  12731. WOLFSSL_ENTER("wolfSSL_ED25519_generate_key");
  12732. /* Validate parameters. */
  12733. if ((priv == NULL) || (privSz == NULL) ||
  12734. (*privSz < ED25519_PRV_KEY_SIZE) || (pub == NULL) ||
  12735. (pubSz == NULL) || (*pubSz < ED25519_PUB_KEY_SIZE)) {
  12736. WOLFSSL_MSG("Bad arguments");
  12737. res = 0;
  12738. }
  12739. if (res) {
  12740. /* Create a random number generator. */
  12741. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12742. if (rng == NULL) {
  12743. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12744. res = 0;
  12745. }
  12746. }
  12747. /* Initialize an Ed25519 key. */
  12748. if (res && (wc_ed25519_init(&key) != 0)) {
  12749. WOLFSSL_MSG("wc_ed25519_init failed");
  12750. res = 0;
  12751. }
  12752. if (res) {
  12753. /* Make an Ed25519 key pair. */
  12754. int ret = wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key);
  12755. if (ret != 0) {
  12756. WOLFSSL_MSG("wc_ed25519_make_key failed");
  12757. res = 0;
  12758. }
  12759. if (res) {
  12760. /* Export Curve25519 key pair to buffers. */
  12761. ret = wc_ed25519_export_key(&key, priv, privSz, pub, pubSz);
  12762. if (ret != 0) {
  12763. WOLFSSL_MSG("wc_ed25519_export_key failed");
  12764. res = 0;
  12765. }
  12766. }
  12767. wc_ed25519_free(&key);
  12768. }
  12769. if (initTmpRng) {
  12770. wc_FreeRng(rng);
  12771. #ifdef WOLFSSL_SMALL_STACK
  12772. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12773. #endif
  12774. }
  12775. return res;
  12776. #else
  12777. #ifndef WOLFSSL_KEY_GEN
  12778. WOLFSSL_MSG("No Key Gen built in");
  12779. #else
  12780. WOLFSSL_MSG("No ED25519 key export built in");
  12781. #endif
  12782. (void)priv;
  12783. (void)privSz;
  12784. (void)pub;
  12785. (void)pubSz;
  12786. return 0;
  12787. #endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */
  12788. }
  12789. /* Sign a message with Ed25519 using the private key.
  12790. *
  12791. * Input and output keys are in little endian format.
  12792. * Priv is a buffer containing private and public part of key.
  12793. *
  12794. * @param [in] msg Message to be signed.
  12795. * @param [in] msgSz Length of message in bytes.
  12796. * @param [in] priv ED25519 private key data.
  12797. * @param [in] privSz Length in bytes of private key data.
  12798. * @param [out] sig Signature buffer.
  12799. * @param [in, out] sigSz On in, the length of the signature buffer in bytes.
  12800. * On out, the length of the signature in bytes.
  12801. * @return 1 on success
  12802. * @return 0 on failure.
  12803. */
  12804. int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz,
  12805. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  12806. unsigned int *sigSz)
  12807. {
  12808. #if defined(HAVE_ED25519_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  12809. defined(HAVE_ED25519_KEY_IMPORT)
  12810. ed25519_key key;
  12811. int res = 1;
  12812. WOLFSSL_ENTER("wolfSSL_ED25519_sign");
  12813. /* Validate parameters. */
  12814. if ((priv == NULL) || (privSz != ED25519_PRV_KEY_SIZE) ||
  12815. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  12816. (*sigSz < ED25519_SIG_SIZE)) {
  12817. WOLFSSL_MSG("Bad arguments");
  12818. res = 0;
  12819. }
  12820. /* Initialize Ed25519 key. */
  12821. if (res && (wc_ed25519_init(&key) != 0)) {
  12822. WOLFSSL_MSG("wc_curve25519_init failed");
  12823. res = 0;
  12824. }
  12825. if (res) {
  12826. /* Import private and public key. */
  12827. int ret = wc_ed25519_import_private_key(priv, privSz / 2,
  12828. priv + (privSz / 2), ED25519_PUB_KEY_SIZE, &key);
  12829. if (ret != 0) {
  12830. WOLFSSL_MSG("wc_ed25519_import_private failed");
  12831. res = 0;
  12832. }
  12833. if (res) {
  12834. /* Sign message with Ed25519. */
  12835. ret = wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key);
  12836. if (ret != 0) {
  12837. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  12838. res = 0;
  12839. }
  12840. }
  12841. wc_ed25519_free(&key);
  12842. }
  12843. return res;
  12844. #else
  12845. #if !defined(HAVE_ED25519_SIGN)
  12846. WOLFSSL_MSG("No ED25519 sign built in");
  12847. #elif !defined(WOLFSSL_KEY_GEN)
  12848. WOLFSSL_MSG("No Key Gen built in");
  12849. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  12850. WOLFSSL_MSG("No ED25519 Key import built in");
  12851. #endif
  12852. (void)msg;
  12853. (void)msgSz;
  12854. (void)priv;
  12855. (void)privSz;
  12856. (void)sig;
  12857. (void)sigSz;
  12858. return 0;
  12859. #endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  12860. }
  12861. /* Verify a message with Ed25519 using the public key.
  12862. *
  12863. * Input keys are in little endian format.
  12864. *
  12865. * @param [in] msg Message to be verified.
  12866. * @param [in] msgSz Length of message in bytes.
  12867. * @param [in] pub ED25519 public key data.
  12868. * @param [in] privSz Length in bytes of public key data.
  12869. * @param [in] sig Signature buffer.
  12870. * @param [in] sigSz Length of the signature in bytes.
  12871. * @return 1 on success
  12872. * @return 0 on failure.
  12873. */
  12874. int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz,
  12875. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  12876. unsigned int sigSz)
  12877. {
  12878. #if defined(HAVE_ED25519_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  12879. defined(HAVE_ED25519_KEY_IMPORT)
  12880. ed25519_key key;
  12881. int res = 1;
  12882. WOLFSSL_ENTER("wolfSSL_ED25519_verify");
  12883. /* Validate parameters. */
  12884. if ((pub == NULL) || (pubSz != ED25519_PUB_KEY_SIZE) || (msg == NULL) ||
  12885. (sig == NULL) || (sigSz != ED25519_SIG_SIZE)) {
  12886. WOLFSSL_MSG("Bad arguments");
  12887. res = 0;
  12888. }
  12889. /* Initialize Ed25519 key. */
  12890. if (res && (wc_ed25519_init(&key) != 0)) {
  12891. WOLFSSL_MSG("wc_curve25519_init failed");
  12892. res = 0;
  12893. }
  12894. if (res) {
  12895. /* Import public key. */
  12896. int ret = wc_ed25519_import_public(pub, pubSz, &key);
  12897. if (ret != 0) {
  12898. WOLFSSL_MSG("wc_ed25519_import_public failed");
  12899. res = 0;
  12900. }
  12901. if (res) {
  12902. int check = 0;
  12903. /* Verify signature with message and public key. */
  12904. ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  12905. &key);
  12906. /* Check for errors in verification process. */
  12907. if (ret != 0) {
  12908. WOLFSSL_MSG("wc_ed25519_verify_msg failed");
  12909. res = 0;
  12910. }
  12911. /* Check signature is valid. */
  12912. else if (!check) {
  12913. WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)");
  12914. res = 0;
  12915. }
  12916. }
  12917. wc_ed25519_free(&key);
  12918. }
  12919. return res;
  12920. #else
  12921. #if !defined(HAVE_ED25519_VERIFY)
  12922. WOLFSSL_MSG("No ED25519 verify built in");
  12923. #elif !defined(WOLFSSL_KEY_GEN)
  12924. WOLFSSL_MSG("No Key Gen built in");
  12925. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  12926. WOLFSSL_MSG("No ED25519 Key import built in");
  12927. #endif
  12928. (void)msg;
  12929. (void)msgSz;
  12930. (void)pub;
  12931. (void)pubSz;
  12932. (void)sig;
  12933. (void)sigSz;
  12934. return 0;
  12935. #endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  12936. }
  12937. #endif /* OPENSSL_EXTRA && HAVE_ED25519 */
  12938. /*******************************************************************************
  12939. * END OF ED25519 API
  12940. ******************************************************************************/
  12941. /*******************************************************************************
  12942. * START OF EC448 API
  12943. ******************************************************************************/
  12944. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448)
  12945. /* Generate an EC448 key pair.
  12946. *
  12947. * Output keys are in little endian format.
  12948. *
  12949. * @param [out] priv EC448 private key data.
  12950. * @param [in, out] privSz On in, the size of priv in bytes.
  12951. * On out, the length of the private key data in bytes.
  12952. * @param [out] pub EC448 public key data.
  12953. * @param [in, out] pubSz On in, the size of pub in bytes.
  12954. * On out, the length of the public key data in bytes.
  12955. * @return 1 on success
  12956. * @return 0 on failure.
  12957. */
  12958. int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz,
  12959. unsigned char *pub, unsigned int *pubSz)
  12960. {
  12961. #ifdef WOLFSSL_KEY_GEN
  12962. int res = 1;
  12963. int initTmpRng = 0;
  12964. WC_RNG *rng = NULL;
  12965. #ifdef WOLFSSL_SMALL_STACK
  12966. WC_RNG *tmpRng = NULL;
  12967. #else
  12968. WC_RNG tmpRng[1];
  12969. #endif
  12970. curve448_key key;
  12971. WOLFSSL_ENTER("wolfSSL_EC448_generate_key");
  12972. /* Validate parameters. */
  12973. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE448_KEY_SIZE) ||
  12974. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE448_KEY_SIZE)) {
  12975. WOLFSSL_MSG("Bad arguments");
  12976. res = 0;
  12977. }
  12978. if (res) {
  12979. /* Create a random number generator. */
  12980. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12981. if (rng == NULL) {
  12982. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12983. res = 0;
  12984. }
  12985. }
  12986. /* Initialize a Curve448 key. */
  12987. if (res && (wc_curve448_init(&key) != 0)) {
  12988. WOLFSSL_MSG("wc_curve448_init failed");
  12989. res = 0;
  12990. }
  12991. if (res) {
  12992. /* Make a Curve448 key pair. */
  12993. int ret = wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key);
  12994. if (ret != 0) {
  12995. WOLFSSL_MSG("wc_curve448_make_key failed");
  12996. res = 0;
  12997. }
  12998. if (res) {
  12999. /* Export Curve448 key pair to buffers. */
  13000. ret = wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz,
  13001. EC448_LITTLE_ENDIAN);
  13002. if (ret != 0) {
  13003. WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed");
  13004. res = 0;
  13005. }
  13006. }
  13007. /* Dispose of key. */
  13008. wc_curve448_free(&key);
  13009. }
  13010. if (initTmpRng) {
  13011. wc_FreeRng(rng);
  13012. #ifdef WOLFSSL_SMALL_STACK
  13013. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  13014. #endif
  13015. }
  13016. return res;
  13017. #else
  13018. WOLFSSL_MSG("No Key Gen built in");
  13019. (void)priv;
  13020. (void)privSz;
  13021. (void)pub;
  13022. (void)pubSz;
  13023. return 0;
  13024. #endif /* WOLFSSL_KEY_GEN */
  13025. }
  13026. /* Compute a shared secret from private and public EC448 keys.
  13027. *
  13028. * Input and output keys are in little endian format
  13029. *
  13030. * @param [out] shared Shared secret buffer.
  13031. * @param [in, out] sharedSz On in, the size of shared in bytes.
  13032. * On out, the length of the secret in bytes.
  13033. * @param [in] priv EC448 private key data.
  13034. * @param [in] privSz Length of the private key data in bytes.
  13035. * @param [in] pub EC448 public key data.
  13036. * @param [in] pubSz Length of the public key data in bytes.
  13037. * @return 1 on success
  13038. * @return 0 on failure.
  13039. */
  13040. int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz,
  13041. const unsigned char *priv, unsigned int privSz,
  13042. const unsigned char *pub, unsigned int pubSz)
  13043. {
  13044. #ifdef WOLFSSL_KEY_GEN
  13045. int res = 1;
  13046. curve448_key privkey;
  13047. curve448_key pubkey;
  13048. WOLFSSL_ENTER("wolfSSL_EC448_shared_key");
  13049. /* Validate parameters. */
  13050. if ((shared == NULL) || (sharedSz == NULL) ||
  13051. (*sharedSz < CURVE448_KEY_SIZE) || (priv == NULL) ||
  13052. (privSz < CURVE448_KEY_SIZE) || (pub == NULL) ||
  13053. (pubSz < CURVE448_KEY_SIZE)) {
  13054. WOLFSSL_MSG("Bad arguments");
  13055. res = 0;
  13056. }
  13057. /* Initialize private key object. */
  13058. if (res && (wc_curve448_init(&privkey) != 0)) {
  13059. WOLFSSL_MSG("wc_curve448_init privkey failed");
  13060. res = 0;
  13061. }
  13062. if (res) {
  13063. /* Initialize public key object. */
  13064. if (wc_curve448_init(&pubkey) != MP_OKAY) {
  13065. WOLFSSL_MSG("wc_curve448_init pubkey failed");
  13066. res = 0;
  13067. }
  13068. if (res) {
  13069. /* Import our private key. */
  13070. int ret = wc_curve448_import_private_ex(priv, privSz, &privkey,
  13071. EC448_LITTLE_ENDIAN);
  13072. if (ret != 0) {
  13073. WOLFSSL_MSG("wc_curve448_import_private_ex failed");
  13074. res = 0;
  13075. }
  13076. if (res) {
  13077. /* Import peer's public key. */
  13078. ret = wc_curve448_import_public_ex(pub, pubSz, &pubkey,
  13079. EC448_LITTLE_ENDIAN);
  13080. if (ret != 0) {
  13081. WOLFSSL_MSG("wc_curve448_import_public_ex failed");
  13082. res = 0;
  13083. }
  13084. }
  13085. if (res) {
  13086. /* Compute shared secret. */
  13087. ret = wc_curve448_shared_secret_ex(&privkey, &pubkey, shared,
  13088. sharedSz, EC448_LITTLE_ENDIAN);
  13089. if (ret != 0) {
  13090. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13091. res = 0;
  13092. }
  13093. }
  13094. wc_curve448_free(&pubkey);
  13095. }
  13096. wc_curve448_free(&privkey);
  13097. }
  13098. return res;
  13099. #else
  13100. WOLFSSL_MSG("No Key Gen built in");
  13101. (void)shared;
  13102. (void)sharedSz;
  13103. (void)priv;
  13104. (void)privSz;
  13105. (void)pub;
  13106. (void)pubSz;
  13107. return 0;
  13108. #endif /* WOLFSSL_KEY_GEN */
  13109. }
  13110. #endif /* OPENSSL_EXTRA && HAVE_CURVE448 */
  13111. /*******************************************************************************
  13112. * END OF EC448 API
  13113. ******************************************************************************/
  13114. /*******************************************************************************
  13115. * START OF ED448 API
  13116. ******************************************************************************/
  13117. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED448)
  13118. /* Generate an ED448 key pair.
  13119. *
  13120. * Output keys are in little endian format.
  13121. *
  13122. * @param [out] priv ED448 private key data.
  13123. * @param [in, out] privSz On in, the size of priv in bytes.
  13124. * On out, the length of the private key data in bytes.
  13125. * @param [out] pub ED448 public key data.
  13126. * @param [in, out] pubSz On in, the size of pub in bytes.
  13127. * On out, the length of the public key data in bytes.
  13128. * @return 1 on success
  13129. * @return 0 on failure.
  13130. */
  13131. int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz,
  13132. unsigned char *pub, unsigned int *pubSz)
  13133. {
  13134. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED448_KEY_EXPORT)
  13135. int res = 1;
  13136. int initTmpRng = 0;
  13137. WC_RNG *rng = NULL;
  13138. #ifdef WOLFSSL_SMALL_STACK
  13139. WC_RNG *tmpRng = NULL;
  13140. #else
  13141. WC_RNG tmpRng[1];
  13142. #endif
  13143. ed448_key key;
  13144. WOLFSSL_ENTER("wolfSSL_ED448_generate_key");
  13145. /* Validate parameters. */
  13146. if ((priv == NULL) || (privSz == NULL) ||
  13147. (*privSz < ED448_PRV_KEY_SIZE) || (pub == NULL) ||
  13148. (pubSz == NULL) || (*pubSz < ED448_PUB_KEY_SIZE)) {
  13149. WOLFSSL_MSG("Bad arguments");
  13150. res = 0;
  13151. }
  13152. if (res) {
  13153. /* Create a random number generator. */
  13154. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  13155. if (rng == NULL) {
  13156. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  13157. res = 0;
  13158. }
  13159. }
  13160. /* Initialize an Ed448 key. */
  13161. if (res && (wc_ed448_init(&key) != 0)) {
  13162. WOLFSSL_MSG("wc_ed448_init failed");
  13163. res = 0;
  13164. }
  13165. if (res) {
  13166. /* Make an Ed448 key pair. */
  13167. int ret = wc_ed448_make_key(rng, ED448_KEY_SIZE, &key);
  13168. if (ret != 0) {
  13169. WOLFSSL_MSG("wc_ed448_make_key failed");
  13170. res = 0;
  13171. }
  13172. if (res) {
  13173. /* Export Curve448 key pair to buffers. */
  13174. ret = wc_ed448_export_key(&key, priv, privSz, pub, pubSz);
  13175. if (ret != 0) {
  13176. WOLFSSL_MSG("wc_ed448_export_key failed");
  13177. res = 0;
  13178. }
  13179. }
  13180. wc_ed448_free(&key);
  13181. }
  13182. if (initTmpRng) {
  13183. wc_FreeRng(rng);
  13184. #ifdef WOLFSSL_SMALL_STACK
  13185. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  13186. #endif
  13187. }
  13188. return res;
  13189. #else
  13190. #ifndef WOLFSSL_KEY_GEN
  13191. WOLFSSL_MSG("No Key Gen built in");
  13192. #else
  13193. WOLFSSL_MSG("No ED448 key export built in");
  13194. #endif
  13195. (void)priv;
  13196. (void)privSz;
  13197. (void)pub;
  13198. (void)pubSz;
  13199. return 0;
  13200. #endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */
  13201. }
  13202. /* Sign a message with Ed448 using the private key.
  13203. *
  13204. * Input and output keys are in little endian format.
  13205. * Priv is a buffer containing private and public part of key.
  13206. *
  13207. * @param [in] msg Message to be signed.
  13208. * @param [in] msgSz Length of message in bytes.
  13209. * @param [in] priv ED448 private key data.
  13210. * @param [in] privSz Length in bytes of private key data.
  13211. * @param [out] sig Signature buffer.
  13212. * @param [in, out] sigSz On in, the length of the signature buffer in bytes.
  13213. * On out, the length of the signature in bytes.
  13214. * @return 1 on success
  13215. * @return 0 on failure.
  13216. */
  13217. int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz,
  13218. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  13219. unsigned int *sigSz)
  13220. {
  13221. #if defined(HAVE_ED448_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  13222. defined(HAVE_ED448_KEY_IMPORT)
  13223. ed448_key key;
  13224. int res = 1;
  13225. WOLFSSL_ENTER("wolfSSL_ED448_sign");
  13226. /* Validate parameters. */
  13227. if ((priv == NULL) || (privSz != ED448_PRV_KEY_SIZE) ||
  13228. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  13229. (*sigSz < ED448_SIG_SIZE)) {
  13230. WOLFSSL_MSG("Bad arguments");
  13231. res = 0;
  13232. }
  13233. /* Initialize Ed448 key. */
  13234. if (res && (wc_ed448_init(&key) != 0)) {
  13235. WOLFSSL_MSG("wc_curve448_init failed");
  13236. res = 0;
  13237. }
  13238. if (res) {
  13239. /* Import private and public key. */
  13240. int ret = wc_ed448_import_private_key(priv, privSz / 2,
  13241. priv + (privSz / 2), ED448_PUB_KEY_SIZE, &key);
  13242. if (ret != 0) {
  13243. WOLFSSL_MSG("wc_ed448_import_private failed");
  13244. res = 0;
  13245. }
  13246. if (res) {
  13247. /* Sign message with Ed448 - no context. */
  13248. ret = wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0);
  13249. if (ret != 0) {
  13250. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13251. res = 0;
  13252. }
  13253. }
  13254. wc_ed448_free(&key);
  13255. }
  13256. return res;
  13257. #else
  13258. #if !defined(HAVE_ED448_SIGN)
  13259. WOLFSSL_MSG("No ED448 sign built in");
  13260. #elif !defined(WOLFSSL_KEY_GEN)
  13261. WOLFSSL_MSG("No Key Gen built in");
  13262. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13263. WOLFSSL_MSG("No ED448 Key import built in");
  13264. #endif
  13265. (void)msg;
  13266. (void)msgSz;
  13267. (void)priv;
  13268. (void)privSz;
  13269. (void)sig;
  13270. (void)sigSz;
  13271. return 0;
  13272. #endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13273. }
  13274. /* Verify a message with Ed448 using the public key.
  13275. *
  13276. * Input keys are in little endian format.
  13277. *
  13278. * @param [in] msg Message to be verified.
  13279. * @param [in] msgSz Length of message in bytes.
  13280. * @param [in] pub ED448 public key data.
  13281. * @param [in] privSz Length in bytes of public key data.
  13282. * @param [in] sig Signature buffer.
  13283. * @param [in] sigSz Length of the signature in bytes.
  13284. * @return 1 on success
  13285. * @return 0 on failure.
  13286. */
  13287. int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz,
  13288. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  13289. unsigned int sigSz)
  13290. {
  13291. #if defined(HAVE_ED448_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  13292. defined(HAVE_ED448_KEY_IMPORT)
  13293. ed448_key key;
  13294. int res = 1;
  13295. WOLFSSL_ENTER("wolfSSL_ED448_verify");
  13296. /* Validate parameters. */
  13297. if ((pub == NULL) || (pubSz != ED448_PUB_KEY_SIZE) || (msg == NULL) ||
  13298. (sig == NULL) || (sigSz != ED448_SIG_SIZE)) {
  13299. WOLFSSL_MSG("Bad arguments");
  13300. res = 0;
  13301. }
  13302. /* Initialize Ed448 key. */
  13303. if (res && (wc_ed448_init(&key) != 0)) {
  13304. WOLFSSL_MSG("wc_curve448_init failed");
  13305. res = 0;
  13306. }
  13307. if (res) {
  13308. /* Import public key. */
  13309. int ret = wc_ed448_import_public(pub, pubSz, &key);
  13310. if (ret != 0) {
  13311. WOLFSSL_MSG("wc_ed448_import_public failed");
  13312. res = 0;
  13313. }
  13314. if (res) {
  13315. int check = 0;
  13316. /* Verify signature with message and public key - no context. */
  13317. ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  13318. &key, NULL, 0);
  13319. /* Check for errors in verification process. */
  13320. if (ret != 0) {
  13321. WOLFSSL_MSG("wc_ed448_verify_msg failed");
  13322. res = 0;
  13323. }
  13324. /* Check signature is valid. */
  13325. else if (!check) {
  13326. WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)");
  13327. res = 0;
  13328. }
  13329. }
  13330. wc_ed448_free(&key);
  13331. }
  13332. return res;
  13333. #else
  13334. #if !defined(HAVE_ED448_VERIFY)
  13335. WOLFSSL_MSG("No ED448 verify built in");
  13336. #elif !defined(WOLFSSL_KEY_GEN)
  13337. WOLFSSL_MSG("No Key Gen built in");
  13338. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13339. WOLFSSL_MSG("No ED448 Key import built in");
  13340. #endif
  13341. (void)msg;
  13342. (void)msgSz;
  13343. (void)pub;
  13344. (void)pubSz;
  13345. (void)sig;
  13346. (void)sigSz;
  13347. return 0;
  13348. #endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13349. }
  13350. #endif /* OPENSSL_EXTRA && HAVE_ED448 */
  13351. /*******************************************************************************
  13352. * END OF ED448 API
  13353. ******************************************************************************/
  13354. /*******************************************************************************
  13355. * START OF GENERIC PUBLIC KEY PEM APIs
  13356. ******************************************************************************/
  13357. #ifdef OPENSSL_EXTRA
  13358. /* Sets default callback password for PEM.
  13359. *
  13360. * @param [out] buf Buffer to hold password.
  13361. * @param [in] num Number of characters in buffer.
  13362. * @param [in] rwFlag Read/write flag. Ignored.
  13363. * @param [in] userData User data - assumed to be default password.
  13364. * @return Password size on success.
  13365. * @return 0 on failure.
  13366. */
  13367. int wolfSSL_PEM_def_callback(char* buf, int num, int rwFlag, void* userData)
  13368. {
  13369. int sz = 0;
  13370. WOLFSSL_ENTER("wolfSSL_PEM_def_callback");
  13371. (void)rwFlag;
  13372. /* We assume that the user passes a default password as userdata */
  13373. if ((buf != NULL) && (userData != NULL)) {
  13374. sz = (int)XSTRLEN((const char*)userData);
  13375. sz = (int)min((word32)sz, (word32)num);
  13376. XMEMCPY(buf, userData, sz);
  13377. }
  13378. else {
  13379. WOLFSSL_MSG("Error, default password cannot be created.");
  13380. }
  13381. return sz;
  13382. }
  13383. #ifndef NO_BIO
  13384. /* Writes a public key to a WOLFSSL_BIO encoded in PEM format.
  13385. *
  13386. * @param [in] bio BIO to write to.
  13387. * @param [in] key Public key to write in PEM format.
  13388. * @return 1 on success.
  13389. * @return 0 on failure.
  13390. */
  13391. int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
  13392. {
  13393. int ret = 0;
  13394. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY");
  13395. if ((bio != NULL) && (key != NULL)) {
  13396. switch (key->type) {
  13397. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)
  13398. case EVP_PKEY_RSA:
  13399. ret = wolfSSL_PEM_write_bio_RSA_PUBKEY(bio, key->rsa);
  13400. break;
  13401. #endif /* WOLFSSL_KEY_GEN && !NO_RSA */
  13402. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && \
  13403. (defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN))
  13404. case EVP_PKEY_DSA:
  13405. ret = wolfSSL_PEM_write_bio_DSA_PUBKEY(bio, key->dsa);
  13406. break;
  13407. #endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  13408. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && \
  13409. defined(WOLFSSL_KEY_GEN)
  13410. case EVP_PKEY_EC:
  13411. ret = wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key->ecc);
  13412. break;
  13413. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13414. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  13415. case EVP_PKEY_DH:
  13416. /* DH public key not supported. */
  13417. WOLFSSL_MSG("Writing DH PUBKEY not supported!");
  13418. break;
  13419. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  13420. default:
  13421. /* Key type not supported. */
  13422. WOLFSSL_MSG("Unknown Key type!");
  13423. break;
  13424. }
  13425. }
  13426. return ret;
  13427. }
  13428. /* Writes a private key to a WOLFSSL_BIO encoded in PEM format.
  13429. *
  13430. * @param [in] bio BIO to write to.
  13431. * @param [in] key Public key to write in PEM format.
  13432. * @param [in] cipher Encryption cipher to use.
  13433. * @param [in] passwd Password to use when encrypting.
  13434. * @param [in] len Length of password.
  13435. * @param [in] cb Password callback.
  13436. * @param [in] arg Password callback argument.
  13437. * @return 1 on success.
  13438. * @return 0 on failure.
  13439. */
  13440. int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key,
  13441. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  13442. wc_pem_password_cb* cb, void* arg)
  13443. {
  13444. int ret = 1;
  13445. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey");
  13446. (void)cipher;
  13447. (void)passwd;
  13448. (void)len;
  13449. (void)cb;
  13450. (void)arg;
  13451. /* Validate parameters. */
  13452. if ((bio == NULL) || (key == NULL)) {
  13453. WOLFSSL_MSG("Bad Function Arguments");
  13454. ret = 0;
  13455. }
  13456. if (ret == 1) {
  13457. #ifdef WOLFSSL_KEY_GEN
  13458. switch (key->type) {
  13459. #ifndef NO_RSA
  13460. case EVP_PKEY_RSA:
  13461. /* Write using RSA specific API. */
  13462. ret = wolfSSL_PEM_write_bio_RSAPrivateKey(bio, key->rsa,
  13463. cipher, passwd, len, cb, arg);
  13464. break;
  13465. #endif
  13466. #ifndef NO_DSA
  13467. case EVP_PKEY_DSA:
  13468. /* Write using DSA specific API. */
  13469. ret = wolfSSL_PEM_write_bio_DSAPrivateKey(bio, key->dsa,
  13470. cipher, passwd, len, cb, arg);
  13471. break;
  13472. #endif
  13473. #ifdef HAVE_ECC
  13474. case EVP_PKEY_EC:
  13475. #if defined(HAVE_ECC_KEY_EXPORT)
  13476. /* Write using EC specific API. */
  13477. ret = wolfSSL_PEM_write_bio_ECPrivateKey(bio, key->ecc,
  13478. cipher, passwd, len, cb, arg);
  13479. #else
  13480. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13481. key->pkey_sz, bio, EC_PRIVATEKEY_TYPE);
  13482. #endif
  13483. break;
  13484. #endif
  13485. #ifndef NO_DH
  13486. case EVP_PKEY_DH:
  13487. /* Write using generic API with DH type. */
  13488. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13489. key->pkey_sz, bio, DH_PRIVATEKEY_TYPE);
  13490. break;
  13491. #endif
  13492. default:
  13493. WOLFSSL_MSG("Unknown Key type!");
  13494. ret = 0;
  13495. break;
  13496. }
  13497. #else
  13498. int type = 0;
  13499. switch (key->type) {
  13500. #ifndef NO_DSA
  13501. case EVP_PKEY_DSA:
  13502. type = DSA_PRIVATEKEY_TYPE;
  13503. break;
  13504. #endif
  13505. #ifdef HAVE_ECC
  13506. case EVP_PKEY_EC:
  13507. type = ECC_PRIVATEKEY_TYPE;
  13508. break;
  13509. #endif
  13510. #ifndef NO_DH
  13511. case EVP_PKEY_DH:
  13512. type = DH_PRIVATEKEY_TYPE;
  13513. break;
  13514. #endif
  13515. #ifndef NO_RSA
  13516. case EVP_PKEY_RSA:
  13517. type = PRIVATEKEY_TYPE;
  13518. break;
  13519. #endif
  13520. default:
  13521. ret = 0;
  13522. break;
  13523. }
  13524. if (ret == 1) {
  13525. /* Write using generic API with generic type. */
  13526. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, key->pkey_sz,
  13527. bio, type);
  13528. }
  13529. #endif
  13530. }
  13531. return ret;
  13532. }
  13533. #endif /* !NO_BIO */
  13534. #ifndef NO_BIO
  13535. /* Create a private key object from the data in the BIO.
  13536. *
  13537. * @param [in] bio BIO to read from.
  13538. * @param [in, out] key Public key object. Object used if passed in.
  13539. * @param [in] cb Password callback.
  13540. * @param [in] arg Password callback argument.
  13541. * @return A WOLFSSL_EVP_PKEY object on success.
  13542. * @return NULL on failure.
  13543. */
  13544. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio,
  13545. WOLFSSL_EVP_PKEY **key, wc_pem_password_cb *cb, void *arg)
  13546. {
  13547. int err = 0;
  13548. WOLFSSL_EVP_PKEY* pkey = NULL;
  13549. DerBuffer* der = NULL;
  13550. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY");
  13551. if (bio == NULL) {
  13552. err = 1;
  13553. }
  13554. /* Read the PEM public key from the BIO and convert to DER. */
  13555. if ((!err) && (pem_read_bio_key(bio, cb, arg, PUBLICKEY_TYPE, NULL,
  13556. &der) < 0)) {
  13557. err = 1;
  13558. }
  13559. if (!err) {
  13560. const unsigned char* ptr = der->buffer;
  13561. /* Use key passed in if set. */
  13562. if ((key != NULL) && (*key != NULL)) {
  13563. pkey = *key;
  13564. }
  13565. /* Convert DER data to a public key object. */
  13566. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13567. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13568. pkey = NULL;
  13569. err = 1;
  13570. }
  13571. }
  13572. /* Return the key if possible. */
  13573. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13574. *key = pkey;
  13575. }
  13576. /* Dispose of the DER encoding. */
  13577. FreeDer(&der);
  13578. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0);
  13579. return pkey;
  13580. }
  13581. /* Create a private key object from the data in the BIO.
  13582. *
  13583. * @param [in] bio BIO to read from.
  13584. * @param [in, out] key Private key object. Object used if passed in.
  13585. * @param [in] cb Password callback.
  13586. * @param [in] arg Password callback argument.
  13587. * @return A WOLFSSL_EVP_PKEY object on success.
  13588. * @return NULL on failure.
  13589. */
  13590. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio,
  13591. WOLFSSL_EVP_PKEY** key, wc_pem_password_cb* cb, void* arg)
  13592. {
  13593. int err = 0;
  13594. WOLFSSL_EVP_PKEY* pkey = NULL;
  13595. DerBuffer* der = NULL;
  13596. int keyFormat = 0;
  13597. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey");
  13598. /* Validate parameters. */
  13599. if (bio == NULL) {
  13600. err = 1;
  13601. }
  13602. /* Read the PEM private key from the BIO and convert to DER. */
  13603. if ((!err) && (pem_read_bio_key(bio, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13604. &der) < 0)) {
  13605. err = 1;
  13606. }
  13607. if (!err) {
  13608. const unsigned char* ptr = der->buffer;
  13609. int type = -1;
  13610. /* Set key type based on format returned. */
  13611. switch (keyFormat) {
  13612. /* No key format set - default to RSA. */
  13613. case 0:
  13614. case RSAk:
  13615. type = EVP_PKEY_RSA;
  13616. break;
  13617. case DSAk:
  13618. type = EVP_PKEY_DSA;
  13619. break;
  13620. case ECDSAk:
  13621. type = EVP_PKEY_EC;
  13622. break;
  13623. case DHk:
  13624. type = EVP_PKEY_DH;
  13625. break;
  13626. default:
  13627. break;
  13628. }
  13629. /* Use key passed in if set. */
  13630. if ((key != NULL) && (*key != NULL)) {
  13631. pkey = *key;
  13632. }
  13633. /* Convert DER data to a private key object. */
  13634. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13635. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13636. pkey = NULL;
  13637. err = 1;
  13638. }
  13639. }
  13640. /* Return the key if possible. */
  13641. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13642. *key = pkey;
  13643. }
  13644. /* Dispose of the DER encoding. */
  13645. FreeDer(&der);
  13646. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", err);
  13647. return pkey;
  13648. }
  13649. #endif /* !NO_BIO */
  13650. #if !defined(NO_FILESYSTEM)
  13651. /* Create a private key object from the data in a file.
  13652. *
  13653. * @param [in] fp File pointer.
  13654. * @param [in, out] key Public key object. Object used if passed in.
  13655. * @param [in] cb Password callback.
  13656. * @param [in] arg Password callback argument.
  13657. * @return A WOLFSSL_EVP_PKEY object on success.
  13658. * @return NULL on failure.
  13659. */
  13660. WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13661. wc_pem_password_cb *cb, void *arg)
  13662. {
  13663. int err = 0;
  13664. WOLFSSL_EVP_PKEY* pkey = NULL;
  13665. DerBuffer* der = NULL;
  13666. WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY");
  13667. /* Validate parameters. */
  13668. if (fp == XBADFILE) {
  13669. err = 1;
  13670. }
  13671. /* Read the PEM public key from the file and convert to DER. */
  13672. if ((!err) && ((pem_read_file_key(fp, cb, arg, PUBLICKEY_TYPE, NULL,
  13673. &der) < 0) || (der == NULL))) {
  13674. err = 1;
  13675. }
  13676. if (!err) {
  13677. const unsigned char* ptr = der->buffer;
  13678. /* Use key passed in if set. */
  13679. if ((key != NULL) && (*key != NULL)) {
  13680. pkey = *key;
  13681. }
  13682. /* Convert DER data to a public key object. */
  13683. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13684. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13685. pkey = NULL;
  13686. err = 1;
  13687. }
  13688. }
  13689. /* Return the key if possible. */
  13690. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13691. *key = pkey;
  13692. }
  13693. /* Dispose of the DER encoding. */
  13694. FreeDer(&der);
  13695. WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0);
  13696. return pkey;
  13697. }
  13698. #ifndef NO_CERTS
  13699. /* Create a private key object from the data in a file.
  13700. *
  13701. * @param [in] fp File pointer.
  13702. * @param [in, out] key Private key object. Object used if passed in.
  13703. * @param [in] cb Password callback.
  13704. * @param [in] arg Password callback argument.
  13705. * @return A WOLFSSL_EVP_PKEY object on success.
  13706. * @return NULL on failure.
  13707. */
  13708. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13709. wc_pem_password_cb *cb, void *arg)
  13710. {
  13711. int err = 0;
  13712. WOLFSSL_EVP_PKEY* pkey = NULL;
  13713. DerBuffer* der = NULL;
  13714. int keyFormat = 0;
  13715. WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey");
  13716. /* Validate parameters. */
  13717. if (fp == XBADFILE) {
  13718. err = 1;
  13719. }
  13720. /* Read the PEM private key from the file and convert to DER. */
  13721. if ((!err) && (pem_read_file_key(fp, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13722. &der)) < 0) {
  13723. err = 1;
  13724. }
  13725. if (!err) {
  13726. const unsigned char* ptr = der->buffer;
  13727. int type = -1;
  13728. /* Set key type based on format returned. */
  13729. switch (keyFormat) {
  13730. /* No key format set - default to RSA. */
  13731. case 0:
  13732. case RSAk:
  13733. type = EVP_PKEY_RSA;
  13734. break;
  13735. case DSAk:
  13736. type = EVP_PKEY_DSA;
  13737. break;
  13738. case ECDSAk:
  13739. type = EVP_PKEY_EC;
  13740. break;
  13741. case DHk:
  13742. type = EVP_PKEY_DH;
  13743. break;
  13744. default:
  13745. break;
  13746. }
  13747. /* Use key passed in if set. */
  13748. if ((key != NULL) && (*key != NULL)) {
  13749. pkey = *key;
  13750. }
  13751. /* Convert DER data to a private key object. */
  13752. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13753. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13754. pkey = NULL;
  13755. err = 1;
  13756. }
  13757. }
  13758. /* Return the key if possible. */
  13759. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13760. *key = pkey;
  13761. }
  13762. /* Dispose of the DER encoding. */
  13763. FreeDer(&der);
  13764. WOLFSSL_LEAVE("wolfSSL_PEM_read_PrivateKey", 0);
  13765. return pkey;
  13766. }
  13767. #endif /* !NO_CERTS */
  13768. #endif /* !NO_FILESYSTEM */
  13769. #ifndef NO_CERTS
  13770. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  13771. #define PEM_BEGIN "-----BEGIN "
  13772. #define PEM_BEGIN_SZ 11
  13773. #define PEM_END "-----END "
  13774. #define PEM_END_SZ 9
  13775. #define PEM_HDR_FIN "-----"
  13776. #define PEM_HDR_FIN_SZ 5
  13777. #define PEM_HDR_FIN_EOL_NEWLINE "-----\n"
  13778. #define PEM_HDR_FIN_EOL_NULL_TERM "-----\0"
  13779. #define PEM_HDR_FIN_EOL_SZ 6
  13780. /* Find strings and return middle offsets.
  13781. *
  13782. * Find first string in pem as a prefix and then locate second string as a
  13783. * postfix.
  13784. * len returning with 0 indicates not found.
  13785. *
  13786. * @param [in] pem PEM data.
  13787. * @param [in] pemLen Length of PEM data.
  13788. * @param [in] idx Current index.
  13789. * @param [in] prefix First string to find.
  13790. * @param [in] postfix Second string to find after first.
  13791. * @param [out] start Start index of data between strings.
  13792. * @param [out] len Length of data between strings.
  13793. */
  13794. static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix,
  13795. const char* postfix, int* start, int* len)
  13796. {
  13797. int prefixLen = (int)XSTRLEN(prefix);
  13798. int postfixLen = (int)XSTRLEN(postfix);
  13799. *start = *len = 0;
  13800. /* Find prefix part. */
  13801. for (; idx < pemLen - prefixLen; idx++) {
  13802. if ((pem[idx] == prefix[0]) &&
  13803. (XMEMCMP(pem + idx, prefix, prefixLen) == 0)) {
  13804. idx += prefixLen;
  13805. *start = idx;
  13806. break;
  13807. }
  13808. }
  13809. /* Find postfix part. */
  13810. for (; idx < pemLen - postfixLen; idx++) {
  13811. if ((pem[idx] == postfix[0]) &&
  13812. (XMEMCMP(pem + idx, postfix, postfixLen) == 0)) {
  13813. *len = idx - *start;
  13814. break;
  13815. }
  13816. }
  13817. }
  13818. /* Parse out content type name, any encryption headers and DER encoding.
  13819. *
  13820. * @param [in] pem PEM data.
  13821. * @param [in] pemLen Length of PEM data.
  13822. * @param [out] name Name of content type.
  13823. * @param [out] header Encryption headers.
  13824. * @param [out] data DER encoding from PEM.
  13825. * @param [out] len Length of DER data.
  13826. * @return 0 on success.
  13827. * @return MEMORY_E when dynamic memory allocation fails.
  13828. * @return ASN_NO_PEM_HEADER when no header found or different names found.
  13829. */
  13830. static int pem_read_data(char* pem, int pemLen, char **name, char **header,
  13831. unsigned char **data, long *len)
  13832. {
  13833. int ret = 0;
  13834. int start;
  13835. int nameLen;
  13836. int startHdr = 0;
  13837. int hdrLen = 0;
  13838. int startEnd = 0;
  13839. int endLen;
  13840. *name = NULL;
  13841. *header = NULL;
  13842. /* Find header. */
  13843. pem_find_pattern(pem, pemLen, 0, PEM_BEGIN, PEM_HDR_FIN, &start, &nameLen);
  13844. /* Allocate memory for header name. */
  13845. *name = (char*)XMALLOC(nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13846. if (*name == NULL) {
  13847. ret = MEMORY_E;
  13848. }
  13849. if (ret == 0) {
  13850. /* Put in header name. */
  13851. (*name)[nameLen] = '\0';
  13852. if (nameLen == 0) {
  13853. ret = ASN_NO_PEM_HEADER;
  13854. }
  13855. else {
  13856. XMEMCPY(*name, pem + start, nameLen);
  13857. }
  13858. }
  13859. if (ret == 0) {
  13860. /* Find encryption headers after header. */
  13861. start += nameLen + PEM_HDR_FIN_SZ;
  13862. pem_find_pattern(pem, pemLen, start, "\n", "\n\n", &startHdr, &hdrLen);
  13863. if (hdrLen > 0) {
  13864. /* Include first of two '\n' characters. */
  13865. hdrLen++;
  13866. }
  13867. /* Allocate memory for encryption header string. */
  13868. *header = (char*)XMALLOC(hdrLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13869. if (*header == NULL) {
  13870. ret = MEMORY_E;
  13871. }
  13872. }
  13873. if (ret == 0) {
  13874. /* Put in encryption header string. */
  13875. (*header)[hdrLen] = '\0';
  13876. if (hdrLen > 0) {
  13877. XMEMCPY(*header, pem + startHdr, hdrLen);
  13878. start = startHdr + hdrLen + 1;
  13879. }
  13880. /* Find footer. */
  13881. pem_find_pattern(pem, pemLen, start, PEM_END, PEM_HDR_FIN, &startEnd,
  13882. &endLen);
  13883. /* Validate header name and footer name are the same. */
  13884. if ((endLen != nameLen) ||
  13885. (XMEMCMP(*name, pem + startEnd, nameLen) != 0)) {
  13886. ret = ASN_NO_PEM_HEADER;
  13887. }
  13888. }
  13889. if (ret == 0) {
  13890. unsigned char* der = (unsigned char*)pem;
  13891. word32 derLen;
  13892. /* Convert PEM body to DER. */
  13893. derLen = (word32)(startEnd - PEM_END_SZ - start);
  13894. ret = Base64_Decode(der + start, derLen, der, &derLen);
  13895. if (ret == 0) {
  13896. /* Return the DER data. */
  13897. *data = der;
  13898. *len = derLen;
  13899. }
  13900. }
  13901. return ret;
  13902. }
  13903. /* Encode the DER data in PEM format into a newly allocated buffer.
  13904. *
  13905. * @param [in] name Header/footer name.
  13906. * @param [in] header Encryption header.
  13907. * @param [in] data DER data.
  13908. * @param [in] len Length of DER data.
  13909. * @param [out] pemOut PEM encoded data.
  13910. * @param [out] pemOutLen Length of PEM encoded data.
  13911. * @return 0 on success.
  13912. * @return MEMORY_E when dynamic memory allocation fails.
  13913. */
  13914. static int pem_write_data(const char *name, const char *header,
  13915. const unsigned char *data, long len, char** pemOut, word32* pemOutLen)
  13916. {
  13917. int ret = 0;
  13918. int nameLen;
  13919. int headerLen;
  13920. char* pem = NULL;
  13921. word32 pemLen;
  13922. word32 derLen = (word32)len;
  13923. byte* p;
  13924. nameLen = (int)XSTRLEN(name);
  13925. headerLen = (int)XSTRLEN(header);
  13926. /* DER encode for PEM. */
  13927. pemLen = (derLen + 2) / 3 * 4;
  13928. pemLen += (pemLen + 63) / 64;
  13929. /* Header */
  13930. pemLen += PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  13931. if (headerLen > 0) {
  13932. /* Encryption lines plus extra carriage return. */
  13933. pemLen += headerLen + 1;
  13934. }
  13935. /* Trailer */
  13936. pemLen += PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  13937. pem = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13938. if (pem == NULL) {
  13939. ret = MEMORY_E;
  13940. }
  13941. p = (byte*)pem;
  13942. if (ret == 0) {
  13943. /* Add header. */
  13944. XMEMCPY(p, PEM_BEGIN, PEM_BEGIN_SZ);
  13945. p += PEM_BEGIN_SZ;
  13946. XMEMCPY(p, name, nameLen);
  13947. p += nameLen;
  13948. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  13949. p += PEM_HDR_FIN_EOL_SZ;
  13950. if (headerLen > 0) {
  13951. /* Add encryption header. */
  13952. XMEMCPY(p, header, headerLen);
  13953. p += headerLen;
  13954. /* Blank line after a header and before body. */
  13955. *(p++) = '\n';
  13956. }
  13957. /* Add DER data as PEM. */
  13958. pemLen -= (word32)((size_t)p - (size_t)pem);
  13959. ret = Base64_Encode(data, derLen, p, &pemLen);
  13960. }
  13961. if (ret == 0) {
  13962. p += pemLen;
  13963. /* Add trailer. */
  13964. XMEMCPY(p, PEM_END, PEM_END_SZ);
  13965. p += PEM_END_SZ;
  13966. XMEMCPY(p, name, nameLen);
  13967. p += nameLen;
  13968. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  13969. p += PEM_HDR_FIN_EOL_SZ;
  13970. /* Return buffer and length of data. */
  13971. *pemOut = pem;
  13972. *pemOutLen = (word32)((size_t)p - (size_t)pem);
  13973. }
  13974. return ret;
  13975. }
  13976. #endif /* !NO_BIO || !NO_FILESYSTEM */
  13977. #ifndef NO_BIO
  13978. /* Read PEM encoded data from a BIO.
  13979. *
  13980. * Reads the entire contents in.
  13981. *
  13982. * @param [in] bio BIO to read from.
  13983. * @param [out] name Name of content type.
  13984. * @param [out] header Encryption headers.
  13985. * @param [out] data DER encoding from PEM.
  13986. * @param [out] len Length of DER data.
  13987. * @return 1 on success.
  13988. * @return 0 on failure.
  13989. */
  13990. int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header,
  13991. unsigned char **data, long *len)
  13992. {
  13993. int res = 1;
  13994. char* pem = NULL;
  13995. int pemLen = 0;
  13996. int memAlloced = 1;
  13997. /* Validate parameters. */
  13998. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL) ||
  13999. (len == NULL)) {
  14000. res = 0;
  14001. }
  14002. /* Load all the data from the BIO. */
  14003. if ((res == 1) && (wolfssl_read_bio(bio, &pem, &pemLen, &memAlloced) !=
  14004. 0)) {
  14005. res = 0;
  14006. }
  14007. if ((res == 1) && (!memAlloced)) {
  14008. /* Need to return allocated memory - make sure it is allocated. */
  14009. char* p = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14010. if (p == NULL) {
  14011. res = 0;
  14012. }
  14013. else {
  14014. /* Copy the data into new buffer. */
  14015. XMEMCPY(p, pem, pemLen);
  14016. pem = p;
  14017. }
  14018. }
  14019. /* Read the PEM data. */
  14020. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  14021. 0)) {
  14022. /* Dispose of any allocated memory. */
  14023. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14024. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14025. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14026. *name = NULL;
  14027. *header = NULL;
  14028. res = 0;
  14029. }
  14030. return res;
  14031. }
  14032. /* Encode the DER data in PEM format into a BIO.
  14033. *
  14034. * @param [in] bio BIO to write to.
  14035. * @param [in] name Header/footer name.
  14036. * @param [in] header Encryption header.
  14037. * @param [in] data DER data.
  14038. * @param [in] len Length of DER data.
  14039. * @return 0 on failure.
  14040. */
  14041. int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name,
  14042. const char *header, const unsigned char *data, long len)
  14043. {
  14044. int err = 0;
  14045. char* pem = NULL;
  14046. word32 pemLen = 0;
  14047. /* Validate parameters. */
  14048. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL)) {
  14049. err = BAD_FUNC_ARG;
  14050. }
  14051. /* Encode into a buffer. */
  14052. if (!err) {
  14053. err = pem_write_data(name, header, data, len, &pem, &pemLen);
  14054. }
  14055. /* Write PEM into BIO. */
  14056. if ((!err) && (wolfSSL_BIO_write(bio, pem, (int)pemLen) != (int)pemLen)) {
  14057. err = IO_FAILED_E;
  14058. }
  14059. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14060. return (!err) ? pemLen : 0;
  14061. }
  14062. #endif /* !NO_BIO */
  14063. #if !defined(NO_FILESYSTEM)
  14064. /* Read PEM encoded data from a file.
  14065. *
  14066. * Reads the entire contents in.
  14067. *
  14068. * @param [in] bio BIO to read from.
  14069. * @param [out] name Name of content type.
  14070. * @param [out] header Encryption headers.
  14071. * @param [out] data DER encoding from PEM.
  14072. * @param [out] len Length of DER data.
  14073. * @return 1 on success.
  14074. * @return 0 on failure.
  14075. */
  14076. int wolfSSL_PEM_read(XFILE fp, char **name, char **header, unsigned char **data,
  14077. long *len)
  14078. {
  14079. int res = 1;
  14080. char* pem = NULL;
  14081. int pemLen = 0;
  14082. /* Validate parameters. */
  14083. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14084. (data == NULL) || (len == NULL)) {
  14085. res = 0;
  14086. }
  14087. /* Load all the data from the file. */
  14088. if ((res == 1) && (wolfssl_read_file(fp, &pem, &pemLen) != 0)) {
  14089. res = 0;
  14090. }
  14091. /* Read the PEM data. */
  14092. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  14093. 0)) {
  14094. /* Dispose of any allocated memory. */
  14095. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14096. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14097. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14098. *name = NULL;
  14099. *header = NULL;
  14100. res = 0;
  14101. }
  14102. return res;
  14103. }
  14104. /* Encode the DER data in PEM format into a file.
  14105. *
  14106. * @param [in] fp File pointer to write to.
  14107. * @param [in] name Header/footer name.
  14108. * @param [in] header Encryption header.
  14109. * @param [in] data DER data.
  14110. * @param [in] len Length of DER data.
  14111. * @return 0 on success.
  14112. * @return MEMORY_E when dynamic memory allocation fails.
  14113. */
  14114. int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header,
  14115. const unsigned char *data, long len)
  14116. {
  14117. int err = 0;
  14118. char* pem = NULL;
  14119. word32 pemLen = 0;
  14120. /* Validate parameters. */
  14121. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14122. (data == NULL)) {
  14123. err = 1;
  14124. }
  14125. /* Encode into a buffer. */
  14126. if ((!err) && (pem_write_data(name, header, data, len, &pem, &pemLen) !=
  14127. 0)) {
  14128. pemLen = 0;
  14129. err = 1;
  14130. }
  14131. /* Write PEM to a file. */
  14132. if ((!err) && (XFWRITE(pem, 1, pemLen, fp) != pemLen)) {
  14133. pemLen = 0;
  14134. }
  14135. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14136. return (int)pemLen;
  14137. }
  14138. #endif
  14139. /* Get EVP cipher info from encryption header string.
  14140. *
  14141. * @param [in] header Encryption header.
  14142. * @param [out] cipher EVP Cipher info.
  14143. * @return 1 on success.
  14144. * @return 0 on failure.
  14145. */
  14146. int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header, EncryptedInfo* cipher)
  14147. {
  14148. int res = 1;
  14149. /* Validate parameters. */
  14150. if ((header == NULL) || (cipher == NULL)) {
  14151. res = 0;
  14152. }
  14153. if (res == 1) {
  14154. XMEMSET(cipher, 0, sizeof(*cipher));
  14155. if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0) {
  14156. res = 0;
  14157. }
  14158. }
  14159. return res;
  14160. }
  14161. /* Apply cipher to DER data.
  14162. *
  14163. * @param [in] cipher EVP cipher info.
  14164. * @param [in, out] data On in, encrypted DER data.
  14165. * On out, unencrypted DER data.
  14166. * @param [in, out] len On in, length of encrypted DER data.
  14167. * On out, length of unencrypted DER data.
  14168. * @param [in] cb Password callback.
  14169. * @param [in] ctx Context for password callback.
  14170. * @return 1 on success.
  14171. * @return 0 on failure.
  14172. */
  14173. int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len,
  14174. wc_pem_password_cb* cb, void* ctx)
  14175. {
  14176. int ret = 1;
  14177. char password[NAME_SZ];
  14178. int passwordSz = 0;
  14179. /* Validate parameters. */
  14180. if ((cipher == NULL) || (data == NULL) || (len == NULL) || (cb == NULL)) {
  14181. ret = 0;
  14182. }
  14183. if (ret == 1) {
  14184. /* Get password and length. */
  14185. passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx);
  14186. if (passwordSz < 0) {
  14187. ret = 0;
  14188. }
  14189. }
  14190. if (ret == 1) {
  14191. /* Decrypt the data using password and MD5. */
  14192. if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password,
  14193. passwordSz, WC_MD5) != 0) {
  14194. ret = WOLFSSL_FAILURE;
  14195. }
  14196. }
  14197. if (passwordSz > 0) {
  14198. /* Ensure password is erased from memory. */
  14199. ForceZero(password, (word32)passwordSz);
  14200. }
  14201. return ret;
  14202. }
  14203. #endif /* !NO_CERTS */
  14204. #endif /* OPENSSL_EXTRA */
  14205. #ifdef OPENSSL_ALL
  14206. #if !defined(NO_PWDBASED) && defined(HAVE_PKCS8)
  14207. #if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \
  14208. !defined(NO_STDIO_FILESYSTEM))
  14209. /* Encrypt the key into a buffer using PKCS$8 and a password.
  14210. *
  14211. * @param [in] pkey Private key to encrypt.
  14212. * @param [in] enc EVP cipher.
  14213. * @param [in] passwd Password to encrypt with.
  14214. * @param [in] passwdSz Number of bytes in password.
  14215. * @param [in] key Buffer to hold encrypted key.
  14216. * @param [in, out] keySz On in, size of buffer in bytes.
  14217. * On out, size of encrypted key in bytes.
  14218. * @return 0 on success.
  14219. * @return BAD_FUNC_ARG when EVP cipher not supported.
  14220. */
  14221. static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey,
  14222. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key,
  14223. word32* keySz)
  14224. {
  14225. int ret;
  14226. WC_RNG rng;
  14227. /* Initialize a new random number generator. */
  14228. ret = wc_InitRng(&rng);
  14229. if (ret == 0) {
  14230. int encAlgId = 0;
  14231. /* Convert EVP cipher to a support encryption id. */
  14232. #ifndef NO_DES3
  14233. if (enc == EVP_DES_CBC) {
  14234. encAlgId = DESb;
  14235. }
  14236. else if (enc == EVP_DES_EDE3_CBC) {
  14237. encAlgId = DES3b;
  14238. }
  14239. else
  14240. #endif
  14241. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  14242. #ifdef WOLFSSL_AES_128
  14243. if (enc == EVP_AES_128_CBC) {
  14244. encAlgId = AES128CBCb;
  14245. }
  14246. else
  14247. #endif
  14248. #ifdef WOLFSSL_AES_256
  14249. if (enc == EVP_AES_256_CBC) {
  14250. encAlgId = AES256CBCb;
  14251. }
  14252. else
  14253. #endif
  14254. #endif
  14255. {
  14256. ret = BAD_FUNC_ARG;
  14257. }
  14258. if (ret == 0) {
  14259. /* Encrypt private into buffer. */
  14260. ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz,
  14261. key, keySz, passwd, passwdSz, PKCS5, PBES2, encAlgId,
  14262. NULL, 0, WC_PKCS12_ITT_DEFAULT, &rng, NULL);
  14263. if (ret > 0) {
  14264. *keySz = (word32)ret;
  14265. }
  14266. }
  14267. /* Dispose of random number generator. */
  14268. wc_FreeRng(&rng);
  14269. }
  14270. return ret;
  14271. }
  14272. /* Encode private key in PKCS#8 format.
  14273. *
  14274. * @param [in] pkey Private key.
  14275. * @param [out] key Buffer to hold encoding.
  14276. * @param [in, out] keySz On in, size of buffer in bytes.
  14277. * @param On out, size of encoded key in bytes.
  14278. * @return 0 on success.
  14279. */
  14280. static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz)
  14281. {
  14282. int ret = 0;
  14283. int algId;
  14284. const byte* curveOid;
  14285. word32 oidSz;
  14286. /* Get the details of the private key. */
  14287. #ifdef HAVE_ECC
  14288. if (pkey->type == EVP_PKEY_EC) {
  14289. /* ECC private and get curve OID information. */
  14290. algId = ECDSAk;
  14291. ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid,
  14292. &oidSz);
  14293. }
  14294. else
  14295. #endif
  14296. if (pkey->type == EVP_PKEY_RSA) {
  14297. /* RSA private has no curve information. */
  14298. algId = RSAk;
  14299. curveOid = NULL;
  14300. oidSz = 0;
  14301. }
  14302. else {
  14303. ret = NOT_COMPILED_IN;
  14304. }
  14305. if (ret >= 0) {
  14306. /* Encode private key in PKCS#8 format. */
  14307. ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr,
  14308. pkey->pkey_sz, algId, curveOid, oidSz);
  14309. }
  14310. return ret;
  14311. }
  14312. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14313. *
  14314. * @param [out] pem Buffer holding PEM encoding.
  14315. * @param [out] pemSz Size of data in buffer in bytes.
  14316. * @param [in] pkey Private key to write.
  14317. * @param [in] enc Encryption information to use. May be NULL.
  14318. * @param [in] passwd Password to use when encrypting. May be NULL.
  14319. * @param [in] passwdSz Size of password in bytes.
  14320. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14321. * NULL.
  14322. * @param [in] ctx Context for password callback.
  14323. * @return Length of PEM encoding on success.
  14324. * @return 0 on failure.
  14325. */
  14326. static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz,
  14327. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14328. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14329. {
  14330. int res = 1;
  14331. int ret = 0;
  14332. char password[NAME_SZ];
  14333. byte* key = NULL;
  14334. word32 keySz;
  14335. int type = PKCS8_PRIVATEKEY_TYPE;
  14336. /* Validate parameters. */
  14337. if (pkey == NULL) {
  14338. res = 0;
  14339. }
  14340. if (res == 1) {
  14341. /* Guestimate key size and PEM size. */
  14342. if (pem_pkcs8_encode(pkey, NULL, &keySz) != LENGTH_ONLY_E) {
  14343. res = 0;
  14344. }
  14345. }
  14346. if (res == 1) {
  14347. if (enc != NULL) {
  14348. /* Add on enough for extra DER data when encrypting. */
  14349. keySz += 128;
  14350. }
  14351. /* PEM encoding size from DER size. */
  14352. *pemSz = (int)(keySz + 2) / 3 * 4;
  14353. *pemSz += (*pemSz + 63) / 64;
  14354. /* Header and footer. */
  14355. if (enc != NULL) {
  14356. /* Name is: 'ENCRYPTED PRIVATE KEY'. */
  14357. *pemSz += 74;
  14358. }
  14359. else {
  14360. /* Name is: 'PRIVATE KEY'. */
  14361. *pemSz += 54;
  14362. }
  14363. /* Allocate enough memory to hold PEM encoded encrypted key. */
  14364. *pem = (byte*)XMALLOC((size_t)*pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14365. if (*pem == NULL) {
  14366. res = 0;
  14367. }
  14368. else {
  14369. /* Use end of PEM buffer for key data. */
  14370. key = *pem + *pemSz - keySz;
  14371. }
  14372. }
  14373. if ((res == 1) && (enc != NULL)) {
  14374. /* Set type for PEM. */
  14375. type = PKCS8_ENC_PRIVATEKEY_TYPE;
  14376. if (passwd == NULL) {
  14377. /* Get the password by using callback. */
  14378. passwdSz = cb(password, sizeof(password), 1, ctx);
  14379. if (passwdSz < 0) {
  14380. res = 0;
  14381. }
  14382. passwd = password;
  14383. }
  14384. if (res == 1) {
  14385. /* Encrypt the private key. */
  14386. ret = pem_pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz);
  14387. if (ret <= 0) {
  14388. res = 0;
  14389. }
  14390. }
  14391. /* Zeroize the password from memory. */
  14392. if ((password == passwd) && (passwdSz > 0)) {
  14393. ForceZero(password, (word32)passwdSz);
  14394. }
  14395. }
  14396. else if ((res == 1) && (enc == NULL)) {
  14397. /* Set type for PEM. */
  14398. type = PKCS8_PRIVATEKEY_TYPE;
  14399. /* Encode private key in PKCS#8 format. */
  14400. ret = pem_pkcs8_encode(pkey, key, &keySz);
  14401. if (ret < 0) {
  14402. res = 0;
  14403. }
  14404. }
  14405. if (res == 1) {
  14406. /* Encode PKCS#8 formatted key to PEM. */
  14407. ret = wc_DerToPemEx(key, keySz, *pem, (word32)*pemSz, NULL, type);
  14408. if (ret < 0) {
  14409. res = 0;
  14410. }
  14411. else {
  14412. *pemSz = ret;
  14413. }
  14414. }
  14415. /* Return appropriate return code. */
  14416. return (res == 0) ? 0 : ret;
  14417. }
  14418. #endif /* !NO_BIO || (!NO_FILESYSTEM && !NO_STDIO_FILESYSTEM) */
  14419. #ifndef NO_BIO
  14420. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14421. *
  14422. * TODO: OpenSSL returns 1 and 0 only.
  14423. *
  14424. * @param [in] bio BIO to write to.
  14425. * @param [in] pkey Private key to write.
  14426. * @param [in] enc Encryption information to use. May be NULL.
  14427. * @param [in] passwd Password to use when encrypting. May be NULL.
  14428. * @param [in] passwdSz Size of password in bytes.
  14429. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14430. * NULL.
  14431. * @param [in] ctx Context for password callback.
  14432. * @return Length of PEM encoding on success.
  14433. * @return 0 on failure.
  14434. */
  14435. int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio,
  14436. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14437. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14438. {
  14439. byte* pem = NULL;
  14440. int pemSz = 0;
  14441. int res = 1;
  14442. /* Validate parameters. */
  14443. if (bio == NULL) {
  14444. res = 0;
  14445. }
  14446. if (res == 1) {
  14447. /* Write private key to memory. */
  14448. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14449. passwdSz, cb, ctx);
  14450. }
  14451. /* Write encoded key to BIO. */
  14452. if ((res >= 1) && (wolfSSL_BIO_write(bio, pem, pemSz) != pemSz)) {
  14453. res = 0;
  14454. }
  14455. /* Dispose of dynamically allocated memory (pem and key). */
  14456. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14457. return res;
  14458. }
  14459. #endif /* !NO_BIO */
  14460. #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
  14461. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14462. *
  14463. * TODO: OpenSSL returns 1 and 0 only.
  14464. *
  14465. * @param [in] f File pointer.
  14466. * @param [in] pkey Private key to write.
  14467. * @param [in] enc Encryption information to use. May be NULL.
  14468. * @param [in] passwd Password to use when encrypting. May be NULL.
  14469. * @param [in] passwdSz Size of password in bytes.
  14470. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14471. * NULL.
  14472. * @param [in] ctx Context for password callback.
  14473. * @return Length of PEM encoding on success.
  14474. * @return 0 on failure.
  14475. */
  14476. int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey,
  14477. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz,
  14478. wc_pem_password_cb* cb, void* ctx)
  14479. {
  14480. byte* pem = NULL;
  14481. int pemSz = 0;
  14482. int res = 1;
  14483. /* Validate parameters. */
  14484. if (f == XBADFILE) {
  14485. res = 0;
  14486. }
  14487. if (res == 1) {
  14488. /* Write private key to memory. */
  14489. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14490. passwdSz, cb, ctx);
  14491. }
  14492. /* Write encoded key to file. */
  14493. if ((res >= 1) && (XFWRITE(pem, 1, (size_t)pemSz, f) != (size_t)pemSz)) {
  14494. res = 0;
  14495. }
  14496. /* Dispose of dynamically allocated memory (pem and key). */
  14497. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14498. return res;
  14499. }
  14500. #endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  14501. #endif /* !NO_PWDBASED && HAVE_PKCS8 */
  14502. #endif /* OPENSSL_ALL */
  14503. /*******************************************************************************
  14504. * END OF GENERIC PUBLIC KEY PEM APIs
  14505. ******************************************************************************/
  14506. #endif /* !WOLFSSL_PK_INCLUDED */