pk.c 339 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102
  1. /* pk.c
  2. *
  3. * Copyright (C) 2006-2022 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. #if !defined(WOLFSSL_PK_INCLUDED)
  26. #ifndef WOLFSSL_IGNORE_FILE_WARN
  27. #warning pk.c does not need to be compiled separately from ssl.c
  28. #endif
  29. #else
  30. #ifndef NO_RSA
  31. #include <wolfssl/wolfcrypt/rsa.h>
  32. #endif
  33. #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) && defined(WOLFSSL_KEY_GEN) && \
  34. (!defined(HAVE_USER_RSA) || defined(HAVE_ECC) || \
  35. (!defined(NO_DSA) && !defined(HAVE_SELFTEST)))
  36. /* Forward declaration for wolfSSL_PEM_write_bio_RSA_PUBKEY,
  37. * wolfSSL_PEM_write_bio_DSA_PUBKEY and wolfSSL_PEM_write_bio_EC_PUBKEY.
  38. * Implementation in ssl.c.
  39. */
  40. static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key);
  41. #endif
  42. /*******************************************************************************
  43. * COMMON FUNCTIONS
  44. ******************************************************************************/
  45. #if defined(OPENSSL_EXTRA)
  46. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  47. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  48. /* Convert the PEM encoding in the buffer to DER.
  49. *
  50. * @param [in] pem Buffer containing PEM encoded data.
  51. * @param [in] pemSz Size of data in buffer in bytes.
  52. * @param [in] cb Password callback when PEM encrypted.
  53. * @param [in] pass NUL terminated string for passphrase when PEM
  54. * encrypted.
  55. * @param [in] keyType Type of key to match against PEM header/footer.
  56. * @param [out] keyFormat Format of key.
  57. * @param [out] der Buffer holding DER encoding.
  58. * @return Negative on failure.
  59. * @return Number of bytes consumed on success.
  60. */
  61. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  62. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  63. {
  64. #ifdef WOLFSSL_SMALL_STACK
  65. EncryptedInfo* info = NULL;
  66. #else
  67. EncryptedInfo info[1];
  68. #endif /* WOLFSSL_SMALL_STACK */
  69. wc_pem_password_cb* localCb = NULL;
  70. int ret = 0;
  71. if (cb != NULL) {
  72. localCb = cb;
  73. }
  74. else if (pass != NULL) {
  75. localCb = wolfSSL_PEM_def_callback;
  76. }
  77. #ifdef WOLFSSL_SMALL_STACK
  78. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  79. DYNAMIC_TYPE_ENCRYPTEDINFO);
  80. if (info == NULL) {
  81. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  82. ret = MEMORY_E;
  83. }
  84. #endif /* WOLFSSL_SMALL_STACK */
  85. if (ret == 0) {
  86. XMEMSET(info, 0, sizeof(EncryptedInfo));
  87. info->passwd_cb = localCb;
  88. info->passwd_userdata = pass;
  89. /* Do not strip PKCS8 header */
  90. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  91. info, keyFormat);
  92. if (ret < 0) {
  93. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  94. }
  95. }
  96. if (ret >= 0) {
  97. ret = (int)info->consumed;
  98. }
  99. #ifdef WOLFSSL_SMALL_STACK
  100. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  101. #endif
  102. return ret;
  103. }
  104. #endif
  105. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  106. #ifndef NO_BIO
  107. /* Read PEM data from a BIO and decode to DER in a new buffer.
  108. *
  109. * @param [in, out] bio BIO object to read with.
  110. * @param [in] cb Password callback when PEM encrypted.
  111. * @param [in] pass NUL terminated string for passphrase when PEM
  112. * encrypted.
  113. * @param [in] keyType Type of key to match against PEM header/footer.
  114. * @param [out] keyFormat Format of key.
  115. * @param [out] der Buffer holding DER encoding.
  116. * @return Negative on failure.
  117. * @return Number of bytes consumed on success.
  118. */
  119. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  120. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  121. {
  122. int ret;
  123. char* mem = NULL;
  124. int memSz;
  125. int alloced = 0;
  126. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  127. if (ret == 0) {
  128. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  129. /* Write left over data back to BIO if not a file BIO */
  130. if ((ret > 0) && ((memSz - ret) > 0) &&
  131. (bio->type != WOLFSSL_BIO_FILE)) {
  132. int res;
  133. res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  134. if (res != memSz - ret) {
  135. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  136. if (res < 0) {
  137. ret = res;
  138. }
  139. else {
  140. ret = MEMORY_E;
  141. }
  142. }
  143. }
  144. if (alloced) {
  145. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  146. }
  147. }
  148. return ret;
  149. }
  150. #endif /* !NO_BIO */
  151. #if !defined(NO_FILESYSTEM)
  152. /* Read PEM data from a file and decode to DER in a new buffer.
  153. *
  154. * @param [in] fp File pointer to read with.
  155. * @param [in] cb Password callback when PEM encrypted.
  156. * @param [in] pass NUL terminated string for passphrase when PEM
  157. * encrypted.
  158. * @param [in] keyType Type of key to match against PEM header/footer.
  159. * @param [out] keyFormat Format of key.
  160. * @param [out] der Buffer holding DER encoding.
  161. * @return Negative on failure.
  162. * @return Number of bytes consumed on success.
  163. */
  164. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  165. int keyType, int* keyFormat, DerBuffer** der)
  166. {
  167. int ret;
  168. char* mem = NULL;
  169. int memSz;
  170. ret = wolfssl_read_file(fp, &mem, &memSz);
  171. if (ret == 0) {
  172. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  173. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  174. }
  175. return ret;
  176. }
  177. #endif /* !NO_FILESYSTEM */
  178. #endif
  179. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) \
  180. && !defined(HAVE_USER_RSA)) || !defined(WOLFCRYPT_ONLY))
  181. /* Convert DER data to PEM in an allocated buffer.
  182. *
  183. * @param [in] der Buffer containing DER data.
  184. * @param [in] derSz Size of DER data in bytes.
  185. * @param [in] type Type of key being encoded.
  186. * @param [in] heap Heap hint for dynamic memory allocation.
  187. * @param [out] out Allocated buffer containing PEM.
  188. * @param [out] outSz Size of PEM encoding.
  189. * @return WOLFSSL_FAILURE on error.
  190. * @return WOLFSSL_SUCCESS on success.
  191. */
  192. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  193. void* heap, byte** out, int* outSz)
  194. {
  195. int ret = WOLFSSL_SUCCESS;
  196. int pemSz;
  197. byte* pem = NULL;
  198. (void)heap;
  199. pemSz = wc_DerToPem(der, derSz, NULL, 0, type);
  200. if (pemSz < 0) {
  201. ret = WOLFSSL_FAILURE;
  202. }
  203. if (ret == WOLFSSL_SUCCESS) {
  204. pem = (byte*)XMALLOC(pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  205. if (pem == NULL) {
  206. ret = WOLFSSL_FAILURE;
  207. }
  208. }
  209. if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, derSz, pem, pemSz,
  210. type) < 0)) {
  211. ret = WOLFSSL_FAILURE;
  212. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  213. pem = NULL;
  214. }
  215. *out = pem;
  216. *outSz = pemSz;
  217. return ret;
  218. }
  219. #ifndef NO_BIO
  220. /* Write the DER data as PEM into BIO.
  221. *
  222. * @param [in] der Buffer containing DER data.
  223. * @param [in] derSz Size of DER data in bytes.
  224. * @param [in, out] bio BIO object to write with.
  225. * @param [in] type Type of key being encoded.
  226. * @return WOLFSSL_FAILURE on error.
  227. * @return WOLFSSL_SUCCESS on success.
  228. */
  229. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  230. WOLFSSL_BIO* bio, int type)
  231. {
  232. int ret;
  233. int pemSz;
  234. byte* pem = NULL;
  235. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  236. if (ret == WOLFSSL_SUCCESS) {
  237. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  238. if (len != pemSz) {
  239. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  240. ret = WOLFSSL_FAILURE;
  241. }
  242. }
  243. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  244. return ret;
  245. }
  246. #endif
  247. #endif
  248. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \
  249. !defined(HAVE_USER_RSA)) || (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA))
  250. #if !defined(NO_FILESYSTEM)
  251. /* Write the DER data as PEM into file pointer.
  252. *
  253. * @param [in] der Buffer containing DER data.
  254. * @param [in] derSz Size of DER data in bytes.
  255. * @param [in] fp File pointer to write with.
  256. * @param [in] type Type of key being encoded.
  257. * @param [in] heap Heap hint for dynamic memory allocation.
  258. * @return WOLFSSL_FAILURE on error.
  259. * @return WOLFSSL_SUCCESS on success.
  260. */
  261. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  262. XFILE fp, int type, void* heap)
  263. {
  264. int ret;
  265. int pemSz;
  266. byte* pem = NULL;
  267. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  268. if (ret == WOLFSSL_SUCCESS) {
  269. int len = (int)XFWRITE(pem, 1, pemSz, fp);
  270. if (len != pemSz) {
  271. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  272. ret = WOLFSSL_FAILURE;
  273. }
  274. }
  275. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  276. return ret;
  277. }
  278. #endif
  279. #endif
  280. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  281. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  282. defined(HAVE_ECC))
  283. /* Print the number bn in hex with name field and indentation indent to file fp.
  284. *
  285. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  286. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  287. *
  288. * @param [in] fp File pointer to write to.
  289. * @param [in] indent Number of spaces to prepend to each line.
  290. * @param [in] field Name of field.
  291. * @param [in] bn Big number to print.
  292. * @return 1 on success.
  293. * @return 0 on failure.
  294. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  295. * bn or NULL.
  296. */
  297. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  298. const WOLFSSL_BIGNUM* bn)
  299. {
  300. static const int HEX_INDENT = 4;
  301. static const int MAX_DIGITS_PER_LINE = 30;
  302. int ret = 1;
  303. int i = 0;
  304. char* buf = NULL;
  305. /* Internal function - assume parameters are valid. */
  306. /* Convert BN to hexadecimal character array (allocates buffer). */
  307. buf = wolfSSL_BN_bn2hex(bn);
  308. if (buf == NULL) {
  309. ret = 0;
  310. }
  311. if (ret == 1) {
  312. /* Print leading spaces, name and spaces before data. */
  313. if (indent > 0) {
  314. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  315. ret = 0;
  316. }
  317. }
  318. if (ret == 1) {
  319. if (XFPRINTF(fp, "%s:\n", field) < 0)
  320. ret = 0;
  321. }
  322. if (ret == 1) {
  323. if (indent > 0) {
  324. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  325. ret = 0;
  326. }
  327. }
  328. if (ret == 1) {
  329. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  330. ret = 0;
  331. }
  332. if (ret == 1) {
  333. /* Print first byte - should always exist. */
  334. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  335. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  336. ret = 0;
  337. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  338. ret = 0;
  339. }
  340. }
  341. if (ret == 1) {
  342. /* Print each hexadecimal character with byte separator. */
  343. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  344. /* Byte separator every two nibbles - one byte. */
  345. if (XFPRINTF(fp, ":") < 0) {
  346. ret = 0;
  347. break;
  348. }
  349. /* New line after every 15 bytes - 30 nibbles. */
  350. if (i % MAX_DIGITS_PER_LINE == 0) {
  351. if (XFPRINTF(fp, "\n") < 0) {
  352. ret = 0;
  353. break;
  354. }
  355. if (indent > 0) {
  356. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  357. ret = 0;
  358. break;
  359. }
  360. }
  361. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  362. ret = 0;
  363. break;
  364. }
  365. }
  366. /* Print two nibbles - one byte. */
  367. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  368. ret = 0;
  369. break;
  370. }
  371. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  372. ret = 0;
  373. break;
  374. }
  375. }
  376. /* Ensure on new line after data. */
  377. if (XFPRINTF(fp, "\n") < 0) {
  378. ret = 0;
  379. }
  380. }
  381. /* Dispose of any allocated character array. */
  382. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  383. return ret;
  384. }
  385. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  386. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  387. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  388. #if defined(OPENSSL_EXTRA)
  389. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA) && \
  390. !defined(HAVE_FAST_RSA)
  391. /* snprintf() must be available */
  392. /* Maximum number of extra indent spaces on each line. */
  393. #define PRINT_NUM_MAX_INDENT 48
  394. /* Maximum size of a line containing a value. */
  395. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  396. /* Number of leading spaces on each line. */
  397. #define PRINT_NUM_INDENT_CNT 4
  398. /* Indent spaces for number lines. */
  399. #define PRINT_NUM_INDENT " "
  400. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  401. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  402. /* Print indent to BIO.
  403. *
  404. * @param [in] bio BIO object to write to.
  405. * @param [in] line Buffer to put characters to before writing to BIO.
  406. * @param [in] lineLen Length of buffer.
  407. * @return 1 on success.
  408. * @return 0 on failure.
  409. */
  410. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  411. int indent)
  412. {
  413. int ret = 1;
  414. if (indent > 0) {
  415. /* Print indent spaces. */
  416. int len_wanted = XSNPRINTF(line, lineLen, "%*s", indent, " ");
  417. if (len_wanted >= lineLen) {
  418. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  419. ret = 0;
  420. }
  421. else {
  422. /* Write indents string to BIO */
  423. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  424. ret = 0;
  425. }
  426. }
  427. }
  428. return ret;
  429. }
  430. /* Print out name, and value in decimal and hex to BIO.
  431. *
  432. * @param [in] bio BIO object to write to.
  433. * @param [in] value MP integer to write.
  434. * @param [in] name Name of value.
  435. * @param [in] indent Number of leading spaces before line.
  436. * @return 1 on success.
  437. * @return 0 on failure.
  438. */
  439. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  440. const char* name, int indent)
  441. {
  442. int ret = 1;
  443. int len;
  444. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  445. word32 v;
  446. /* Get the length of hex encoded value. */
  447. len = mp_unsigned_bin_size(value);
  448. /* Value must no more than 32-bits - 4 bytes. */
  449. if ((len < 0) || (len > 4)) {
  450. WOLFSSL_ERROR_MSG("Error getting exponent size");
  451. ret = 0;
  452. }
  453. if (ret == 1) {
  454. /* Print any indent spaces. */
  455. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  456. }
  457. if (ret == 1) {
  458. /* Get 32-bits of value. */
  459. v = (word32)value->dp[0];
  460. /* Print the line to the string. */
  461. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  462. v);
  463. if (len >= (int)sizeof(line)) {
  464. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  465. ret = 0;
  466. } else {
  467. /* Write string to BIO */
  468. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  469. ret = 0;
  470. }
  471. }
  472. }
  473. return ret;
  474. }
  475. /* Print out name and multi-precision number to BIO.
  476. *
  477. * @param [in] bio BIO object to write to.
  478. * @param [in] num MP integer to write.
  479. * @param [in] name Name of value.
  480. * @param [in] indent Number of leading spaces before each line.
  481. * @return 1 on success.
  482. * @return 0 on failure.
  483. */
  484. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  485. int indent)
  486. {
  487. int ret = 1;
  488. int rawLen = 0;
  489. byte* rawKey = NULL;
  490. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  491. int li = 0; /* Line index. */
  492. int i;
  493. /* Allocate a buffer to hold binary encoded data. */
  494. rawLen = mp_unsigned_bin_size(num);
  495. if (rawLen == 0) {
  496. WOLFSSL_ERROR_MSG("Invalid number");
  497. ret = 0;
  498. }
  499. if (ret == 1) {
  500. rawKey = (byte*)XMALLOC(rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  501. if (rawKey == NULL) {
  502. WOLFSSL_ERROR_MSG("Memory allocation error");
  503. ret = 0;
  504. }
  505. }
  506. /* Encode number as big-endian byte array. */
  507. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  508. ret = 0;
  509. }
  510. if (ret == 1) {
  511. /* Print any indent spaces. */
  512. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  513. }
  514. if (ret == 1) {
  515. /* Print header string line to string. */
  516. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  517. if (li >= (int)sizeof(line)) {
  518. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  519. ret = 0;
  520. }
  521. else {
  522. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  523. ret = 0;
  524. }
  525. }
  526. }
  527. if (ret == 1) {
  528. /* Print any indent spaces. */
  529. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  530. }
  531. if (ret == 1) {
  532. /* Start first digit line with spaces.
  533. * Writing out zeros ensures number is a positive value. */
  534. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  535. mp_leading_bit(num) ? "00:" : "");
  536. if (li >= (int)sizeof(line)) {
  537. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  538. ret = 0;
  539. }
  540. }
  541. /* Put out each line of numbers. */
  542. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  543. /* Encode another byte as 2 hex digits and append colon. */
  544. int len_wanted = XSNPRINTF(line + li, sizeof(line) - li, "%02x:",
  545. rawKey[i]);
  546. /* Check if there was room -- if not, print the current line, not
  547. * including the newest octet.
  548. */
  549. if (len_wanted >= (int)sizeof(line) - li) {
  550. /* bump current octet to the next line. */
  551. --i;
  552. /* More bytes coming so add a line break. */
  553. line[li++] = '\n';
  554. /* Write out the line. */
  555. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  556. ret = 0;
  557. }
  558. if (ret == 1) {
  559. /* Print any indent spaces. */
  560. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  561. }
  562. /* Put the leading spaces on new line. */
  563. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  564. li = PRINT_NUM_INDENT_CNT;
  565. }
  566. else {
  567. li += len_wanted;
  568. }
  569. }
  570. if (ret == 1) {
  571. /* Put out last line - replace last colon with carriage return. */
  572. line[li-1] = '\n';
  573. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  574. ret = 0;
  575. }
  576. }
  577. /* Dispose of any allocated data. */
  578. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  579. return ret;
  580. }
  581. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA && !HAVE_FAST_RSA */
  582. #if !defined(NO_RSA) || (!defined(NO_DH) && !defined(NO_CERTS) && \
  583. defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0))
  584. /* Uses the DER SEQUENCE to determine size of DER data.
  585. *
  586. * Outer SEQUENCE encapsulates all the DER encoding.
  587. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  588. *
  589. * @param [in] seq Buffer holding DER encoded sequence.
  590. * @param [in] len Length of data in buffer (may be larger than SEQ).
  591. * @return Size of complete DER encoding on success.
  592. * @return 0 on failure.
  593. */
  594. static int wolfssl_der_length(const unsigned char* seq, int len)
  595. {
  596. int ret = 0;
  597. word32 i = 0;
  598. /* Check it is a SEQUENCE and get the length of the underlying data.
  599. * i is updated to be after SEQUENCE header bytes.
  600. */
  601. if (GetSequence_ex(seq, &i, &ret, len, 0) >= 0) {
  602. /* Add SEQUENCE header length to underlying data length. */
  603. ret += (int)i;
  604. }
  605. return ret;
  606. }
  607. #endif /* !NO_RSA */
  608. #endif /* OPENSSL_EXTRA */
  609. #if !defined(NO_RSA) || !defined(NO_DH)
  610. /* Too many defines to check explicitly - prototype it and always include
  611. * for RSA and DH. */
  612. WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local);
  613. /* Make a random number generator or get global if possible.
  614. *
  615. * Global may not be available and NULL will be returned.
  616. *
  617. * @param [in, out] rng Local random number generator.
  618. * @param [out] local Local random number generator returned.
  619. * @return NULL on failure.
  620. * @return A random number generator object.
  621. */
  622. WC_RNG* wolfssl_make_rng(WC_RNG* rng, int* local)
  623. {
  624. WC_RNG* ret = NULL;
  625. /* Assume not local until one created. */
  626. *local = 0;
  627. #ifdef WOLFSSL_SMALL_STACK
  628. /* Allocate RNG object . */
  629. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  630. #endif
  631. /* Check we have a local RNG object and initialize. */
  632. if ((rng != NULL) && (wc_InitRng(rng) == 0)) {
  633. ret = rng;
  634. *local = 1;
  635. }
  636. if (ret == NULL) {
  637. #ifdef HAVE_GLOBAL_RNG
  638. WOLFSSL_MSG("Bad RNG Init, trying global");
  639. /* Get the global random number generator instead. */
  640. ret = wolfssl_get_global_rng();
  641. if (ret == NULL) {
  642. /* Create a global random if possible. */
  643. (void)wolfSSL_RAND_Init();
  644. ret = wolfssl_get_global_rng();
  645. }
  646. #else
  647. WOLFSSL_ERROR_MSG("Bad RNG Init");
  648. #endif
  649. }
  650. if (ret != rng) {
  651. #ifdef WOLFSSL_SMALL_STACK
  652. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  653. #endif
  654. }
  655. return ret;
  656. }
  657. #endif
  658. /*******************************************************************************
  659. * START OF RSA API
  660. ******************************************************************************/
  661. #ifndef NO_RSA
  662. /*
  663. * RSA METHOD
  664. * Could be used to hold function pointers to implementations of RSA operations.
  665. */
  666. #if defined(OPENSSL_EXTRA)
  667. /* Return a blank RSA method and set the name and flags.
  668. *
  669. * Only one implementation of RSA operations.
  670. * name is duplicated.
  671. *
  672. * @param [in] name Name to use in method.
  673. * @param [in] flags Flags to set into method.
  674. * @return Newly allocated RSA method on success.
  675. * @return NULL on failure.
  676. */
  677. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  678. {
  679. WOLFSSL_RSA_METHOD* meth = NULL;
  680. int name_len = 0;
  681. int err;
  682. /* Validate name is not NULL. */
  683. err = (name == NULL);
  684. if (!err) {
  685. /* Allocate an RSA METHOD to return. */
  686. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  687. DYNAMIC_TYPE_OPENSSL);
  688. err = (meth == NULL);
  689. }
  690. if (!err) {
  691. XMEMSET(meth, 0, sizeof(*meth));
  692. meth->flags = flags;
  693. meth->dynamic = 1;
  694. name_len = (int)XSTRLEN(name);
  695. meth->name = (char*)XMALLOC(name_len + 1, NULL, DYNAMIC_TYPE_OPENSSL);
  696. err = (meth->name == NULL);
  697. }
  698. if (!err) {
  699. XMEMCPY(meth->name, name, name_len+1);
  700. }
  701. if (err) {
  702. /* meth->name won't be allocated on error. */
  703. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  704. }
  705. return meth;
  706. }
  707. /* Default RSA method is one with wolfSSL name and no flags.
  708. *
  709. * @return Newly allocated wolfSSL RSA method on success.
  710. * @return NULL on failure.
  711. */
  712. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  713. {
  714. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  715. 0, /* No flags. */
  716. (char*)"wolfSSL RSA",
  717. 0 /* Static definition. */
  718. };
  719. return &wolfssl_rsa_meth;
  720. }
  721. /* Dispose of RSA method and allocated data.
  722. *
  723. * @param [in] meth RSA method to free.
  724. */
  725. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  726. {
  727. /* Free method if available and dynamically allocated. */
  728. if ((meth != NULL) && meth->dynamic) {
  729. /* Name was duplicated and must be freed. */
  730. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  731. /* Dispose of RSA method. */
  732. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  733. }
  734. }
  735. #ifndef NO_WOLFSSL_STUB
  736. /* Stub function for any RSA method setting function.
  737. *
  738. * Nothing is stored - not even flags or name.
  739. *
  740. * @param [in] meth RSA method.
  741. * @param [in] p A pointer.
  742. * @return 1 to indicate success.
  743. */
  744. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  745. {
  746. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  747. (void)meth;
  748. (void)p;
  749. return 1;
  750. }
  751. #endif /* !NO_WOLFSSL_STUB */
  752. #endif /* OPENSSL_EXTRA */
  753. /*
  754. * RSA constructor/deconstructor APIs
  755. */
  756. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  757. /* Dispose of RSA key and allocated data.
  758. *
  759. * Cannot use rsa after this call.
  760. *
  761. * @param [in] rsa RSA key to free.
  762. */
  763. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  764. {
  765. int doFree = 1;
  766. WOLFSSL_ENTER("wolfSSL_RSA_free");
  767. /* Validate parameter. */
  768. if (rsa == NULL) {
  769. doFree = 0;
  770. }
  771. if (doFree) {
  772. int isZero;
  773. int err;
  774. /* Decrement reference count. */
  775. wolfSSL_RefDec(&rsa->ref, &isZero, &err);
  776. if (err == 0) {
  777. /* Continue if reference count is zero. */
  778. doFree = isZero;
  779. }
  780. else {
  781. /* Didn't reference decrement so can't free. */
  782. doFree = 0;
  783. }
  784. }
  785. if (doFree) {
  786. void* heap = rsa->heap;
  787. /* Dispose of allocated reference counting data. */
  788. wolfSSL_RefFree(&rsa->ref);
  789. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  790. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  791. #endif
  792. if (rsa->internal != NULL) {
  793. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  794. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  795. /* Check if RNG is owned before freeing it. */
  796. if (rsa->ownRng) {
  797. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  798. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  799. wc_FreeRng(rng);
  800. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  801. }
  802. /* RNG isn't freed by wolfCrypt RSA free. */
  803. }
  804. #endif
  805. /* Dispose of allocated data in wolfCrypt RSA key. */
  806. wc_FreeRsaKey((RsaKey*)rsa->internal);
  807. /* Dispose of memory for wolfCrypt RSA key. */
  808. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  809. }
  810. /* Dispose of external representation of RSA values. */
  811. wolfSSL_BN_clear_free(rsa->iqmp);
  812. wolfSSL_BN_clear_free(rsa->dmq1);
  813. wolfSSL_BN_clear_free(rsa->dmp1);
  814. wolfSSL_BN_clear_free(rsa->q);
  815. wolfSSL_BN_clear_free(rsa->p);
  816. wolfSSL_BN_clear_free(rsa->d);
  817. wolfSSL_BN_free(rsa->e);
  818. wolfSSL_BN_free(rsa->n);
  819. #if defined(OPENSSL_EXTRA)
  820. if (rsa->meth) {
  821. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  822. }
  823. #endif
  824. /* Set back to NULLs for safety. */
  825. ForceZero(rsa, sizeof(*rsa));
  826. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  827. (void)heap;
  828. }
  829. }
  830. /* Allocate and initialize a new RSA key.
  831. *
  832. * wolfSSL API.
  833. *
  834. * @param [in] heap Heap hint.
  835. * @param [in] devId Device identifier value.
  836. * @return RSA key on success.
  837. * @return NULL on failure.
  838. */
  839. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  840. {
  841. WOLFSSL_RSA* rsa = NULL;
  842. RsaKey* key = NULL;
  843. int err = 0;
  844. int rsaKeyInited = 0;
  845. WOLFSSL_ENTER("wolfSSL_RSA_new");
  846. /* Allocate memory for new wolfCrypt RSA key. */
  847. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  848. if (key == NULL) {
  849. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  850. err = 1;
  851. }
  852. if (!err) {
  853. /* Allocate memory for new RSA key. */
  854. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  855. DYNAMIC_TYPE_RSA);
  856. if (rsa == NULL) {
  857. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  858. err = 1;
  859. }
  860. }
  861. if (!err) {
  862. /* Clear all fields of RSA key. */
  863. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  864. /* Cache heap to use for all allocations. */
  865. rsa->heap = heap;
  866. #ifdef OPENSSL_EXTRA
  867. /* Always have a method set. */
  868. rsa->meth = wolfSSL_RSA_get_default_method();
  869. #endif
  870. /* Initialize reference counting. */
  871. wolfSSL_RefInit(&rsa->ref, &err);
  872. }
  873. if (!err) {
  874. /* Initialize wolfCrypt RSA key. */
  875. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  876. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  877. err = 1;
  878. }
  879. else {
  880. rsaKeyInited = 1;
  881. }
  882. }
  883. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  884. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  885. if (!err) {
  886. WC_RNG* rng;
  887. /* Create a local RNG. */
  888. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  889. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  890. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  891. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  892. rng = NULL;
  893. }
  894. rsa->ownRng = 1;
  895. if (rng == NULL) {
  896. /* Get the wolfSSL global RNG - not thread safe. */
  897. rng = wolfssl_get_global_rng();
  898. rsa->ownRng = 0;
  899. }
  900. if (rng == NULL) {
  901. /* Couldn't create global either. */
  902. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  903. err = 1;
  904. }
  905. else {
  906. /* Set the local or global RNG into the wolfCrypt RSA key. */
  907. (void)wc_RsaSetRNG(key, rng);
  908. /* Won't fail as key and rng are not NULL. */
  909. }
  910. }
  911. #endif /* !HAVE_FIPS && !HAVE_USER_RSA && !HAVE_FAST_RSA &&
  912. * WC_RSA_BLINDING */
  913. if (!err) {
  914. /* Set wolfCrypt RSA key into RSA key. */
  915. rsa->internal = key;
  916. /* Data from external RSA key has not been set into internal one. */
  917. rsa->inSet = 0;
  918. }
  919. if (err) {
  920. /* Dispose of any allocated data on error. */
  921. /* No failure after RNG allocation - no need to free RNG. */
  922. if (rsaKeyInited) {
  923. wc_FreeRsaKey(key);
  924. }
  925. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  926. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  927. /* Return NULL. */
  928. rsa = NULL;
  929. }
  930. return rsa;
  931. }
  932. /* Allocate and initialize a new RSA key.
  933. *
  934. * @return RSA key on success.
  935. * @return NULL on failure.
  936. */
  937. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  938. {
  939. /* Call wolfSSL API to do work. */
  940. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  941. }
  942. /* Increments ref count of RSA key.
  943. *
  944. * @param [in, out] rsa RSA key.
  945. * @return 1 on success
  946. * @return 0 on error
  947. */
  948. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  949. {
  950. int err = 0;
  951. if (rsa != NULL) {
  952. wolfSSL_RefInc(&rsa->ref, &err);
  953. }
  954. return !err;
  955. }
  956. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  957. #ifdef OPENSSL_EXTRA
  958. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  959. /* Allocate a new RSA key and make it a copy.
  960. *
  961. * Encodes to and from DER to copy.
  962. *
  963. * @param [in] rsa RSA key to duplicate.
  964. * @return RSA key on success.
  965. * @return NULL on error.
  966. */
  967. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  968. {
  969. WOLFSSL_RSA* ret = NULL;
  970. int derSz = 0;
  971. byte* derBuf = NULL;
  972. int err;
  973. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  974. err = (rsa == NULL);
  975. if (!err) {
  976. /* Create a new RSA key to return. */
  977. ret = wolfSSL_RSA_new();
  978. if (ret == NULL) {
  979. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  980. err = 1;
  981. }
  982. }
  983. if (!err) {
  984. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  985. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  986. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  987. err = 1;
  988. }
  989. }
  990. if (!err) {
  991. /* Decode DER of the RSA public key into new key. */
  992. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  993. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  994. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  995. err = 1;
  996. }
  997. }
  998. /* Dispose of any allocated DER buffer. */
  999. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1000. if (err) {
  1001. /* Disposes of any created RSA key - on error. */
  1002. wolfSSL_RSA_free(ret);
  1003. ret = NULL;
  1004. }
  1005. return ret;
  1006. }
  1007. /* wolfSSL_RSAPrivateKey_dup not supported */
  1008. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1009. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1010. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1011. void* heap);
  1012. #endif
  1013. /*
  1014. * RSA to/from bin APIs
  1015. */
  1016. /* Convert RSA public key data to internal.
  1017. *
  1018. * Creates new RSA key from the DER encoded RSA public key.
  1019. *
  1020. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1021. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1022. * @param [in] derSz Length of the data in the DER buffer.
  1023. * @return RSA key on success.
  1024. * @return NULL on failure.
  1025. */
  1026. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1027. const unsigned char **derBuf, long derSz)
  1028. {
  1029. WOLFSSL_RSA *rsa = NULL;
  1030. int err = 0;
  1031. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1032. /* Validate parameters. */
  1033. if (derBuf == NULL) {
  1034. WOLFSSL_ERROR_MSG("Bad argument");
  1035. err = 1;
  1036. }
  1037. /* Create a new RSA key to return. */
  1038. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1039. WOLFSSL_ERROR_MSG("RSA_new failed");
  1040. err = 1;
  1041. }
  1042. /* Decode RSA key from DER. */
  1043. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1044. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1045. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1046. err = 1;
  1047. }
  1048. if ((!err) && (out != NULL)) {
  1049. /* Return through parameter too. */
  1050. *out = rsa;
  1051. /* Move buffer on by the used amount. */
  1052. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1053. }
  1054. if (err) {
  1055. /* Dispose of any created RSA key. */
  1056. wolfSSL_RSA_free(rsa);
  1057. rsa = NULL;
  1058. }
  1059. return rsa;
  1060. }
  1061. /* Convert RSA private key data to internal.
  1062. *
  1063. * Create a new RSA key from the DER encoded RSA private key.
  1064. *
  1065. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1066. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1067. * @param [in] derSz Length of the data in the DER buffer.
  1068. * @return RSA key on success.
  1069. * @return NULL on failure.
  1070. */
  1071. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1072. const unsigned char **derBuf, long derSz)
  1073. {
  1074. WOLFSSL_RSA *rsa = NULL;
  1075. int err = 0;
  1076. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1077. /* Validate parameters. */
  1078. if (derBuf == NULL) {
  1079. WOLFSSL_ERROR_MSG("Bad argument");
  1080. err = 1;
  1081. }
  1082. /* Create a new RSA key to return. */
  1083. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1084. WOLFSSL_ERROR_MSG("RSA_new failed");
  1085. err = 1;
  1086. }
  1087. /* Decode RSA key from DER. */
  1088. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1089. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1090. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1091. err = 1;
  1092. }
  1093. if ((!err) && (out != NULL)) {
  1094. /* Return through parameter too. */
  1095. *out = rsa;
  1096. /* Move buffer on by the used amount. */
  1097. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1098. }
  1099. if (err) {
  1100. /* Dispose of any created RSA key. */
  1101. wolfSSL_RSA_free(rsa);
  1102. rsa = NULL;
  1103. }
  1104. return rsa;
  1105. }
  1106. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1107. !defined(HAVE_FAST_RSA)
  1108. /* Converts an internal RSA structure to DER format for the private key.
  1109. *
  1110. * If "pp" is null then buffer size only is returned.
  1111. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1112. * responsible for free'ing it.
  1113. *
  1114. * @param [in] rsa RSA key.
  1115. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1116. * May be NULL.
  1117. * On out, newly allocated buffer or pointer to byte after
  1118. * encoding in passed in buffer.
  1119. *
  1120. * @return Size of DER encoding on success
  1121. * @return BAD_FUNC_ARG when rsa is NULL.
  1122. * @return 0 on failure.
  1123. */
  1124. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1125. {
  1126. int ret;
  1127. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1128. /* Validate parameters. */
  1129. if (rsa == NULL) {
  1130. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1131. ret = BAD_FUNC_ARG;
  1132. }
  1133. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1134. * No heap hint as this gets returned to the user */
  1135. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1136. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1137. ret = 0;
  1138. }
  1139. /* Size of DER encoding. */
  1140. return ret;
  1141. }
  1142. /* Converts an internal RSA structure to DER format for the public key.
  1143. *
  1144. * If "pp" is null then buffer size only is returned.
  1145. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1146. * responsible for free'ing it.
  1147. *
  1148. * @param [in] rsa RSA key.
  1149. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1150. * May be NULL.
  1151. * On out, newly allocated buffer or pointer to byte after
  1152. * encoding in passed in buffer.
  1153. * @return Size of DER encoding on success
  1154. * @return BAD_FUNC_ARG when rsa is NULL.
  1155. * @return 0 on failure.
  1156. */
  1157. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1158. {
  1159. int ret;
  1160. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1161. /* check for bad functions arguments */
  1162. if (rsa == NULL) {
  1163. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1164. ret = BAD_FUNC_ARG;
  1165. }
  1166. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1167. * No heap hint as this gets returned to the user */
  1168. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1169. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1170. ret = 0;
  1171. }
  1172. return ret;
  1173. }
  1174. #endif /* defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) &&
  1175. * !defined(HAVE_FAST_RSA) */
  1176. #endif /* OPENSSL_EXTRA */
  1177. /*
  1178. * RSA to/from BIO APIs
  1179. */
  1180. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1181. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1182. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1183. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1184. !defined(HAVE_FAST_RSA) && !defined(NO_BIO)
  1185. /* Read DER data from a BIO.
  1186. *
  1187. * DER structures start with a constructed sequence. Use this to calculate the
  1188. * total length of the DER data.
  1189. *
  1190. * @param [in] bio BIO object to read from.
  1191. * @param [out] out Buffer holding DER encoding.
  1192. * @return Number of bytes to DER encoding on success.
  1193. * @return 0 on failure.
  1194. */
  1195. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1196. {
  1197. int err = 0;
  1198. unsigned char seq[MAX_SEQ_SZ];
  1199. unsigned char* der = NULL;
  1200. int derLen = 0;
  1201. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1202. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1203. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1204. err = 1;
  1205. }
  1206. /* Calculate complete DER encoding length. */
  1207. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1208. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1209. err = 1;
  1210. }
  1211. /* Allocate a buffer to read DER data into. */
  1212. if ((!err) && ((der = (unsigned char*)XMALLOC(derLen, bio->heap,
  1213. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1214. WOLFSSL_ERROR_MSG("Malloc failure");
  1215. err = 1;
  1216. }
  1217. if (!err) {
  1218. /* Calculate the unread amount. */
  1219. int len = derLen - sizeof(seq);
  1220. /* Copy the previously read data into the buffer. */
  1221. XMEMCPY(der, seq, sizeof(seq));
  1222. /* Read rest of DER data from BIO. */
  1223. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1224. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1225. err = 1;
  1226. }
  1227. }
  1228. if (!err) {
  1229. /* Return buffer through parameter. */
  1230. *out = der;
  1231. }
  1232. if (err) {
  1233. /* Dispose of any allocated buffer on error. */
  1234. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1235. derLen = 0;
  1236. }
  1237. return derLen;
  1238. }
  1239. /* Reads the RSA private key data from a BIO to the internal form.
  1240. *
  1241. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1242. *
  1243. * @param [in] bio BIO object to read from.
  1244. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1245. * @return RSA key on success.
  1246. * @return NULL on failure.
  1247. */
  1248. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1249. {
  1250. WOLFSSL_RSA* key = NULL;
  1251. unsigned char* der = NULL;
  1252. int derLen = 0;
  1253. int err;
  1254. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio()");
  1255. /* Validate parameters. */
  1256. err = (bio == NULL);
  1257. /* Read just DER encoding from BIO - buffer allocated in call. */
  1258. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1259. err = 1;
  1260. }
  1261. if (!err) {
  1262. /* Keep der for call to deallocate. */
  1263. const unsigned char* cder = der;
  1264. /* Create an RSA key from the data from the BIO. */
  1265. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1266. err = (key == NULL);
  1267. }
  1268. if ((!err) && (out != NULL)) {
  1269. /* Return the created RSA key through the parameter. */
  1270. *out = key;
  1271. }
  1272. if (err) {
  1273. /* Dispose of created key on error. */
  1274. wolfSSL_RSA_free(key);
  1275. key = NULL;
  1276. }
  1277. /* Dispose of allocated data. */
  1278. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1279. return key;
  1280. }
  1281. #endif /* defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) &&
  1282. * !defined(HAVE_FAST_RSA) && !NO_BIO */
  1283. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1284. /*
  1285. * RSA DER APIs
  1286. */
  1287. #ifdef OPENSSL_EXTRA
  1288. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1289. /* Create a DER encoding of key.
  1290. *
  1291. * wolfSSL API.
  1292. *
  1293. * @param [in] rsa RSA key.
  1294. * @param [out] outBuf Allocated buffer containing DER encoding.
  1295. * May be NULL.
  1296. * @param [in] publicKey Whether to encode as public key.
  1297. * @param [in] heap Heap hint.
  1298. * @return Encoding size on success.
  1299. * @return Negative on failure.
  1300. */
  1301. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1302. void* heap)
  1303. {
  1304. byte* p = NULL;
  1305. int ret;
  1306. if (outBuf != NULL) {
  1307. p = *outBuf;
  1308. }
  1309. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1310. if ((ret > 0) && (p != NULL)) {
  1311. *outBuf = p;
  1312. }
  1313. return ret;
  1314. }
  1315. /* Create a DER encoding of key.
  1316. *
  1317. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1318. *
  1319. * @param [in] rsa RSA key.
  1320. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1321. * May be NULL.
  1322. * On out, newly allocated buffer or pointer to byte
  1323. * after encoding in passed in buffer.
  1324. * @param [in] publicKey Whether to encode as public key.
  1325. * @return Encoding size on success.
  1326. * @return Negative on failure.
  1327. */
  1328. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1329. void* heap)
  1330. {
  1331. int ret = 1;
  1332. int derSz = 0;
  1333. byte* derBuf = NULL;
  1334. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1335. /* Unused if memory is disabled. */
  1336. (void)heap;
  1337. /* Validate parameters. */
  1338. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1339. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1340. ret = BAD_FUNC_ARG;
  1341. }
  1342. /* Push external RSA data into internal RSA key if not set. */
  1343. if ((ret == 1) && (!rsa->inSet)) {
  1344. ret = SetRsaInternal(rsa);
  1345. }
  1346. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1347. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1348. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1349. ret = BAD_FUNC_ARG;
  1350. }
  1351. if (ret == 1) {
  1352. if (publicKey) {
  1353. /* Calculate length of DER encoded RSA public key. */
  1354. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1355. if (derSz < 0) {
  1356. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1357. ret = derSz;
  1358. }
  1359. }
  1360. else {
  1361. /* Calculate length of DER encoded RSA private key. */
  1362. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1363. if (derSz < 0) {
  1364. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1365. ret = derSz;
  1366. }
  1367. }
  1368. }
  1369. if ((ret == 1) && (outBuf != NULL)) {
  1370. derBuf = *outBuf;
  1371. if (derBuf == NULL) {
  1372. /* Allocate buffer to hold DER encoded RSA key. */
  1373. derBuf = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1374. if (derBuf == NULL) {
  1375. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1376. ret = MEMORY_ERROR;
  1377. }
  1378. }
  1379. }
  1380. if ((ret == 1) && (outBuf != NULL)) {
  1381. if (publicKey) {
  1382. /* RSA public key to DER. */
  1383. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf, derSz);
  1384. }
  1385. else {
  1386. /* RSA private key to DER. */
  1387. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf, derSz);
  1388. }
  1389. if (derSz < 0) {
  1390. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1391. ret = derSz;
  1392. }
  1393. else if ((*outBuf) != NULL) {
  1394. derBuf = NULL;
  1395. *outBuf += derSz;
  1396. }
  1397. else {
  1398. /* Return allocated buffer. */
  1399. *outBuf = derBuf;
  1400. }
  1401. }
  1402. if (ret == 1) {
  1403. /* Success - return DER encoding size. */
  1404. ret = derSz;
  1405. }
  1406. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1407. /* Not returning buffer, needs to be disposed of. */
  1408. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1409. }
  1410. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1411. return ret;
  1412. }
  1413. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1414. #endif /* OPENSSL_EXTRA */
  1415. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1416. /* Load the DER encoded private RSA key.
  1417. *
  1418. * wolfSSL API.
  1419. *
  1420. * @param [in] rsa RSA key.
  1421. * @param [in] derBuf Buffer holding DER encoding.
  1422. * @param [in] derSz Length of DER encoding.
  1423. * @return 1 on success.
  1424. * @return -1 on failure.
  1425. */
  1426. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1427. int derSz)
  1428. {
  1429. /* Call implementation that handles both private and public keys. */
  1430. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1431. }
  1432. /* Load the DER encoded public or private RSA key.
  1433. *
  1434. * wolfSSL API.
  1435. *
  1436. * @param [in] rsa RSA key.
  1437. * @param [in] derBuf Buffer holding DER encoding.
  1438. * @param [in] derSz Length of DER encoding.
  1439. * @param [in] opt Indicates public or private key.
  1440. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1441. * @return 1 on success.
  1442. * @return -1 on failure.
  1443. */
  1444. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1445. int derSz, int opt)
  1446. {
  1447. int ret = 1;
  1448. int res;
  1449. word32 idx = 0;
  1450. word32 algId;
  1451. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1452. /* Validate parameters. */
  1453. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1454. (derSz <= 0)) {
  1455. WOLFSSL_ERROR_MSG("Bad function arguments");
  1456. ret = -1;
  1457. }
  1458. if (ret == 1) {
  1459. rsa->pkcs8HeaderSz = 0;
  1460. /* Check if input buffer has PKCS8 header. In the case that it does not
  1461. * have a PKCS8 header then do not error out. */
  1462. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1463. &algId);
  1464. if (res > 0) {
  1465. /* Store size of PKCS#8 header for encoding. */
  1466. WOLFSSL_MSG("Found PKCS8 header");
  1467. rsa->pkcs8HeaderSz = (word16)idx;
  1468. }
  1469. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1470. else if (res != ASN_PARSE_E) {
  1471. /* Something went wrong while decoding. */
  1472. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1473. "header");
  1474. ret = -1;
  1475. }
  1476. }
  1477. if (ret == 1) {
  1478. /* Decode private or public key data. */
  1479. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1480. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1481. derSz);
  1482. }
  1483. else {
  1484. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1485. derSz);
  1486. }
  1487. /* Check for error. */
  1488. if (res < 0) {
  1489. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1490. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1491. }
  1492. else {
  1493. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1494. }
  1495. WOLFSSL_ERROR_VERBOSE(res);
  1496. ret = -1;
  1497. }
  1498. }
  1499. if (ret == 1) {
  1500. /* Set external RSA key data from wolfCrypt key. */
  1501. if (SetRsaExternal(rsa) != 1) {
  1502. ret = -1;
  1503. }
  1504. else {
  1505. rsa->inSet = 1;
  1506. }
  1507. }
  1508. return ret;
  1509. }
  1510. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1511. #ifdef OPENSSL_EXTRA
  1512. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1513. /* Load DER encoded data into WOLFSSL_RSA object.
  1514. *
  1515. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1516. *
  1517. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1518. * When rsa or *rsa is NULL a new object is created.
  1519. * When not NULL and *rsa is NULL then new object
  1520. * returned through pointer.
  1521. * @param [in] in DER encoded RSA key data.
  1522. * @param [in] inSz Size of DER encoded data in bytes.
  1523. * @param [in] opt Public or private key encoded in data. Valid values:
  1524. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1525. * @return NULL on failure.
  1526. * @return WOLFSSL_RSA object on success.
  1527. */
  1528. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1529. long inSz, int opt)
  1530. {
  1531. WOLFSSL_RSA* ret = NULL;
  1532. if ((rsa != NULL) && (*rsa != NULL)) {
  1533. ret = *rsa;
  1534. }
  1535. else {
  1536. ret = wolfSSL_RSA_new();
  1537. }
  1538. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1539. != 1)) {
  1540. if ((rsa == NULL) || (ret != *rsa)) {
  1541. wolfSSL_RSA_free(ret);
  1542. }
  1543. ret = NULL;
  1544. }
  1545. if ((rsa != NULL) && (*rsa == NULL)) {
  1546. *rsa = ret;
  1547. }
  1548. return ret;
  1549. }
  1550. #endif
  1551. #endif /* OPENSSL_EXTRA */
  1552. /*
  1553. * RSA PEM APIs
  1554. */
  1555. #ifdef OPENSSL_EXTRA
  1556. #ifndef NO_BIO
  1557. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1558. /* Writes PEM encoding of an RSA public key to a BIO.
  1559. *
  1560. * @param [in] bio BIO object to write to.
  1561. * @param [in] rsa RSA key to write.
  1562. * @return 1 on success.
  1563. * @return 0 on failure.
  1564. */
  1565. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1566. {
  1567. int ret = 1;
  1568. int derSz = 0;
  1569. byte* derBuf = NULL;
  1570. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1571. /* Validate parameters. */
  1572. if ((bio == NULL) || (rsa == NULL)) {
  1573. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1574. ret = 0;
  1575. }
  1576. if (ret == 1) {
  1577. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1578. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1579. ret = 0;
  1580. }
  1581. if (derBuf == NULL) {
  1582. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1583. ret = 0;
  1584. }
  1585. }
  1586. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1587. PUBLICKEY_TYPE) != WOLFSSL_SUCCESS)) {
  1588. ret = 0;
  1589. }
  1590. /* Dispose of DER buffer. */
  1591. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1592. return ret;
  1593. }
  1594. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1595. #endif /* !NO_BIO */
  1596. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1597. #ifndef NO_FILESYSTEM
  1598. /* Writes PEM encoding of an RSA public key to a file pointer.
  1599. *
  1600. * @param [in] fp File pointer to write to.
  1601. * @param [in] rsa RSA key to write.
  1602. * @param [in] type PEM type to write out.
  1603. * @return 1 on success.
  1604. * @return 0 on failure.
  1605. */
  1606. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1607. int type)
  1608. {
  1609. int ret = 1;
  1610. int derSz;
  1611. byte* derBuf = NULL;
  1612. /* Validate parameters. */
  1613. if ((fp == XBADFILE) || (rsa == NULL)) {
  1614. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1615. ret = 0;
  1616. }
  1617. if (ret == 1) {
  1618. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1619. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1620. ret = 0;
  1621. }
  1622. if (derBuf == NULL) {
  1623. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1624. ret = 0;
  1625. }
  1626. }
  1627. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1628. rsa->heap) != WOLFSSL_SUCCESS)) {
  1629. ret = 0;
  1630. }
  1631. /* Dispose of DER buffer. */
  1632. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1633. return ret;
  1634. }
  1635. /* Writes PEM encoding of an RSA public key to a file pointer.
  1636. *
  1637. * Header/footer will contain: PUBLIC KEY
  1638. *
  1639. * @param [in] fp File pointer to write to.
  1640. * @param [in] rsa RSA key to write.
  1641. * @return 1 on success.
  1642. * @return 0 on failure.
  1643. */
  1644. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1645. {
  1646. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1647. }
  1648. /* Writes PEM encoding of an RSA public key to a file pointer.
  1649. *
  1650. * Header/footer will contain: RSA PUBLIC KEY
  1651. *
  1652. * @param [in] fp File pointer to write to.
  1653. * @param [in] rsa RSA key to write.
  1654. * @return 1 on success.
  1655. * @return 0 on failure.
  1656. */
  1657. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1658. {
  1659. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1660. }
  1661. #endif /* !NO_FILESYSTEM */
  1662. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1663. #ifndef NO_BIO
  1664. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1665. *
  1666. * @param [in] bio BIO object to read from.
  1667. * @param [out] out RSA key created.
  1668. * @param [in] cb Password callback when PEM encrypted.
  1669. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1670. * @return RSA key on success.
  1671. * @return NULL on failure.
  1672. */
  1673. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1674. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1675. {
  1676. WOLFSSL_RSA* rsa = NULL;
  1677. DerBuffer* der = NULL;
  1678. int keyFormat = 0;
  1679. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1680. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1681. &keyFormat, &der) >= 0)) {
  1682. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1683. WOLFSSL_RSA_LOAD_PUBLIC);
  1684. if (rsa == NULL) {
  1685. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1686. }
  1687. }
  1688. FreeDer(&der);
  1689. if ((out != NULL) && (rsa != NULL)) {
  1690. *out = rsa;
  1691. }
  1692. return rsa;
  1693. }
  1694. #endif /* !NO_BIO */
  1695. #ifndef NO_FILESYSTEM
  1696. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1697. *
  1698. * Header/footer should contain: PUBLIC KEY
  1699. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1700. *
  1701. * @param [in] fp File pointer to read from.
  1702. * @param [out] out RSA key created.
  1703. * @param [in] cb Password callback when PEM encrypted.
  1704. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1705. * @return RSA key on success.
  1706. * @return NULL on failure.
  1707. */
  1708. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1709. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1710. {
  1711. WOLFSSL_RSA* rsa = NULL;
  1712. DerBuffer* der = NULL;
  1713. int keyFormat = 0;
  1714. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1715. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1716. &keyFormat, &der) >= 0)) {
  1717. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1718. WOLFSSL_RSA_LOAD_PUBLIC);
  1719. if (rsa == NULL) {
  1720. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1721. }
  1722. }
  1723. FreeDer(&der);
  1724. if ((out != NULL) && (rsa != NULL)) {
  1725. *out = rsa;
  1726. }
  1727. return rsa;
  1728. }
  1729. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1730. *
  1731. * Header/footer should contain: RSA PUBLIC KEY
  1732. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1733. *
  1734. * @param [in] fp File pointer to read from.
  1735. * @param [out] rsa RSA key created.
  1736. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1737. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1738. * May be NULL.
  1739. * @return RSA key on success.
  1740. * @return NULL on failure.
  1741. */
  1742. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1743. wc_pem_password_cb* cb, void* pass)
  1744. {
  1745. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1746. }
  1747. #endif /* NO_FILESYSTEM */
  1748. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1749. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1750. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1751. *
  1752. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1753. *
  1754. * @param [in] rsa RSA key to write.
  1755. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1756. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1757. * @param [in] passwdSz Length of password string when PEM encrypted.
  1758. * @param [out] pem Allocated buffer with PEM encoding.
  1759. * @param [out] plen Length of PEM encoding.
  1760. * @return 1 on success.
  1761. * @return 0 on failure.
  1762. */
  1763. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1764. unsigned char* passwd, int passwdSz, unsigned char **pem, int *plen)
  1765. {
  1766. int ret = 1;
  1767. byte* derBuf = NULL;
  1768. byte* tmp = NULL;
  1769. byte* cipherInfo = NULL;
  1770. int derSz = 0;
  1771. int pemSz = 0;
  1772. const int type = PRIVATEKEY_TYPE;
  1773. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1774. /* Validate parameters. */
  1775. if ((pem == NULL) || (plen == NULL) || (rsa == NULL) ||
  1776. (rsa->internal == NULL)) {
  1777. WOLFSSL_ERROR_MSG("Bad function arguments");
  1778. ret = 0;
  1779. }
  1780. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1781. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1782. ret = 0;
  1783. }
  1784. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1785. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1786. rsa->heap)) < 0)) {
  1787. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1788. ret = 0;
  1789. }
  1790. /* Encrypt DER buffer if required. */
  1791. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  1792. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  1793. byte *tmpBuf;
  1794. /* Add space for padding. */
  1795. tmpBuf = (byte*)XREALLOC(derBuf, derSz + blockSz, rsa->heap,
  1796. DYNAMIC_TYPE_TMP_BUFFER);
  1797. if (tmpBuf == NULL) {
  1798. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  1799. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1800. ret = 0;
  1801. }
  1802. else {
  1803. derBuf = tmpBuf;
  1804. /* Encrypt DER inline. */
  1805. ret = EncryptDerKey(derBuf, &derSz, cipher, passwd, passwdSz,
  1806. &cipherInfo, derSz + blockSz);
  1807. if (ret != 1) {
  1808. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  1809. }
  1810. }
  1811. }
  1812. if (ret == 1) {
  1813. /* Calculate PEM encoding size. */
  1814. pemSz = wc_DerToPemEx(derBuf, derSz, NULL, 0, cipherInfo, type);
  1815. if (pemSz <= 0) {
  1816. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  1817. ret = 0;
  1818. }
  1819. }
  1820. if (ret == 1) {
  1821. /* Allocate space for PEM encoding plus a NUL terminator. */
  1822. tmp = (byte*)XMALLOC(pemSz + 1, NULL, DYNAMIC_TYPE_KEY);
  1823. if (tmp == NULL) {
  1824. WOLFSSL_ERROR_MSG("malloc failed");
  1825. ret = 0;
  1826. }
  1827. }
  1828. if (ret == 1) {
  1829. /* DER to PEM */
  1830. pemSz = wc_DerToPemEx(derBuf, derSz, tmp, pemSz, cipherInfo, type);
  1831. if (pemSz <= 0) {
  1832. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  1833. ret = 0;
  1834. }
  1835. }
  1836. if (ret == 1) {
  1837. /* NUL terminate string - PEM. */
  1838. tmp[pemSz] = 0x00;
  1839. /* Return allocated buffer and size. */
  1840. *pem = tmp;
  1841. *plen = pemSz;
  1842. /* Don't free returning buffer. */
  1843. tmp = NULL;
  1844. }
  1845. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  1846. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  1847. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1848. return ret;
  1849. }
  1850. #ifndef NO_BIO
  1851. /* Writes PEM encoding of an RSA private key to a BIO.
  1852. *
  1853. * @param [in] bio BIO object to write to.
  1854. * @param [in] rsa RSA key to write.
  1855. * @param [in] cipher Cipher to use when PEM encrypted.
  1856. * @param [in] passwd Password string when PEM encrypted.
  1857. * @param [in] len Length of password string when PEM encrypted.
  1858. * @param [in] cb Password callback to use when PEM encrypted.
  1859. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1860. * @return 1 on success.
  1861. * @return 0 on failure.
  1862. */
  1863. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1864. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1865. wc_pem_password_cb* cb, void* arg)
  1866. {
  1867. int ret = 1;
  1868. byte* pem = NULL;
  1869. int plen;
  1870. (void)cb;
  1871. (void)arg;
  1872. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1873. /* Validate parameters. */
  1874. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1875. WOLFSSL_ERROR_MSG("Bad function arguments");
  1876. ret = 0;
  1877. }
  1878. if (ret == 1) {
  1879. /* Write PEM to buffer that is allocated in the call. */
  1880. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1881. &pem, &plen);
  1882. if (ret != 1) {
  1883. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1884. }
  1885. }
  1886. /* Write PEM to BIO. */
  1887. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, plen) <= 0)) {
  1888. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1889. ret = 0;
  1890. }
  1891. /* Dispose of any allocated PEM buffer. */
  1892. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1893. return ret;
  1894. }
  1895. #endif /* !NO_BIO */
  1896. #ifndef NO_FILESYSTEM
  1897. /* Writes PEM encoding of an RSA private key to a file pointer.
  1898. *
  1899. * TODO: Support use of the password callback and callback context.
  1900. *
  1901. * @param [in] fp File pointer to write to.
  1902. * @param [in] rsa RSA key to write.
  1903. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1904. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1905. * @param [in] passwdSz Length of password string when PEM encrypted.
  1906. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  1907. * @param [in] arg NUL terminated string for passphrase when PEM
  1908. * encrypted. Unused.
  1909. * @return 1 on success.
  1910. * @return 0 on failure.
  1911. */
  1912. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  1913. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  1914. wc_pem_password_cb *cb, void *arg)
  1915. {
  1916. int ret = 1;
  1917. byte* pem = NULL;
  1918. int plen;
  1919. (void)cb;
  1920. (void)arg;
  1921. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  1922. /* Validate parameters. */
  1923. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  1924. WOLFSSL_ERROR_MSG("Bad function arguments");
  1925. ret = 0;
  1926. }
  1927. if (ret == 1) {
  1928. /* Write PEM to buffer that is allocated in the call. */
  1929. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  1930. &pem, &plen);
  1931. if (ret != 1) {
  1932. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1933. }
  1934. }
  1935. /* Write PEM to file pointer. */
  1936. if ((ret == 1) && ((int)XFWRITE(pem, plen, 1, fp) != 1)) {
  1937. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  1938. ret = 0;
  1939. }
  1940. /* Dispose of any allocated PEM buffer. */
  1941. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1942. return ret;
  1943. }
  1944. #endif /* NO_FILESYSTEM */
  1945. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA && WOLFSSL_PEM_TO_DER */
  1946. #ifndef NO_BIO
  1947. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  1948. *
  1949. * @param [in] bio BIO object to read from.
  1950. * @param [out] out RSA key created.
  1951. * @param [in] cb Password callback when PEM encrypted.
  1952. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1953. * @return RSA key on success.
  1954. * @return NULL on failure.
  1955. */
  1956. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  1957. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  1958. {
  1959. WOLFSSL_RSA* rsa = NULL;
  1960. DerBuffer* der = NULL;
  1961. int keyFormat = 0;
  1962. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  1963. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  1964. &keyFormat, &der) >= 0)) {
  1965. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1966. WOLFSSL_RSA_LOAD_PRIVATE);
  1967. if (rsa == NULL) {
  1968. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1969. }
  1970. }
  1971. FreeDer(&der);
  1972. if ((out != NULL) && (rsa != NULL)) {
  1973. *out = rsa;
  1974. }
  1975. return rsa;
  1976. }
  1977. #endif /* !NO_BIO */
  1978. /* Create an RSA private key by reading the PEM encoded data from the file
  1979. * pointer.
  1980. *
  1981. * @param [in] fp File pointer to read from.
  1982. * @param [out] out RSA key created.
  1983. * @param [in] cb Password callback when PEM encrypted.
  1984. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1985. * @return RSA key on success.
  1986. * @return NULL on failure.
  1987. */
  1988. #ifndef NO_FILESYSTEM
  1989. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  1990. wc_pem_password_cb* cb, void* pass)
  1991. {
  1992. WOLFSSL_RSA* rsa = NULL;
  1993. DerBuffer* der = NULL;
  1994. int keyFormat = 0;
  1995. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  1996. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  1997. &keyFormat, &der) >= 0)) {
  1998. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1999. WOLFSSL_RSA_LOAD_PRIVATE);
  2000. if (rsa == NULL) {
  2001. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2002. }
  2003. }
  2004. FreeDer(&der);
  2005. if ((out != NULL) && (rsa != NULL)) {
  2006. *out = rsa;
  2007. }
  2008. return rsa;
  2009. }
  2010. #endif /* !NO_FILESYSTEM */
  2011. /*
  2012. * RSA print APIs
  2013. */
  2014. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  2015. !defined(NO_STDIO_FILESYSTEM)
  2016. /* Print an RSA key to a file pointer.
  2017. *
  2018. * @param [in] fp File pointer to write to.
  2019. * @param [in] rsa RSA key to write.
  2020. * @param [in] indent Number of spaces to prepend to each line.
  2021. * @return 1 on success.
  2022. * @return 0 on failure.
  2023. */
  2024. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2025. {
  2026. int ret = 1;
  2027. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2028. /* Validate parameters. */
  2029. if ((fp == XBADFILE) || (rsa == NULL)) {
  2030. ret = 0;
  2031. }
  2032. /* Set the external data from the wolfCrypt RSA key if not done. */
  2033. if ((ret == 1) && (!rsa->exSet)) {
  2034. ret = SetRsaExternal(rsa);
  2035. }
  2036. /* Get the key size from modulus if available. */
  2037. if ((ret == 1) && (rsa->n != NULL)) {
  2038. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2039. if (keySize == 0) {
  2040. ret = 0;
  2041. }
  2042. else {
  2043. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2044. ret = 0;
  2045. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2046. keySize) < 0)
  2047. ret = 0;
  2048. }
  2049. }
  2050. /* Print out any components available. */
  2051. if ((ret == 1) && (rsa->n != NULL)) {
  2052. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2053. }
  2054. if ((ret == 1) && (rsa->d != NULL)) {
  2055. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2056. }
  2057. if ((ret == 1) && (rsa->p != NULL)) {
  2058. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2059. }
  2060. if ((ret == 1) && (rsa->q != NULL)) {
  2061. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2062. }
  2063. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2064. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2065. }
  2066. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2067. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2068. }
  2069. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2070. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2071. }
  2072. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2073. return ret;
  2074. }
  2075. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2076. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(HAVE_FAST_RSA)
  2077. /* snprintf() must be available */
  2078. /* Maximum size of a header line. */
  2079. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2080. /* Writes the human readable form of RSA to a BIO.
  2081. *
  2082. * @param [in] bio BIO object to write to.
  2083. * @param [in] rsa RSA key to write.
  2084. * @param [in] indent Number of spaces before each line.
  2085. * @return 1 on success.
  2086. * @return 0 on failure.
  2087. */
  2088. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2089. {
  2090. int ret = 1;
  2091. int sz = 0;
  2092. RsaKey* key = NULL;
  2093. char line[RSA_PRINT_MAX_HEADER_LINE];
  2094. int len;
  2095. int i = 0;
  2096. mp_int *num = NULL;
  2097. /* Header strings. */
  2098. const char *name[] = {
  2099. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2100. "Exponent1:", "Exponent2:", "Coefficient:"
  2101. };
  2102. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2103. /* Validate parameters. */
  2104. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2105. ret = -1;
  2106. }
  2107. if (ret == 1) {
  2108. key = (RsaKey*)rsa->internal;
  2109. /* Get size in bits of key for printing out. */
  2110. sz = wolfSSL_RSA_bits(rsa);
  2111. if (sz <= 0) {
  2112. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2113. ret = 0;
  2114. }
  2115. }
  2116. if (ret == 1) {
  2117. /* Print any indent spaces. */
  2118. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2119. }
  2120. if (ret == 1) {
  2121. /* Print header line. */
  2122. len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2123. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2124. if (len >= (int)sizeof(line)) {
  2125. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2126. ret = 0;
  2127. }
  2128. else {
  2129. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2130. ret = 0;
  2131. }
  2132. }
  2133. }
  2134. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2135. /* Get mp_int for index. */
  2136. switch(i) {
  2137. case 0:
  2138. /* Print out modulus */
  2139. num = &key->n;
  2140. break;
  2141. case 1:
  2142. num = &key->e;
  2143. break;
  2144. case 2:
  2145. num = &key->d;
  2146. break;
  2147. case 3:
  2148. num = &key->p;
  2149. break;
  2150. case 4:
  2151. num = &key->q;
  2152. break;
  2153. case 5:
  2154. num = &key->dP;
  2155. break;
  2156. case 6:
  2157. num = &key->dQ;
  2158. break;
  2159. case 7:
  2160. num = &key->u;
  2161. break;
  2162. default:
  2163. WOLFSSL_ERROR_MSG("Bad index value");
  2164. }
  2165. if (i == 1) {
  2166. /* Print exponent as a 32-bit value. */
  2167. ret = wolfssl_print_value(bio, num, name[i], indent);
  2168. }
  2169. else if (!mp_iszero(num)) {
  2170. /* Print name and MP integer. */
  2171. ret = wolfssl_print_number(bio, num, name[i], indent);
  2172. }
  2173. }
  2174. return ret;
  2175. }
  2176. #endif /* XSNPRINTF && !NO_BIO && !HAVE_FAST_RSA */
  2177. #endif /* OPENSSL_EXTRA */
  2178. /*
  2179. * RSA get/set/test APIs
  2180. */
  2181. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2182. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2183. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2184. *
  2185. * @param [in, out] rsa RSA key.
  2186. * @return 1 on success.
  2187. * @return 0 on failure.
  2188. */
  2189. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2190. {
  2191. int ret = 1;
  2192. WOLFSSL_ENTER("SetRsaExternal");
  2193. /* Validate parameters. */
  2194. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2195. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2196. ret = -1;
  2197. }
  2198. if (ret == 1) {
  2199. RsaKey* key = (RsaKey*)rsa->internal;
  2200. /* Copy modulus. */
  2201. ret = SetIndividualExternal(&rsa->n, &key->n);
  2202. if (ret != 1) {
  2203. WOLFSSL_ERROR_MSG("rsa n error");
  2204. }
  2205. if (ret == 1) {
  2206. /* Copy public exponent. */
  2207. ret = SetIndividualExternal(&rsa->e, &key->e);
  2208. if (ret != 1) {
  2209. WOLFSSL_ERROR_MSG("rsa e error");
  2210. }
  2211. }
  2212. if (key->type == RSA_PRIVATE) {
  2213. if (ret == 1) {
  2214. /* Copy private exponent. */
  2215. ret = SetIndividualExternal(&rsa->d, &key->d);
  2216. if (ret != 1) {
  2217. WOLFSSL_ERROR_MSG("rsa d error");
  2218. }
  2219. }
  2220. if (ret == 1) {
  2221. /* Copy first prime. */
  2222. ret = SetIndividualExternal(&rsa->p, &key->p);
  2223. if (ret != 1) {
  2224. WOLFSSL_ERROR_MSG("rsa p error");
  2225. }
  2226. }
  2227. if (ret == 1) {
  2228. /* Copy second prime. */
  2229. ret = SetIndividualExternal(&rsa->q, &key->q);
  2230. if (ret != 1) {
  2231. WOLFSSL_ERROR_MSG("rsa q error");
  2232. }
  2233. }
  2234. #ifndef RSA_LOW_MEM
  2235. if (ret == 1) {
  2236. /* Copy d mod p-1. */
  2237. ret = SetIndividualExternal(&rsa->dmp1, &key->dP);
  2238. if (ret != 1) {
  2239. WOLFSSL_ERROR_MSG("rsa dP error");
  2240. }
  2241. }
  2242. if (ret == 1) {
  2243. /* Copy d mod q-1. */
  2244. ret = SetIndividualExternal(&rsa->dmq1, &key->dQ);
  2245. if (ret != 1) {
  2246. WOLFSSL_ERROR_MSG("rsa dq error");
  2247. }
  2248. }
  2249. if (ret == 1) {
  2250. /* Copy 1/q mod p. */
  2251. ret = SetIndividualExternal(&rsa->iqmp, &key->u);
  2252. if (ret != 1) {
  2253. WOLFSSL_ERROR_MSG("rsa u error");
  2254. }
  2255. }
  2256. #endif /* !RSA_LOW_MEM */
  2257. }
  2258. }
  2259. if (ret == 1) {
  2260. /* External values set. */
  2261. rsa->exSet = 1;
  2262. }
  2263. else {
  2264. /* Return 0 on failure. */
  2265. ret = 0;
  2266. }
  2267. return ret;
  2268. }
  2269. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  2270. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2271. #ifdef OPENSSL_EXTRA
  2272. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2273. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2274. *
  2275. * @param [in, out] rsa RSA key.
  2276. * @return 1 on success.
  2277. * @return 0 on failure.
  2278. */
  2279. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2280. {
  2281. int ret = 1;
  2282. WOLFSSL_ENTER("SetRsaInternal");
  2283. /* Validate parameters. */
  2284. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2285. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2286. ret = -1;
  2287. }
  2288. if (ret == 1) {
  2289. RsaKey* key = (RsaKey*)rsa->internal;
  2290. /* Copy down modulus if available. */
  2291. if ((rsa->n != NULL) && (SetIndividualInternal(rsa->n, &key->n) != 1)) {
  2292. WOLFSSL_ERROR_MSG("rsa n key error");
  2293. ret = -1;
  2294. }
  2295. /* Copy down public exponent if available. */
  2296. if ((ret == 1) && (rsa->e != NULL) &&
  2297. (SetIndividualInternal(rsa->e, &key->e) != 1)) {
  2298. WOLFSSL_ERROR_MSG("rsa e key error");
  2299. ret = -1;
  2300. }
  2301. /* Enough numbers for public key */
  2302. key->type = RSA_PUBLIC;
  2303. /* Copy down private exponent if available. */
  2304. if ((ret == 1) && (rsa->d != NULL)) {
  2305. if (SetIndividualInternal(rsa->d, &key->d) != 1) {
  2306. WOLFSSL_ERROR_MSG("rsa d key error");
  2307. ret = -1;
  2308. }
  2309. else {
  2310. /* Enough numbers for private key */
  2311. key->type = RSA_PRIVATE;
  2312. }
  2313. }
  2314. /* Copy down first prime if available. */
  2315. if ((ret == 1) && (rsa->p != NULL) &&
  2316. (SetIndividualInternal(rsa->p, &key->p) != 1)) {
  2317. WOLFSSL_ERROR_MSG("rsa p key error");
  2318. ret = -1;
  2319. }
  2320. /* Copy down second prime if available. */
  2321. if ((ret == 1) && (rsa->q != NULL) &&
  2322. (SetIndividualInternal(rsa->q, &key->q) != 1)) {
  2323. WOLFSSL_ERROR_MSG("rsa q key error");
  2324. ret = -1;
  2325. }
  2326. #ifndef RSA_LOW_MEM
  2327. /* Copy down d mod p-1 if available. */
  2328. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2329. (SetIndividualInternal(rsa->dmp1, &key->dP) != 1)) {
  2330. WOLFSSL_ERROR_MSG("rsa dP key error");
  2331. ret = -1;
  2332. }
  2333. /* Copy down d mod q-1 if available. */
  2334. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2335. (SetIndividualInternal(rsa->dmq1, &key->dQ) != 1)) {
  2336. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2337. ret = -1;
  2338. }
  2339. /* Copy down 1/q mod p if available. */
  2340. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2341. (SetIndividualInternal(rsa->iqmp, &key->u) != 1)) {
  2342. WOLFSSL_ERROR_MSG("rsa u key error");
  2343. ret = -1;
  2344. }
  2345. #endif /* !RSA_LOW_MEM */
  2346. if (ret == 1) {
  2347. /* All available numbers have been set down. */
  2348. rsa->inSet = 1;
  2349. }
  2350. }
  2351. return ret;
  2352. }
  2353. #endif /* HAVE_USER_RSA */
  2354. /* Set the RSA method into object.
  2355. *
  2356. * @param [in, out] rsa RSA key.
  2357. * @param [in] meth RSA method.
  2358. * @return 1 always.
  2359. */
  2360. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2361. {
  2362. if (rsa != NULL) {
  2363. /* Store the method into object. */
  2364. rsa->meth = meth;
  2365. /* Copy over flags. */
  2366. rsa->flags = meth->flags;
  2367. }
  2368. /* OpenSSL always assumes it will work. */
  2369. return 1;
  2370. }
  2371. /* Get the RSA method from the RSA object.
  2372. *
  2373. * @param [in] rsa RSA key.
  2374. * @return RSA method on success.
  2375. * @return NULL when RSA is NULL or no method set.
  2376. */
  2377. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2378. {
  2379. return (rsa != NULL) ? rsa->meth : NULL;
  2380. }
  2381. /* Get the size in bytes of the RSA key.
  2382. *
  2383. * Return compliant with OpenSSL
  2384. *
  2385. * @param [in] rsa RSA key.
  2386. * @return RSA modulus size in bytes.
  2387. * @return 0 on error.
  2388. */
  2389. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2390. {
  2391. int ret = 0;
  2392. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2393. if (rsa != NULL) {
  2394. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2395. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2396. /* Get key size in bytes using wolfCrypt RSA key. */
  2397. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2398. }
  2399. }
  2400. return ret;
  2401. }
  2402. /* Get the size in bits of the RSA key.
  2403. *
  2404. * Uses external modulus field.
  2405. *
  2406. * @param [in] rsa RSA key.
  2407. * @return RSA modulus size in bits.
  2408. * @return 0 on error.
  2409. */
  2410. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2411. {
  2412. int ret = 0;
  2413. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2414. if (rsa != NULL) {
  2415. /* Get number of bits in external modulus. */
  2416. ret = wolfSSL_BN_num_bits(rsa->n);
  2417. }
  2418. return ret;
  2419. }
  2420. #ifndef HAVE_USER_RSA
  2421. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2422. *
  2423. * Only for those that are not NULL parameters.
  2424. *
  2425. * @param [in] rsa RSA key.
  2426. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2427. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2428. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2429. */
  2430. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2431. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2432. const WOLFSSL_BIGNUM **iqmp)
  2433. {
  2434. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2435. /* For any parameters not NULL, return the BN from the key or NULL. */
  2436. if (dmp1 != NULL) {
  2437. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2438. }
  2439. if (dmq1 != NULL) {
  2440. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2441. }
  2442. if (iqmp != NULL) {
  2443. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2444. }
  2445. }
  2446. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2447. * into RSA key.
  2448. *
  2449. * If CRT parameter is NULL then there must be one in the RSA key already.
  2450. *
  2451. * @param [in, out] rsa RSA key.
  2452. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2453. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2454. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2455. * @return 1 on success.
  2456. * @return 0 on failure.
  2457. */
  2458. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2459. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2460. {
  2461. int ret = 1;
  2462. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2463. /* If a param is NULL in rsa then it must be non-NULL in the
  2464. * corresponding user input. */
  2465. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2466. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2467. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2468. WOLFSSL_ERROR_MSG("Bad parameters");
  2469. ret = 0;
  2470. }
  2471. if (ret == 1) {
  2472. /* Replace the BNs. */
  2473. if (dmp1 != NULL) {
  2474. wolfSSL_BN_clear_free(rsa->dmp1);
  2475. rsa->dmp1 = dmp1;
  2476. }
  2477. if (dmq1 != NULL) {
  2478. wolfSSL_BN_clear_free(rsa->dmq1);
  2479. rsa->dmq1 = dmq1;
  2480. }
  2481. if (iqmp != NULL) {
  2482. wolfSSL_BN_clear_free(rsa->iqmp);
  2483. rsa->iqmp = iqmp;
  2484. }
  2485. /* Set the values into the wolfCrypt RSA key. */
  2486. if (SetRsaInternal(rsa) != 1) {
  2487. ret = 0;
  2488. }
  2489. }
  2490. return ret;
  2491. }
  2492. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2493. *
  2494. * @param [in] rsa RSA key.
  2495. * @param [out] p BN that is first prime. May be NULL.
  2496. * @param [out] q BN that is second prime. May be NULL.
  2497. */
  2498. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2499. const WOLFSSL_BIGNUM **q)
  2500. {
  2501. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2502. /* For any primes not NULL, return the BN from the key or NULL. */
  2503. if (p != NULL) {
  2504. *p = (rsa != NULL) ? rsa->p : NULL;
  2505. }
  2506. if (q != NULL) {
  2507. *q = (rsa != NULL) ? rsa->q : NULL;
  2508. }
  2509. }
  2510. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2511. *
  2512. * If factor parameter is NULL then there must be one in the RSA key already.
  2513. *
  2514. * @param [in, out] rsa RSA key.
  2515. * @param [in] p BN that is first prime. May be NULL.
  2516. * @param [in] q BN that is second prime. May be NULL.
  2517. * @return 1 on success.
  2518. * @return 0 on failure.
  2519. */
  2520. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2521. WOLFSSL_BIGNUM *q)
  2522. {
  2523. int ret = 1;
  2524. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2525. /* If a param is null in r then it must be non-null in the
  2526. * corresponding user input. */
  2527. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2528. ((rsa->q == NULL) && (q == NULL))) {
  2529. WOLFSSL_ERROR_MSG("Bad parameters");
  2530. ret = 0;
  2531. }
  2532. if (ret == 1) {
  2533. /* Replace the BNs. */
  2534. if (p != NULL) {
  2535. wolfSSL_BN_clear_free(rsa->p);
  2536. rsa->p = p;
  2537. }
  2538. if (q != NULL) {
  2539. wolfSSL_BN_clear_free(rsa->q);
  2540. rsa->q = q;
  2541. }
  2542. /* Set the values into the wolfCrypt RSA key. */
  2543. if (SetRsaInternal(rsa) != 1) {
  2544. ret = 0;
  2545. }
  2546. }
  2547. return ret;
  2548. }
  2549. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2550. * exponent, private exponent).
  2551. *
  2552. * @param [in] rsa RSA key.
  2553. * @param [out] n BN that is the modulus. May be NULL.
  2554. * @param [out] e BN that is the public exponent. May be NULL.
  2555. * @param [out] d BN that is the private exponent. May be NULL.
  2556. */
  2557. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2558. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2559. {
  2560. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2561. /* For any parameters not NULL, return the BN from the key or NULL. */
  2562. if (n != NULL) {
  2563. *n = (rsa != NULL) ? rsa->n : NULL;
  2564. }
  2565. if (e != NULL) {
  2566. *e = (rsa != NULL) ? rsa->e : NULL;
  2567. }
  2568. if (d != NULL) {
  2569. *d = (rsa != NULL) ? rsa->d : NULL;
  2570. }
  2571. }
  2572. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2573. * public exponent, private exponent).
  2574. *
  2575. * If BN parameter is NULL then there must be one in the RSA key already.
  2576. *
  2577. * @param [in,out] rsa RSA key.
  2578. * @param [in] n BN that is the modulus. May be NULL.
  2579. * @param [in] e BN that is the public exponent. May be NULL.
  2580. * @param [in] d BN that is the private exponent. May be NULL.
  2581. * @return 1 on success.
  2582. * @return 0 on failure.
  2583. */
  2584. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2585. WOLFSSL_BIGNUM *d)
  2586. {
  2587. int ret = 1;
  2588. /* If the fields n and e in r are NULL, the corresponding input
  2589. * parameters MUST be non-NULL for n and e. d may be
  2590. * left NULL (in case only the public key is used).
  2591. */
  2592. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2593. ((rsa->e == NULL) && (e == NULL))) {
  2594. ret = 0;
  2595. }
  2596. if (ret == 1) {
  2597. /* Replace the BNs. */
  2598. if (n != NULL) {
  2599. wolfSSL_BN_free(rsa->n);
  2600. rsa->n = n;
  2601. }
  2602. if (e != NULL) {
  2603. wolfSSL_BN_free(rsa->e);
  2604. rsa->e = e;
  2605. }
  2606. if (d != NULL) {
  2607. /* Private key is sensitive data. */
  2608. wolfSSL_BN_clear_free(rsa->d);
  2609. rsa->d = d;
  2610. }
  2611. /* Set the values into the wolfCrypt RSA key. */
  2612. if (SetRsaInternal(rsa) != 1) {
  2613. ret = 0;
  2614. }
  2615. }
  2616. return ret;
  2617. }
  2618. #endif /* !HAVE_USER_RSA */
  2619. /* Get the flags of the RSA key.
  2620. *
  2621. * @param [in] rsa RSA key.
  2622. * @return Flags set in RSA key on success.
  2623. * @return 0 when RSA key is NULL.
  2624. */
  2625. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2626. {
  2627. int ret = 0;
  2628. /* Get flags from the RSA key if available. */
  2629. if (rsa != NULL) {
  2630. ret = rsa->flags;
  2631. }
  2632. return ret;
  2633. }
  2634. /* Set the flags into the RSA key.
  2635. *
  2636. * @param [in, out] rsa RSA key.
  2637. * @param [in] flags Flags to set.
  2638. */
  2639. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2640. {
  2641. /* Add the flags into RSA key if available. */
  2642. if (rsa != NULL) {
  2643. rsa->flags |= flags;
  2644. }
  2645. }
  2646. /* Clear the flags in the RSA key.
  2647. *
  2648. * @param [in, out] rsa RSA key.
  2649. * @param [in] flags Flags to clear.
  2650. */
  2651. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2652. {
  2653. /* Clear the flags passed in that are on the RSA key if available. */
  2654. if (rsa != NULL) {
  2655. rsa->flags &= ~flags;
  2656. }
  2657. }
  2658. /* Test the flags in the RSA key.
  2659. *
  2660. * @param [in] rsa RSA key.
  2661. * @return Matching flags of RSA key on success.
  2662. * @return 0 when RSA key is NULL.
  2663. */
  2664. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2665. {
  2666. /* Return the flags passed in that are set on the RSA key if available. */
  2667. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2668. }
  2669. /* Get the extra data, by index, associated with the RSA key.
  2670. *
  2671. * @param [in] rsa RSA key.
  2672. * @param [in] idx Index of extra data.
  2673. * @return Extra data (anonymous type) on success.
  2674. * @return NULL on failure.
  2675. */
  2676. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2677. {
  2678. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2679. #ifdef HAVE_EX_DATA
  2680. return (rsa == NULL) ? NULL :
  2681. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2682. #else
  2683. (void)rsa;
  2684. (void)idx;
  2685. return NULL;
  2686. #endif
  2687. }
  2688. /* Set extra data against the RSA key at an index.
  2689. *
  2690. * @param [in, out] rsa RSA key.
  2691. * @param [in] idx Index set set extra data at.
  2692. * @param [in] data Extra data of anonymous type.
  2693. * @return 1 on success.
  2694. * @return 0 on failure.
  2695. */
  2696. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2697. {
  2698. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2699. #ifdef HAVE_EX_DATA
  2700. return (rsa == NULL) ? 0 :
  2701. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2702. #else
  2703. (void)rsa;
  2704. (void)idx;
  2705. (void)data;
  2706. return 0;
  2707. #endif
  2708. }
  2709. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2710. /* Set the extra data and cleanup callback against the RSA key at an index.
  2711. *
  2712. * wolfSSL API.
  2713. *
  2714. * @param [in, out] rsa RSA key.
  2715. * @param [in] idx Index set set extra data at.
  2716. * @param [in] data Extra data of anonymous type.
  2717. * @param [in] freeCb Callback function to free extra data.
  2718. * @return 1 on success.
  2719. * @return 0 on failure.
  2720. */
  2721. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2722. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2723. {
  2724. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2725. return (rsa == NULL) ? 0 :
  2726. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2727. freeCb);
  2728. }
  2729. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2730. /*
  2731. * RSA check key APIs
  2732. */
  2733. #ifdef WOLFSSL_RSA_KEY_CHECK
  2734. /* Check that the RSA key is valid using wolfCrypt.
  2735. *
  2736. * @param [in] rsa RSA key.
  2737. * @return 1 on success.
  2738. * @return 0 on failure.
  2739. */
  2740. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2741. {
  2742. int ret = 1;
  2743. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2744. /* Validate parameters. */
  2745. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2746. ret = 0;
  2747. }
  2748. /* Constant RSA - assume internal data has been set. */
  2749. /* Check wolfCrypt RSA key. */
  2750. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2751. ret = 0;
  2752. }
  2753. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2754. return ret;
  2755. }
  2756. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2757. /*
  2758. * RSA generate APIs
  2759. */
  2760. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2761. /* Get a random number generator associated with the RSA key.
  2762. *
  2763. * If not able, then get the global if possible.
  2764. * *tmpRng must not be an initialized RNG.
  2765. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2766. * associated with the wolfCrypt RSA key.
  2767. *
  2768. * @param [in] rsa RSA key.
  2769. * @param [out] tmpRng Temporary random number generator.
  2770. * @param [out] initTmpRng Temporary random number generator was initialized.
  2771. *
  2772. * @return A wolfCrypt RNG to use on success.
  2773. * @return NULL on error.
  2774. */
  2775. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2776. {
  2777. WC_RNG* rng = NULL;
  2778. int err = 0;
  2779. /* Check validity of parameters. */
  2780. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2781. err = 1;
  2782. }
  2783. if (!err) {
  2784. /* Haven't initialized any RNG passed through tmpRng. */
  2785. *initTmpRng = 0;
  2786. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2787. /* Use wolfCrypt RSA key's RNG if available/set. */
  2788. rng = ((RsaKey*)rsa->internal)->rng;
  2789. #endif
  2790. }
  2791. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2792. /* Make an RNG with tmpRng or get global. */
  2793. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2794. if ((rng != NULL) && *initTmpRng) {
  2795. *tmpRng = rng;
  2796. }
  2797. }
  2798. return rng;
  2799. }
  2800. #endif
  2801. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2802. *
  2803. * @param [in, out] rsa RSA key.
  2804. * @param [in] bits Number of bits that the modulus must have.
  2805. * @param [in] e A BN object holding the public exponent to use.
  2806. * @param [in] cb Status callback. Unused.
  2807. * @return 0 on success.
  2808. * @return wolfSSL native error code on error.
  2809. */
  2810. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2811. WOLFSSL_BIGNUM* e, void* cb)
  2812. {
  2813. #ifdef WOLFSSL_KEY_GEN
  2814. int ret = 0;
  2815. #ifdef WOLFSSL_SMALL_STACK
  2816. WC_RNG* tmpRng = NULL;
  2817. #else
  2818. WC_RNG _tmpRng[1];
  2819. WC_RNG* tmpRng = _tmpRng;
  2820. #endif
  2821. int initTmpRng = 0;
  2822. WC_RNG* rng = NULL;
  2823. #endif
  2824. (void)cb;
  2825. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2826. #ifdef WOLFSSL_KEY_GEN
  2827. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2828. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2829. if (rng == NULL) {
  2830. /* Something went wrong so return memory error. */
  2831. ret = MEMORY_E;
  2832. }
  2833. if (ret == 0) {
  2834. /* Generate an RSA key. */
  2835. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2836. (long)wolfSSL_BN_get_word(e), rng);
  2837. if (ret != MP_OKAY) {
  2838. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2839. }
  2840. }
  2841. if (ret == 0) {
  2842. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2843. ret = SetRsaExternal(rsa);
  2844. if (ret == 1) {
  2845. /* Internal matches external. */
  2846. rsa->inSet = 1;
  2847. /* Return success. */
  2848. ret = 0;
  2849. }
  2850. else {
  2851. /* Something went wrong so return memory error. */
  2852. ret = MEMORY_E;
  2853. }
  2854. }
  2855. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2856. if (initTmpRng) {
  2857. wc_FreeRng(tmpRng);
  2858. }
  2859. #ifdef WOLFSSL_SMALL_STACK
  2860. /* Dispose of any allocated RNG. */
  2861. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2862. #endif
  2863. return ret;
  2864. #else
  2865. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2866. (void)rsa;
  2867. (void)e;
  2868. (void)bits;
  2869. return NOT_COMPILED_IN;
  2870. #endif
  2871. }
  2872. /* Generate an RSA key that has the specified modulus size and public exponent.
  2873. *
  2874. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2875. * down to nearest multiple of 8. For example generating a key of size
  2876. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2877. *
  2878. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2879. * @param [in] e Public exponent to use i.e. 65537.
  2880. * @param [in] cb Status callback. Unused.
  2881. * @param [in] data Data to pass to status callback. Unused.
  2882. * @return A new RSA key on success.
  2883. * @return NULL on failure.
  2884. */
  2885. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2886. void(*cb)(int, int, void*), void* data)
  2887. {
  2888. WOLFSSL_RSA* rsa = NULL;
  2889. WOLFSSL_BIGNUM* bn = NULL;
  2890. int err = 0;
  2891. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  2892. (void)cb;
  2893. (void)data;
  2894. /* Validate bits. */
  2895. if (bits < 0) {
  2896. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  2897. err = 1;
  2898. }
  2899. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  2900. * longer values. */
  2901. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  2902. WOLFSSL_ERROR_MSG("Error creating big number");
  2903. err = 1;
  2904. }
  2905. /* Set public exponent. */
  2906. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  2907. WOLFSSL_ERROR_MSG("Error using e value");
  2908. err = 1;
  2909. }
  2910. /* Create an RSA key object to hold generated key. */
  2911. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  2912. WOLFSSL_ERROR_MSG("memory error");
  2913. err = 1;
  2914. }
  2915. while (!err) {
  2916. int ret;
  2917. /* Use wolfCrypt to generate RSA key. */
  2918. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  2919. #ifdef HAVE_FIPS
  2920. /* Keep trying if failed to find a prime. */
  2921. if (ret == PRIME_GEN_E) {
  2922. continue;
  2923. }
  2924. #endif
  2925. if (ret != WOLFSSL_ERROR_NONE) {
  2926. /* Unrecoverable error in generation. */
  2927. err = 1;
  2928. }
  2929. /* Done generating - unrecoverable error or success. */
  2930. break;
  2931. }
  2932. if (err) {
  2933. /* Dispose of RSA key object if generation didn't work. */
  2934. wolfSSL_RSA_free(rsa);
  2935. /* Returning NULL on error. */
  2936. rsa = NULL;
  2937. }
  2938. /* Dispose of the temporary BN used for the public exponent. */
  2939. wolfSSL_BN_free(bn);
  2940. return rsa;
  2941. }
  2942. /* Generate an RSA key that has the specified modulus size and public exponent.
  2943. *
  2944. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2945. * down to nearest multiple of 8. For example generating a key of size
  2946. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2947. *
  2948. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2949. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  2950. * @param [in] cb Status callback. Unused.
  2951. * @return 1 on success.
  2952. * @return 0 on failure.
  2953. */
  2954. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  2955. void* cb)
  2956. {
  2957. int ret = 1;
  2958. /* Validate parameters. */
  2959. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2960. WOLFSSL_ERROR_MSG("bad arguments");
  2961. ret = 0;
  2962. }
  2963. else {
  2964. for (;;) {
  2965. /* Use wolfCrypt to generate RSA key. */
  2966. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  2967. #ifdef HAVE_FIPS
  2968. /* Keep trying again if public key value didn't work. */
  2969. if (gen_ret == PRIME_GEN_E) {
  2970. continue;
  2971. }
  2972. #endif
  2973. if (gen_ret != WOLFSSL_ERROR_NONE) {
  2974. /* Unrecoverable error in generation. */
  2975. ret = 0;
  2976. }
  2977. /* Done generating - unrecoverable error or success. */
  2978. break;
  2979. }
  2980. }
  2981. return ret;
  2982. }
  2983. #endif /* OPENSSL_EXTRA */
  2984. /*
  2985. * RSA padding APIs
  2986. */
  2987. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  2988. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  2989. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  2990. /* Add PKCS#1 PSS padding to hash.
  2991. *
  2992. *
  2993. * +-----------+
  2994. * | M |
  2995. * +-----------+
  2996. * |
  2997. * V
  2998. * Hash
  2999. * |
  3000. * V
  3001. * +--------+----------+----------+
  3002. * M' = |Padding1| mHash | salt |
  3003. * +--------+----------+----------+
  3004. * |
  3005. * +--------+----------+ V
  3006. * DB = |Padding2|maskedseed| Hash
  3007. * +--------+----------+ |
  3008. * | |
  3009. * V | +--+
  3010. * xor <--- MGF <---| |bc|
  3011. * | | +--+
  3012. * | | |
  3013. * V V V
  3014. * +-------------------+----------+--+
  3015. * EM = | maskedDB |maskedseed|bc|
  3016. * +-------------------+----------+--+
  3017. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3018. *
  3019. * @param [in] rsa RSA key.
  3020. * @param [out] em Encoded message.
  3021. * @param [in[ mHash Message hash.
  3022. * @param [in] hashAlg Hash algorithm.
  3023. * @param [in] saltLen Length of salt to generate.
  3024. * @return 1 on success.
  3025. * @return 0 on failure.
  3026. */
  3027. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3028. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3029. {
  3030. int ret = 1;
  3031. enum wc_HashType hashType;
  3032. int hashLen;
  3033. int emLen;
  3034. int mgf;
  3035. int initTmpRng = 0;
  3036. WC_RNG *rng = NULL;
  3037. #ifdef WOLFSSL_SMALL_STACK
  3038. WC_RNG* tmpRng = NULL;
  3039. #else
  3040. WC_RNG _tmpRng[1];
  3041. WC_RNG* tmpRng = _tmpRng;
  3042. #endif
  3043. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3044. /* Validate parameters. */
  3045. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3046. ret = 0;
  3047. }
  3048. if (ret == 1) {
  3049. /* Get/create an RNG. */
  3050. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3051. if (rng == NULL) {
  3052. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3053. ret = 0;
  3054. }
  3055. }
  3056. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3057. /* Set the external data from the wolfCrypt RSA key if not done. */
  3058. if ((ret == 1) && (!rsa->exSet)) {
  3059. ret = SetRsaExternal(rsa);
  3060. }
  3061. if (ret == 1) {
  3062. /* Get the wolfCrypt hash algorithm type. */
  3063. hashType = EvpMd2MacType(hashAlg);
  3064. if (hashType > WC_HASH_TYPE_MAX) {
  3065. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3066. ret = 0;
  3067. }
  3068. }
  3069. if (ret == 1) {
  3070. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3071. mgf = wc_hash2mgf(hashType);
  3072. if (mgf == WC_MGF1NONE) {
  3073. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3074. ret = 0;
  3075. }
  3076. }
  3077. if (ret == 1) {
  3078. /* Get the length of the hash output. */
  3079. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3080. if (hashLen < 0) {
  3081. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3082. ret = 0;
  3083. }
  3084. }
  3085. if (ret == 1) {
  3086. /* Get length of RSA key - encrypted message length. */
  3087. emLen = wolfSSL_RSA_size(rsa);
  3088. if (ret <= 0) {
  3089. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3090. ret = 0;
  3091. }
  3092. }
  3093. if (ret == 1) {
  3094. /* Calculate the salt length to use for special cases. */
  3095. /* TODO: use special case wolfCrypt values? */
  3096. switch (saltLen) {
  3097. /* Negative saltLen values are treated differently. */
  3098. case RSA_PSS_SALTLEN_DIGEST:
  3099. saltLen = hashLen;
  3100. break;
  3101. case RSA_PSS_SALTLEN_MAX_SIGN:
  3102. case RSA_PSS_SALTLEN_MAX:
  3103. #ifdef WOLFSSL_PSS_LONG_SALT
  3104. saltLen = emLen - hashLen - 2;
  3105. #else
  3106. saltLen = hashLen;
  3107. #endif
  3108. break;
  3109. default:
  3110. if (saltLen < 0) {
  3111. /* No other negative values implemented. */
  3112. WOLFSSL_ERROR_MSG("invalid saltLen");
  3113. ret = 0;
  3114. }
  3115. }
  3116. }
  3117. if (ret == 1) {
  3118. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3119. if (wc_RsaPad_ex(mHash, hashLen, em, emLen, RSA_BLOCK_TYPE_1, rng,
  3120. WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3121. wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3122. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3123. ret = 0;
  3124. }
  3125. }
  3126. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3127. if (initTmpRng) {
  3128. wc_FreeRng(tmpRng);
  3129. }
  3130. #ifdef WOLFSSL_SMALL_STACK
  3131. /* Dispose of any allocated RNG. */
  3132. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3133. #endif
  3134. return ret;
  3135. }
  3136. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3137. *
  3138. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3139. *
  3140. * @param [in] rsa RSA key.
  3141. * @param [in[ mHash Message hash.
  3142. * @param [in] hashAlg Hash algorithm.
  3143. * @param [in] em Encoded message.
  3144. * @param [in] saltLen Length of salt to generate.
  3145. * @return 1 on success.
  3146. * @return 0 on failure.
  3147. */
  3148. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3149. const WOLFSSL_EVP_MD *hashAlg,
  3150. const unsigned char *em, int saltLen)
  3151. {
  3152. int ret = 1;
  3153. int hashLen;
  3154. int mgf;
  3155. int emLen;
  3156. int mPrimeLen;
  3157. enum wc_HashType hashType;
  3158. byte *mPrime = NULL;
  3159. byte *buf = NULL;
  3160. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3161. /* Validate parameters. */
  3162. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3163. ret = 0;
  3164. }
  3165. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3166. /* Set the external data from the wolfCrypt RSA key if not done. */
  3167. if ((ret == 1) && (!rsa->exSet)) {
  3168. ret = SetRsaExternal(rsa);
  3169. }
  3170. if (ret == 1) {
  3171. /* Get hash length for hash algorithm. */
  3172. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3173. if (hashLen < 0) {
  3174. ret = 0;
  3175. }
  3176. }
  3177. if (ret == 1) {
  3178. /* Get length of RSA key - encrypted message length. */
  3179. emLen = wolfSSL_RSA_size(rsa);
  3180. if (emLen <= 0) {
  3181. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3182. ret = 0;
  3183. }
  3184. }
  3185. if (ret == 1) {
  3186. /* Calculate the salt length to use for special cases. */
  3187. /* TODO: use special case wolfCrypt values. */
  3188. switch (saltLen) {
  3189. /* Negative saltLen values are treated differently */
  3190. case RSA_PSS_SALTLEN_DIGEST:
  3191. saltLen = hashLen;
  3192. break;
  3193. case RSA_PSS_SALTLEN_MAX_SIGN:
  3194. case RSA_PSS_SALTLEN_MAX:
  3195. #ifdef WOLFSSL_PSS_LONG_SALT
  3196. saltLen = emLen - hashLen - 2;
  3197. #else
  3198. saltLen = hashLen;
  3199. #endif
  3200. break;
  3201. default:
  3202. if (saltLen < 0) {
  3203. /* No other negative values implemented. */
  3204. WOLFSSL_ERROR_MSG("invalid saltLen");
  3205. ret = 0;
  3206. }
  3207. }
  3208. }
  3209. if (ret == 1) {
  3210. /* Get the wolfCrypt hash algorithm type. */
  3211. hashType = EvpMd2MacType(hashAlg);
  3212. if (hashType > WC_HASH_TYPE_MAX) {
  3213. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3214. ret = 0;
  3215. }
  3216. }
  3217. if (ret == 1) {
  3218. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3219. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3220. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3221. ret = 0;
  3222. }
  3223. }
  3224. if (ret == 1) {
  3225. /* Allocate buffer to unpad inline with. */
  3226. buf = (byte*)XMALLOC(emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3227. if (buf == NULL) {
  3228. WOLFSSL_ERROR_MSG("malloc error");
  3229. ret = 0;
  3230. }
  3231. }
  3232. if (ret == 1) {
  3233. /* Copy encrypted message to temp for inline unpadding. */
  3234. XMEMCPY(buf, em, emLen);
  3235. /* Remove and verify the PSS padding. */
  3236. mPrimeLen = wc_RsaUnPad_ex(buf, emLen, &mPrime, RSA_BLOCK_TYPE_1,
  3237. WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3238. wolfSSL_BN_num_bits(rsa->n), NULL);
  3239. if (mPrimeLen < 0) {
  3240. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3241. ret = 0;
  3242. }
  3243. }
  3244. if (ret == 1) {
  3245. /* Verify the hash is correct. */
  3246. if (wc_RsaPSS_CheckPadding_ex(mHash, hashLen, mPrime, mPrimeLen,
  3247. hashType, saltLen, wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3248. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3249. ret = 0;
  3250. }
  3251. }
  3252. /* Dispose of any allocated buffer. */
  3253. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3254. return ret;
  3255. }
  3256. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3257. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3258. * WOLFSSL_NGINX) */
  3259. /*
  3260. * RSA sign/verify APIs
  3261. */
  3262. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3263. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3264. #else
  3265. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3266. #endif
  3267. #if defined(OPENSSL_EXTRA)
  3268. #if !defined(HAVE_USER_RSA)
  3269. /* Encode the message hash.
  3270. *
  3271. * Used by signing and verification.
  3272. *
  3273. * @param [in] hashAlg Hash algorithm OID.
  3274. * @param [in] hash Hash of message to encode for signing.
  3275. * @param [in] hLen Length of hash of message.
  3276. * @param [out] enc Encoded message hash.
  3277. * @param [out] encLen Length of encoded message hash.
  3278. * @param [in] padding Which padding scheme is being used.
  3279. * @return 1 on success.
  3280. * @return 0 on failure.
  3281. */
  3282. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3283. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3284. {
  3285. int ret = 1;
  3286. int hType = WC_HASH_TYPE_NONE;
  3287. /* Validate parameters. */
  3288. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3289. ret = 0;
  3290. }
  3291. if ((ret == 1) && (hashAlg != NID_undef) &&
  3292. (padding == RSA_PKCS1_PADDING)) {
  3293. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3294. hType = nid2oid(hashAlg, oidHashType);
  3295. if (hType == -1) {
  3296. ret = 0;
  3297. }
  3298. }
  3299. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3300. /* PKCS#1.5 encoding. */
  3301. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3302. if (encSz == 0) {
  3303. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3304. ret = 0;
  3305. }
  3306. else {
  3307. *encLen = (unsigned int)encSz;
  3308. }
  3309. }
  3310. /* Other padding schemes require the hash as is. */
  3311. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3312. XMEMCPY(enc, hash, hLen);
  3313. *encLen = hLen;
  3314. }
  3315. return ret;
  3316. }
  3317. /* Sign the message hash using hash algorithm and RSA key.
  3318. *
  3319. * @param [in] hashAlg Hash algorithm OID.
  3320. * @param [in] hash Hash of message to encode for signing.
  3321. * @param [in] hLen Length of hash of message.
  3322. * @param [out] enc Encoded message hash.
  3323. * @param [out] encLen Length of encoded message hash.
  3324. * @param [in] rsa RSA key.
  3325. * @return 1 on success.
  3326. * @return 0 on failure.
  3327. */
  3328. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3329. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3330. {
  3331. if (sigLen != NULL) {
  3332. /* No size checking in this API */
  3333. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3334. }
  3335. /* flag is 1: output complete signature. */
  3336. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3337. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3338. }
  3339. /* Sign the message hash using hash algorithm and RSA key.
  3340. * wolfSSL API.
  3341. *
  3342. * @param [in] hashAlg Hash algorithm NID.
  3343. * @param [in] hash Hash of message to encode for signing.
  3344. * @param [in] hLen Length of hash of message.
  3345. * @param [out] enc Encoded message hash.
  3346. * @param [out] encLen Length of encoded message hash.
  3347. * @param [in] rsa RSA key.
  3348. * @param [in] flag When 1: Output encrypted signature.
  3349. * When 0: Output encoded hash.
  3350. * @return 1 on success.
  3351. * @return 0 on failure.
  3352. */
  3353. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3354. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3355. WOLFSSL_RSA* rsa, int flag)
  3356. {
  3357. int ret = 0;
  3358. if ((flag == 0) || (flag == 1)) {
  3359. if (sigLen != NULL) {
  3360. /* No size checking in this API */
  3361. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3362. }
  3363. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3364. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3365. }
  3366. return ret;
  3367. }
  3368. /**
  3369. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3370. *
  3371. * wolfSSL API.
  3372. *
  3373. * @param [in] hashAlg Hash NID
  3374. * @param [in] hash Message hash to sign.
  3375. * @param [in] mLen Length of message hash to sign.
  3376. * @param [out] sigRet Output buffer.
  3377. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3378. * On Output: length of data written to sigRet.
  3379. * @param [in] rsa RSA key used to sign the input.
  3380. * @param [in] flag 1: Output the signature.
  3381. * 0: Output the value that the unpadded signature
  3382. * should be compared to.
  3383. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3384. * RSA_PKCS1_PADDING are currently supported for
  3385. * signing.
  3386. * @return 1 on success.
  3387. * @return 0 on failure.
  3388. */
  3389. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3390. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3391. WOLFSSL_RSA* rsa, int flag, int padding)
  3392. {
  3393. int ret = 1;
  3394. word32 outLen = 0;
  3395. int signSz = 0;
  3396. WC_RNG* rng = NULL;
  3397. int initTmpRng = 0;
  3398. #ifdef WOLFSSL_SMALL_STACK
  3399. WC_RNG* tmpRng = NULL;
  3400. byte* encodedSig = NULL;
  3401. #else
  3402. WC_RNG _tmpRng[1];
  3403. WC_RNG* tmpRng = _tmpRng;
  3404. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3405. #endif
  3406. unsigned int encSz = 0;
  3407. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3408. if (flag == 0) {
  3409. /* Only encode message. */
  3410. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3411. padding);
  3412. }
  3413. /* Validate parameters. */
  3414. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3415. WOLFSSL_ERROR_MSG("Bad function arguments");
  3416. ret = 0;
  3417. }
  3418. /* Set wolfCrypt RSA key data from external if not already done. */
  3419. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3420. ret = 0;
  3421. }
  3422. if (ret == 1) {
  3423. /* Get the maximum signature length. */
  3424. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3425. /* Check not an error return. */
  3426. if (outLen == 0) {
  3427. WOLFSSL_ERROR_MSG("Bad RSA size");
  3428. ret = 0;
  3429. }
  3430. /* Check signature buffer is big enough. */
  3431. else if (outLen > *sigLen) {
  3432. WOLFSSL_ERROR_MSG("Output buffer too small");
  3433. ret = 0;
  3434. }
  3435. }
  3436. #ifdef WOLFSSL_SMALL_STACK
  3437. if (ret == 1) {
  3438. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3439. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3440. DYNAMIC_TYPE_SIGNATURE);
  3441. if (encodedSig == NULL) {
  3442. ret = 0;
  3443. }
  3444. }
  3445. #endif
  3446. if (ret == 1) {
  3447. /* Get/create an RNG. */
  3448. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3449. if (rng == NULL) {
  3450. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3451. ret = 0;
  3452. }
  3453. }
  3454. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3455. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3456. &encSz, padding) == 0)) {
  3457. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3458. ret = 0;
  3459. }
  3460. if (ret == 1) {
  3461. switch (padding) {
  3462. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3463. case RSA_NO_PADDING:
  3464. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3465. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3466. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3467. ret = 0;
  3468. }
  3469. break;
  3470. #endif
  3471. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3472. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3473. case RSA_PKCS1_PSS_PADDING:
  3474. {
  3475. enum wc_HashType hType =
  3476. wc_OidGetHash(nid2oid(hashAlg, oidHashType));
  3477. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3478. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3479. "OpenSSL uses max length by default.");
  3480. #endif
  3481. /* Create RSA PSS signature. */
  3482. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3483. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3484. (RsaKey*)rsa->internal, rng)) <= 0) {
  3485. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3486. ret = 0;
  3487. }
  3488. break;
  3489. }
  3490. #endif
  3491. #ifndef WC_NO_RSA_OAEP
  3492. case RSA_PKCS1_OAEP_PADDING:
  3493. /* Not a signature padding scheme. */
  3494. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3495. "signing");
  3496. ret = 0;
  3497. break;
  3498. #endif
  3499. case RSA_PKCS1_PADDING:
  3500. {
  3501. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3502. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3503. (RsaKey*)rsa->internal, rng)) <= 0) {
  3504. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3505. ret = 0;
  3506. }
  3507. break;
  3508. }
  3509. default:
  3510. WOLFSSL_ERROR_MSG("Unsupported padding");
  3511. ret = 0;
  3512. break;
  3513. }
  3514. }
  3515. if (ret == 1) {
  3516. /* Return the size of signature generated. */
  3517. *sigLen = (unsigned int)signSz;
  3518. }
  3519. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3520. if (initTmpRng) {
  3521. wc_FreeRng(tmpRng);
  3522. }
  3523. #ifdef WOLFSSL_SMALL_STACK
  3524. /* Dispose of any allocated RNG and encoded signature. */
  3525. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3526. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3527. #endif
  3528. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3529. return ret;
  3530. }
  3531. /**
  3532. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3533. *
  3534. * @param [in] hashAlg Hash NID
  3535. * @param [in] hash Message hash.
  3536. * @param [in] mLen Length of message hash.
  3537. * @param [in] sigRet Signature data.
  3538. * @param [in] sigLen Length of signature data.
  3539. * @param [in] rsa RSA key used to sign the input
  3540. * @return 1 on success.
  3541. * @return 0 on failure.
  3542. */
  3543. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3544. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3545. WOLFSSL_RSA* rsa)
  3546. {
  3547. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3548. RSA_PKCS1_PADDING);
  3549. }
  3550. /**
  3551. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3552. *
  3553. * wolfSSL API.
  3554. *
  3555. * @param [in] hashAlg Hash NID
  3556. * @param [in] hash Message hash.
  3557. * @param [in] mLen Length of message hash.
  3558. * @param [in] sigRet Signature data.
  3559. * @param [in] sigLen Length of signature data.
  3560. * @param [in] rsa RSA key used to sign the input
  3561. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3562. * RSA_PKCS1_PADDING are currently supported for
  3563. * signing.
  3564. * @return 1 on success.
  3565. * @return 0 on failure.
  3566. */
  3567. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3568. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3569. WOLFSSL_RSA* rsa, int padding)
  3570. {
  3571. int ret = 1;
  3572. #ifdef WOLFSSL_SMALL_STACK
  3573. unsigned char* encodedSig = NULL;
  3574. #else
  3575. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3576. #endif
  3577. unsigned char* sigDec = NULL;
  3578. unsigned int len = MAX_ENCODED_SIG_SZ;
  3579. int verLen = 0;
  3580. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3581. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3582. #endif
  3583. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3584. /* Validate parameters. */
  3585. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3586. WOLFSSL_ERROR_MSG("Bad function arguments");
  3587. ret = 0;
  3588. }
  3589. if (ret == 1) {
  3590. /* Allocate memory for decrypted signature. */
  3591. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3592. DYNAMIC_TYPE_TMP_BUFFER);
  3593. if (sigDec == NULL) {
  3594. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3595. ret = 0;
  3596. }
  3597. }
  3598. #ifdef WOLFSSL_SMALL_STACK
  3599. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3600. /* Allocate memory for encoded signature. */
  3601. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3602. DYNAMIC_TYPE_TMP_BUFFER);
  3603. if (encodedSig == NULL) {
  3604. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3605. ret = 0;
  3606. }
  3607. }
  3608. #endif
  3609. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3610. /* Make encoded signature to compare with decrypted signature. */
  3611. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3612. padding) <= 0) {
  3613. WOLFSSL_ERROR_MSG("Message Digest Error");
  3614. ret = 0;
  3615. }
  3616. }
  3617. if (ret == 1) {
  3618. /* Decrypt signature */
  3619. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3620. !defined(HAVE_SELFTEST)
  3621. hType = wc_OidGetHash(nid2oid(hashAlg, oidHashType));
  3622. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3623. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3624. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3625. ret = 0;
  3626. }
  3627. #else
  3628. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3629. (RsaKey*)rsa->internal);
  3630. if (verLen < 0) {
  3631. ret = 0;
  3632. }
  3633. #endif
  3634. }
  3635. if (ret == 1) {
  3636. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3637. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3638. if (padding == RSA_PKCS1_PSS_PADDING) {
  3639. /* Check PSS padding is valid. */
  3640. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, verLen,
  3641. hType, DEF_PSS_SALT_LEN,
  3642. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3643. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3644. ret = 0;
  3645. }
  3646. }
  3647. else
  3648. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3649. * FIPS_VERSION >= 5.1) */
  3650. /* Compare decrypted signature to encoded signature. */
  3651. if ((int)len != verLen || XMEMCMP(encodedSig, sigDec, verLen) != 0) {
  3652. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3653. ret = 0;
  3654. }
  3655. }
  3656. /* Dispose of any allocated data. */
  3657. #ifdef WOLFSSL_SMALL_STACK
  3658. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3659. #endif
  3660. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3661. return ret;
  3662. }
  3663. /*
  3664. * RSA public/private encrypt/decrypt APIs
  3665. */
  3666. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  3667. /* Encrypt with the RSA public key.
  3668. *
  3669. * Return compliant with OpenSSL.
  3670. *
  3671. * @param [in] len Length of data to encrypt.
  3672. * @param [in] from Data to encrypt.
  3673. * @param [out] to Encrypted data.
  3674. * @param [in] rsa RSA key.
  3675. * @param [in] padding Type of padding to place around plaintext.
  3676. * @return Size of encrypted data on success.
  3677. * @return -1 on failure.
  3678. */
  3679. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3680. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3681. {
  3682. int ret = 0;
  3683. int initTmpRng = 0;
  3684. WC_RNG *rng = NULL;
  3685. #ifdef WOLFSSL_SMALL_STACK
  3686. WC_RNG* tmpRng = NULL;
  3687. #else
  3688. WC_RNG _tmpRng[1];
  3689. WC_RNG* tmpRng = _tmpRng;
  3690. #endif
  3691. #if !defined(HAVE_FIPS)
  3692. int mgf = WC_MGF1NONE;
  3693. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3694. int pad_type = WC_RSA_NO_PAD;
  3695. #endif
  3696. int outLen = 0;
  3697. WOLFSSL_ENTER("RSA_public_encrypt");
  3698. /* Validate parameters. */
  3699. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3700. (from == NULL)) {
  3701. WOLFSSL_ERROR_MSG("Bad function arguments");
  3702. ret = -1;
  3703. }
  3704. if (ret == 0) {
  3705. #if !defined(HAVE_FIPS)
  3706. /* Convert to wolfCrypt padding, hash and MGF. */
  3707. switch (padding) {
  3708. case RSA_PKCS1_PADDING:
  3709. pad_type = WC_RSA_PKCSV15_PAD;
  3710. break;
  3711. case RSA_PKCS1_OAEP_PADDING:
  3712. pad_type = WC_RSA_OAEP_PAD;
  3713. hash = WC_HASH_TYPE_SHA;
  3714. mgf = WC_MGF1SHA1;
  3715. break;
  3716. case RSA_NO_PADDING:
  3717. pad_type = WC_RSA_NO_PAD;
  3718. break;
  3719. default:
  3720. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3721. "scheme");
  3722. ret = -1;
  3723. }
  3724. #else
  3725. /* Check for supported padding schemes in FIPS. */
  3726. /* TODO: Do we support more schemes in later versions of FIPS? */
  3727. if (padding != RSA_PKCS1_PADDING) {
  3728. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3729. "FIPS");
  3730. ret = -1;
  3731. }
  3732. #endif
  3733. }
  3734. /* Set wolfCrypt RSA key data from external if not already done. */
  3735. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3736. ret = -1;
  3737. }
  3738. if (ret == 0) {
  3739. /* Calculate maximum length of encrypted data. */
  3740. outLen = wolfSSL_RSA_size(rsa);
  3741. if (outLen == 0) {
  3742. WOLFSSL_ERROR_MSG("Bad RSA size");
  3743. ret = -1;
  3744. }
  3745. }
  3746. if (ret == 0) {
  3747. /* Get an RNG. */
  3748. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3749. if (rng == NULL) {
  3750. ret = -1;
  3751. }
  3752. }
  3753. if (ret == 0) {
  3754. /* Use wolfCrypt to public-encrypt with RSA key. */
  3755. #if !defined(HAVE_FIPS)
  3756. ret = wc_RsaPublicEncrypt_ex(from, len, to, outLen,
  3757. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3758. #else
  3759. ret = wc_RsaPublicEncrypt(from, len, to, outLen, (RsaKey*)rsa->internal,
  3760. rng);
  3761. #endif
  3762. }
  3763. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3764. if (initTmpRng) {
  3765. wc_FreeRng(tmpRng);
  3766. }
  3767. #ifdef WOLFSSL_SMALL_STACK
  3768. /* Dispose of any allocated RNG. */
  3769. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3770. #endif
  3771. /* wolfCrypt error means return -1. */
  3772. if (ret <= 0) {
  3773. ret = -1;
  3774. }
  3775. WOLFSSL_LEAVE("RSA_public_encrypt", ret);
  3776. return ret;
  3777. }
  3778. /* Decrypt with the RSA public key.
  3779. *
  3780. * Return compliant with OpenSSL.
  3781. *
  3782. * @param [in] len Length of encrypted data.
  3783. * @param [in] from Encrypted data.
  3784. * @param [out] to Decrypted data.
  3785. * @param [in] rsa RSA key.
  3786. * @param [in] padding Type of padding to around plaintext to remove.
  3787. * @return Size of decrypted data on success.
  3788. * @return -1 on failure.
  3789. */
  3790. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3791. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3792. {
  3793. int ret = 0;
  3794. #if !defined(HAVE_FIPS)
  3795. int mgf = WC_MGF1NONE;
  3796. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3797. int pad_type = WC_RSA_NO_PAD;
  3798. #endif
  3799. int outLen = 0;
  3800. WOLFSSL_ENTER("RSA_private_decrypt");
  3801. /* Validate parameters. */
  3802. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3803. (from == NULL)) {
  3804. WOLFSSL_ERROR_MSG("Bad function arguments");
  3805. ret = -1;
  3806. }
  3807. if (ret == 0) {
  3808. #if !defined(HAVE_FIPS)
  3809. switch (padding) {
  3810. case RSA_PKCS1_PADDING:
  3811. pad_type = WC_RSA_PKCSV15_PAD;
  3812. break;
  3813. case RSA_PKCS1_OAEP_PADDING:
  3814. pad_type = WC_RSA_OAEP_PAD;
  3815. hash = WC_HASH_TYPE_SHA;
  3816. mgf = WC_MGF1SHA1;
  3817. break;
  3818. case RSA_NO_PADDING:
  3819. pad_type = WC_RSA_NO_PAD;
  3820. break;
  3821. default:
  3822. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3823. ret = -1;
  3824. }
  3825. #else
  3826. /* Check for supported padding schemes in FIPS. */
  3827. /* TODO: Do we support more schemes in later versions of FIPS? */
  3828. if (padding != RSA_PKCS1_PADDING) {
  3829. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3830. "FIPS");
  3831. ret = -1;
  3832. }
  3833. #endif
  3834. }
  3835. /* Set wolfCrypt RSA key data from external if not already done. */
  3836. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3837. ret = -1;
  3838. }
  3839. if (ret == 0) {
  3840. /* Calculate maximum length of decrypted data. */
  3841. outLen = wolfSSL_RSA_size(rsa);
  3842. if (outLen == 0) {
  3843. WOLFSSL_ERROR_MSG("Bad RSA size");
  3844. ret = -1;
  3845. }
  3846. }
  3847. if (ret == 0) {
  3848. /* Use wolfCrypt to private-decrypt with RSA key.
  3849. * Size of 'to' buffer must be size of RSA key */
  3850. #if !defined(HAVE_FIPS)
  3851. ret = wc_RsaPrivateDecrypt_ex(from, len, to, outLen,
  3852. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3853. #else
  3854. ret = wc_RsaPrivateDecrypt(from, len, to, outLen,
  3855. (RsaKey*)rsa->internal);
  3856. #endif
  3857. }
  3858. /* wolfCrypt error means return -1. */
  3859. if (ret <= 0) {
  3860. ret = -1;
  3861. }
  3862. WOLFSSL_LEAVE("RSA_private_decrypt", ret);
  3863. return ret;
  3864. }
  3865. /* Decrypt with the RSA public key.
  3866. *
  3867. * @param [in] len Length of encrypted data.
  3868. * @param [in] from Encrypted data.
  3869. * @param [out] to Decrypted data.
  3870. * @param [in] rsa RSA key.
  3871. * @param [in] padding Type of padding to around plaintext to remove.
  3872. * @return Size of decrypted data on success.
  3873. * @return -1 on failure.
  3874. */
  3875. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3876. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3877. {
  3878. int ret = 0;
  3879. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3880. int pad_type = WC_RSA_NO_PAD;
  3881. #endif
  3882. int outLen = 0;
  3883. WOLFSSL_ENTER("RSA_public_decrypt");
  3884. /* Validate parameters. */
  3885. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3886. (from == NULL)) {
  3887. WOLFSSL_ERROR_MSG("Bad function arguments");
  3888. ret = -1;
  3889. }
  3890. if (ret == 0) {
  3891. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3892. switch (padding) {
  3893. case RSA_PKCS1_PADDING:
  3894. pad_type = WC_RSA_PKCSV15_PAD;
  3895. break;
  3896. case RSA_NO_PADDING:
  3897. pad_type = WC_RSA_NO_PAD;
  3898. break;
  3899. /* TODO: RSA_X931_PADDING not supported */
  3900. default:
  3901. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  3902. ret = -1;
  3903. }
  3904. #else
  3905. if (padding != RSA_PKCS1_PADDING) {
  3906. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  3907. "FIPS");
  3908. ret = -1;
  3909. }
  3910. #endif
  3911. }
  3912. /* Set wolfCrypt RSA key data from external if not already done. */
  3913. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3914. ret = -1;
  3915. }
  3916. if (ret == 0) {
  3917. /* Calculate maximum length of encrypted data. */
  3918. outLen = wolfSSL_RSA_size(rsa);
  3919. if (outLen == 0) {
  3920. WOLFSSL_ERROR_MSG("Bad RSA size");
  3921. ret = -1;
  3922. }
  3923. }
  3924. if (ret == 0) {
  3925. /* Use wolfCrypt to public-decrypt with RSA key. */
  3926. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3927. /* Size of 'to' buffer must be size of RSA key. */
  3928. ret = wc_RsaSSL_Verify_ex(from, len, to, outLen,
  3929. (RsaKey*)rsa->internal, pad_type);
  3930. #else
  3931. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  3932. ret = wc_RsaSSL_Verify(from, len, to, outLen, (RsaKey*)rsa->internal);
  3933. #endif
  3934. }
  3935. /* wolfCrypt error means return -1. */
  3936. if (ret <= 0) {
  3937. ret = -1;
  3938. }
  3939. WOLFSSL_LEAVE("RSA_public_decrypt", ret);
  3940. return ret;
  3941. }
  3942. /* Encrypt with the RSA private key.
  3943. *
  3944. * Calls wc_RsaSSL_Sign.
  3945. *
  3946. * @param [in] len Length of data to encrypt.
  3947. * @param [in] from Data to encrypt.
  3948. * @param [out] to Encrypted data.
  3949. * @param [in] rsa RSA key.
  3950. * @param [in] padding Type of padding to place around plaintext.
  3951. * @return Size of encrypted data on success.
  3952. * @return -1 on failure.
  3953. */
  3954. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  3955. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3956. {
  3957. int ret = 0;
  3958. int initTmpRng = 0;
  3959. WC_RNG *rng = NULL;
  3960. #ifdef WOLFSSL_SMALL_STACK
  3961. WC_RNG* tmpRng = NULL;
  3962. #else
  3963. WC_RNG _tmpRng[1];
  3964. WC_RNG* tmpRng = _tmpRng;
  3965. #endif
  3966. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  3967. /* Validate parameters. */
  3968. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3969. (from == NULL)) {
  3970. WOLFSSL_ERROR_MSG("Bad function arguments");
  3971. ret = -1;
  3972. }
  3973. if (ret == 0) {
  3974. switch (padding) {
  3975. case RSA_PKCS1_PADDING:
  3976. #ifdef WC_RSA_NO_PADDING
  3977. case RSA_NO_PADDING:
  3978. #endif
  3979. break;
  3980. /* TODO: RSA_X931_PADDING not supported */
  3981. default:
  3982. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  3983. ret = -1;
  3984. }
  3985. }
  3986. /* Set wolfCrypt RSA key data from external if not already done. */
  3987. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3988. ret = -1;
  3989. }
  3990. if (ret == 0) {
  3991. /* Get an RNG. */
  3992. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3993. if (rng == NULL) {
  3994. ret = -1;
  3995. }
  3996. }
  3997. if (ret == 0) {
  3998. /* Use wolfCrypt to private-encrypt with RSA key.
  3999. * Size of output buffer must be size of RSA key. */
  4000. if (padding == RSA_PKCS1_PADDING) {
  4001. ret = wc_RsaSSL_Sign(from, (word32)len, to, wolfSSL_RSA_size(rsa),
  4002. (RsaKey*)rsa->internal, rng);
  4003. }
  4004. #ifdef WC_RSA_NO_PADDING
  4005. else if (padding == RSA_NO_PADDING) {
  4006. word32 outLen = wolfSSL_RSA_size(rsa);
  4007. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  4008. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  4009. if (ret == 0)
  4010. ret = (int)outLen;
  4011. }
  4012. #endif
  4013. }
  4014. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4015. if (initTmpRng) {
  4016. wc_FreeRng(tmpRng);
  4017. }
  4018. #ifdef WOLFSSL_SMALL_STACK
  4019. /* Dispose of any allocated RNG. */
  4020. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4021. #endif
  4022. /* wolfCrypt error means return -1. */
  4023. if (ret <= 0) {
  4024. ret = -1;
  4025. }
  4026. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4027. return ret;
  4028. }
  4029. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  4030. /*
  4031. * RSA misc operation APIs
  4032. */
  4033. /* Calculate d mod p-1 and q-1 into BNs.
  4034. *
  4035. * wolfSSL API.
  4036. *
  4037. * @param [in, out] rsa RSA key.
  4038. * @return 1 on success.
  4039. * @return -1 on failure.
  4040. */
  4041. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4042. {
  4043. int ret = 1;
  4044. int err;
  4045. mp_int* t = NULL;
  4046. #ifdef WOLFSSL_SMALL_STACK
  4047. mp_int *tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4048. DYNAMIC_TYPE_TMP_BUFFER);
  4049. if (tmp == NULL) {
  4050. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4051. return -1;
  4052. }
  4053. #else
  4054. mp_int tmp[1];
  4055. #endif
  4056. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4057. /* Validate parameters. */
  4058. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4059. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4060. WOLFSSL_ERROR_MSG("rsa no init error");
  4061. ret = -1;
  4062. }
  4063. if (ret == 1) {
  4064. /* Initialize temp MP integer. */
  4065. if (mp_init(tmp) != MP_OKAY) {
  4066. WOLFSSL_ERROR_MSG("mp_init error");
  4067. ret = -1;
  4068. }
  4069. }
  4070. if (ret == 1) {
  4071. t = tmp;
  4072. /* Sub 1 from p into temp. */
  4073. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4074. if (err != MP_OKAY) {
  4075. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4076. ret = -1;
  4077. }
  4078. }
  4079. if (ret == 1) {
  4080. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4081. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4082. (mp_int*)rsa->dmp1->internal);
  4083. if (err != MP_OKAY) {
  4084. WOLFSSL_ERROR_MSG("mp_mod error");
  4085. ret = -1;
  4086. }
  4087. }
  4088. if (ret == 1) {
  4089. /* Sub 1 from q into temp. */
  4090. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4091. if (err != MP_OKAY) {
  4092. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4093. ret = -1;
  4094. }
  4095. }
  4096. if (ret == 1) {
  4097. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4098. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4099. (mp_int*)rsa->dmq1->internal);
  4100. if (err != MP_OKAY) {
  4101. WOLFSSL_ERROR_MSG("mp_mod error");
  4102. ret = -1;
  4103. }
  4104. }
  4105. mp_clear(t);
  4106. #ifdef WOLFSSL_SMALL_STACK
  4107. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4108. #endif
  4109. return ret;
  4110. }
  4111. #endif /* !HAVE_USER_RSA */
  4112. #ifndef NO_WOLFSSL_STUB
  4113. /* Enable blinding for RSA key operations.
  4114. *
  4115. * Blinding is a compile time option in wolfCrypt.
  4116. *
  4117. * @param [in] rsa RSA key. Unused.
  4118. * @param [in] bnCtx BN context to use for blinding. Unused.
  4119. * @return 1 always.
  4120. */
  4121. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4122. {
  4123. WOLFSSL_STUB("RSA_blinding_on");
  4124. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4125. (void)rsa;
  4126. (void)bnCtx;
  4127. return 1; /* on by default */
  4128. }
  4129. #endif
  4130. #endif /* OPENSSL_EXTRA */
  4131. #endif /* !NO_RSA */
  4132. /*******************************************************************************
  4133. * END OF RSA API
  4134. ******************************************************************************/
  4135. /*******************************************************************************
  4136. * START OF DSA API
  4137. ******************************************************************************/
  4138. #ifndef NO_DSA
  4139. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4140. !defined(NO_STDIO_FILESYSTEM)
  4141. /* return code compliant with OpenSSL :
  4142. * 1 if success, 0 if error
  4143. */
  4144. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4145. {
  4146. int ret = 1;
  4147. int pBits;
  4148. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4149. if (fp == XBADFILE || dsa == NULL) {
  4150. ret = 0;
  4151. }
  4152. if (ret == 1 && dsa->p != NULL) {
  4153. pBits = wolfSSL_BN_num_bits(dsa->p);
  4154. if (pBits == 0) {
  4155. ret = 0;
  4156. }
  4157. else {
  4158. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4159. ret = 0;
  4160. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4161. ret = 0;
  4162. }
  4163. }
  4164. if (ret == 1 && dsa->priv_key != NULL) {
  4165. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4166. }
  4167. if (ret == 1 && dsa->pub_key != NULL) {
  4168. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4169. }
  4170. if (ret == 1 && dsa->p != NULL) {
  4171. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4172. }
  4173. if (ret == 1 && dsa->q != NULL) {
  4174. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4175. }
  4176. if (ret == 1 && dsa->g != NULL) {
  4177. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4178. }
  4179. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4180. return ret;
  4181. }
  4182. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4183. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4184. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4185. {
  4186. if (dsa) {
  4187. dsa->p = NULL;
  4188. dsa->q = NULL;
  4189. dsa->g = NULL;
  4190. dsa->pub_key = NULL;
  4191. dsa->priv_key = NULL;
  4192. dsa->internal = NULL;
  4193. dsa->inSet = 0;
  4194. dsa->exSet = 0;
  4195. }
  4196. }
  4197. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4198. {
  4199. WOLFSSL_DSA* external;
  4200. DsaKey* key;
  4201. WOLFSSL_MSG("wolfSSL_DSA_new");
  4202. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4203. if (key == NULL) {
  4204. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4205. return NULL;
  4206. }
  4207. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4208. DYNAMIC_TYPE_DSA);
  4209. if (external == NULL) {
  4210. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4211. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4212. return NULL;
  4213. }
  4214. InitwolfSSL_DSA(external);
  4215. if (wc_InitDsaKey(key) != 0) {
  4216. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4217. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4218. wolfSSL_DSA_free(external);
  4219. return NULL;
  4220. }
  4221. external->internal = key;
  4222. return external;
  4223. }
  4224. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4225. {
  4226. WOLFSSL_MSG("wolfSSL_DSA_free");
  4227. if (dsa) {
  4228. if (dsa->internal) {
  4229. FreeDsaKey((DsaKey*)dsa->internal);
  4230. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4231. dsa->internal = NULL;
  4232. }
  4233. wolfSSL_BN_free(dsa->priv_key);
  4234. wolfSSL_BN_free(dsa->pub_key);
  4235. wolfSSL_BN_free(dsa->g);
  4236. wolfSSL_BN_free(dsa->q);
  4237. wolfSSL_BN_free(dsa->p);
  4238. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4239. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4240. /* dsa = NULL, don't try to access or double free it */
  4241. }
  4242. }
  4243. /* wolfSSL -> OpenSSL */
  4244. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4245. {
  4246. DsaKey* key;
  4247. WOLFSSL_MSG("Entering SetDsaExternal");
  4248. if (dsa == NULL || dsa->internal == NULL) {
  4249. WOLFSSL_MSG("dsa key NULL error");
  4250. return -1;
  4251. }
  4252. key = (DsaKey*)dsa->internal;
  4253. if (SetIndividualExternal(&dsa->p, &key->p) != 1) {
  4254. WOLFSSL_MSG("dsa p key error");
  4255. return -1;
  4256. }
  4257. if (SetIndividualExternal(&dsa->q, &key->q) != 1) {
  4258. WOLFSSL_MSG("dsa q key error");
  4259. return -1;
  4260. }
  4261. if (SetIndividualExternal(&dsa->g, &key->g) != 1) {
  4262. WOLFSSL_MSG("dsa g key error");
  4263. return -1;
  4264. }
  4265. if (SetIndividualExternal(&dsa->pub_key, &key->y) != 1) {
  4266. WOLFSSL_MSG("dsa y key error");
  4267. return -1;
  4268. }
  4269. if (SetIndividualExternal(&dsa->priv_key, &key->x) != 1) {
  4270. WOLFSSL_MSG("dsa x key error");
  4271. return -1;
  4272. }
  4273. dsa->exSet = 1;
  4274. return 1;
  4275. }
  4276. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4277. #ifdef OPENSSL_EXTRA
  4278. /* Openssl -> WolfSSL */
  4279. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4280. {
  4281. DsaKey* key;
  4282. WOLFSSL_MSG("Entering SetDsaInternal");
  4283. if (dsa == NULL || dsa->internal == NULL) {
  4284. WOLFSSL_MSG("dsa key NULL error");
  4285. return -1;
  4286. }
  4287. key = (DsaKey*)dsa->internal;
  4288. if (dsa->p != NULL &&
  4289. SetIndividualInternal(dsa->p, &key->p) != 1) {
  4290. WOLFSSL_MSG("rsa p key error");
  4291. return -1;
  4292. }
  4293. if (dsa->q != NULL &&
  4294. SetIndividualInternal(dsa->q, &key->q) != 1) {
  4295. WOLFSSL_MSG("rsa q key error");
  4296. return -1;
  4297. }
  4298. if (dsa->g != NULL &&
  4299. SetIndividualInternal(dsa->g, &key->g) != 1) {
  4300. WOLFSSL_MSG("rsa g key error");
  4301. return -1;
  4302. }
  4303. if (dsa->pub_key != NULL) {
  4304. if (SetIndividualInternal(dsa->pub_key, &key->y) != 1) {
  4305. WOLFSSL_MSG("rsa pub_key error");
  4306. return -1;
  4307. }
  4308. /* public key */
  4309. key->type = DSA_PUBLIC;
  4310. }
  4311. if (dsa->priv_key != NULL) {
  4312. if (SetIndividualInternal(dsa->priv_key, &key->x) != 1) {
  4313. WOLFSSL_MSG("rsa priv_key error");
  4314. return -1;
  4315. }
  4316. /* private key */
  4317. key->type = DSA_PRIVATE;
  4318. }
  4319. dsa->inSet = 1;
  4320. return 1;
  4321. }
  4322. /* return code compliant with OpenSSL :
  4323. * 1 if success, 0 if error
  4324. */
  4325. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4326. {
  4327. int ret = 0;
  4328. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4329. if (dsa == NULL || dsa->internal == NULL) {
  4330. WOLFSSL_MSG("Bad arguments");
  4331. return 0;
  4332. }
  4333. if (dsa->inSet == 0) {
  4334. WOLFSSL_MSG("No DSA internal set, do it");
  4335. if (SetDsaInternal(dsa) != 1) {
  4336. WOLFSSL_MSG("SetDsaInternal failed");
  4337. return ret;
  4338. }
  4339. }
  4340. #ifdef WOLFSSL_KEY_GEN
  4341. {
  4342. int initTmpRng = 0;
  4343. WC_RNG *rng = NULL;
  4344. #ifdef WOLFSSL_SMALL_STACK
  4345. WC_RNG *tmpRng;
  4346. #else
  4347. WC_RNG tmpRng[1];
  4348. #endif
  4349. #ifdef WOLFSSL_SMALL_STACK
  4350. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4351. if (tmpRng == NULL)
  4352. return -1;
  4353. #endif
  4354. if (wc_InitRng(tmpRng) == 0) {
  4355. rng = tmpRng;
  4356. initTmpRng = 1;
  4357. }
  4358. else {
  4359. WOLFSSL_MSG("Bad RNG Init, trying global");
  4360. rng = wolfssl_get_global_rng();
  4361. }
  4362. if (rng) {
  4363. /* These were allocated above by SetDsaInternal(). They should
  4364. * be cleared before wc_MakeDsaKey() which reinitializes
  4365. * x and y. */
  4366. mp_clear(&((DsaKey*)dsa->internal)->x);
  4367. mp_clear(&((DsaKey*)dsa->internal)->y);
  4368. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4369. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4370. else if (SetDsaExternal(dsa) != 1)
  4371. WOLFSSL_MSG("SetDsaExternal failed");
  4372. else
  4373. ret = 1;
  4374. }
  4375. if (initTmpRng)
  4376. wc_FreeRng(tmpRng);
  4377. #ifdef WOLFSSL_SMALL_STACK
  4378. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4379. #endif
  4380. }
  4381. #else /* WOLFSSL_KEY_GEN */
  4382. WOLFSSL_MSG("No Key Gen built in");
  4383. #endif
  4384. return ret;
  4385. }
  4386. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4387. */
  4388. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4389. int seedLen, int* counterRet, unsigned long* hRet,
  4390. WOLFSSL_BN_CB cb, void* CBArg)
  4391. {
  4392. WOLFSSL_DSA* dsa;
  4393. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters()");
  4394. (void)cb;
  4395. (void)CBArg;
  4396. dsa = wolfSSL_DSA_new();
  4397. if (dsa == NULL) {
  4398. return NULL;
  4399. }
  4400. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4401. counterRet, hRet, NULL) != 1) {
  4402. wolfSSL_DSA_free(dsa);
  4403. return NULL;
  4404. }
  4405. return dsa;
  4406. }
  4407. /* return code compliant with OpenSSL :
  4408. * 1 if success, 0 if error
  4409. */
  4410. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4411. unsigned char* seed, int seedLen,
  4412. int* counterRet,
  4413. unsigned long* hRet, void* cb)
  4414. {
  4415. int ret = 0;
  4416. (void)bits;
  4417. (void)seed;
  4418. (void)seedLen;
  4419. (void)counterRet;
  4420. (void)hRet;
  4421. (void)cb;
  4422. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4423. if (dsa == NULL || dsa->internal == NULL) {
  4424. WOLFSSL_MSG("Bad arguments");
  4425. return 0;
  4426. }
  4427. #ifdef WOLFSSL_KEY_GEN
  4428. {
  4429. int initTmpRng = 0;
  4430. WC_RNG *rng = NULL;
  4431. #ifdef WOLFSSL_SMALL_STACK
  4432. WC_RNG *tmpRng;
  4433. #else
  4434. WC_RNG tmpRng[1];
  4435. #endif
  4436. #ifdef WOLFSSL_SMALL_STACK
  4437. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4438. if (tmpRng == NULL)
  4439. return -1;
  4440. #endif
  4441. if (wc_InitRng(tmpRng) == 0) {
  4442. rng = tmpRng;
  4443. initTmpRng = 1;
  4444. }
  4445. else {
  4446. WOLFSSL_MSG("Bad RNG Init, trying global");
  4447. rng = wolfssl_get_global_rng();
  4448. }
  4449. if (rng) {
  4450. if (wc_MakeDsaParameters(rng, bits,
  4451. (DsaKey*)dsa->internal) != MP_OKAY)
  4452. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4453. else if (SetDsaExternal(dsa) != 1)
  4454. WOLFSSL_MSG("SetDsaExternal failed");
  4455. else
  4456. ret = 1;
  4457. }
  4458. if (initTmpRng)
  4459. wc_FreeRng(tmpRng);
  4460. #ifdef WOLFSSL_SMALL_STACK
  4461. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4462. #endif
  4463. }
  4464. #else /* WOLFSSL_KEY_GEN */
  4465. WOLFSSL_MSG("No Key Gen built in");
  4466. #endif
  4467. return ret;
  4468. }
  4469. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4470. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4471. {
  4472. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4473. if (d != NULL) {
  4474. if (p != NULL)
  4475. *p = d->p;
  4476. if (q != NULL)
  4477. *q = d->q;
  4478. if (g != NULL)
  4479. *g = d->g;
  4480. }
  4481. }
  4482. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4483. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4484. {
  4485. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4486. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4487. WOLFSSL_MSG("Bad parameter");
  4488. return 0;
  4489. }
  4490. wolfSSL_BN_free(d->p);
  4491. wolfSSL_BN_free(d->q);
  4492. wolfSSL_BN_free(d->g);
  4493. d->p = p;
  4494. d->q = q;
  4495. d->g = g;
  4496. return 1;
  4497. }
  4498. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4499. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4500. {
  4501. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4502. if (d != NULL) {
  4503. if (pub_key != NULL)
  4504. *pub_key = d->pub_key;
  4505. if (priv_key != NULL)
  4506. *priv_key = d->priv_key;
  4507. }
  4508. }
  4509. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4510. WOLFSSL_BIGNUM *priv_key)
  4511. {
  4512. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4513. /* The private key may be NULL */
  4514. if (pub_key == NULL) {
  4515. WOLFSSL_MSG("Bad parameter");
  4516. return 0;
  4517. }
  4518. wolfSSL_BN_free(d->pub_key);
  4519. wolfSSL_BN_free(d->priv_key);
  4520. d->pub_key = pub_key;
  4521. d->priv_key = priv_key;
  4522. return 1;
  4523. }
  4524. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4525. {
  4526. WOLFSSL_DSA_SIG* sig;
  4527. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4528. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4529. DYNAMIC_TYPE_OPENSSL);
  4530. if (sig)
  4531. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4532. return sig;
  4533. }
  4534. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4535. {
  4536. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4537. if (sig) {
  4538. if (sig->r) {
  4539. wolfSSL_BN_free(sig->r);
  4540. }
  4541. if (sig->s) {
  4542. wolfSSL_BN_free(sig->s);
  4543. }
  4544. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4545. }
  4546. }
  4547. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4548. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4549. {
  4550. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4551. if (sig != NULL) {
  4552. *r = sig->r;
  4553. *s = sig->s;
  4554. }
  4555. }
  4556. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4557. WOLFSSL_BIGNUM *s)
  4558. {
  4559. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4560. if (r == NULL || s == NULL) {
  4561. WOLFSSL_MSG("Bad parameter");
  4562. return 0;
  4563. }
  4564. wolfSSL_BN_clear_free(sig->r);
  4565. wolfSSL_BN_clear_free(sig->s);
  4566. sig->r = r;
  4567. sig->s = s;
  4568. return 1;
  4569. }
  4570. #ifndef HAVE_SELFTEST
  4571. /**
  4572. *
  4573. * @param sig The input signature to encode
  4574. * @param out The output buffer. If *out is NULL then a new buffer is
  4575. * allocated. Otherwise the output is written to the buffer.
  4576. * @return length on success and -1 on error
  4577. */
  4578. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4579. {
  4580. /* Space for sequence + two asn ints */
  4581. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4582. word32 bufLen = sizeof(buf);
  4583. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4584. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4585. out == NULL) {
  4586. WOLFSSL_MSG("Bad function arguments");
  4587. return -1;
  4588. }
  4589. if (StoreECC_DSA_Sig(buf, &bufLen,
  4590. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4591. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4592. return -1;
  4593. }
  4594. if (*out == NULL) {
  4595. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4596. if (tmp == NULL) {
  4597. WOLFSSL_MSG("malloc error");
  4598. return -1;
  4599. }
  4600. *out = tmp;
  4601. }
  4602. XMEMCPY(*out, buf, bufLen);
  4603. return (int)bufLen;
  4604. }
  4605. /**
  4606. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4607. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4608. */
  4609. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4610. {
  4611. WOLFSSL_DSA_SIG* ret;
  4612. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4613. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4614. return NULL;
  4615. }
  4616. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4617. WOLFSSL_MSG("wolfSSL_BN_new error");
  4618. wolfSSL_DSA_SIG_free(ret);
  4619. return NULL;
  4620. }
  4621. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4622. WOLFSSL_MSG("wolfSSL_BN_new error");
  4623. wolfSSL_DSA_SIG_free(ret);
  4624. return NULL;
  4625. }
  4626. return ret;
  4627. }
  4628. /**
  4629. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4630. * ASN1_SEQUENCE
  4631. * ASN1_INTEGER (DSA r)
  4632. * ASN1_INTEGER (DSA s)
  4633. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4634. * length then this API interprets this as two unsigned binary numbers.
  4635. * @param sig If non-null then free'd first and then newly created
  4636. * WOLFSSL_DSA_SIG is assigned
  4637. * @param pp Input buffer that is moved forward on success
  4638. * @param length Length of input buffer
  4639. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4640. */
  4641. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4642. const unsigned char **pp, long length)
  4643. {
  4644. WOLFSSL_DSA_SIG* ret;
  4645. mp_int* r;
  4646. mp_int* s;
  4647. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4648. if (pp == NULL || *pp == NULL || length < 0) {
  4649. WOLFSSL_MSG("Bad function arguments");
  4650. return NULL;
  4651. }
  4652. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4653. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4654. return NULL;
  4655. }
  4656. r = (mp_int*)ret->r->internal;
  4657. s = (mp_int*)ret->s->internal;
  4658. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4659. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4660. /* Two raw numbers of length/2 size each */
  4661. if (mp_read_unsigned_bin(r, *pp, (int)length/2) != 0) {
  4662. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4663. wolfSSL_DSA_SIG_free(ret);
  4664. return NULL;
  4665. }
  4666. if (mp_read_unsigned_bin(s, *pp + (length/2), (int)length/2) != 0) {
  4667. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4668. wolfSSL_DSA_SIG_free(ret);
  4669. return NULL;
  4670. }
  4671. *pp += length;
  4672. }
  4673. else {
  4674. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4675. wolfSSL_DSA_SIG_free(ret);
  4676. return NULL;
  4677. }
  4678. }
  4679. else {
  4680. /* DecodeECC_DSA_Sig success move pointer forward */
  4681. #ifndef NO_STRICT_ECDSA_LEN
  4682. *pp += length;
  4683. #else
  4684. {
  4685. /* We need to figure out how much to move by ourselves */
  4686. word32 idx = 0;
  4687. int len = 0;
  4688. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4689. WOLFSSL_MSG("GetSequence error");
  4690. wolfSSL_DSA_SIG_free(ret);
  4691. return NULL;
  4692. }
  4693. *pp += len;
  4694. }
  4695. #endif
  4696. }
  4697. if (sig != NULL) {
  4698. if (*sig != NULL)
  4699. wolfSSL_DSA_SIG_free(*sig);
  4700. *sig = ret;
  4701. }
  4702. return ret;
  4703. }
  4704. #endif /* HAVE_SELFTEST */
  4705. /* return 1 on success, < 0 otherwise */
  4706. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4707. WOLFSSL_DSA* dsa)
  4708. {
  4709. int ret = -1;
  4710. int initTmpRng = 0;
  4711. WC_RNG* rng = NULL;
  4712. #ifdef WOLFSSL_SMALL_STACK
  4713. WC_RNG* tmpRng = NULL;
  4714. #else
  4715. WC_RNG tmpRng[1];
  4716. #endif
  4717. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4718. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4719. WOLFSSL_MSG("Bad function arguments");
  4720. return ret;
  4721. }
  4722. if (dsa->inSet == 0) {
  4723. WOLFSSL_MSG("No DSA internal set, do it");
  4724. if (SetDsaInternal(dsa) != 1) {
  4725. WOLFSSL_MSG("SetDsaInternal failed");
  4726. return ret;
  4727. }
  4728. }
  4729. #ifdef WOLFSSL_SMALL_STACK
  4730. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4731. if (tmpRng == NULL)
  4732. return -1;
  4733. #endif
  4734. if (wc_InitRng(tmpRng) == 0) {
  4735. rng = tmpRng;
  4736. initTmpRng = 1;
  4737. }
  4738. else {
  4739. WOLFSSL_MSG("Bad RNG Init, trying global");
  4740. rng = wolfssl_get_global_rng();
  4741. }
  4742. if (rng) {
  4743. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4744. WOLFSSL_MSG("DsaSign failed");
  4745. else
  4746. ret = 1;
  4747. }
  4748. if (initTmpRng)
  4749. wc_FreeRng(tmpRng);
  4750. #ifdef WOLFSSL_SMALL_STACK
  4751. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4752. #endif
  4753. return ret;
  4754. }
  4755. #ifndef HAVE_SELFTEST
  4756. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4757. int inLen, WOLFSSL_DSA* dsa)
  4758. {
  4759. byte sigBin[DSA_MAX_SIG_SIZE];
  4760. const byte *tmp = sigBin;
  4761. int sigLen;
  4762. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4763. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4764. WOLFSSL_MSG("Bad function arguments");
  4765. return NULL;
  4766. }
  4767. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4768. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4769. return NULL;
  4770. }
  4771. if (dsa->internal == NULL) {
  4772. WOLFSSL_MSG("dsa->internal is null");
  4773. return NULL;
  4774. }
  4775. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4776. if (sigLen <= 0) {
  4777. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4778. return NULL;
  4779. }
  4780. /* 2 * sigLen for the two points r and s */
  4781. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4782. }
  4783. #endif /* !HAVE_SELFTEST */
  4784. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4785. WOLFSSL_DSA* dsa, int *dsacheck)
  4786. {
  4787. int ret = -1;
  4788. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4789. if (d == NULL || sig == NULL || dsa == NULL) {
  4790. WOLFSSL_MSG("Bad function arguments");
  4791. return -1;
  4792. }
  4793. if (dsa->inSet == 0)
  4794. {
  4795. WOLFSSL_MSG("No DSA internal set, do it");
  4796. if (SetDsaInternal(dsa) != 1) {
  4797. WOLFSSL_MSG("SetDsaInternal failed");
  4798. return -1;
  4799. }
  4800. }
  4801. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4802. if (ret != 0 || *dsacheck != 1) {
  4803. WOLFSSL_MSG("DsaVerify failed");
  4804. return ret;
  4805. }
  4806. return 1;
  4807. }
  4808. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4809. {
  4810. if (!d)
  4811. return 0;
  4812. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4813. return 0;
  4814. return wolfSSL_BN_num_bits(d->p);
  4815. }
  4816. #ifndef HAVE_SELFTEST
  4817. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4818. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4819. {
  4820. int dsacheck, sz;
  4821. byte sigBin[DSA_MAX_SIG_SIZE];
  4822. byte* sigBinPtr = sigBin;
  4823. DsaKey* key;
  4824. int qSz;
  4825. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4826. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4827. WOLFSSL_MSG("Bad function arguments");
  4828. return 0;
  4829. }
  4830. if (!sig->r || !sig->s) {
  4831. WOLFSSL_MSG("No signature found in DSA_SIG");
  4832. return 0;
  4833. }
  4834. if (dsa->inSet == 0) {
  4835. WOLFSSL_MSG("No DSA internal set, do it");
  4836. if (SetDsaInternal(dsa) != 1) {
  4837. WOLFSSL_MSG("SetDsaInternal failed");
  4838. return 0;
  4839. }
  4840. }
  4841. key = (DsaKey*)dsa->internal;
  4842. if (key == NULL) {
  4843. WOLFSSL_MSG("dsa->internal is null");
  4844. return 0;
  4845. }
  4846. qSz = mp_unsigned_bin_size(&key->q);
  4847. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4848. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4849. return 0;
  4850. }
  4851. /* read r */
  4852. /* front pad with zeros */
  4853. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4854. return 0;
  4855. while (sz++ < qSz)
  4856. *sigBinPtr++ = 0;
  4857. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4858. return 0;
  4859. /* Move to s */
  4860. sigBinPtr = sigBin + qSz;
  4861. /* read s */
  4862. /* front pad with zeros */
  4863. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4864. return 0;
  4865. while (sz++ < qSz)
  4866. *sigBinPtr++ = 0;
  4867. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4868. return 0;
  4869. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4870. != 1) || dsacheck != 1) {
  4871. return 0;
  4872. }
  4873. return 1;
  4874. }
  4875. #endif /* !HAVE_SELFTEST */
  4876. WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  4877. unsigned char** out)
  4878. {
  4879. int ret = 0;
  4880. word32 derLen = 0;
  4881. int preAllocated = 1;
  4882. DsaKey* key = NULL;
  4883. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  4884. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  4885. ret = BAD_FUNC_ARG;
  4886. }
  4887. if (ret == 0) {
  4888. key = (DsaKey*)dsa->internal;
  4889. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  4890. if (ret == LENGTH_ONLY_E) {
  4891. ret = 0;
  4892. }
  4893. }
  4894. if (ret == 0 && *out == NULL) {
  4895. /* If we're allocating out for the caller, we don't increment out just
  4896. past the end of the DER buffer. If out is already allocated, we do.
  4897. (OpenSSL convention) */
  4898. preAllocated = 0;
  4899. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  4900. if (*out == NULL) {
  4901. ret = MEMORY_E;
  4902. }
  4903. }
  4904. if (ret == 0) {
  4905. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  4906. }
  4907. if (ret >= 0 && preAllocated == 1) {
  4908. *out += derLen;
  4909. }
  4910. if (ret < 0 && preAllocated == 0) {
  4911. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  4912. }
  4913. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  4914. return ret;
  4915. }
  4916. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  4917. long derLen)
  4918. {
  4919. WOLFSSL_DSA* ret = NULL;
  4920. int err = 0;
  4921. word32 idx = 0;
  4922. int asnLen;
  4923. DsaKey* internalKey = NULL;
  4924. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  4925. if (der == NULL || *der == NULL || derLen <= 0) {
  4926. err = 1;
  4927. }
  4928. if (err == 0) {
  4929. ret = wolfSSL_DSA_new();
  4930. err = ret == NULL;
  4931. }
  4932. if (err == 0) {
  4933. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  4934. }
  4935. if (err == 0) {
  4936. internalKey = (DsaKey*)ret->internal;
  4937. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  4938. }
  4939. if (err == 0) {
  4940. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  4941. }
  4942. if (err == 0) {
  4943. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  4944. }
  4945. if (err == 0) {
  4946. err = SetIndividualExternal(&ret->p, &internalKey->p)
  4947. != 1;
  4948. }
  4949. if (err == 0) {
  4950. err = SetIndividualExternal(&ret->q, &internalKey->q)
  4951. != 1;
  4952. }
  4953. if (err == 0) {
  4954. err = SetIndividualExternal(&ret->g, &internalKey->g)
  4955. != 1;
  4956. }
  4957. if (err == 0 && dsa != NULL) {
  4958. *dsa = ret;
  4959. }
  4960. if (err != 0 && ret != NULL) {
  4961. wolfSSL_DSA_free(ret);
  4962. ret = NULL;
  4963. }
  4964. return ret;
  4965. }
  4966. #if defined(WOLFSSL_KEY_GEN)
  4967. #ifndef NO_BIO
  4968. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  4969. * Returns 1 or 0
  4970. */
  4971. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  4972. const EVP_CIPHER* cipher,
  4973. unsigned char* passwd, int len,
  4974. wc_pem_password_cb* cb, void* arg)
  4975. {
  4976. int ret = 0, der_max_len = 0, derSz = 0;
  4977. byte *derBuf;
  4978. WOLFSSL_EVP_PKEY* pkey;
  4979. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  4980. if (bio == NULL || dsa == NULL) {
  4981. WOLFSSL_MSG("Bad Function Arguments");
  4982. return 0;
  4983. }
  4984. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  4985. if (pkey == NULL) {
  4986. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  4987. return 0;
  4988. }
  4989. pkey->type = EVP_PKEY_DSA;
  4990. pkey->dsa = dsa;
  4991. pkey->ownDsa = 0;
  4992. /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */
  4993. der_max_len = MAX_DSA_PRIVKEY_SZ;
  4994. derBuf = (byte*)XMALLOC(der_max_len, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4995. if (derBuf == NULL) {
  4996. WOLFSSL_MSG("Malloc failed");
  4997. wolfSSL_EVP_PKEY_free(pkey);
  4998. return 0;
  4999. }
  5000. /* convert key to der format */
  5001. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len);
  5002. if (derSz < 0) {
  5003. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5004. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5005. wolfSSL_EVP_PKEY_free(pkey);
  5006. return 0;
  5007. }
  5008. pkey->pkey.ptr = (char*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5009. if (pkey->pkey.ptr == NULL) {
  5010. WOLFSSL_MSG("key malloc failed");
  5011. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5012. wolfSSL_EVP_PKEY_free(pkey);
  5013. return 0;
  5014. }
  5015. /* add der info to the evp key */
  5016. pkey->pkey_sz = derSz;
  5017. XMEMCPY(pkey->pkey.ptr, derBuf, derSz);
  5018. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5019. ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len,
  5020. cb, arg);
  5021. wolfSSL_EVP_PKEY_free(pkey);
  5022. return ret;
  5023. }
  5024. #ifndef HAVE_SELFTEST
  5025. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5026. * Returns 1 or 0
  5027. */
  5028. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5029. {
  5030. int ret = 0;
  5031. WOLFSSL_EVP_PKEY* pkey;
  5032. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5033. if (bio == NULL || dsa == NULL) {
  5034. WOLFSSL_MSG("Bad function arguments");
  5035. return 0;
  5036. }
  5037. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  5038. if (pkey == NULL) {
  5039. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  5040. return 0;
  5041. }
  5042. pkey->type = EVP_PKEY_DSA;
  5043. pkey->dsa = dsa;
  5044. pkey->ownDsa = 0;
  5045. ret = pem_write_bio_pubkey(bio, pkey);
  5046. wolfSSL_EVP_PKEY_free(pkey);
  5047. return ret;
  5048. }
  5049. #endif /* HAVE_SELFTEST */
  5050. #endif /* !NO_BIO */
  5051. /* return code compliant with OpenSSL :
  5052. * 1 if success, 0 if error
  5053. */
  5054. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5055. const EVP_CIPHER* cipher,
  5056. unsigned char* passwd, int passwdSz,
  5057. unsigned char **pem, int *plen)
  5058. {
  5059. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5060. byte *derBuf, *tmp, *cipherInfo = NULL;
  5061. int der_max_len = 0, derSz = 0;
  5062. const int type = DSA_PRIVATEKEY_TYPE;
  5063. const char* header = NULL;
  5064. const char* footer = NULL;
  5065. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5066. if (pem == NULL || plen == NULL || dsa == NULL || dsa->internal == NULL) {
  5067. WOLFSSL_MSG("Bad function arguments");
  5068. return 0;
  5069. }
  5070. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5071. return 0;
  5072. if (dsa->inSet == 0) {
  5073. WOLFSSL_MSG("No DSA internal set, do it");
  5074. if (SetDsaInternal(dsa) != 1) {
  5075. WOLFSSL_MSG("SetDsaInternal failed");
  5076. return 0;
  5077. }
  5078. }
  5079. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5080. derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_DER);
  5081. if (derBuf == NULL) {
  5082. WOLFSSL_MSG("malloc failed");
  5083. return 0;
  5084. }
  5085. /* Key to DER */
  5086. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len);
  5087. if (derSz < 0) {
  5088. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5089. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5090. return 0;
  5091. }
  5092. /* encrypt DER buffer if required */
  5093. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5094. int ret;
  5095. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5096. passwd, passwdSz, &cipherInfo, der_max_len);
  5097. if (ret != 1) {
  5098. WOLFSSL_MSG("EncryptDerKey failed");
  5099. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5100. return ret;
  5101. }
  5102. /* tmp buffer with a max size */
  5103. *plen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5104. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5105. }
  5106. else { /* tmp buffer with a max size */
  5107. *plen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5108. (int)XSTRLEN(footer) + 1;
  5109. }
  5110. tmp = (byte*)XMALLOC(*plen, NULL, DYNAMIC_TYPE_PEM);
  5111. if (tmp == NULL) {
  5112. WOLFSSL_MSG("malloc failed");
  5113. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5114. if (cipherInfo != NULL)
  5115. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5116. return 0;
  5117. }
  5118. /* DER to PEM */
  5119. *plen = wc_DerToPemEx(derBuf, derSz, tmp, *plen, cipherInfo, type);
  5120. if (*plen <= 0) {
  5121. WOLFSSL_MSG("wc_DerToPemEx failed");
  5122. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5123. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5124. if (cipherInfo != NULL)
  5125. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5126. return 0;
  5127. }
  5128. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5129. if (cipherInfo != NULL)
  5130. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5131. *pem = (byte*)XMALLOC((*plen)+1, NULL, DYNAMIC_TYPE_KEY);
  5132. if (*pem == NULL) {
  5133. WOLFSSL_MSG("malloc failed");
  5134. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5135. return 0;
  5136. }
  5137. XMEMSET(*pem, 0, (*plen)+1);
  5138. if (XMEMCPY(*pem, tmp, *plen) == NULL) {
  5139. WOLFSSL_MSG("XMEMCPY failed");
  5140. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5141. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5142. return 0;
  5143. }
  5144. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5145. return 1;
  5146. #else
  5147. (void)dsa;
  5148. (void)cipher;
  5149. (void)passwd;
  5150. (void)passwdSz;
  5151. (void)pem;
  5152. (void)plen;
  5153. return 0;
  5154. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5155. }
  5156. #ifndef NO_FILESYSTEM
  5157. /* return code compliant with OpenSSL :
  5158. * 1 if success, 0 if error
  5159. */
  5160. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5161. const EVP_CIPHER *enc,
  5162. unsigned char *kstr, int klen,
  5163. wc_pem_password_cb *cb, void *u)
  5164. {
  5165. byte *pem;
  5166. int plen, ret;
  5167. (void)cb;
  5168. (void)u;
  5169. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5170. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5171. WOLFSSL_MSG("Bad function arguments");
  5172. return 0;
  5173. }
  5174. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5175. &plen);
  5176. if (ret != 1) {
  5177. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5178. return 0;
  5179. }
  5180. ret = (int)XFWRITE(pem, plen, 1, fp);
  5181. if (ret != 1) {
  5182. WOLFSSL_MSG("DSA private key file write failed");
  5183. return 0;
  5184. }
  5185. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5186. return 1;
  5187. }
  5188. #endif /* NO_FILESYSTEM */
  5189. #endif /* defined(WOLFSSL_KEY_GEN) */
  5190. #ifndef NO_FILESYSTEM
  5191. /* return code compliant with OpenSSL :
  5192. * 1 if success, 0 if error
  5193. */
  5194. #ifndef NO_WOLFSSL_STUB
  5195. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5196. {
  5197. (void)fp;
  5198. (void)x;
  5199. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5200. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5201. return 0;
  5202. }
  5203. #endif
  5204. #endif /* NO_FILESYSTEM */
  5205. #ifndef NO_BIO
  5206. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5207. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5208. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5209. * the results to be an DSA key.
  5210. *
  5211. * bio structure to read DSA private key from
  5212. * dsa if not null is then set to the result
  5213. * cb password callback for reading PEM
  5214. * pass password string
  5215. *
  5216. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5217. */
  5218. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5219. WOLFSSL_DSA** dsa,
  5220. wc_pem_password_cb* cb,
  5221. void* pass)
  5222. {
  5223. WOLFSSL_EVP_PKEY* pkey = NULL;
  5224. WOLFSSL_DSA* local;
  5225. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5226. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5227. if (pkey == NULL) {
  5228. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5229. return NULL;
  5230. }
  5231. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5232. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5233. * to avoid having it free'd */
  5234. pkey->ownDsa = 0;
  5235. local = pkey->dsa;
  5236. if (dsa != NULL) {
  5237. *dsa = local;
  5238. }
  5239. wolfSSL_EVP_PKEY_free(pkey);
  5240. return local;
  5241. }
  5242. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5243. * Returns 1 or 0
  5244. */
  5245. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5246. wc_pem_password_cb* cb, void* pass)
  5247. {
  5248. WOLFSSL_EVP_PKEY* pkey;
  5249. WOLFSSL_DSA* local;
  5250. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5251. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5252. if (pkey == NULL) {
  5253. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5254. return NULL;
  5255. }
  5256. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5257. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5258. * to avoid having it free'd */
  5259. pkey->ownDsa = 0;
  5260. local = pkey->dsa;
  5261. if (dsa != NULL) {
  5262. *dsa = local;
  5263. }
  5264. wolfSSL_EVP_PKEY_free(pkey);
  5265. return local;
  5266. }
  5267. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5268. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5269. #endif /* NO_BIO */
  5270. #endif /* OPENSSL_EXTRA */
  5271. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5272. /* return 1 if success, -1 if error */
  5273. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5274. {
  5275. word32 idx = 0;
  5276. int ret;
  5277. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5278. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5279. WOLFSSL_MSG("Bad function arguments");
  5280. return -1;
  5281. }
  5282. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5283. if (ret < 0) {
  5284. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5285. return -1;
  5286. }
  5287. if (SetDsaExternal(dsa) != 1) {
  5288. WOLFSSL_MSG("SetDsaExternal failed");
  5289. return -1;
  5290. }
  5291. dsa->inSet = 1;
  5292. return 1;
  5293. }
  5294. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5295. returns 1 on success, or 0 on failure. */
  5296. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5297. int derSz, int opt)
  5298. {
  5299. word32 idx = 0;
  5300. int ret;
  5301. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5302. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5303. WOLFSSL_MSG("Bad function arguments");
  5304. return -1;
  5305. }
  5306. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5307. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5308. }
  5309. else {
  5310. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5311. }
  5312. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5313. WOLFSSL_ERROR_VERBOSE(ret);
  5314. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5315. return -1;
  5316. }
  5317. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5318. WOLFSSL_ERROR_VERBOSE(ret);
  5319. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5320. return -1;
  5321. }
  5322. if (SetDsaExternal(dsa) != 1) {
  5323. WOLFSSL_MSG("SetDsaExternal failed");
  5324. return -1;
  5325. }
  5326. dsa->inSet = 1;
  5327. return 1;
  5328. }
  5329. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5330. #ifdef OPENSSL_EXTRA
  5331. #ifndef NO_BIO
  5332. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5333. wc_pem_password_cb *cb, void *u)
  5334. {
  5335. WOLFSSL_DSA* dsa;
  5336. DsaKey* key;
  5337. int length;
  5338. unsigned char* buf;
  5339. word32 bufSz;
  5340. int ret;
  5341. word32 idx = 0;
  5342. DerBuffer* pDer;
  5343. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5344. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5345. if (ret <= 0) {
  5346. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5347. return NULL;
  5348. }
  5349. bufSz = (word32)ret;
  5350. if (cb != NULL || u != NULL) {
  5351. /*
  5352. * cb is for a call back when encountering encrypted PEM files
  5353. * if cb == NULL and u != NULL then u = null terminated password string
  5354. */
  5355. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5356. }
  5357. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5358. NULL) < 0 ) {
  5359. WOLFSSL_MSG("Issue converting from PEM to DER");
  5360. return NULL;
  5361. }
  5362. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5363. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5364. FreeDer(&pDer);
  5365. return NULL;
  5366. }
  5367. dsa = wolfSSL_DSA_new();
  5368. if (dsa == NULL) {
  5369. FreeDer(&pDer);
  5370. WOLFSSL_MSG("Error creating DSA struct");
  5371. return NULL;
  5372. }
  5373. key = (DsaKey*)dsa->internal;
  5374. if (key == NULL) {
  5375. FreeDer(&pDer);
  5376. wolfSSL_DSA_free(dsa);
  5377. WOLFSSL_MSG("Error finding DSA key struct");
  5378. return NULL;
  5379. }
  5380. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5381. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5382. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5383. WOLFSSL_MSG("dsa key error");
  5384. FreeDer(&pDer);
  5385. wolfSSL_DSA_free(dsa);
  5386. return NULL;
  5387. }
  5388. if (SetIndividualExternal(&dsa->p, &key->p) != 1) {
  5389. WOLFSSL_MSG("dsa p key error");
  5390. FreeDer(&pDer);
  5391. wolfSSL_DSA_free(dsa);
  5392. return NULL;
  5393. }
  5394. if (SetIndividualExternal(&dsa->q, &key->q) != 1) {
  5395. WOLFSSL_MSG("dsa q key error");
  5396. FreeDer(&pDer);
  5397. wolfSSL_DSA_free(dsa);
  5398. return NULL;
  5399. }
  5400. if (SetIndividualExternal(&dsa->g, &key->g) != 1) {
  5401. WOLFSSL_MSG("dsa g key error");
  5402. FreeDer(&pDer);
  5403. wolfSSL_DSA_free(dsa);
  5404. return NULL;
  5405. }
  5406. if (x != NULL) {
  5407. *x = dsa;
  5408. }
  5409. FreeDer(&pDer);
  5410. return dsa;
  5411. }
  5412. #endif /* !NO_BIO */
  5413. #if !defined(NO_DH)
  5414. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5415. {
  5416. WOLFSSL_DH* dh;
  5417. DhKey* key;
  5418. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5419. if (dsa == NULL) {
  5420. return NULL;
  5421. }
  5422. dh = wolfSSL_DH_new();
  5423. if (dh == NULL) {
  5424. return NULL;
  5425. }
  5426. key = (DhKey*)dh->internal;
  5427. if (dsa->p != NULL &&
  5428. SetIndividualInternal(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5429. != 1) {
  5430. WOLFSSL_MSG("rsa p key error");
  5431. wolfSSL_DH_free(dh);
  5432. return NULL;
  5433. }
  5434. if (dsa->g != NULL &&
  5435. SetIndividualInternal(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5436. != 1) {
  5437. WOLFSSL_MSG("rsa g key error");
  5438. wolfSSL_DH_free(dh);
  5439. return NULL;
  5440. }
  5441. if (SetIndividualExternal(&dh->p, &key->p) != 1) {
  5442. WOLFSSL_MSG("dsa p key error");
  5443. wolfSSL_DH_free(dh);
  5444. return NULL;
  5445. }
  5446. if (SetIndividualExternal(&dh->g, &key->g) != 1) {
  5447. WOLFSSL_MSG("dsa g key error");
  5448. wolfSSL_DH_free(dh);
  5449. return NULL;
  5450. }
  5451. return dh;
  5452. }
  5453. #endif /* !NO_DH */
  5454. #endif /* OPENSSL_EXTRA */
  5455. #endif /* !NO_DSA */
  5456. /*******************************************************************************
  5457. * END OF DSA API
  5458. ******************************************************************************/
  5459. /*******************************************************************************
  5460. * START OF DH API
  5461. ******************************************************************************/
  5462. #ifndef NO_DH
  5463. #ifdef OPENSSL_EXTRA
  5464. /*
  5465. * DH constructor/deconstructor APIs
  5466. */
  5467. /* Allocate and initialize a new DH key.
  5468. *
  5469. * @return DH key on success.
  5470. * @return NULL on failure.
  5471. */
  5472. WOLFSSL_DH* wolfSSL_DH_new(void)
  5473. {
  5474. int err = 0;
  5475. WOLFSSL_DH* dh = NULL;
  5476. DhKey* key = NULL;
  5477. WOLFSSL_ENTER("wolfSSL_DH_new");
  5478. /* Allocate OpenSSL DH key. */
  5479. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5480. if (dh == NULL) {
  5481. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5482. err = 1;
  5483. }
  5484. if (!err) {
  5485. /* Clear key data. */
  5486. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5487. /* Initialize reference counting. */
  5488. wolfSSL_RefInit(&dh->ref, &err);
  5489. }
  5490. if (!err) {
  5491. /* Allocate wolfSSL DH key. */
  5492. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5493. if (key == NULL) {
  5494. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5495. err = 1;
  5496. }
  5497. }
  5498. if (!err) {
  5499. /* Set and initialize wolfSSL DH key. */
  5500. dh->internal = key;
  5501. if (wc_InitDhKey(key) != 0) {
  5502. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5503. err = 1;
  5504. }
  5505. }
  5506. if (err && (dh != NULL)) {
  5507. /* Dispose of the allocated memory. */
  5508. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5509. wolfSSL_RefFree(&dh->ref);
  5510. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5511. dh = NULL;
  5512. }
  5513. return dh;
  5514. }
  5515. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5516. /* Set the DH parameters based on the NID.
  5517. *
  5518. * @param [in, out] dh DH key to set.
  5519. * @param [in] nid Numeric ID of predefined DH parameters.
  5520. * @return 0 on success.
  5521. * @return 1 on failure.
  5522. */
  5523. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5524. {
  5525. int err = 0;
  5526. const DhParams* params = NULL;
  5527. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5528. * FIPS v2 module */
  5529. switch (nid) {
  5530. #ifdef HAVE_FFDHE_2048
  5531. case NID_ffdhe2048:
  5532. params = wc_Dh_ffdhe2048_Get();
  5533. break;
  5534. #endif /* HAVE_FFDHE_2048 */
  5535. #ifdef HAVE_FFDHE_3072
  5536. case NID_ffdhe3072:
  5537. params = wc_Dh_ffdhe3072_Get();
  5538. break;
  5539. #endif /* HAVE_FFDHE_3072 */
  5540. #ifdef HAVE_FFDHE_4096
  5541. case NID_ffdhe4096:
  5542. params = wc_Dh_ffdhe4096_Get();
  5543. break;
  5544. #endif /* HAVE_FFDHE_4096 */
  5545. default:
  5546. break;
  5547. }
  5548. if (params == NULL) {
  5549. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5550. err = 1;
  5551. }
  5552. if (!err) {
  5553. /* Set prime from data retrieved. */
  5554. dh->p = wolfSSL_BN_bin2bn(params->p, params->p_len, NULL);
  5555. if (dh->p == NULL) {
  5556. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5557. err = 1;
  5558. }
  5559. }
  5560. if (!err) {
  5561. /* Set generator from data retrieved. */
  5562. dh->g = wolfSSL_BN_bin2bn(params->g, params->g_len, NULL);
  5563. if (dh->g == NULL) {
  5564. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5565. err = 1;
  5566. }
  5567. }
  5568. #ifdef HAVE_FFDHE_Q
  5569. if (!err) {
  5570. /* Set order from data retrieved. */
  5571. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5572. if (dh->q == NULL) {
  5573. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5574. err = 1;
  5575. }
  5576. }
  5577. #endif
  5578. /* Synchronize the external into internal DH key's parameters. */
  5579. if ((!err) && (SetDhInternal(dh) != 1)) {
  5580. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5581. err = 1;
  5582. }
  5583. if (!err) {
  5584. /* External DH key parameters were set. */
  5585. dh->exSet = 1;
  5586. }
  5587. if (err == 1) {
  5588. /* Dispose of any external parameters. */
  5589. #ifdef HAVE_FFDHE_Q
  5590. wolfSSL_BN_free(dh->q);
  5591. dh->q = NULL;
  5592. #endif
  5593. wolfSSL_BN_free(dh->p);
  5594. dh->p = NULL;
  5595. wolfSSL_BN_free(dh->g);
  5596. dh->g = NULL;
  5597. }
  5598. return err;
  5599. }
  5600. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5601. FIPS_VERSION_GT(2,0))
  5602. /* Set the DH parameters based on the NID.
  5603. *
  5604. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5605. *
  5606. * @param [in, out] dh DH key to set.
  5607. * @param [in] nid Numeric ID of predefined DH parameters.
  5608. * @return 0 on success.
  5609. * @return 1 on failure.
  5610. */
  5611. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5612. {
  5613. int err = 0;
  5614. int name = 0;
  5615. #ifdef HAVE_FFDHE_Q
  5616. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5617. #else
  5618. int elements = ELEMENT_P | ELEMENT_G;
  5619. #endif /* HAVE_FFDHE_Q */
  5620. switch (nid) {
  5621. #ifdef HAVE_FFDHE_2048
  5622. case NID_ffdhe2048:
  5623. name = WC_FFDHE_2048;
  5624. break;
  5625. #endif /* HAVE_FFDHE_2048 */
  5626. #ifdef HAVE_FFDHE_3072
  5627. case NID_ffdhe3072:
  5628. name = WC_FFDHE_3072;
  5629. break;
  5630. #endif /* HAVE_FFDHE_3072 */
  5631. #ifdef HAVE_FFDHE_4096
  5632. case NID_ffdhe4096:
  5633. name = WC_FFDHE_4096;
  5634. break;
  5635. #endif /* HAVE_FFDHE_4096 */
  5636. default:
  5637. err = 1;
  5638. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5639. break;
  5640. }
  5641. /* Set the internal DH key's parameters based on name. */
  5642. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5643. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5644. err = 1;
  5645. }
  5646. /* Synchronize the internal into external DH key's parameters. */
  5647. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5648. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5649. err = 1;
  5650. }
  5651. return err;
  5652. }
  5653. #else
  5654. /* Set the DH parameters based on the NID.
  5655. *
  5656. * Pre-defined DH parameters not available.
  5657. *
  5658. * @param [in, out] dh DH key to set.
  5659. * @param [in] nid Numeric ID of predefined DH parameters.
  5660. * @return 1 for failure.
  5661. */
  5662. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5663. {
  5664. return 1;
  5665. }
  5666. #endif
  5667. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5668. *
  5669. * @param [in] nid Numeric ID of DH parameters.
  5670. *
  5671. * @return DH key on success.
  5672. * @return NULL on failure.
  5673. */
  5674. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5675. {
  5676. WOLFSSL_DH* dh = NULL;
  5677. int err = 0;
  5678. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5679. /* Allocate a new DH key. */
  5680. dh = wolfSSL_DH_new();
  5681. if (dh == NULL) {
  5682. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5683. err = 1;
  5684. }
  5685. if (!err) {
  5686. /* Set the parameters based on NID. */
  5687. err = wolfssl_dh_set_nid(dh, nid);
  5688. }
  5689. if (err && (dh != NULL)) {
  5690. /* Dispose of the key on failure to set. */
  5691. wolfSSL_DH_free(dh);
  5692. dh = NULL;
  5693. }
  5694. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5695. return dh;
  5696. }
  5697. /* Dispose of DH key and allocated data.
  5698. *
  5699. * Cannot use dh after this call.
  5700. *
  5701. * @param [in] dh DH key to free.
  5702. */
  5703. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5704. {
  5705. int doFree = 0;
  5706. WOLFSSL_ENTER("wolfSSL_DH_free");
  5707. if (dh != NULL) {
  5708. int err;
  5709. /* Only free if all references to it are done */
  5710. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5711. /* Ignore errors - doFree will be 0 on error. */
  5712. (void)err;
  5713. }
  5714. if (doFree) {
  5715. /* Dispose of allocated reference counting data. */
  5716. wolfSSL_RefFree(&dh->ref);
  5717. /* Dispose of wolfSSL DH key. */
  5718. if (dh->internal) {
  5719. wc_FreeDhKey((DhKey*)dh->internal);
  5720. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5721. dh->internal = NULL;
  5722. }
  5723. /* Dispose of any allocated BNs. */
  5724. wolfSSL_BN_free(dh->priv_key);
  5725. wolfSSL_BN_free(dh->pub_key);
  5726. wolfSSL_BN_free(dh->g);
  5727. wolfSSL_BN_free(dh->p);
  5728. wolfSSL_BN_free(dh->q);
  5729. /* Set back to NULLs for safety. */
  5730. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5731. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5732. }
  5733. }
  5734. /* Increments ref count of DH key.
  5735. *
  5736. * @param [in, out] dh DH key.
  5737. * @return 1 on success
  5738. * @return 0 on error
  5739. */
  5740. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5741. {
  5742. int err = 1;
  5743. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5744. if (dh != NULL) {
  5745. wolfSSL_RefInc(&dh->ref, &err);
  5746. }
  5747. return !err;
  5748. }
  5749. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5750. defined(OPENSSL_EXTRA)
  5751. #ifdef WOLFSSL_DH_EXTRA
  5752. /* Duplicate the DH key.
  5753. *
  5754. * Internal DH key in 'dh' is updated if necessary.
  5755. *
  5756. * @param [in, out] dh DH key to duplicate.
  5757. * @return NULL on failure.
  5758. * @return DH key on success.
  5759. */
  5760. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5761. {
  5762. WOLFSSL_DH* ret = NULL;
  5763. int err = 0;
  5764. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5765. /* Validate parameters. */
  5766. if (dh == NULL) {
  5767. WOLFSSL_ERROR_MSG("Bad parameter");
  5768. err = 1;
  5769. }
  5770. /* Ensure internal DH key is set. */
  5771. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5772. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5773. err = 1;
  5774. }
  5775. /* Create a new DH key object. */
  5776. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5777. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5778. err = 1;
  5779. }
  5780. /* Copy internal DH key from original to new. */
  5781. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5782. MP_OKAY)) {
  5783. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5784. err = 1;
  5785. }
  5786. if (!err) {
  5787. ret->inSet = 1;
  5788. /* Synchronize the internal into external DH key's parameters. */
  5789. if (SetDhExternal(ret) != 1) {
  5790. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5791. err = 1;
  5792. }
  5793. }
  5794. /* Dispose of any allocated DH key on error. */
  5795. if (err && (ret != NULL)) {
  5796. wolfSSL_DH_free(ret);
  5797. ret = NULL;
  5798. }
  5799. return ret;
  5800. }
  5801. #endif /* WOLFSSL_DH_EXTRA */
  5802. #endif
  5803. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5804. *
  5805. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5806. * Subgroup."
  5807. *
  5808. * @return NULL on failure.
  5809. * @return DH Key on success.
  5810. */
  5811. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5812. {
  5813. WOLFSSL_DH* dh;
  5814. int err = 0;
  5815. static const byte pHex[] = {
  5816. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5817. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5818. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5819. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5820. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5821. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5822. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5823. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5824. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5825. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5826. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5827. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5828. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5829. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5830. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5831. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5832. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5833. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5834. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5835. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5836. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5837. 0x1E, 0x1A, 0x15, 0x97
  5838. };
  5839. static const byte gHex[] = {
  5840. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5841. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5842. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5843. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5844. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5845. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5846. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5847. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5848. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5849. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5850. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5851. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5852. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  5853. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  5854. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  5855. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  5856. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  5857. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  5858. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  5859. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  5860. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  5861. 0x6C, 0xC4, 0x16, 0x59
  5862. };
  5863. static const byte qHex[] = {
  5864. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  5865. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  5866. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  5867. };
  5868. /* Create a new DH key to return. */
  5869. dh = wolfSSL_DH_new();
  5870. if (dh == NULL) {
  5871. err = 1;
  5872. }
  5873. if (!err) {
  5874. /* Set prime. */
  5875. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  5876. if (dh->p == NULL) {
  5877. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5878. err = 1;
  5879. }
  5880. }
  5881. if (!err) {
  5882. /* Set generator. */
  5883. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  5884. if (dh->g == NULL) {
  5885. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5886. err = 1;
  5887. }
  5888. }
  5889. if (!err) {
  5890. /* Set order. */
  5891. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  5892. if (dh->q == NULL) {
  5893. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5894. err = 1;
  5895. }
  5896. }
  5897. /* Set values into wolfSSL DH key. */
  5898. if ((!err) && (SetDhInternal(dh) != 1)) {
  5899. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  5900. err = 1;
  5901. }
  5902. if (!err) {
  5903. /* External DH key parameters were set. */
  5904. dh->exSet = 1;
  5905. }
  5906. /* Dispose of any allocated DH key on error. */
  5907. if (err && (dh != NULL)) {
  5908. wolfSSL_DH_free(dh);
  5909. dh = NULL;
  5910. }
  5911. return dh;
  5912. }
  5913. /* TODO: consider changing strings to byte arrays. */
  5914. /* Returns a big number with the 768-bit prime from RFC 2409.
  5915. *
  5916. * @param [in, out] bn If not NULL then this BN is set and returned.
  5917. * If NULL then a new BN is created, set and returned.
  5918. *
  5919. * @return NULL on failure.
  5920. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  5921. */
  5922. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  5923. {
  5924. #if WOLFSSL_MAX_BN_BITS >= 768
  5925. static const char prm[] = {
  5926. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5927. "C4C6628B80DC1CD129024E088A67CC74"
  5928. "020BBEA63B139B22514A08798E3404DD"
  5929. "EF9519B3CD3A431B302B0A6DF25F1437"
  5930. "4FE1356D6D51C245E485B576625E7EC6"
  5931. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  5932. };
  5933. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  5934. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5935. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5936. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  5937. bn = NULL;
  5938. }
  5939. return bn;
  5940. #else
  5941. (void)bn;
  5942. return NULL;
  5943. #endif
  5944. }
  5945. /* Returns a big number with the 1024-bit prime from RFC 2409.
  5946. *
  5947. * @param [in, out] bn If not NULL then this BN is set and returned.
  5948. * If NULL then a new BN is created, set and returned.
  5949. *
  5950. * @return NULL on failure.
  5951. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  5952. */
  5953. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  5954. {
  5955. #if WOLFSSL_MAX_BN_BITS >= 1024
  5956. static const char prm[] = {
  5957. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5958. "C4C6628B80DC1CD129024E088A67CC74"
  5959. "020BBEA63B139B22514A08798E3404DD"
  5960. "EF9519B3CD3A431B302B0A6DF25F1437"
  5961. "4FE1356D6D51C245E485B576625E7EC6"
  5962. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5963. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5964. "49286651ECE65381FFFFFFFFFFFFFFFF"
  5965. };
  5966. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  5967. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5968. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5969. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  5970. bn = NULL;
  5971. }
  5972. return bn;
  5973. #else
  5974. (void)bn;
  5975. return NULL;
  5976. #endif
  5977. }
  5978. /* Returns a big number with the 1536-bit prime from RFC 3526.
  5979. *
  5980. * @param [in, out] bn If not NULL then this BN is set and returned.
  5981. * If NULL then a new BN is created, set and returned.
  5982. *
  5983. * @return NULL on failure.
  5984. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  5985. */
  5986. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  5987. {
  5988. #if WOLFSSL_MAX_BN_BITS >= 1536
  5989. static const char prm[] = {
  5990. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5991. "C4C6628B80DC1CD129024E088A67CC74"
  5992. "020BBEA63B139B22514A08798E3404DD"
  5993. "EF9519B3CD3A431B302B0A6DF25F1437"
  5994. "4FE1356D6D51C245E485B576625E7EC6"
  5995. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5996. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5997. "49286651ECE45B3DC2007CB8A163BF05"
  5998. "98DA48361C55D39A69163FA8FD24CF5F"
  5999. "83655D23DCA3AD961C62F356208552BB"
  6000. "9ED529077096966D670C354E4ABC9804"
  6001. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6002. };
  6003. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6004. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6005. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6006. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6007. bn = NULL;
  6008. }
  6009. return bn;
  6010. #else
  6011. (void)bn;
  6012. return NULL;
  6013. #endif
  6014. }
  6015. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6016. *
  6017. * @param [in, out] bn If not NULL then this BN is set and returned.
  6018. * If NULL then a new BN is created, set and returned.
  6019. *
  6020. * @return NULL on failure.
  6021. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6022. */
  6023. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6024. {
  6025. #if WOLFSSL_MAX_BN_BITS >= 2048
  6026. static const char prm[] = {
  6027. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6028. "C4C6628B80DC1CD129024E088A67CC74"
  6029. "020BBEA63B139B22514A08798E3404DD"
  6030. "EF9519B3CD3A431B302B0A6DF25F1437"
  6031. "4FE1356D6D51C245E485B576625E7EC6"
  6032. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6033. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6034. "49286651ECE45B3DC2007CB8A163BF05"
  6035. "98DA48361C55D39A69163FA8FD24CF5F"
  6036. "83655D23DCA3AD961C62F356208552BB"
  6037. "9ED529077096966D670C354E4ABC9804"
  6038. "F1746C08CA18217C32905E462E36CE3B"
  6039. "E39E772C180E86039B2783A2EC07A28F"
  6040. "B5C55DF06F4C52C9DE2BCBF695581718"
  6041. "3995497CEA956AE515D2261898FA0510"
  6042. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6043. };
  6044. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6045. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6046. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6047. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6048. bn = NULL;
  6049. }
  6050. return bn;
  6051. #else
  6052. (void)bn;
  6053. return NULL;
  6054. #endif
  6055. }
  6056. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6057. *
  6058. * @param [in, out] bn If not NULL then this BN is set and returned.
  6059. * If NULL then a new BN is created, set and returned.
  6060. *
  6061. * @return NULL on failure.
  6062. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6063. */
  6064. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6065. {
  6066. #if WOLFSSL_MAX_BN_BITS >= 3072
  6067. static const char prm[] = {
  6068. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6069. "C4C6628B80DC1CD129024E088A67CC74"
  6070. "020BBEA63B139B22514A08798E3404DD"
  6071. "EF9519B3CD3A431B302B0A6DF25F1437"
  6072. "4FE1356D6D51C245E485B576625E7EC6"
  6073. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6074. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6075. "49286651ECE45B3DC2007CB8A163BF05"
  6076. "98DA48361C55D39A69163FA8FD24CF5F"
  6077. "83655D23DCA3AD961C62F356208552BB"
  6078. "9ED529077096966D670C354E4ABC9804"
  6079. "F1746C08CA18217C32905E462E36CE3B"
  6080. "E39E772C180E86039B2783A2EC07A28F"
  6081. "B5C55DF06F4C52C9DE2BCBF695581718"
  6082. "3995497CEA956AE515D2261898FA0510"
  6083. "15728E5A8AAAC42DAD33170D04507A33"
  6084. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6085. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6086. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6087. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6088. "D87602733EC86A64521F2B18177B200C"
  6089. "BBE117577A615D6C770988C0BAD946E2"
  6090. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6091. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6092. };
  6093. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6094. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6095. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6096. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6097. bn = NULL;
  6098. }
  6099. return bn;
  6100. #else
  6101. (void)bn;
  6102. return NULL;
  6103. #endif
  6104. }
  6105. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6106. *
  6107. * @param [in, out] bn If not NULL then this BN is set and returned.
  6108. * If NULL then a new BN is created, set and returned.
  6109. *
  6110. * @return NULL on failure.
  6111. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6112. */
  6113. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6114. {
  6115. #if WOLFSSL_MAX_BN_BITS >= 4096
  6116. static const char prm[] = {
  6117. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6118. "C4C6628B80DC1CD129024E088A67CC74"
  6119. "020BBEA63B139B22514A08798E3404DD"
  6120. "EF9519B3CD3A431B302B0A6DF25F1437"
  6121. "4FE1356D6D51C245E485B576625E7EC6"
  6122. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6123. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6124. "49286651ECE45B3DC2007CB8A163BF05"
  6125. "98DA48361C55D39A69163FA8FD24CF5F"
  6126. "83655D23DCA3AD961C62F356208552BB"
  6127. "9ED529077096966D670C354E4ABC9804"
  6128. "F1746C08CA18217C32905E462E36CE3B"
  6129. "E39E772C180E86039B2783A2EC07A28F"
  6130. "B5C55DF06F4C52C9DE2BCBF695581718"
  6131. "3995497CEA956AE515D2261898FA0510"
  6132. "15728E5A8AAAC42DAD33170D04507A33"
  6133. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6134. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6135. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6136. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6137. "D87602733EC86A64521F2B18177B200C"
  6138. "BBE117577A615D6C770988C0BAD946E2"
  6139. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6140. "4B82D120A92108011A723C12A787E6D7"
  6141. "88719A10BDBA5B2699C327186AF4E23C"
  6142. "1A946834B6150BDA2583E9CA2AD44CE8"
  6143. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6144. "287C59474E6BC05D99B2964FA090C3A2"
  6145. "233BA186515BE7ED1F612970CEE2D7AF"
  6146. "B81BDD762170481CD0069127D5B05AA9"
  6147. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6148. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6149. };
  6150. WOLFSSL_ENTER("wolfSSL_DH_4096_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 4096 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 6144-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 6144-bit prime on success.
  6169. */
  6170. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6171. {
  6172. #if WOLFSSL_MAX_BN_BITS >= 6144
  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. "15728E5A8AAAC42DAD33170D04507A33"
  6190. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6191. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6192. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6193. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6194. "D87602733EC86A64521F2B18177B200C"
  6195. "BBE117577A615D6C770988C0BAD946E2"
  6196. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6197. "4B82D120A92108011A723C12A787E6D7"
  6198. "88719A10BDBA5B2699C327186AF4E23C"
  6199. "1A946834B6150BDA2583E9CA2AD44CE8"
  6200. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6201. "287C59474E6BC05D99B2964FA090C3A2"
  6202. "233BA186515BE7ED1F612970CEE2D7AF"
  6203. "B81BDD762170481CD0069127D5B05AA9"
  6204. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6205. "4DF435C93402849236C3FAB4D27C7026"
  6206. "C1D4DCB2602646DEC9751E763DBA37BD"
  6207. "F8FF9406AD9E530EE5DB382F413001AE"
  6208. "B06A53ED9027D831179727B0865A8918"
  6209. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6210. "DB7F1447E6CC254B332051512BD7AF42"
  6211. "6FB8F401378CD2BF5983CA01C64B92EC"
  6212. "F032EA15D1721D03F482D7CE6E74FEF6"
  6213. "D55E702F46980C82B5A84031900B1C9E"
  6214. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6215. "0F1D45B7FF585AC54BD407B22B4154AA"
  6216. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6217. "A79715EEF29BE32806A1D58BB7C5DA76"
  6218. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6219. "DA56C9EC2EF29632387FE8D76E3C0468"
  6220. "043E8F663F4860EE12BF2D5B0B7474D6"
  6221. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6222. };
  6223. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6224. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6225. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6226. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6227. bn = NULL;
  6228. }
  6229. return bn;
  6230. #else
  6231. (void)bn;
  6232. return NULL;
  6233. #endif
  6234. }
  6235. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6236. *
  6237. * @param [in, out] bn If not NULL then this BN is set and returned.
  6238. * If NULL then a new BN is created, set and returned.
  6239. *
  6240. * @return NULL on failure.
  6241. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6242. */
  6243. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6244. {
  6245. #if WOLFSSL_MAX_BN_BITS >= 8192
  6246. static const char prm[] = {
  6247. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6248. "C4C6628B80DC1CD129024E088A67CC74"
  6249. "020BBEA63B139B22514A08798E3404DD"
  6250. "EF9519B3CD3A431B302B0A6DF25F1437"
  6251. "4FE1356D6D51C245E485B576625E7EC6"
  6252. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6253. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6254. "49286651ECE45B3DC2007CB8A163BF05"
  6255. "98DA48361C55D39A69163FA8FD24CF5F"
  6256. "83655D23DCA3AD961C62F356208552BB"
  6257. "9ED529077096966D670C354E4ABC9804"
  6258. "F1746C08CA18217C32905E462E36CE3B"
  6259. "E39E772C180E86039B2783A2EC07A28F"
  6260. "B5C55DF06F4C52C9DE2BCBF695581718"
  6261. "3995497CEA956AE515D2261898FA0510"
  6262. "15728E5A8AAAC42DAD33170D04507A33"
  6263. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6264. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6265. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6266. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6267. "D87602733EC86A64521F2B18177B200C"
  6268. "BBE117577A615D6C770988C0BAD946E2"
  6269. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6270. "4B82D120A92108011A723C12A787E6D7"
  6271. "88719A10BDBA5B2699C327186AF4E23C"
  6272. "1A946834B6150BDA2583E9CA2AD44CE8"
  6273. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6274. "287C59474E6BC05D99B2964FA090C3A2"
  6275. "233BA186515BE7ED1F612970CEE2D7AF"
  6276. "B81BDD762170481CD0069127D5B05AA9"
  6277. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6278. "4DF435C93402849236C3FAB4D27C7026"
  6279. "C1D4DCB2602646DEC9751E763DBA37BD"
  6280. "F8FF9406AD9E530EE5DB382F413001AE"
  6281. "B06A53ED9027D831179727B0865A8918"
  6282. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6283. "DB7F1447E6CC254B332051512BD7AF42"
  6284. "6FB8F401378CD2BF5983CA01C64B92EC"
  6285. "F032EA15D1721D03F482D7CE6E74FEF6"
  6286. "D55E702F46980C82B5A84031900B1C9E"
  6287. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6288. "0F1D45B7FF585AC54BD407B22B4154AA"
  6289. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6290. "A79715EEF29BE32806A1D58BB7C5DA76"
  6291. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6292. "DA56C9EC2EF29632387FE8D76E3C0468"
  6293. "043E8F663F4860EE12BF2D5B0B7474D6"
  6294. "E694F91E6DBE115974A3926F12FEE5E4"
  6295. "38777CB6A932DF8CD8BEC4D073B931BA"
  6296. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6297. "2576F6936BA424663AAB639C5AE4F568"
  6298. "3423B4742BF1C978238F16CBE39D652D"
  6299. "E3FDB8BEFC848AD922222E04A4037C07"
  6300. "13EB57A81A23F0C73473FC646CEA306B"
  6301. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6302. "79683303ED5BDD3A062B3CF5B3A278A6"
  6303. "6D2A13F83F44F82DDF310EE074AB6A36"
  6304. "4597E899A0255DC164F31CC50846851D"
  6305. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6306. "FAF36BC31ECFA268359046F4EB879F92"
  6307. "4009438B481C6CD7889A002ED5EE382B"
  6308. "C9190DA6FC026E479558E4475677E9AA"
  6309. "9E3050E2765694DFC81F56E880B96E71"
  6310. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6311. };
  6312. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6313. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6314. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6315. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6316. bn = NULL;
  6317. }
  6318. return bn;
  6319. #else
  6320. (void)bn;
  6321. return NULL;
  6322. #endif
  6323. }
  6324. /*
  6325. * DH to/from bin APIs
  6326. */
  6327. #ifndef NO_CERTS
  6328. /* Load the DER encoded DH parameters/key into DH key.
  6329. *
  6330. * @param [in, out] dh DH key to load parameters into.
  6331. * @param [in] der Buffer holding DER encoded parameters data.
  6332. * @param [in, out] idx On in, index at which DH key DER data starts.
  6333. * On out, index after DH key DER data.
  6334. * @param [in] derSz Size of DER buffer in bytes.
  6335. *
  6336. * @return 0 on success.
  6337. * @return 1 when decoding DER or setting the external key fails.
  6338. */
  6339. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6340. word32* idx, word32 derSz)
  6341. {
  6342. int err = 0;
  6343. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6344. int ret;
  6345. /* Decode DH parameters/key from DER. */
  6346. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6347. if (ret != 0) {
  6348. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6349. err = 1;
  6350. }
  6351. if (!err) {
  6352. /* wolfSSL DH key set. */
  6353. dh->inSet = 1;
  6354. /* Set the external DH key based on wolfSSL DH key. */
  6355. if (SetDhExternal(dh) != 1) {
  6356. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6357. err = 1;
  6358. }
  6359. }
  6360. #else
  6361. byte* p;
  6362. byte* g;
  6363. word32 pSz = MAX_DH_SIZE;
  6364. word32 gSz = MAX_DH_SIZE;
  6365. /* Only DH parameters supported. */
  6366. /* Load external and set internal. */
  6367. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6368. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6369. if ((p == NULL) || (g == NULL)) {
  6370. err = 1;
  6371. }
  6372. /* Extract the p and g as data from the DER encoded DH parameters. */
  6373. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6374. &gSz) < 0)) {
  6375. err = 1;
  6376. }
  6377. if (!err) {
  6378. /* Put p and g in as big numbers - free existing BNs. */
  6379. if (dh->p != NULL) {
  6380. wolfSSL_BN_free(dh->p);
  6381. dh->p = NULL;
  6382. }
  6383. if (dh->g != NULL) {
  6384. wolfSSL_BN_free(dh->g);
  6385. dh->g = NULL;
  6386. }
  6387. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6388. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6389. if (dh->p == NULL || dh->g == NULL) {
  6390. err = 1;
  6391. }
  6392. else {
  6393. /* External DH key parameters were set. */
  6394. dh->exSet = 1;
  6395. }
  6396. }
  6397. /* Set internal as the outside has been updated. */
  6398. if ((!err) && (SetDhInternal(dh) != 1)) {
  6399. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6400. err = 1;
  6401. }
  6402. if (!err) {
  6403. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6404. }
  6405. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6406. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6407. #endif
  6408. return err;
  6409. }
  6410. #ifdef OPENSSL_ALL
  6411. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6412. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6413. *
  6414. * @param [out] dh DH key to put parameters into. May be NULL.
  6415. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6416. * Value updated to end of data when dh is not NULL.
  6417. * @param [in] length Length of data available in bytes.
  6418. *
  6419. * @return DH key on success.
  6420. * @return NULL on failure.
  6421. */
  6422. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6423. long length)
  6424. {
  6425. WOLFSSL_DH *newDh = NULL;
  6426. word32 idx = 0;
  6427. int err = 0;
  6428. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6429. /* Validate parameters. */
  6430. if ((pp == NULL) || (length <= 0)) {
  6431. WOLFSSL_ERROR_MSG("bad argument");
  6432. err = 1;
  6433. }
  6434. /* Create new DH key to return. */
  6435. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6436. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6437. err = 1;
  6438. }
  6439. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6440. (word32)length) != 0)) {
  6441. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6442. err = 1;
  6443. }
  6444. if ((!err) && (dh != NULL)) {
  6445. /* Return through parameter too. */
  6446. *dh = newDh;
  6447. /* Move buffer on by the used amount. */
  6448. *pp += idx;
  6449. }
  6450. if (err && (newDh != NULL)) {
  6451. /* Dispose of any created DH key. */
  6452. wolfSSL_DH_free(newDh);
  6453. newDh = NULL;
  6454. }
  6455. return newDh;
  6456. }
  6457. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6458. /* Calculate the number of bytes require to represent a length value in ASN.
  6459. *
  6460. * @param [in] l Length value to use.
  6461. * @return Number of bytes required to represent length value.
  6462. */
  6463. #define ASN_LEN_SIZE(l) \
  6464. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  6465. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6466. *
  6467. * @params [in] dh DH key with parameters to encode.
  6468. * @params [in, out] out Pointer to buffer to encode into.
  6469. * When NULL or pointer to NULL, only length returned.
  6470. * @return 0 on error.
  6471. * @return Size of DER encoding in bytes on success.
  6472. */
  6473. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6474. {
  6475. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6476. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6477. word32 len = (word32)-1;
  6478. int err = 0;
  6479. /* Validate parameters. */
  6480. if (dh == NULL) {
  6481. WOLFSSL_ERROR_MSG("Bad parameters");
  6482. err = 1;
  6483. }
  6484. /* Push external DH data into internal DH key if not set. */
  6485. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6486. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6487. err = 1;
  6488. }
  6489. if (!err) {
  6490. int ret;
  6491. unsigned char* der = NULL;
  6492. /* Use *out when available otherwise NULL. */
  6493. if (out != NULL) {
  6494. der = *out;
  6495. }
  6496. /* Get length and/or encode. */
  6497. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6498. /* Length of encoded data is returned on success. */
  6499. if (ret > 0) {
  6500. *out += len;
  6501. }
  6502. /* An error occurred unless only length returned. */
  6503. else if (ret != LENGTH_ONLY_E) {
  6504. err = 1;
  6505. }
  6506. }
  6507. /* Set return to 0 on error. */
  6508. if (err) {
  6509. len = 0;
  6510. }
  6511. return (int)len;
  6512. #else
  6513. word32 len;
  6514. int ret = 0;
  6515. int pSz;
  6516. int gSz;
  6517. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6518. /* Validate parameters. */
  6519. if (dh == NULL) {
  6520. WOLFSSL_ERROR_MSG("Bad parameters");
  6521. len = 0;
  6522. }
  6523. else {
  6524. /* SEQ <len>
  6525. * INT <len> [0x00] <prime>
  6526. * INT <len> [0x00] <generator>
  6527. * Integers have 0x00 prepended if the top bit of positive number is
  6528. * set.
  6529. */
  6530. /* Get total length of prime including any prepended zeros. */
  6531. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6532. mp_leading_bit((mp_int*)dh->p->internal);
  6533. /* Get total length of generator including any prepended zeros. */
  6534. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6535. mp_leading_bit((mp_int*)dh->g->internal);
  6536. /* Calculate length of data in sequence. */
  6537. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6538. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6539. /* Add in the length of the SEQUENCE. */
  6540. len += 1 + ASN_LEN_SIZE(len);
  6541. if ((out != NULL) && (*out != NULL)) {
  6542. /* Encode parameters. */
  6543. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6544. (mp_int*)dh->g->internal);
  6545. if (ret != MP_OKAY) {
  6546. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6547. len = 0;
  6548. }
  6549. else {
  6550. /* Move pointer on if encoded. */
  6551. *out += len;
  6552. }
  6553. }
  6554. }
  6555. return (int)len;
  6556. #endif
  6557. }
  6558. #endif /* OPENSSL_ALL */
  6559. #endif /* !NO_CERTS */
  6560. #endif /* OPENSSL_EXTRA */
  6561. #if defined(OPENSSL_EXTRA) || \
  6562. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6563. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6564. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6565. /* Load the DER encoded DH parameters into DH key.
  6566. *
  6567. * @param [in, out] dh DH key to load parameters into.
  6568. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6569. * @param [in] derSz Size of DER data in buffer in bytes.
  6570. *
  6571. * @return 1 on success.
  6572. * @return -1 when DH or derBuf is NULL,
  6573. * internal DH key in DH is NULL,
  6574. * derSz is 0 or less,
  6575. * error decoding DER data or
  6576. * setting external parameter values fails.
  6577. */
  6578. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6579. {
  6580. int ret = 1;
  6581. word32 idx = 0;
  6582. /* Validate parameters. */
  6583. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6584. (derSz <= 0)) {
  6585. WOLFSSL_ERROR_MSG("Bad function arguments");
  6586. ret = -1;
  6587. }
  6588. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6589. (word32)derSz) != 0)) {
  6590. WOLFSSL_ERROR_MSG("DH key decode failed");
  6591. ret = -1;
  6592. }
  6593. return ret;
  6594. }
  6595. #endif
  6596. /*
  6597. * DH PEM APIs
  6598. */
  6599. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6600. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6601. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6602. /* Create a DH key by reading the PEM encoded data from the BIO.
  6603. *
  6604. * @param [in] bio BIO object to read from.
  6605. * @param [in, out] dh DH key to use. May be NULL.
  6606. * @param [in] pem PEM data to decode.
  6607. * @param [in] pemSz Size of PEM data in bytes.
  6608. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6609. * freed after use.
  6610. * @return DH key on success.
  6611. * @return NULL on failure.
  6612. */
  6613. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6614. unsigned char* pem, int pemSz, int memAlloced)
  6615. {
  6616. WOLFSSL_DH* localDh = NULL;
  6617. DerBuffer *der = NULL;
  6618. int err = 0;
  6619. /* Convert PEM to DER assuming DH Parameter format. */
  6620. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6621. NULL) < 0)) {
  6622. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6623. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6624. != 0) {
  6625. err = 1;
  6626. }
  6627. }
  6628. if (memAlloced) {
  6629. /* PEM data no longer needed. */
  6630. XFREE(pem, NULL, DYNAMIC_TYPE_PEM);
  6631. }
  6632. if (!err) {
  6633. /* Use the DH key passed in or allocate a new one. */
  6634. if (dh != NULL) {
  6635. localDh = *dh;
  6636. }
  6637. if (localDh == NULL) {
  6638. localDh = wolfSSL_DH_new();
  6639. if (localDh == NULL) {
  6640. err = 1;
  6641. }
  6642. }
  6643. }
  6644. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6645. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, der->length)
  6646. != 1)) {
  6647. /* Free an allocated DH key. */
  6648. if ((dh == NULL) || (localDh != *dh)) {
  6649. wolfSSL_DH_free(localDh);
  6650. }
  6651. localDh = NULL;
  6652. err = 1;
  6653. }
  6654. /* Return the DH key on success. */
  6655. if ((!err) && (dh != NULL)) {
  6656. *dh = localDh;
  6657. }
  6658. /* Dispose of DER data. */
  6659. if (der != NULL) {
  6660. FreeDer(&der);
  6661. }
  6662. return localDh;
  6663. }
  6664. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6665. #ifndef NO_BIO
  6666. /* Create a DH key by reading the PEM encoded data from the BIO.
  6667. *
  6668. * DH parameters are public data and are not expected to be encrypted.
  6669. *
  6670. * @param [in] bio BIO object to read from.
  6671. * @param [in, out] dh DH key to When pointer to
  6672. * NULL, a new DH key is created.
  6673. * @param [in] cb Password callback when PEM encrypted. Not used.
  6674. * @param [in] pass NUL terminated string for passphrase when PEM
  6675. * encrypted. Not used.
  6676. * @return DH key on success.
  6677. * @return NULL on failure.
  6678. */
  6679. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6680. wc_pem_password_cb *cb, void *pass)
  6681. {
  6682. WOLFSSL_DH* localDh = NULL;
  6683. int err = 0;
  6684. unsigned char* mem = NULL;
  6685. int size = 0;
  6686. int memAlloced = 0;
  6687. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6688. (void)cb;
  6689. (void)pass;
  6690. /* Validate parameters. */
  6691. if (bio == NULL) {
  6692. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6693. err = 1;
  6694. }
  6695. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6696. */
  6697. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6698. != 0)) {
  6699. err = 1;
  6700. }
  6701. if (!err) {
  6702. /* Create a DH key from the PEM - try two different headers. */
  6703. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6704. }
  6705. return localDh;
  6706. }
  6707. #endif /* !NO_BIO */
  6708. #ifndef NO_FILESYSTEM
  6709. /* Read DH parameters from a file pointer into DH key.
  6710. *
  6711. * DH parameters are public data and are not expected to be encrypted.
  6712. *
  6713. * @param [in] fp File pointer to read DH parameter file from.
  6714. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6715. * NULL, a new DH key is created.
  6716. * @param [in] cb Password callback when PEM encrypted. Not used.
  6717. * @param [in] pass NUL terminated string for passphrase when PEM
  6718. * encrypted. Not used.
  6719. *
  6720. * @return NULL on failure.
  6721. * @return DH key with parameters set on success.
  6722. */
  6723. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6724. wc_pem_password_cb* cb, void* pass)
  6725. {
  6726. WOLFSSL_DH* localDh = NULL;
  6727. int err = 0;
  6728. unsigned char* mem = NULL;
  6729. int size = 0;
  6730. (void)cb;
  6731. (void)pass;
  6732. /* Read data from file pointer. */
  6733. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6734. err = 1;
  6735. }
  6736. if (!err) {
  6737. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6738. }
  6739. return localDh;
  6740. }
  6741. #endif /* !NO_FILESYSTEM */
  6742. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6743. /* Encoded parameter data in DH key as DER.
  6744. *
  6745. * @param [in, out] dh DH key object to encode.
  6746. * @param [out] out Buffer containing DER encoding.
  6747. * @param [in] heap Heap hint.
  6748. * @return <0 on error.
  6749. * @return Length of DER encoded DH parameters in bytes.
  6750. */
  6751. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6752. void* heap)
  6753. {
  6754. int ret = -1;
  6755. int err = 0;
  6756. byte* der = NULL;
  6757. word32 derSz;
  6758. DhKey* key;
  6759. /* Set internal parameters based on external parameters. */
  6760. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6761. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6762. err = 1;
  6763. }
  6764. if (!err) {
  6765. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6766. key = (DhKey*)dh->internal;
  6767. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6768. if (ret != LENGTH_ONLY_E) {
  6769. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6770. err = 1;
  6771. }
  6772. }
  6773. if (!err) {
  6774. /* Allocate memory for DER encoding. */
  6775. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6776. if (der == NULL) {
  6777. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6778. err = 1;
  6779. }
  6780. }
  6781. if (!err) {
  6782. /* Encode DH parameters into DER buffer. */
  6783. ret = wc_DhParamsToDer(key, der, &derSz);
  6784. if (ret < 0) {
  6785. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6786. err = 1;
  6787. }
  6788. }
  6789. if (!err) {
  6790. *out = der;
  6791. der = NULL;
  6792. }
  6793. if (der != NULL) {
  6794. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6795. }
  6796. return ret;
  6797. }
  6798. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6799. * passed in.
  6800. *
  6801. * @param [in] fp File pointer to write to.
  6802. * @param [in] dh DH key to write.
  6803. * @return 1 on success.
  6804. * @return 0 on failure.
  6805. */
  6806. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6807. {
  6808. int ret = 1;
  6809. int derSz;
  6810. byte* derBuf = NULL;
  6811. void* heap = NULL;
  6812. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6813. /* Validate parameters. */
  6814. if ((fp == XBADFILE) || (dh == NULL)) {
  6815. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6816. ret = 0;
  6817. }
  6818. if (ret == 1) {
  6819. DhKey* key = (DhKey*)dh->internal;
  6820. if (key)
  6821. heap = key->heap;
  6822. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6823. WOLFSSL_ERROR_MSG("DER encoding failed");
  6824. ret = 0;
  6825. }
  6826. if (derBuf == NULL) {
  6827. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6828. ret = 0;
  6829. }
  6830. }
  6831. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6832. DH_PARAM_TYPE, NULL) != WOLFSSL_SUCCESS)) {
  6833. ret = 0;
  6834. }
  6835. /* Dispose of DER buffer. */
  6836. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6837. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6838. return ret;
  6839. }
  6840. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6841. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6842. * OPENSSL_EXTRA */
  6843. /*
  6844. * DH get/set APIs
  6845. */
  6846. #ifdef OPENSSL_EXTRA
  6847. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6848. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6849. /* Set the members of DhKey into WOLFSSL_DH
  6850. * Specify elements to set via the 2nd parameter
  6851. *
  6852. * @param [in, out] dh DH key to synchronize.
  6853. * @param [in] elm Elements to synchronize.
  6854. * @return 1 on success.
  6855. * @return -1 on failure.
  6856. */
  6857. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  6858. {
  6859. int ret = 1;
  6860. DhKey *key = NULL;
  6861. WOLFSSL_ENTER("SetDhExternal_ex");
  6862. /* Validate parameters. */
  6863. if ((dh == NULL) || (dh->internal == NULL)) {
  6864. WOLFSSL_ERROR_MSG("dh key NULL error");
  6865. ret = -1;
  6866. }
  6867. if (ret == 1) {
  6868. /* Get the wolfSSL DH key. */
  6869. key = (DhKey*)dh->internal;
  6870. }
  6871. if ((ret == 1) && (elm & ELEMENT_P)) {
  6872. /* Set the prime. */
  6873. if (SetIndividualExternal(&dh->p, &key->p) != 1) {
  6874. WOLFSSL_ERROR_MSG("dh param p error");
  6875. ret = -1;
  6876. }
  6877. }
  6878. if ((ret == 1) && (elm & ELEMENT_G)) {
  6879. /* Set the generator. */
  6880. if (SetIndividualExternal(&dh->g, &key->g) != 1) {
  6881. WOLFSSL_ERROR_MSG("dh param g error");
  6882. ret = -1;
  6883. }
  6884. }
  6885. if ((ret == 1) && (elm & ELEMENT_Q)) {
  6886. /* Set the order. */
  6887. if (SetIndividualExternal(&dh->q, &key->q) != 1) {
  6888. WOLFSSL_ERROR_MSG("dh param q error");
  6889. ret = -1;
  6890. }
  6891. }
  6892. #ifdef WOLFSSL_DH_EXTRA
  6893. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  6894. /* Set the private key. */
  6895. if (SetIndividualExternal(&dh->priv_key, &key->priv) != 1) {
  6896. WOLFSSL_ERROR_MSG("No DH Private Key");
  6897. ret = -1;
  6898. }
  6899. }
  6900. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  6901. /* Set the public key. */
  6902. if (SetIndividualExternal(&dh->pub_key, &key->pub) != 1) {
  6903. WOLFSSL_ERROR_MSG("No DH Public Key");
  6904. ret = -1;
  6905. }
  6906. }
  6907. #endif /* WOLFSSL_DH_EXTRA */
  6908. if (ret == 1) {
  6909. /* On success record that the external values have been set. */
  6910. dh->exSet = 1;
  6911. }
  6912. return ret;
  6913. }
  6914. /* Set the members of DhKey into WOLFSSL_DH
  6915. * DhKey was populated from wc_DhKeyDecode
  6916. * p, g, pub_key and priv_key are set.
  6917. *
  6918. * @param [in, out] dh DH key to synchronize.
  6919. * @return 1 on success.
  6920. * @return -1 on failure.
  6921. */
  6922. int SetDhExternal(WOLFSSL_DH *dh)
  6923. {
  6924. /* Assuming Q not required when using this API. */
  6925. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  6926. WOLFSSL_ENTER("SetDhExternal");
  6927. return SetDhExternal_ex(dh, elements);
  6928. }
  6929. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  6930. /* Set the internal/wolfSSL DH key with data from the external parts.
  6931. *
  6932. * @param [in, out] dh DH key to synchronize.
  6933. * @return 1 on success.
  6934. * @return -1 on failure.
  6935. */
  6936. int SetDhInternal(WOLFSSL_DH* dh)
  6937. {
  6938. int ret = 1;
  6939. DhKey *key = NULL;
  6940. WOLFSSL_ENTER("SetDhInternal");
  6941. /* Validate parameters. */
  6942. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  6943. WOLFSSL_ERROR_MSG("Bad function arguments");
  6944. ret = -1;
  6945. }
  6946. if (ret == 1) {
  6947. /* Get the wolfSSL DH key. */
  6948. key = (DhKey*)dh->internal;
  6949. /* Clear out key and initialize. */
  6950. wc_FreeDhKey(key);
  6951. if (wc_InitDhKey(key) != 0) {
  6952. ret = -1;
  6953. }
  6954. }
  6955. if (ret == 1) {
  6956. /* Transfer prime. */
  6957. if (SetIndividualInternal(dh->p, &key->p) != 1) {
  6958. ret = -1;
  6959. }
  6960. }
  6961. if (ret == 1) {
  6962. /* Transfer generator. */
  6963. if (SetIndividualInternal(dh->g, &key->g) != 1) {
  6964. ret = -1;
  6965. }
  6966. }
  6967. #ifdef HAVE_FFDHE_Q
  6968. /* Transfer order if available. */
  6969. if ((ret == 1) && (dh->q != NULL)) {
  6970. if (SetIndividualInternal(dh->q, &key->q) != 1) {
  6971. ret = -1;
  6972. }
  6973. }
  6974. #endif
  6975. #ifdef WOLFSSL_DH_EXTRA
  6976. /* Transfer private key if available. */
  6977. if ((ret == 1) && (dh->priv_key != NULL) &&
  6978. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  6979. if (SetIndividualInternal(dh->priv_key, &key->priv) != 1) {
  6980. ret = -1;
  6981. }
  6982. }
  6983. /* Transfer public key if available. */
  6984. if ((ret == 1) && (dh->pub_key != NULL) &&
  6985. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  6986. if (SetIndividualInternal(dh->pub_key, &key->pub) != 1) {
  6987. ret = -1;
  6988. }
  6989. }
  6990. #endif /* WOLFSSL_DH_EXTRA */
  6991. if (ret == 1) {
  6992. /* On success record that the internal values have been set. */
  6993. dh->inSet = 1;
  6994. }
  6995. return ret;
  6996. }
  6997. /* Get the size, in bytes, of the DH key.
  6998. *
  6999. * Return code compliant with OpenSSL.
  7000. *
  7001. * @param [in] dh DH key.
  7002. * @return -1 on error.
  7003. * @return Size of DH key in bytes on success.
  7004. */
  7005. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7006. {
  7007. int ret = -1;
  7008. WOLFSSL_ENTER("wolfSSL_DH_size");
  7009. /* Validate paramater. */
  7010. if (dh != NULL) {
  7011. /* Size of key is size of prime in bytes. */
  7012. ret = wolfSSL_BN_num_bytes(dh->p);
  7013. }
  7014. return ret;
  7015. }
  7016. /**
  7017. * Return parameters p, q and/or g of the DH key.
  7018. *
  7019. * @param [in] dh DH key to retrieve parameters from.
  7020. * @param [out] p Pointer to return prime in. May be NULL.
  7021. * @param [out] q Pointer to return order in. May be NULL.
  7022. * @param [out] g Pointer to return generator in. May be NULL.
  7023. */
  7024. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7025. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7026. {
  7027. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7028. if (dh != NULL) {
  7029. /* Return prime if required. */
  7030. if (p != NULL) {
  7031. *p = dh->p;
  7032. }
  7033. /* Return order if required. */
  7034. if (q != NULL) {
  7035. *q = dh->q;
  7036. }
  7037. /* Return generator if required. */
  7038. if (g != NULL) {
  7039. *g = dh->g;
  7040. }
  7041. }
  7042. }
  7043. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7044. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7045. #if defined(OPENSSL_ALL) || \
  7046. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7047. /* Sets the parameters p, g and optionally q into the DH key.
  7048. *
  7049. * Ownership of p, q and g get taken over by "dh" on success and should be
  7050. * free'd with a call to wolfSSL_DH_free -- not individually.
  7051. *
  7052. * @param [in, out] dh DH key to set.
  7053. * @parma [in] p Prime value to set. May be NULL when value already
  7054. * present.
  7055. * @parma [in] q Order value to set. May be NULL.
  7056. * @parma [in] g Generator value to set. May be NULL when value already
  7057. * present.
  7058. * @return 1 on success.
  7059. * @return 0 on failure.
  7060. */
  7061. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7062. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7063. {
  7064. int ret = 1;
  7065. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7066. /* Validate parameters - q is optional. */
  7067. if (dh == NULL) {
  7068. WOLFSSL_ERROR_MSG("Bad function arguments");
  7069. ret = 0;
  7070. }
  7071. /* p can be NULL if we already have one set. */
  7072. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7073. WOLFSSL_ERROR_MSG("Bad function arguments");
  7074. ret = 0;
  7075. }
  7076. /* g can be NULL if we already have one set. */
  7077. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7078. WOLFSSL_ERROR_MSG("Bad function arguments");
  7079. ret = 0;
  7080. }
  7081. if (ret == 1) {
  7082. /* Invalidate internal key. */
  7083. dh->inSet = 0;
  7084. /* Free external representation of parameters and set with those passed
  7085. * in. */
  7086. if (p != NULL) {
  7087. wolfSSL_BN_free(dh->p);
  7088. dh->p = p;
  7089. }
  7090. if (q != NULL) {
  7091. wolfSSL_BN_free(dh->q);
  7092. dh->q = q;
  7093. }
  7094. if (g != NULL) {
  7095. wolfSSL_BN_free(dh->g);
  7096. dh->g = g;
  7097. }
  7098. /* External DH key parameters were set. */
  7099. dh->exSet = 1;
  7100. /* Set internal/wolfSSL DH key as well. */
  7101. if (SetDhInternal(dh) != 1) {
  7102. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7103. /* Don't keep parameters on failure. */
  7104. dh->p = NULL;
  7105. dh->q = NULL;
  7106. dh->g = NULL;
  7107. /* Internal and external DH key not set. */
  7108. dh->inSet = 0;
  7109. dh->exSet = 0;
  7110. ret = 0;
  7111. }
  7112. }
  7113. return ret;
  7114. }
  7115. /* Set the length of the DH private key in bits.
  7116. *
  7117. * Length field is checked at generation.
  7118. *
  7119. * @param [in, out] dh DH key to set.
  7120. * @param [in] len Length of DH private key in bytes.
  7121. * @return 0 on failure.
  7122. * @return 1 on success.
  7123. */
  7124. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7125. {
  7126. int ret = 1;
  7127. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7128. /* Validate parameter. */
  7129. if (dh == NULL) {
  7130. WOLFSSL_ERROR_MSG("Bad function arguments");
  7131. ret = 0;
  7132. }
  7133. else {
  7134. /* Store length. */
  7135. dh->length = (int)len;
  7136. }
  7137. return ret;
  7138. }
  7139. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7140. #endif
  7141. /* Get the public and private keys requested.
  7142. *
  7143. * @param [in] dh DH key to get keys from.
  7144. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7145. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7146. */
  7147. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7148. const WOLFSSL_BIGNUM **priv_key)
  7149. {
  7150. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7151. /* Get only when valid DH passed in. */
  7152. if (dh != NULL) {
  7153. /* Return public key if required and available. */
  7154. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7155. *pub_key = dh->pub_key;
  7156. }
  7157. /* Return private key if required and available. */
  7158. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7159. *priv_key = dh->priv_key;
  7160. }
  7161. }
  7162. }
  7163. /* Set the public and/or private key.
  7164. *
  7165. * @param [in, out] dh DH key to have keys set into.
  7166. * @param [in] pub_key Public key to set. May be NULL.
  7167. * @param [in] priv_key Private key to set. May be NULL.
  7168. * @return 0 on failure.
  7169. * @return 1 on success.
  7170. */
  7171. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7172. WOLFSSL_BIGNUM *priv_key)
  7173. {
  7174. int ret = 1;
  7175. #ifdef WOLFSSL_DH_EXTRA
  7176. DhKey *key = NULL;
  7177. #endif
  7178. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7179. /* Validate parameters. */
  7180. if (dh == NULL) {
  7181. ret = 0;
  7182. }
  7183. #ifdef WOLFSSL_DH_EXTRA
  7184. else {
  7185. key = (DhKey*)dh->internal;
  7186. }
  7187. #endif
  7188. /* Replace public key when one passed in. */
  7189. if ((ret == 1) && (pub_key != NULL)) {
  7190. wolfSSL_BN_free(dh->pub_key);
  7191. dh->pub_key = pub_key;
  7192. #ifdef WOLFSSL_DH_EXTRA
  7193. if (SetIndividualInternal(dh->pub_key, &key->pub) != 1) {
  7194. ret = 0;
  7195. }
  7196. #endif
  7197. }
  7198. /* Replace private key when one passed in. */
  7199. if ((ret == 1) && (priv_key != NULL)) {
  7200. wolfSSL_BN_clear_free(dh->priv_key);
  7201. dh->priv_key = priv_key;
  7202. #ifdef WOLFSSL_DH_EXTRA
  7203. if (SetIndividualInternal(dh->priv_key, &key->priv) != 1) {
  7204. ret = 0;
  7205. }
  7206. #endif
  7207. }
  7208. return ret;
  7209. }
  7210. #endif /* OPENSSL_EXTRA */
  7211. /*
  7212. * DH check APIs
  7213. */
  7214. #ifdef OPENSSL_EXTRA
  7215. #ifndef NO_CERTS
  7216. #ifdef OPENSSL_ALL
  7217. /* Check whether BN number is a prime.
  7218. *
  7219. * @param [in] n Number to check.
  7220. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7221. * @return 1 on success.
  7222. * @return 0 on error.
  7223. */
  7224. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7225. {
  7226. int ret = 1;
  7227. #ifdef WOLFSSL_SMALL_STACK
  7228. WC_RNG* tmpRng = NULL;
  7229. #else
  7230. WC_RNG tmpRng[1];
  7231. #endif
  7232. WC_RNG* rng;
  7233. int localRng;
  7234. /* Make an RNG with tmpRng or get global. */
  7235. rng = wolfssl_make_rng(tmpRng, &localRng);
  7236. if (rng == NULL) {
  7237. ret = 0;
  7238. }
  7239. if (ret == 1) {
  7240. mp_int* prime = (mp_int*)n->internal;
  7241. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7242. ret = 0;
  7243. }
  7244. /* Free local random number generator if created. */
  7245. if (localRng) {
  7246. wc_FreeRng(rng);
  7247. #ifdef WOLFSSL_SMALL_STACK
  7248. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7249. #endif
  7250. }
  7251. }
  7252. return ret;
  7253. }
  7254. /* Checks the Diffie-Hellman parameters.
  7255. *
  7256. * Checks that the generator and prime are available.
  7257. * Checks that the prime is prime.
  7258. * OpenSSL expects codes to be non-NULL.
  7259. *
  7260. * @param [in] dh DH key to check.
  7261. * @param [out] codes Codes of checks that failed.
  7262. * @return 1 on success.
  7263. * @return 0 when DH is NULL, there were errors or failed to create a random
  7264. * number generator.
  7265. */
  7266. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7267. {
  7268. int ret = 1;
  7269. int errors = 0;
  7270. WOLFSSL_ENTER("wolfSSL_DH_check");
  7271. /* Validate parameters. */
  7272. if (dh == NULL) {
  7273. ret = 0;
  7274. }
  7275. /* Check generator available. */
  7276. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7277. errors |= DH_NOT_SUITABLE_GENERATOR;
  7278. }
  7279. if (ret == 1) {
  7280. /* Check prime available. */
  7281. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7282. errors |= DH_CHECK_P_NOT_PRIME;
  7283. }
  7284. else {
  7285. /* Test if dh->p is prime. */
  7286. int isPrime = MP_NO;
  7287. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7288. /* Set error code if parameter p is not prime. */
  7289. if ((ret == 1) && (isPrime != MP_YES)) {
  7290. errors |= DH_CHECK_P_NOT_PRIME;
  7291. }
  7292. }
  7293. }
  7294. /* Return errors when user wants exact issues. */
  7295. if (codes != NULL) {
  7296. *codes = errors;
  7297. }
  7298. else if (errors) {
  7299. ret = 0;
  7300. }
  7301. return ret;
  7302. }
  7303. #endif /* OPENSSL_ALL */
  7304. #endif /* !NO_CERTS */
  7305. #endif /* OPENSSL_EXTRA */
  7306. /*
  7307. * DH generate APIs
  7308. */
  7309. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7310. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7311. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7312. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7313. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7314. /* Generate DH parameters.
  7315. *
  7316. * @param [in] prime_len Length of prime in bits.
  7317. * @param [in] generator Gnerator value to use.
  7318. * @param [in] callback Called with progress information. Unused.
  7319. * @param [in] cb_arg User callback argument. Unused.
  7320. * @return NULL on failure.
  7321. * @return DH key on success.
  7322. */
  7323. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7324. void (*callback) (int, int, void *), void *cb_arg)
  7325. {
  7326. WOLFSSL_DH* dh = NULL;
  7327. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7328. /* Not supported by wolfSSl APIs. */
  7329. (void)callback;
  7330. (void)cb_arg;
  7331. /* Create an empty DH key. */
  7332. if ((dh = wolfSSL_DH_new()) == NULL) {
  7333. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7334. }
  7335. /* Generate parameters into DH key. */
  7336. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7337. != 1) {
  7338. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7339. wolfSSL_DH_free(dh);
  7340. dh = NULL;
  7341. }
  7342. return dh;
  7343. }
  7344. /* Generate DH parameters.
  7345. *
  7346. * @param [in] dh DH key to generate parameters into.
  7347. * @param [in] prime_len Length of prime in bits.
  7348. * @param [in] generator Gnerator value to use.
  7349. * @param [in] callback Called with progress information. Unused.
  7350. * @param [in] cb_arg User callback argument. Unused.
  7351. * @return 0 on failure.
  7352. * @return 1 on success.
  7353. */
  7354. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7355. int generator, void (*callback) (int, int, void *))
  7356. {
  7357. int ret = 1;
  7358. DhKey* key;
  7359. #ifdef WOLFSSL_SMALL_STACK
  7360. WC_RNG* tmpRng = NULL;
  7361. #else
  7362. WC_RNG tmpRng[1];
  7363. #endif
  7364. WC_RNG* rng = NULL;
  7365. int localRng = 0;
  7366. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7367. /* Not supported by wolfSSL APIs. */
  7368. (void)callback;
  7369. (void)generator;
  7370. /* Validate parameters. */
  7371. if (dh == NULL) {
  7372. WOLFSSL_ERROR_MSG("Bad parameter");
  7373. ret = 0;
  7374. }
  7375. if (ret == 1) {
  7376. /* Make an RNG with tmpRng or get global. */
  7377. rng = wolfssl_make_rng(tmpRng, &localRng);
  7378. if (rng == NULL) {
  7379. WOLFSSL_ERROR_MSG("No RNG to use");
  7380. ret = 0;
  7381. }
  7382. }
  7383. if (ret == 1) {
  7384. /* Get internal/wolfSSL DH key. */
  7385. key = (DhKey*)dh->internal;
  7386. /* Clear out data from internal DH key. */
  7387. wc_FreeDhKey(key);
  7388. /* Re-initialize internal DH key. */
  7389. if (wc_InitDhKey(key) != 0) {
  7390. ret = 0;
  7391. }
  7392. }
  7393. if (ret == 1) {
  7394. /* Generate parameters into internal DH key. */
  7395. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7396. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7397. ret = 0;
  7398. }
  7399. }
  7400. /* Free local random number generator if created. */
  7401. if (localRng) {
  7402. wc_FreeRng(rng);
  7403. #ifdef WOLFSSL_SMALL_STACK
  7404. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7405. #endif
  7406. }
  7407. if (ret == 1) {
  7408. /* Internal parameters set by generation. */
  7409. dh->inSet = 1;
  7410. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7411. /* Synchronize the external to the internal parameters. */
  7412. if (SetDhExternal(dh) != 1) {
  7413. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7414. ret = 0;
  7415. }
  7416. }
  7417. return ret;
  7418. }
  7419. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7420. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7421. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7422. * HAVE_SBLIM_SFCB)) */
  7423. #ifdef OPENSSL_EXTRA
  7424. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7425. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7426. /* Generate a public/private key pair base on parameters.
  7427. *
  7428. * @param [in, out] dh DH key to generate keys into.
  7429. * @return 1 on success.
  7430. * @return 0 on error.
  7431. */
  7432. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7433. {
  7434. int ret = 1;
  7435. word32 pubSz = 0;
  7436. word32 privSz = 0;
  7437. int localRng = 0;
  7438. WC_RNG* rng = NULL;
  7439. #ifdef WOLFSSL_SMALL_STACK
  7440. WC_RNG* tmpRng = NULL;
  7441. #else
  7442. WC_RNG tmpRng[1];
  7443. #endif
  7444. unsigned char* pub = NULL;
  7445. unsigned char* priv = NULL;
  7446. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7447. /* Validate parameters. */
  7448. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7449. WOLFSSL_ERROR_MSG("Bad function arguments");
  7450. ret = 0;
  7451. }
  7452. /* Synchronize the external and internal parameters. */
  7453. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7454. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7455. ret = 0;
  7456. }
  7457. if (ret == 1) {
  7458. /* Make a new RNG or use global. */
  7459. rng = wolfssl_make_rng(tmpRng, &localRng);
  7460. /* Check we have a random number generator. */
  7461. if (rng == NULL) {
  7462. ret = 0;
  7463. }
  7464. }
  7465. if (ret == 1) {
  7466. /* Get the size of the prime in bytes. */
  7467. pubSz = wolfSSL_BN_num_bytes(dh->p);
  7468. if (pubSz == 0) {
  7469. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7470. ret = 0;
  7471. }
  7472. }
  7473. if (ret == 1) {
  7474. /* Private key size can be as much as the size of the prime. */
  7475. if (dh->length) {
  7476. privSz = dh->length / 8; /* to bytes */
  7477. }
  7478. else {
  7479. privSz = pubSz;
  7480. }
  7481. /* Allocate public and private key arrays. */
  7482. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7483. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7484. if (pub == NULL || priv == NULL) {
  7485. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7486. ret = 0;
  7487. }
  7488. }
  7489. if (ret == 1) {
  7490. /* Dispose of old public and private keys. */
  7491. wolfSSL_BN_free(dh->pub_key);
  7492. wolfSSL_BN_free(dh->priv_key);
  7493. /* Allocate new public and private keys. */
  7494. dh->pub_key = wolfSSL_BN_new();
  7495. dh->priv_key = wolfSSL_BN_new();
  7496. if (dh->pub_key == NULL) {
  7497. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7498. ret = 0;
  7499. }
  7500. if (dh->priv_key == NULL) {
  7501. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7502. ret = 0;
  7503. }
  7504. }
  7505. PRIVATE_KEY_UNLOCK();
  7506. /* Generate public and private keys into arrays. */
  7507. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7508. &privSz, pub, &pubSz) < 0)) {
  7509. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7510. ret = 0;
  7511. }
  7512. /* Set public key from array. */
  7513. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, pubSz, dh->pub_key) == NULL)) {
  7514. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7515. ret = 0;
  7516. }
  7517. /* Set private key from array. */
  7518. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, privSz, dh->priv_key) == NULL)) {
  7519. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7520. ret = 0;
  7521. }
  7522. PRIVATE_KEY_LOCK();
  7523. if (localRng) {
  7524. /* Free an initialized local random number generator. */
  7525. wc_FreeRng(rng);
  7526. #ifdef WOLFSSL_SMALL_STACK
  7527. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7528. #endif
  7529. }
  7530. /* Dispose of allocated data. */
  7531. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7532. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7533. return ret;
  7534. }
  7535. /* Compute the shared key from the private key and peer's public key.
  7536. *
  7537. * Return code compliant with OpenSSL.
  7538. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7539. * supported.
  7540. *
  7541. * @param [out] key Buffer to place shared key.
  7542. * @param [in] otherPub Peer's public key.
  7543. * @param [in] dh DH key containing private key.
  7544. * @return -1 on error.
  7545. * @return Size of shared secret in bytes on success.
  7546. */
  7547. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7548. WOLFSSL_DH* dh)
  7549. {
  7550. int ret = 0;
  7551. word32 keySz = 0;
  7552. int pubSz = MAX_DHKEY_SZ;
  7553. int privSz = MAX_DHKEY_SZ;
  7554. int sz;
  7555. #ifdef WOLFSSL_SMALL_STACK
  7556. unsigned char* pub = NULL;
  7557. unsigned char* priv = NULL;
  7558. #else
  7559. unsigned char pub [MAX_DHKEY_SZ];
  7560. unsigned char priv[MAX_DHKEY_SZ];
  7561. #endif
  7562. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7563. /* Validate parameters. */
  7564. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7565. WOLFSSL_ERROR_MSG("Bad function arguments");
  7566. ret = -1;
  7567. }
  7568. /* Get the maximum size of computed DH key. */
  7569. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7570. WOLFSSL_ERROR_MSG("Bad DH_size");
  7571. ret = -1;
  7572. }
  7573. if (ret == 0) {
  7574. /* Validate the size of the private key. */
  7575. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7576. if (sz > (int)privSz) {
  7577. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7578. ret = -1;
  7579. }
  7580. }
  7581. if (ret == 0) {
  7582. #ifdef WOLFSSL_SMALL_STACK
  7583. /* Keep real private key size to minimize amount allocated. */
  7584. privSz = sz;
  7585. #endif
  7586. /* Validate the size of the public key. */
  7587. sz = wolfSSL_BN_num_bytes(otherPub);
  7588. if (sz > (int)pubSz) {
  7589. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7590. ret = -1;
  7591. }
  7592. }
  7593. if (ret == 0) {
  7594. #ifdef WOLFSSL_SMALL_STACK
  7595. /* Allocate memory for the public key array. */
  7596. pub = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7597. if (pub == NULL)
  7598. ret = -1;
  7599. }
  7600. if (ret == 0) {
  7601. /* Allocate memory for the private key array. */
  7602. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7603. if (priv == NULL) {
  7604. ret = -1;
  7605. }
  7606. }
  7607. if (ret == 0) {
  7608. #endif
  7609. /* Get the private key into the array. */
  7610. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7611. if (privSz <= 0) {
  7612. ret = -1;
  7613. }
  7614. }
  7615. if (ret == 0) {
  7616. /* Get the public key into the array. */
  7617. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7618. if (privSz <= 0) {
  7619. ret = -1;
  7620. }
  7621. }
  7622. /* Synchronize the external into the internal parameters. */
  7623. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7624. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7625. ret = -1;
  7626. }
  7627. PRIVATE_KEY_UNLOCK();
  7628. /* Calculate shared secret from private and public keys. */
  7629. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7630. privSz, pub, pubSz) < 0)) {
  7631. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7632. ret = -1;
  7633. }
  7634. if (ret == 0) {
  7635. /* Return actual length. */
  7636. ret = (int)keySz;
  7637. }
  7638. PRIVATE_KEY_LOCK();
  7639. #ifdef WOLFSSL_SMALL_STACK
  7640. if (priv != NULL)
  7641. #endif
  7642. {
  7643. /* Zeroize sensitive data. */
  7644. ForceZero(priv, privSz);
  7645. }
  7646. #ifdef WOLFSSL_SMALL_STACK
  7647. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7648. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7649. #endif
  7650. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7651. return ret;
  7652. }
  7653. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7654. * HAVE_FIPS_VERSION > 2 */
  7655. #endif /* OPENSSL_EXTRA */
  7656. #endif /* NO_DH */
  7657. /*******************************************************************************
  7658. * END OF DH API
  7659. ******************************************************************************/
  7660. /*******************************************************************************
  7661. * START OF EC API
  7662. ******************************************************************************/
  7663. #ifdef HAVE_ECC
  7664. #if defined(OPENSSL_EXTRA)
  7665. #ifndef NO_CERTS
  7666. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  7667. !defined(NO_STDIO_FILESYSTEM)
  7668. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  7669. {
  7670. int ret = 1;
  7671. int bits = 0;
  7672. int priv = 0;
  7673. int nid = 0;
  7674. const char* curve;
  7675. const char* nistName;
  7676. WOLFSSL_BIGNUM* pubBn = NULL;
  7677. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  7678. if (fp == XBADFILE || key == NULL || key->group == NULL || indent < 0) {
  7679. ret = 0;
  7680. }
  7681. if (ret == 1) {
  7682. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  7683. if (bits <= 0) {
  7684. WOLFSSL_MSG("Failed to get group order bits.");
  7685. ret = 0;
  7686. }
  7687. }
  7688. if (ret == 1) {
  7689. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  7690. ret = 0;
  7691. }
  7692. if (ret == 1) {
  7693. if (key->priv_key != NULL && !wolfSSL_BN_is_zero(key->priv_key)) {
  7694. if (XFPRINTF(fp, "Private-Key: (%d bit)\n", bits) < 0)
  7695. ret = 0;
  7696. priv = 1;
  7697. }
  7698. else {
  7699. if (XFPRINTF(fp, "Public-Key: (%d bit)\n", bits) < 0)
  7700. ret = 0;
  7701. }
  7702. if (priv) {
  7703. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  7704. }
  7705. }
  7706. if (ret == 1 && key->pub_key != NULL && key->pub_key->exSet) {
  7707. pubBn = wolfSSL_EC_POINT_point2bn(key->group, key->pub_key,
  7708. POINT_CONVERSION_UNCOMPRESSED, NULL,
  7709. NULL);
  7710. if (pubBn == NULL) {
  7711. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  7712. ret = 0;
  7713. }
  7714. else {
  7715. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  7716. }
  7717. }
  7718. if (ret == 1) {
  7719. nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  7720. if (nid > 0) {
  7721. curve = wolfSSL_OBJ_nid2ln(nid);
  7722. if (curve != NULL) {
  7723. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  7724. ret = 0;
  7725. else if (XFPRINTF(fp, "ASN1 OID: %s\n", curve) < 0)
  7726. ret = 0;
  7727. }
  7728. nistName = wolfSSL_EC_curve_nid2nist(nid);
  7729. if (nistName != NULL) {
  7730. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  7731. ret = 0;
  7732. else if (XFPRINTF(fp, "NIST CURVE: %s\n", nistName) < 0)
  7733. ret = 0;
  7734. }
  7735. }
  7736. }
  7737. if (pubBn != NULL) {
  7738. wolfSSL_BN_free(pubBn);
  7739. }
  7740. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  7741. return ret;
  7742. }
  7743. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  7744. #if defined(OPENSSL_ALL)
  7745. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  7746. *
  7747. * src : EC_KEY to duplicate. If EC_KEY is not null, create new EC_KEY and copy
  7748. * internal ecc_key from src to dup.
  7749. *
  7750. * Returns pointer to duplicate EC_KEY.
  7751. */
  7752. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  7753. {
  7754. WOLFSSL_EC_KEY *newKey;
  7755. ecc_key *key, *srcKey;
  7756. int ret;
  7757. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  7758. if (src == NULL || src->internal == NULL || src->group == NULL || \
  7759. src->pub_key == NULL || src->priv_key == NULL) {
  7760. WOLFSSL_MSG("src NULL error");
  7761. return NULL;
  7762. }
  7763. newKey = wolfSSL_EC_KEY_new();
  7764. if (newKey == NULL) {
  7765. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  7766. return NULL;
  7767. }
  7768. key = (ecc_key*)newKey->internal;
  7769. if (key == NULL) {
  7770. WOLFSSL_MSG("ecc_key NULL error");
  7771. wolfSSL_EC_KEY_free(newKey);
  7772. return NULL;
  7773. }
  7774. srcKey = (ecc_key*)src->internal;
  7775. /* ecc_key */
  7776. /* copy pubkey */
  7777. ret = wc_ecc_copy_point(&srcKey->pubkey, &key->pubkey);
  7778. if (ret != MP_OKAY) {
  7779. WOLFSSL_MSG("wc_ecc_copy_point error");
  7780. wolfSSL_EC_KEY_free(newKey);
  7781. return NULL;
  7782. }
  7783. /* copy private key k */
  7784. ret = mp_copy(&srcKey->k, &key->k);
  7785. if (ret != MP_OKAY) {
  7786. WOLFSSL_MSG("mp_copy error");
  7787. wolfSSL_EC_KEY_free(newKey);
  7788. return NULL;
  7789. }
  7790. /* copy domain parameters */
  7791. if (srcKey->dp) {
  7792. ret = wc_ecc_set_curve(key, 0, srcKey->dp->id);
  7793. if (ret != 0) {
  7794. WOLFSSL_MSG("wc_ecc_set_curve error");
  7795. return NULL;
  7796. }
  7797. }
  7798. key->type = srcKey->type;
  7799. key->idx = srcKey->idx;
  7800. key->state = srcKey->state;
  7801. key->flags = srcKey->flags;
  7802. /* Copy group */
  7803. if (newKey->group == NULL) {
  7804. WOLFSSL_MSG("EC_GROUP_new_by_curve_name error");
  7805. wolfSSL_EC_KEY_free(newKey);
  7806. return NULL;
  7807. }
  7808. newKey->group->curve_idx = src->group->curve_idx;
  7809. newKey->group->curve_nid = src->group->curve_nid;
  7810. newKey->group->curve_oid = src->group->curve_oid;
  7811. /* Copy public key */
  7812. if (src->pub_key->internal == NULL || newKey->pub_key->internal == NULL) {
  7813. WOLFSSL_MSG("NULL pub_key error");
  7814. wolfSSL_EC_KEY_free(newKey);
  7815. return NULL;
  7816. }
  7817. /* Copy public key internal */
  7818. ret = wc_ecc_copy_point((ecc_point*)src->pub_key->internal,
  7819. (ecc_point*)newKey->pub_key->internal);
  7820. if (ret != MP_OKAY) {
  7821. WOLFSSL_MSG("ecc_copy_point error");
  7822. wolfSSL_EC_KEY_free(newKey);
  7823. return NULL;
  7824. }
  7825. /* Copy X, Y, Z */
  7826. newKey->pub_key->X = wolfSSL_BN_dup(src->pub_key->X);
  7827. if (!newKey->pub_key->X && src->pub_key->X) {
  7828. WOLFSSL_MSG("Error copying EC_POINT");
  7829. wolfSSL_EC_KEY_free(newKey);
  7830. return NULL;
  7831. }
  7832. newKey->pub_key->Y = wolfSSL_BN_dup(src->pub_key->Y);
  7833. if (!newKey->pub_key->Y && src->pub_key->Y) {
  7834. WOLFSSL_MSG("Error copying EC_POINT");
  7835. wolfSSL_EC_KEY_free(newKey);
  7836. return NULL;
  7837. }
  7838. newKey->pub_key->Z = wolfSSL_BN_dup(src->pub_key->Z);
  7839. if (!newKey->pub_key->Z && src->pub_key->Z) {
  7840. WOLFSSL_MSG("Error copying EC_POINT");
  7841. wolfSSL_EC_KEY_free(newKey);
  7842. return NULL;
  7843. }
  7844. newKey->pub_key->inSet = src->pub_key->inSet;
  7845. newKey->pub_key->exSet = src->pub_key->exSet;
  7846. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  7847. /* Copy private key */
  7848. if (src->priv_key->internal == NULL || newKey->priv_key->internal == NULL) {
  7849. WOLFSSL_MSG("NULL priv_key error");
  7850. wolfSSL_EC_KEY_free(newKey);
  7851. return NULL;
  7852. }
  7853. /* Free priv_key before call to newKey function */
  7854. wolfSSL_BN_free(newKey->priv_key);
  7855. newKey->priv_key = wolfSSL_BN_dup(src->priv_key);
  7856. if (newKey->priv_key == NULL) {
  7857. WOLFSSL_MSG("BN_newKey error");
  7858. wolfSSL_EC_KEY_free(newKey);
  7859. return NULL;
  7860. }
  7861. return newKey;
  7862. }
  7863. #endif /* OPENSSL_ALL */
  7864. #endif /* !NO_CERTS */
  7865. #ifdef ALT_ECC_SIZE
  7866. static int SetIndividualInternalEcc(WOLFSSL_BIGNUM* bn, mp_int* mpi)
  7867. {
  7868. WOLFSSL_MSG("Entering SetIndividualInternal");
  7869. if (bn == NULL || bn->internal == NULL) {
  7870. WOLFSSL_MSG("bn NULL error");
  7871. return -1;
  7872. }
  7873. if (mpi == NULL) {
  7874. WOLFSSL_MSG("mpi NULL error");
  7875. return -1;
  7876. }
  7877. if (mp_copy((mp_int*)bn->internal, mpi) != MP_OKAY) {
  7878. WOLFSSL_MSG("mp_copy error");
  7879. return -1;
  7880. }
  7881. return 1;
  7882. }
  7883. #endif /* ALT_ECC_SIZE */
  7884. /* EC_POINT Openssl -> WolfSSL */
  7885. static int SetECPointInternal(WOLFSSL_EC_POINT *p)
  7886. {
  7887. ecc_point* point;
  7888. WOLFSSL_ENTER("SetECPointInternal");
  7889. if (p == NULL || p->internal == NULL) {
  7890. WOLFSSL_MSG("ECPoint NULL error");
  7891. return -1;
  7892. }
  7893. point = (ecc_point*)p->internal;
  7894. #ifndef ALT_ECC_SIZE
  7895. if (p->X != NULL && SetIndividualInternal(p->X, point->x)
  7896. != 1) {
  7897. WOLFSSL_MSG("ecc point X error");
  7898. return -1;
  7899. }
  7900. if (p->Y != NULL && SetIndividualInternal(p->Y, point->y)
  7901. != 1) {
  7902. WOLFSSL_MSG("ecc point Y error");
  7903. return -1;
  7904. }
  7905. if (p->Z != NULL && SetIndividualInternal(p->Z, point->z)
  7906. != 1) {
  7907. WOLFSSL_MSG("ecc point Z error");
  7908. return -1;
  7909. }
  7910. #else
  7911. if (p->X != NULL && SetIndividualInternalEcc(p->X, point->x)
  7912. != 1) {
  7913. WOLFSSL_MSG("ecc point X error");
  7914. return -1;
  7915. }
  7916. if (p->Y != NULL && SetIndividualInternalEcc(p->Y, point->y)
  7917. != 1) {
  7918. WOLFSSL_MSG("ecc point Y error");
  7919. return -1;
  7920. }
  7921. if (p->Z != NULL && SetIndividualInternalEcc(p->Z, point->z)
  7922. != 1) {
  7923. WOLFSSL_MSG("ecc point Z error");
  7924. return -1;
  7925. }
  7926. #endif
  7927. p->inSet = 1;
  7928. return 1;
  7929. }
  7930. /* EC_POINT WolfSSL -> OpenSSL */
  7931. static int SetECPointExternal(WOLFSSL_EC_POINT *p)
  7932. {
  7933. ecc_point* point;
  7934. WOLFSSL_ENTER("SetECPointExternal");
  7935. if (p == NULL || p->internal == NULL) {
  7936. WOLFSSL_MSG("ECPoint NULL error");
  7937. return -1;
  7938. }
  7939. point = (ecc_point*)p->internal;
  7940. if (SetIndividualExternal(&p->X, point->x) != 1) {
  7941. WOLFSSL_MSG("ecc point X error");
  7942. return -1;
  7943. }
  7944. if (SetIndividualExternal(&p->Y, point->y) != 1) {
  7945. WOLFSSL_MSG("ecc point Y error");
  7946. return -1;
  7947. }
  7948. if (SetIndividualExternal(&p->Z, point->z) != 1) {
  7949. WOLFSSL_MSG("ecc point Z error");
  7950. return -1;
  7951. }
  7952. p->exSet = 1;
  7953. return 1;
  7954. }
  7955. /* EC_KEY wolfSSL -> OpenSSL */
  7956. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  7957. {
  7958. ecc_key* key;
  7959. WOLFSSL_ENTER("SetECKeyExternal");
  7960. if (eckey == NULL || eckey->internal == NULL) {
  7961. WOLFSSL_MSG("ec key NULL error");
  7962. return -1;
  7963. }
  7964. key = (ecc_key*)eckey->internal;
  7965. /* set group (OID, nid and idx) */
  7966. eckey->group->curve_oid = ecc_sets[key->idx].oidSum;
  7967. eckey->group->curve_nid = EccEnumToNID(ecc_sets[key->idx].id);
  7968. eckey->group->curve_idx = key->idx;
  7969. if (eckey->pub_key->internal != NULL) {
  7970. /* set the internal public key */
  7971. if (wc_ecc_copy_point(&key->pubkey,
  7972. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  7973. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  7974. return -1;
  7975. }
  7976. /* set the external pubkey (point) */
  7977. if (SetECPointExternal(eckey->pub_key) != 1) {
  7978. WOLFSSL_MSG("SetECKeyExternal SetECPointExternal failed");
  7979. return -1;
  7980. }
  7981. }
  7982. /* set the external privkey */
  7983. if (key->type == ECC_PRIVATEKEY) {
  7984. if (SetIndividualExternal(&eckey->priv_key, &key->k) != 1) {
  7985. WOLFSSL_MSG("ec priv key error");
  7986. return -1;
  7987. }
  7988. }
  7989. eckey->exSet = 1;
  7990. return 1;
  7991. }
  7992. /* EC_KEY Openssl -> WolfSSL */
  7993. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  7994. {
  7995. ecc_key* key;
  7996. WOLFSSL_ENTER("SetECKeyInternal");
  7997. if (eckey == NULL || eckey->internal == NULL || eckey->group == NULL) {
  7998. WOLFSSL_MSG("ec key NULL error");
  7999. return -1;
  8000. }
  8001. key = (ecc_key*)eckey->internal;
  8002. /* validate group */
  8003. if ((eckey->group->curve_idx < 0) ||
  8004. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  8005. WOLFSSL_MSG("invalid curve idx");
  8006. return -1;
  8007. }
  8008. /* set group (idx of curve and corresponding domain parameters) */
  8009. key->idx = eckey->group->curve_idx;
  8010. key->dp = &ecc_sets[key->idx];
  8011. /* set pubkey (point) */
  8012. if (eckey->pub_key != NULL) {
  8013. if (SetECPointInternal(eckey->pub_key) != 1) {
  8014. WOLFSSL_MSG("ec key pub error");
  8015. return -1;
  8016. }
  8017. /* copy over the public point to key */
  8018. if (wc_ecc_copy_point((ecc_point*)eckey->pub_key->internal,
  8019. &key->pubkey) != MP_OKAY) {
  8020. WOLFSSL_MSG("wc_ecc_copy_point error");
  8021. return -1;
  8022. }
  8023. /* public key */
  8024. key->type = ECC_PUBLICKEY;
  8025. }
  8026. /* set privkey */
  8027. if (eckey->priv_key != NULL) {
  8028. if (SetIndividualInternal(eckey->priv_key, &key->k)
  8029. != 1) {
  8030. WOLFSSL_MSG("ec key priv error");
  8031. return -1;
  8032. }
  8033. /* private key */
  8034. if (!mp_iszero(&key->k))
  8035. key->type = ECC_PRIVATEKEY;
  8036. }
  8037. eckey->inSet = 1;
  8038. return 1;
  8039. }
  8040. WOLFSSL_EC_POINT *wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  8041. {
  8042. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  8043. if (key == NULL) {
  8044. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_public_key Bad arguments");
  8045. return NULL;
  8046. }
  8047. return key->pub_key;
  8048. }
  8049. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  8050. {
  8051. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  8052. if (key == NULL) {
  8053. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_group Bad arguments");
  8054. return NULL;
  8055. }
  8056. return key->group;
  8057. }
  8058. /* return code compliant with OpenSSL :
  8059. * 1 if success, 0 if error
  8060. */
  8061. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  8062. const WOLFSSL_BIGNUM *priv_key)
  8063. {
  8064. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  8065. if (key == NULL || priv_key == NULL) {
  8066. WOLFSSL_MSG("Bad arguments");
  8067. return 0;
  8068. }
  8069. /* free key if previously set */
  8070. if (key->priv_key != NULL)
  8071. wolfSSL_BN_free(key->priv_key);
  8072. key->priv_key = wolfSSL_BN_dup(priv_key);
  8073. if (key->priv_key == NULL) {
  8074. WOLFSSL_MSG("key ecc priv key NULL");
  8075. return 0;
  8076. }
  8077. if (SetECKeyInternal(key) != 1) {
  8078. WOLFSSL_MSG("SetECKeyInternal failed");
  8079. wolfSSL_BN_free(key->priv_key);
  8080. return 0;
  8081. }
  8082. return 1;
  8083. }
  8084. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  8085. {
  8086. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  8087. if (key == NULL) {
  8088. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  8089. return NULL;
  8090. }
  8091. if (wolfSSL_BN_is_zero(key->priv_key)) {
  8092. /* return NULL if not set */
  8093. return NULL;
  8094. }
  8095. return key->priv_key;
  8096. }
  8097. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  8098. {
  8099. WOLFSSL_EC_KEY *key;
  8100. int x;
  8101. int eccEnum = NIDToEccEnum(nid);
  8102. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  8103. key = wolfSSL_EC_KEY_new();
  8104. if (key == NULL) {
  8105. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  8106. return NULL;
  8107. }
  8108. /* set the nid of the curve */
  8109. key->group->curve_nid = nid;
  8110. if (eccEnum != -1) {
  8111. /* search and set the corresponding internal curve idx */
  8112. for (x = 0; ecc_sets[x].size != 0; x++)
  8113. if (ecc_sets[x].id == eccEnum) {
  8114. key->group->curve_idx = x;
  8115. key->group->curve_oid = ecc_sets[x].oidSum;
  8116. break;
  8117. }
  8118. }
  8119. return key;
  8120. }
  8121. const char* wolfSSL_EC_curve_nid2nist(int nid)
  8122. {
  8123. const WOLF_EC_NIST_NAME* nist_name;
  8124. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  8125. if (nist_name->nid == nid) {
  8126. return nist_name->name;
  8127. }
  8128. }
  8129. return NULL;
  8130. }
  8131. /**
  8132. * return nist curve id
  8133. * @param name nist curve name
  8134. * @return nist curve id when found, 0 when not found
  8135. */
  8136. int wolfSSL_EC_curve_nist2nid(const char* name)
  8137. {
  8138. const WOLF_EC_NIST_NAME* nist_name;
  8139. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  8140. if (XSTRCMP(nist_name->name, name) == 0) {
  8141. return nist_name->nid;
  8142. }
  8143. }
  8144. return 0;
  8145. }
  8146. static void InitwolfSSL_ECKey(WOLFSSL_EC_KEY* key)
  8147. {
  8148. if (key) {
  8149. key->group = NULL;
  8150. key->pub_key = NULL;
  8151. key->priv_key = NULL;
  8152. key->internal = NULL;
  8153. key->inSet = 0;
  8154. key->exSet = 0;
  8155. key->form = POINT_CONVERSION_UNCOMPRESSED;
  8156. }
  8157. }
  8158. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  8159. {
  8160. WOLFSSL_EC_KEY *external;
  8161. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  8162. external = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  8163. DYNAMIC_TYPE_ECC);
  8164. if (external == NULL) {
  8165. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  8166. return NULL;
  8167. }
  8168. XMEMSET(external, 0, sizeof(WOLFSSL_EC_KEY));
  8169. external->heap = heap;
  8170. InitwolfSSL_ECKey(external);
  8171. external->refCount = 1;
  8172. #ifndef SINGLE_THREADED
  8173. if (wc_InitMutex(&external->refMutex) != 0) {
  8174. WOLFSSL_MSG("wc_InitMutex WOLFSSL_EC_KEY failure");
  8175. XFREE(external, heap, DYNAMIC_TYPE_ECC);
  8176. return NULL;
  8177. }
  8178. #endif
  8179. external->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  8180. DYNAMIC_TYPE_ECC);
  8181. if (external->internal == NULL) {
  8182. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  8183. goto error;
  8184. }
  8185. XMEMSET(external->internal, 0, sizeof(ecc_key));
  8186. if (wc_ecc_init_ex((ecc_key*)external->internal, heap, devId) != 0) {
  8187. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  8188. goto error;
  8189. }
  8190. /* Group unknown at creation */
  8191. external->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  8192. if (external->group == NULL) {
  8193. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  8194. goto error;
  8195. }
  8196. /* public key */
  8197. external->pub_key = wolfSSL_EC_POINT_new(external->group);
  8198. if (external->pub_key == NULL) {
  8199. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  8200. goto error;
  8201. }
  8202. /* private key */
  8203. external->priv_key = wolfSSL_BN_new();
  8204. if (external->priv_key == NULL) {
  8205. WOLFSSL_MSG("wolfSSL_BN_new failure");
  8206. goto error;
  8207. }
  8208. return external;
  8209. error:
  8210. wolfSSL_EC_KEY_free(external);
  8211. return NULL;
  8212. }
  8213. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  8214. {
  8215. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  8216. }
  8217. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  8218. {
  8219. int doFree = 0;
  8220. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  8221. if (key != NULL) {
  8222. void* heap = key->heap;
  8223. #ifndef SINGLE_THREADED
  8224. if (wc_LockMutex(&key->refMutex) != 0) {
  8225. WOLFSSL_MSG("Could not lock EC_KEY mutex");
  8226. return;
  8227. }
  8228. #endif
  8229. /* only free if all references to it are done */
  8230. key->refCount--;
  8231. if (key->refCount == 0) {
  8232. doFree = 1;
  8233. }
  8234. #ifndef SINGLE_THREADED
  8235. wc_UnLockMutex(&key->refMutex);
  8236. #endif
  8237. if (doFree == 0) {
  8238. return;
  8239. }
  8240. #ifndef SINGLE_THREADED
  8241. wc_FreeMutex(&key->refMutex);
  8242. #endif
  8243. if (key->internal != NULL) {
  8244. wc_ecc_free((ecc_key*)key->internal);
  8245. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  8246. }
  8247. wolfSSL_BN_free(key->priv_key);
  8248. wolfSSL_EC_POINT_free(key->pub_key);
  8249. wolfSSL_EC_GROUP_free(key->group);
  8250. InitwolfSSL_ECKey(key); /* set back to NULLs for safety */
  8251. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  8252. (void)heap;
  8253. /* key = NULL, don't try to access or double free it */
  8254. }
  8255. }
  8256. /* Increments ref count of WOLFSSL_EC_KEY.
  8257. * Return 1 on success, 0 on error */
  8258. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  8259. {
  8260. if (key) {
  8261. #ifndef SINGLE_THREADED
  8262. if (wc_LockMutex(&key->refMutex) != 0) {
  8263. WOLFSSL_MSG("Failed to lock EC_KEY mutex");
  8264. }
  8265. #endif
  8266. key->refCount++;
  8267. #ifndef SINGLE_THREADED
  8268. wc_UnLockMutex(&key->refMutex);
  8269. #endif
  8270. return 1;
  8271. }
  8272. return 0;
  8273. }
  8274. /* set the group in WOLFSSL_EC_KEY and return 1 on success */
  8275. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  8276. {
  8277. if (key == NULL || group == NULL)
  8278. return 0;
  8279. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  8280. if (key->group != NULL) {
  8281. /* free the current group */
  8282. wolfSSL_EC_GROUP_free(key->group);
  8283. }
  8284. key->group = wolfSSL_EC_GROUP_dup(group);
  8285. if (key->group == NULL) {
  8286. return 0;
  8287. }
  8288. return 1;
  8289. }
  8290. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  8291. {
  8292. int initTmpRng = 0;
  8293. int eccEnum;
  8294. WC_RNG* rng = NULL;
  8295. #ifdef WOLFSSL_SMALL_STACK
  8296. WC_RNG* tmpRng = NULL;
  8297. #else
  8298. WC_RNG tmpRng[1];
  8299. #endif
  8300. int ret;
  8301. ecc_key* ecKey;
  8302. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  8303. if (key == NULL || key->internal == NULL ||
  8304. key->group == NULL) {
  8305. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  8306. return 0;
  8307. }
  8308. if (key->group->curve_idx < 0) {
  8309. /* generate key using the default curve */
  8310. /* group should be set, but to retain compat use index 0 */
  8311. key->group->curve_idx = ECC_CURVE_DEF;
  8312. }
  8313. #ifdef WOLFSSL_SMALL_STACK
  8314. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  8315. if (tmpRng == NULL)
  8316. return 0;
  8317. #endif
  8318. if (wc_InitRng(tmpRng) == 0) {
  8319. rng = tmpRng;
  8320. initTmpRng = 1;
  8321. }
  8322. else {
  8323. WOLFSSL_MSG("Bad RNG Init, trying global");
  8324. rng = wolfssl_get_global_rng();
  8325. }
  8326. if (rng == NULL) {
  8327. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to set RNG");
  8328. #ifdef WOLFSSL_SMALL_STACK
  8329. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  8330. #endif
  8331. return 0;
  8332. }
  8333. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  8334. * is 0 then pass ECC_CURVE_DEF as arg */
  8335. ecKey = (ecc_key*)key->internal;
  8336. eccEnum = key->group->curve_nid ?
  8337. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  8338. ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  8339. #if defined(WOLFSSL_ASYNC_CRYPT)
  8340. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  8341. #endif
  8342. if (ret != 0) {
  8343. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  8344. #ifdef WOLFSSL_SMALL_STACK
  8345. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  8346. #endif
  8347. return 0;
  8348. }
  8349. if (initTmpRng)
  8350. wc_FreeRng(tmpRng);
  8351. #ifdef WOLFSSL_SMALL_STACK
  8352. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  8353. #endif
  8354. if (SetECKeyExternal(key) != 1) {
  8355. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  8356. return 0;
  8357. }
  8358. return 1;
  8359. }
  8360. #ifndef NO_WOLFSSL_STUB
  8361. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  8362. {
  8363. (void)key;
  8364. (void)asn1_flag;
  8365. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  8366. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  8367. }
  8368. #endif
  8369. static int setupPoint(const WOLFSSL_EC_POINT *p) {
  8370. if (!p) {
  8371. return 0;
  8372. }
  8373. if (p->inSet == 0) {
  8374. WOLFSSL_MSG("No ECPoint internal set, do it");
  8375. if (SetECPointInternal((WOLFSSL_EC_POINT *)p) != 1) {
  8376. WOLFSSL_MSG("SetECPointInternal SetECPointInternal failed");
  8377. return 0;
  8378. }
  8379. }
  8380. return 1;
  8381. }
  8382. /* return code compliant with OpenSSL :
  8383. * 1 if success, 0 if error
  8384. */
  8385. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  8386. const WOLFSSL_EC_POINT *pub)
  8387. {
  8388. ecc_point *pub_p, *key_p;
  8389. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  8390. if (key == NULL || key->internal == NULL ||
  8391. pub == NULL || pub->internal == NULL) {
  8392. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  8393. return 0;
  8394. }
  8395. if (key->inSet == 0) {
  8396. if (SetECKeyInternal(key) != 1) {
  8397. WOLFSSL_MSG("SetECKeyInternal failed");
  8398. return 0;
  8399. }
  8400. }
  8401. if (setupPoint(pub) != 1) {
  8402. return 0;
  8403. }
  8404. pub_p = (ecc_point*)pub->internal;
  8405. key_p = (ecc_point*)key->pub_key->internal;
  8406. /* create new point if required */
  8407. if (key_p == NULL)
  8408. key_p = wc_ecc_new_point();
  8409. if (key_p == NULL) {
  8410. WOLFSSL_MSG("key ecc point NULL");
  8411. return 0;
  8412. }
  8413. if (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY) {
  8414. WOLFSSL_MSG("ecc_copy_point failure");
  8415. return 0;
  8416. }
  8417. if (SetECPointExternal(key->pub_key) != 1) {
  8418. WOLFSSL_MSG("SetECKeyInternal failed");
  8419. return 0;
  8420. }
  8421. if (SetECKeyInternal(key) != 1) {
  8422. WOLFSSL_MSG("SetECKeyInternal failed");
  8423. return 0;
  8424. }
  8425. wolfSSL_EC_POINT_dump("pub", pub);
  8426. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  8427. return 1;
  8428. }
  8429. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  8430. {
  8431. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  8432. if (key == NULL || key->internal == NULL) {
  8433. WOLFSSL_MSG("Bad parameter");
  8434. return 0;
  8435. }
  8436. if (key->inSet == 0) {
  8437. if (SetECKeyInternal((WOLFSSL_EC_KEY*)key) != 1) {
  8438. WOLFSSL_MSG("SetECKeyInternal failed");
  8439. return 0;
  8440. }
  8441. }
  8442. return wc_ecc_check_key((ecc_key*)key->internal) == 0 ?
  8443. 1 : 0;
  8444. }
  8445. /* End EC_KEY */
  8446. /* Calculate and return maximum size of the ECDSA signature for the curve */
  8447. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  8448. {
  8449. const EC_GROUP *group;
  8450. int bits, bytes;
  8451. word32 headerSz = SIG_HEADER_SZ; /* 2*ASN_TAG + 2*LEN(ENUM) */
  8452. if (key == NULL) {
  8453. return 0;
  8454. }
  8455. if ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL) {
  8456. return 0;
  8457. }
  8458. if ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0) {
  8459. /* group is not set */
  8460. return 0;
  8461. }
  8462. bytes = (bits + 7) / 8; /* bytes needed to hold bits */
  8463. return headerSz +
  8464. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  8465. bytes + bytes; /* r and s */
  8466. }
  8467. int wolfSSL_ECDSA_sign(int type,
  8468. const unsigned char *digest, int digestSz,
  8469. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  8470. {
  8471. int ret = 1;
  8472. WC_RNG* rng = NULL;
  8473. #ifdef WOLFSSL_SMALL_STACK
  8474. WC_RNG* tmpRng = NULL;
  8475. #else
  8476. WC_RNG tmpRng[1];
  8477. #endif
  8478. int initTmpRng = 0;
  8479. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  8480. if (!key) {
  8481. return 0;
  8482. }
  8483. #ifdef WOLFSSL_SMALL_STACK
  8484. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  8485. if (tmpRng == NULL)
  8486. return 0;
  8487. #endif
  8488. if (wc_InitRng(tmpRng) == 0) {
  8489. rng = tmpRng;
  8490. initTmpRng = 1;
  8491. }
  8492. else {
  8493. WOLFSSL_MSG("Bad RNG Init, trying global");
  8494. rng = wolfssl_get_global_rng();
  8495. }
  8496. if (rng) {
  8497. if (wc_ecc_sign_hash(digest, digestSz, sig, sigSz, rng,
  8498. (ecc_key*)key->internal) != 0) {
  8499. ret = 0;
  8500. }
  8501. if (initTmpRng) {
  8502. wc_FreeRng(tmpRng);
  8503. }
  8504. } else {
  8505. ret = 0;
  8506. }
  8507. #ifdef WOLFSSL_SMALL_STACK
  8508. if (tmpRng)
  8509. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  8510. #endif
  8511. (void)type;
  8512. return ret;
  8513. }
  8514. int wolfSSL_ECDSA_verify(int type,
  8515. const unsigned char *digest, int digestSz,
  8516. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  8517. {
  8518. int ret = 1;
  8519. int verify = 0;
  8520. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  8521. if (key == NULL) {
  8522. return 0;
  8523. }
  8524. if (wc_ecc_verify_hash(sig, sigSz, digest, digestSz,
  8525. &verify, (ecc_key*)key->internal) != 0) {
  8526. ret = 0;
  8527. }
  8528. if (ret == 1 && verify != 1) {
  8529. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  8530. ret = 0;
  8531. }
  8532. (void)type;
  8533. return ret;
  8534. }
  8535. #ifndef HAVE_SELFTEST
  8536. /* ECC point compression types were not included in selftest ecc.h */
  8537. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8538. const WOLFSSL_EC_POINT* point, int form,
  8539. WOLFSSL_BN_CTX* ctx)
  8540. {
  8541. static const char* hexDigit = "0123456789ABCDEF";
  8542. char* hex = NULL;
  8543. int id;
  8544. int i, sz, len;
  8545. (void)ctx;
  8546. if (group == NULL || point == NULL)
  8547. return NULL;
  8548. id = wc_ecc_get_curve_id(group->curve_idx);
  8549. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0)
  8550. return NULL;
  8551. len = sz + 1;
  8552. if (form == POINT_CONVERSION_UNCOMPRESSED)
  8553. len += sz;
  8554. hex = (char*)XMALLOC(2 * len + 1, NULL, DYNAMIC_TYPE_ECC);
  8555. if (hex == NULL)
  8556. return NULL;
  8557. XMEMSET(hex, 0, 2 * len + 1);
  8558. /* Put in x-ordinate after format byte. */
  8559. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8560. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) < 0) {
  8561. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8562. return NULL;
  8563. }
  8564. if (form == POINT_CONVERSION_COMPRESSED) {
  8565. hex[0] = mp_isodd((mp_int*)point->Y->internal) ? ECC_POINT_COMP_ODD :
  8566. ECC_POINT_COMP_EVEN;
  8567. }
  8568. else {
  8569. hex[0] = ECC_POINT_UNCOMP;
  8570. /* Put in y-ordinate after x-ordinate */
  8571. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8572. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8573. (byte*)(hex + i)) < 0) {
  8574. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8575. return NULL;
  8576. }
  8577. }
  8578. for (i = len-1; i >= 0; i--) {
  8579. byte b = hex[i];
  8580. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8581. hex[i * 2 ] = hexDigit[b >> 4];
  8582. }
  8583. return hex;
  8584. }
  8585. #endif /* HAVE_SELFTEST */
  8586. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *p)
  8587. {
  8588. #if defined(DEBUG_WOLFSSL)
  8589. char *num;
  8590. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8591. if (!WOLFSSL_IS_DEBUG_ON() || wolfSSL_GetLoggingCb()) {
  8592. return;
  8593. }
  8594. if (p == NULL) {
  8595. printf("%s = NULL", msg);
  8596. return;
  8597. }
  8598. printf("%s:\n\tinSet=%d, exSet=%d\n", msg, p->inSet, p->exSet);
  8599. num = wolfSSL_BN_bn2hex(p->X);
  8600. printf("\tX = %s\n", num);
  8601. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8602. num = wolfSSL_BN_bn2hex(p->Y);
  8603. printf("\tY = %s\n", num);
  8604. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8605. num = wolfSSL_BN_bn2hex(p->Z);
  8606. printf("\tZ = %s\n", num);
  8607. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8608. #else
  8609. (void)msg;
  8610. (void)p;
  8611. #endif
  8612. }
  8613. /* Start EC_GROUP */
  8614. /* return code compliant with OpenSSL :
  8615. * 0 if equal, 1 if not and -1 in case of error
  8616. */
  8617. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8618. WOLFSSL_BN_CTX *ctx)
  8619. {
  8620. (void)ctx;
  8621. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8622. if (a == NULL || b == NULL) {
  8623. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8624. return -1;
  8625. }
  8626. /* ok */
  8627. if ((a->curve_idx == b->curve_idx) && (a->curve_nid == b->curve_nid))
  8628. return 0;
  8629. /* ko */
  8630. return 1;
  8631. }
  8632. WOLFSSL_EC_GROUP *wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8633. {
  8634. if (!src)
  8635. return NULL;
  8636. return wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8637. }
  8638. #endif /* OPENSSL_EXTRA */
  8639. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8640. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  8641. const WOLFSSL_EC_GROUP *group)
  8642. {
  8643. return group;
  8644. }
  8645. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  8646. {
  8647. if (meth) {
  8648. return NID_X9_62_prime_field;
  8649. }
  8650. return 0;
  8651. }
  8652. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8653. {
  8654. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8655. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8656. /* group = NULL, don't try to access or double free it */
  8657. }
  8658. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8659. #ifdef OPENSSL_EXTRA
  8660. #ifndef NO_WOLFSSL_STUB
  8661. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8662. {
  8663. (void)group;
  8664. (void)flag;
  8665. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8666. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8667. }
  8668. #endif
  8669. /* return code compliant with OpenSSL :
  8670. * the curve nid if success, 0 if error
  8671. */
  8672. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8673. {
  8674. int nid;
  8675. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8676. if (group == NULL) {
  8677. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8678. return 0;
  8679. }
  8680. /* If curve_nid is ECC Enum type, return corresponding OpenSSL nid */
  8681. if ((nid = EccEnumToNID(group->curve_nid)) != -1)
  8682. return nid;
  8683. return group->curve_nid;
  8684. }
  8685. /* return code compliant with OpenSSL :
  8686. * the degree of the curve if success, 0 if error
  8687. */
  8688. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8689. {
  8690. int nid;
  8691. int tmp;
  8692. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8693. if (group == NULL || group->curve_idx < 0) {
  8694. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8695. return 0;
  8696. }
  8697. /* If curve_nid passed in is an ecc_curve_id enum, convert it to the
  8698. corresponding OpenSSL NID */
  8699. tmp = EccEnumToNID(group->curve_nid);
  8700. if (tmp != -1) {
  8701. nid = tmp;
  8702. }
  8703. else {
  8704. nid = group->curve_nid;
  8705. }
  8706. switch(nid) {
  8707. case NID_secp112r1:
  8708. case NID_secp112r2:
  8709. return 112;
  8710. case NID_secp128r1:
  8711. case NID_secp128r2:
  8712. return 128;
  8713. case NID_secp160k1:
  8714. case NID_secp160r1:
  8715. case NID_secp160r2:
  8716. case NID_brainpoolP160r1:
  8717. return 160;
  8718. case NID_secp192k1:
  8719. case NID_brainpoolP192r1:
  8720. case NID_X9_62_prime192v1:
  8721. return 192;
  8722. case NID_secp224k1:
  8723. case NID_secp224r1:
  8724. case NID_brainpoolP224r1:
  8725. return 224;
  8726. case NID_secp256k1:
  8727. case NID_brainpoolP256r1:
  8728. case NID_X9_62_prime256v1:
  8729. return 256;
  8730. case NID_brainpoolP320r1:
  8731. return 320;
  8732. case NID_secp384r1:
  8733. case NID_brainpoolP384r1:
  8734. return 384;
  8735. case NID_secp521r1:
  8736. return 521;
  8737. case NID_brainpoolP512r1:
  8738. return 512;
  8739. default:
  8740. return 0;
  8741. }
  8742. }
  8743. #endif /* OPENSSL_EXTRA */
  8744. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8745. WOLFSSL_EC_GROUP *wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  8746. {
  8747. WOLFSSL_EC_GROUP *g;
  8748. int x, eccEnum;
  8749. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  8750. /* curve group */
  8751. g = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  8752. DYNAMIC_TYPE_ECC);
  8753. if (g == NULL) {
  8754. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  8755. return NULL;
  8756. }
  8757. XMEMSET(g, 0, sizeof(WOLFSSL_EC_GROUP));
  8758. /* set the nid of the curve */
  8759. g->curve_nid = nid;
  8760. g->curve_idx = -1;
  8761. /* If NID passed in is OpenSSL type, convert it to ecc_curve_id enum */
  8762. eccEnum = NIDToEccEnum(nid);
  8763. if (eccEnum != -1) {
  8764. /* search and set the corresponding internal curve idx */
  8765. for (x = 0; ecc_sets[x].size != 0; x++) {
  8766. if (ecc_sets[x].id == eccEnum) {
  8767. g->curve_idx = x;
  8768. g->curve_oid = ecc_sets[x].oidSum;
  8769. break;
  8770. }
  8771. }
  8772. }
  8773. return g;
  8774. }
  8775. /* Converts OpenSSL NID value of ECC curves to the associated enum values in
  8776. ecc_curve_id, used by ecc_sets[].*/
  8777. int NIDToEccEnum(int n)
  8778. {
  8779. WOLFSSL_ENTER("NIDToEccEnum()");
  8780. switch(n) {
  8781. case NID_X9_62_prime192v1:
  8782. return ECC_SECP192R1;
  8783. case NID_X9_62_prime192v2:
  8784. return ECC_PRIME192V2;
  8785. case NID_X9_62_prime192v3:
  8786. return ECC_PRIME192V3;
  8787. case NID_X9_62_prime239v1:
  8788. return ECC_PRIME239V1;
  8789. case NID_X9_62_prime239v2:
  8790. return ECC_PRIME239V2;
  8791. case NID_X9_62_prime239v3:
  8792. return ECC_PRIME239V3;
  8793. case NID_X9_62_prime256v1:
  8794. return ECC_SECP256R1;
  8795. case NID_secp112r1:
  8796. return ECC_SECP112R1;
  8797. case NID_secp112r2:
  8798. return ECC_SECP112R2;
  8799. case NID_secp128r1:
  8800. return ECC_SECP128R1;
  8801. case NID_secp128r2:
  8802. return ECC_SECP128R2;
  8803. case NID_secp160r1:
  8804. return ECC_SECP160R1;
  8805. case NID_secp160r2:
  8806. return ECC_SECP160R2;
  8807. case NID_secp224r1:
  8808. return ECC_SECP224R1;
  8809. case NID_secp384r1:
  8810. return ECC_SECP384R1;
  8811. case NID_secp521r1:
  8812. return ECC_SECP521R1;
  8813. case NID_secp160k1:
  8814. return ECC_SECP160K1;
  8815. case NID_secp192k1:
  8816. return ECC_SECP192K1;
  8817. case NID_secp224k1:
  8818. return ECC_SECP224K1;
  8819. case NID_secp256k1:
  8820. return ECC_SECP256K1;
  8821. case NID_brainpoolP160r1:
  8822. return ECC_BRAINPOOLP160R1;
  8823. case NID_brainpoolP192r1:
  8824. return ECC_BRAINPOOLP192R1;
  8825. case NID_brainpoolP224r1:
  8826. return ECC_BRAINPOOLP224R1;
  8827. case NID_brainpoolP256r1:
  8828. return ECC_BRAINPOOLP256R1;
  8829. case NID_brainpoolP320r1:
  8830. return ECC_BRAINPOOLP320R1;
  8831. case NID_brainpoolP384r1:
  8832. return ECC_BRAINPOOLP384R1;
  8833. case NID_brainpoolP512r1:
  8834. return ECC_BRAINPOOLP512R1;
  8835. default:
  8836. WOLFSSL_MSG("NID not found");
  8837. return -1;
  8838. }
  8839. }
  8840. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8841. {
  8842. int ret = 0;
  8843. #ifdef WOLFSSL_SMALL_STACK
  8844. mp_int *order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8845. DYNAMIC_TYPE_TMP_BUFFER);
  8846. if (order == NULL)
  8847. return 0;
  8848. #else
  8849. mp_int order[1];
  8850. #endif
  8851. if (group == NULL || group->curve_idx < 0) {
  8852. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8853. ret = -1;
  8854. }
  8855. if (ret == 0)
  8856. ret = mp_init(order);
  8857. if (ret == 0) {
  8858. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8859. MP_RADIX_HEX);
  8860. if (ret == 0)
  8861. ret = mp_count_bits(order);
  8862. mp_clear(order);
  8863. }
  8864. #ifdef WOLFSSL_SMALL_STACK
  8865. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8866. #endif
  8867. if (ret == -1)
  8868. ret = 0;
  8869. return ret;
  8870. }
  8871. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8872. #if defined(OPENSSL_EXTRA)
  8873. /* return code compliant with OpenSSL :
  8874. * 1 if success, 0 if error
  8875. */
  8876. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8877. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8878. {
  8879. (void)ctx;
  8880. if (group == NULL || order == NULL || order->internal == NULL) {
  8881. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8882. return 0;
  8883. }
  8884. if (mp_init((mp_int*)order->internal) != MP_OKAY) {
  8885. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8886. return 0;
  8887. }
  8888. if (mp_read_radix((mp_int*)order->internal,
  8889. ecc_sets[group->curve_idx].order, MP_RADIX_HEX) != MP_OKAY) {
  8890. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8891. mp_clear((mp_int*)order->internal);
  8892. return 0;
  8893. }
  8894. return 1;
  8895. }
  8896. /* End EC_GROUP */
  8897. /* Start EC_POINT */
  8898. /* return code compliant with OpenSSL :
  8899. * 1 if success, 0 if error
  8900. */
  8901. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8902. const WOLFSSL_EC_POINT *p,
  8903. unsigned char *out, unsigned int *len)
  8904. {
  8905. int err;
  8906. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8907. if (group == NULL || p == NULL || len == NULL) {
  8908. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8909. return 0;
  8910. }
  8911. if (setupPoint(p) != 1) {
  8912. return 0;
  8913. }
  8914. if (out != NULL) {
  8915. wolfSSL_EC_POINT_dump("i2d p", p);
  8916. }
  8917. err = wc_ecc_export_point_der(group->curve_idx, (ecc_point*)p->internal,
  8918. out, len);
  8919. if (err != MP_OKAY && !(out == NULL && err == LENGTH_ONLY_E)) {
  8920. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8921. return 0;
  8922. }
  8923. return 1;
  8924. }
  8925. /* return code compliant with OpenSSL :
  8926. * 1 if success, 0 if error
  8927. */
  8928. int wolfSSL_ECPoint_d2i(unsigned char *in, unsigned int len,
  8929. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *p)
  8930. {
  8931. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8932. if (group == NULL || p == NULL || p->internal == NULL || in == NULL) {
  8933. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8934. return 0;
  8935. }
  8936. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8937. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8938. (ecc_point*)p->internal, 0) != MP_OKAY) {
  8939. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8940. return 0;
  8941. }
  8942. #else
  8943. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8944. if (in[0] == 0x04) {
  8945. if (wc_ecc_import_point_der(in, len, group->curve_idx,
  8946. (ecc_point*)p->internal) != MP_OKAY) {
  8947. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8948. return 0;
  8949. }
  8950. }
  8951. else {
  8952. WOLFSSL_MSG("Only uncompressed points supported with HAVE_SELFTEST");
  8953. return 0;
  8954. }
  8955. #endif
  8956. /* Set new external point */
  8957. if (SetECPointExternal(p) != 1) {
  8958. WOLFSSL_MSG("SetECPointExternal failed");
  8959. return 0;
  8960. }
  8961. wolfSSL_EC_POINT_dump("d2i p", p);
  8962. return 1;
  8963. }
  8964. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  8965. const WOLFSSL_EC_POINT *p,
  8966. char form,
  8967. byte *buf, size_t len, WOLFSSL_BN_CTX *ctx)
  8968. {
  8969. word32 min_len = (word32)len;
  8970. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8971. int compressed = form == POINT_CONVERSION_COMPRESSED ? 1 : 0;
  8972. #endif /* !HAVE_SELFTEST */
  8973. WOLFSSL_ENTER("EC_POINT_point2oct");
  8974. if (!group || !p) {
  8975. return 0;
  8976. }
  8977. if (setupPoint(p) != 1) {
  8978. return 0;
  8979. }
  8980. if (wolfSSL_EC_POINT_is_at_infinity(group, p)) {
  8981. /* encodes to a single 0 octet */
  8982. if (buf != NULL) {
  8983. if (len < 1) {
  8984. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  8985. return 0;
  8986. }
  8987. buf[0] = 0;
  8988. }
  8989. return 1;
  8990. }
  8991. if (form != POINT_CONVERSION_UNCOMPRESSED
  8992. #ifndef HAVE_SELFTEST
  8993. && form != POINT_CONVERSION_COMPRESSED
  8994. #endif /* !HAVE_SELFTEST */
  8995. ) {
  8996. WOLFSSL_MSG("Unsupported curve form");
  8997. return 0;
  8998. }
  8999. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9000. if (wc_ecc_export_point_der_ex(group->curve_idx, (ecc_point*)p->internal,
  9001. buf, &min_len, compressed) != (buf ? MP_OKAY : LENGTH_ONLY_E)) {
  9002. return 0;
  9003. }
  9004. #else
  9005. if (wc_ecc_export_point_der(group->curve_idx, (ecc_point*)p->internal,
  9006. buf, &min_len) != (buf ? MP_OKAY : LENGTH_ONLY_E)) {
  9007. return 0;
  9008. }
  9009. #endif /* !HAVE_SELFTEST */
  9010. (void)ctx;
  9011. return (size_t)min_len;
  9012. }
  9013. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  9014. WOLFSSL_EC_POINT *p, const unsigned char *buf,
  9015. size_t len, WOLFSSL_BN_CTX *ctx)
  9016. {
  9017. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9018. if (!group || !p) {
  9019. return 0;
  9020. }
  9021. (void)ctx;
  9022. return wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group, p);
  9023. }
  9024. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **a, const unsigned char **in,
  9025. long len)
  9026. {
  9027. WOLFSSL_EC_KEY* ret;
  9028. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  9029. if (!a || !*a || !(*a)->group || !in || !*in || len <= 0) {
  9030. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  9031. return NULL;
  9032. }
  9033. ret = *a;
  9034. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in, len, NULL)
  9035. != 1) {
  9036. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  9037. return NULL;
  9038. }
  9039. *in += len;
  9040. return ret;
  9041. }
  9042. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *in, unsigned char **out)
  9043. {
  9044. size_t len;
  9045. unsigned char *tmp = NULL;
  9046. char form;
  9047. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  9048. if (!in) {
  9049. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  9050. return 0;
  9051. }
  9052. if (!in->exSet) {
  9053. if (SetECKeyExternal((WOLFSSL_EC_KEY*)in) != 1) {
  9054. WOLFSSL_MSG("SetECKeyExternal failure");
  9055. return 0;
  9056. }
  9057. }
  9058. #ifdef HAVE_COMP_KEY
  9059. /* Default to compressed form if not set */
  9060. form = in->form == POINT_CONVERSION_UNCOMPRESSED ?
  9061. POINT_CONVERSION_UNCOMPRESSED:
  9062. POINT_CONVERSION_COMPRESSED;
  9063. #else
  9064. form = POINT_CONVERSION_UNCOMPRESSED;
  9065. #endif
  9066. len = wolfSSL_EC_POINT_point2oct(in->group, in->pub_key, form,
  9067. NULL, 0, NULL);
  9068. if (len != 0 && out) {
  9069. if (!*out) {
  9070. if (!(tmp = (unsigned char*)XMALLOC(len, NULL,
  9071. DYNAMIC_TYPE_OPENSSL))) {
  9072. WOLFSSL_MSG("malloc failed");
  9073. return 0;
  9074. }
  9075. *out = tmp;
  9076. }
  9077. if (wolfSSL_EC_POINT_point2oct(in->group, in->pub_key, form, *out,
  9078. len, NULL) == 0) {
  9079. if (tmp) {
  9080. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  9081. *out = NULL;
  9082. }
  9083. return 0;
  9084. }
  9085. if (!tmp) {
  9086. /* Move buffer forward if it was not alloced in this function */
  9087. *out += len;
  9088. }
  9089. }
  9090. return (int)len;
  9091. }
  9092. #ifdef HAVE_ECC_KEY_IMPORT
  9093. WOLFSSL_EC_KEY *wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY **key, const unsigned char **in,
  9094. long len)
  9095. {
  9096. word32 idx = 0;
  9097. WOLFSSL_EC_KEY *eckey = NULL;
  9098. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  9099. if (!in || !*in || len <= 0) {
  9100. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  9101. return NULL;
  9102. }
  9103. if (!(eckey = wolfSSL_EC_KEY_new())) {
  9104. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  9105. return NULL;
  9106. }
  9107. if (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)eckey->internal,
  9108. (word32)len) != 0) {
  9109. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  9110. goto error;
  9111. }
  9112. eckey->inSet = 1;
  9113. if (SetECKeyExternal(eckey) != 1) {
  9114. WOLFSSL_MSG("SetECKeyExternal error");
  9115. goto error;
  9116. }
  9117. if (key) {
  9118. *key = eckey;
  9119. }
  9120. return eckey;
  9121. error:
  9122. wolfSSL_EC_KEY_free(eckey);
  9123. return NULL;
  9124. }
  9125. #endif /* HAVE_ECC_KEY_IMPORT */
  9126. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *in, unsigned char **out)
  9127. {
  9128. word32 len;
  9129. byte* buf = NULL;
  9130. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  9131. if (!in) {
  9132. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  9133. return 0;
  9134. }
  9135. if (!in->inSet && SetECKeyInternal(
  9136. (WOLFSSL_EC_KEY*)in) != 1) {
  9137. WOLFSSL_MSG("SetECKeyInternal error");
  9138. return 0;
  9139. }
  9140. if ((len = wc_EccKeyDerSize((ecc_key*)in->internal, 0)) <= 0) {
  9141. WOLFSSL_MSG("wc_EccKeyDerSize error");
  9142. return 0;
  9143. }
  9144. if (out) {
  9145. if (!(buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER))) {
  9146. WOLFSSL_MSG("tmp buffer malloc error");
  9147. return 0;
  9148. }
  9149. if (wc_EccPrivateKeyToDer((ecc_key*)in->internal, buf, len) < 0) {
  9150. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  9151. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9152. return 0;
  9153. }
  9154. if (*out) {
  9155. XMEMCPY(*out, buf, len);
  9156. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9157. }
  9158. else {
  9159. *out = buf;
  9160. }
  9161. }
  9162. return (int)len;
  9163. }
  9164. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *eckey, char form)
  9165. {
  9166. if (eckey && (form == POINT_CONVERSION_UNCOMPRESSED
  9167. #ifdef HAVE_COMP_KEY
  9168. || form == POINT_CONVERSION_COMPRESSED
  9169. #endif
  9170. )) {
  9171. eckey->form = form;
  9172. } else {
  9173. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  9174. }
  9175. }
  9176. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  9177. {
  9178. if (key != NULL) {
  9179. return key->form;
  9180. }
  9181. return -1;
  9182. }
  9183. /* wolfSSL_EC_POINT_point2bn should return "in" if not null */
  9184. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP *group,
  9185. const WOLFSSL_EC_POINT *p, char form, WOLFSSL_BIGNUM *in,
  9186. WOLFSSL_BN_CTX *ctx)
  9187. {
  9188. size_t len;
  9189. byte *buf;
  9190. WOLFSSL_BIGNUM *ret = NULL;
  9191. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9192. if (!group || !p) {
  9193. return NULL;
  9194. }
  9195. if ((len = wolfSSL_EC_POINT_point2oct(group, p, form,
  9196. NULL, 0, ctx)) == 0) {
  9197. return NULL;
  9198. }
  9199. if (!(buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER))) {
  9200. WOLFSSL_MSG("malloc failed");
  9201. return NULL;
  9202. }
  9203. if (wolfSSL_EC_POINT_point2oct(group, p, form,
  9204. buf, len, ctx) == len) {
  9205. ret = wolfSSL_BN_bin2bn(buf, (int)len, in);
  9206. }
  9207. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9208. return ret;
  9209. }
  9210. #if defined(USE_ECC_B_PARAM) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9211. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9212. const WOLFSSL_EC_POINT *point,
  9213. WOLFSSL_BN_CTX *ctx)
  9214. {
  9215. (void)ctx;
  9216. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9217. if (!group || !point) {
  9218. WOLFSSL_MSG("Invalid arguments");
  9219. return 0;
  9220. }
  9221. if (!point->inSet && SetECPointInternal((WOLFSSL_EC_POINT*)point)) {
  9222. WOLFSSL_MSG("SetECPointInternal error");
  9223. return 0;
  9224. }
  9225. return wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9226. group->curve_idx)
  9227. == MP_OKAY ? 1 : 0;
  9228. }
  9229. #endif /* USE_ECC_B_PARAM && !(FIPS_VERSION <= 2) */
  9230. WOLFSSL_EC_POINT *wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP *group)
  9231. {
  9232. WOLFSSL_EC_POINT *p;
  9233. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  9234. if (group == NULL) {
  9235. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  9236. return NULL;
  9237. }
  9238. p = (WOLFSSL_EC_POINT *)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  9239. DYNAMIC_TYPE_ECC);
  9240. if (p == NULL) {
  9241. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  9242. return NULL;
  9243. }
  9244. XMEMSET(p, 0, sizeof(WOLFSSL_EC_POINT));
  9245. p->internal = wc_ecc_new_point();
  9246. if (p->internal == NULL) {
  9247. WOLFSSL_MSG("ecc_new_point failure");
  9248. XFREE(p, NULL, DYNAMIC_TYPE_ECC);
  9249. return NULL;
  9250. }
  9251. return p;
  9252. }
  9253. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9254. /* return code compliant with OpenSSL :
  9255. * 1 if success, 0 if error
  9256. */
  9257. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP *group,
  9258. const WOLFSSL_EC_POINT *point,
  9259. WOLFSSL_BIGNUM *x,
  9260. WOLFSSL_BIGNUM *y,
  9261. WOLFSSL_BN_CTX *ctx)
  9262. {
  9263. mp_digit mp;
  9264. #ifdef WOLFSSL_SMALL_STACK
  9265. mp_int* modulus = NULL;
  9266. #else
  9267. mp_int modulus[1];
  9268. #endif
  9269. (void)ctx;
  9270. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9271. if (group == NULL || point == NULL || point->internal == NULL ||
  9272. x == NULL || y == NULL ||
  9273. wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9274. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9275. return 0;
  9276. }
  9277. if (setupPoint(point) != 1) {
  9278. return 0;
  9279. }
  9280. #ifdef WOLFSSL_SMALL_STACK
  9281. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9282. if (modulus == NULL) {
  9283. return 0;
  9284. }
  9285. #endif
  9286. if (!wolfSSL_BN_is_one(point->Z)) {
  9287. if (mp_init(modulus) != MP_OKAY) {
  9288. WOLFSSL_MSG("mp_init failed");
  9289. #ifdef WOLFSSL_SMALL_STACK
  9290. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9291. #endif
  9292. return 0;
  9293. }
  9294. /* Map the Jacobian point back to affine space */
  9295. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9296. MP_RADIX_HEX) != MP_OKAY) {
  9297. WOLFSSL_MSG("mp_read_radix failed");
  9298. mp_clear(modulus);
  9299. #ifdef WOLFSSL_SMALL_STACK
  9300. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9301. #endif
  9302. return 0;
  9303. }
  9304. if (mp_montgomery_setup(modulus, &mp) != MP_OKAY) {
  9305. WOLFSSL_MSG("mp_montgomery_setup failed");
  9306. mp_clear(modulus);
  9307. #ifdef WOLFSSL_SMALL_STACK
  9308. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9309. #endif
  9310. return 0;
  9311. }
  9312. if (ecc_map((ecc_point*)point->internal, modulus, mp) != MP_OKAY) {
  9313. WOLFSSL_MSG("ecc_map failed");
  9314. mp_clear(modulus);
  9315. #ifdef WOLFSSL_SMALL_STACK
  9316. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9317. #endif
  9318. return 0;
  9319. }
  9320. if (SetECPointExternal((WOLFSSL_EC_POINT *)point) != 1) {
  9321. WOLFSSL_MSG("SetECPointExternal failed");
  9322. mp_clear(modulus);
  9323. #ifdef WOLFSSL_SMALL_STACK
  9324. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9325. #endif
  9326. return 0;
  9327. }
  9328. mp_clear(modulus);
  9329. }
  9330. BN_copy(x, point->X);
  9331. BN_copy(y, point->Y);
  9332. #ifdef WOLFSSL_SMALL_STACK
  9333. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9334. #endif
  9335. return 1;
  9336. }
  9337. #endif
  9338. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP *group,
  9339. WOLFSSL_EC_POINT *point,
  9340. const WOLFSSL_BIGNUM *x,
  9341. const WOLFSSL_BIGNUM *y,
  9342. WOLFSSL_BN_CTX *ctx)
  9343. {
  9344. (void)ctx;
  9345. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9346. if (group == NULL || point == NULL || point->internal == NULL ||
  9347. x == NULL || y == NULL) {
  9348. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9349. return 0;
  9350. }
  9351. if (!point->X) {
  9352. point->X = wolfSSL_BN_new();
  9353. }
  9354. if (!point->Y) {
  9355. point->Y = wolfSSL_BN_new();
  9356. }
  9357. if (!point->Z) {
  9358. point->Z = wolfSSL_BN_new();
  9359. }
  9360. if (!point->X || !point->Y || !point->Z) {
  9361. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9362. return 0;
  9363. }
  9364. BN_copy(point->X, x);
  9365. BN_copy(point->Y, y);
  9366. BN_copy(point->Z, wolfSSL_BN_value_one());
  9367. if (SetECPointInternal((WOLFSSL_EC_POINT *)point) != 1) {
  9368. WOLFSSL_MSG("SetECPointInternal failed");
  9369. return 0;
  9370. }
  9371. return 1;
  9372. }
  9373. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9374. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9375. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9376. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9377. const WOLFSSL_EC_POINT *p1,
  9378. const WOLFSSL_EC_POINT *p2, WOLFSSL_BN_CTX *ctx)
  9379. {
  9380. #ifdef WOLFSSL_SMALL_STACK
  9381. mp_int* a = NULL;
  9382. mp_int* prime = NULL;
  9383. mp_int* mu = NULL;
  9384. #else
  9385. mp_int a[1];
  9386. mp_int prime[1];
  9387. mp_int mu[1];
  9388. #endif
  9389. mp_digit mp = 0;
  9390. ecc_point* montP1 = NULL;
  9391. ecc_point* montP2 = NULL;
  9392. ecc_point* eccP1;
  9393. ecc_point* eccP2;
  9394. int ret = 0;
  9395. (void)ctx;
  9396. if (!group || !r || !p1 || !p2) {
  9397. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9398. return 0;
  9399. }
  9400. if (setupPoint(r) != 1 ||
  9401. setupPoint(p1) != 1 ||
  9402. setupPoint(p2) != 1) {
  9403. WOLFSSL_MSG("setupPoint error");
  9404. return 0;
  9405. }
  9406. #ifdef WOLFSSL_SMALL_STACK
  9407. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9408. if (a == NULL) {
  9409. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9410. return 0;
  9411. }
  9412. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9413. if (prime == NULL) {
  9414. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9415. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9416. return 0;
  9417. }
  9418. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9419. if (mu == NULL) {
  9420. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9421. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9422. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9423. return 0;
  9424. }
  9425. XMEMSET(a, 0, sizeof(mp_int));
  9426. XMEMSET(prime, 0, sizeof(mp_int));
  9427. XMEMSET(mu, 0, sizeof(mp_int));
  9428. #endif
  9429. /* read the curve prime and a */
  9430. if (mp_init_multi(prime, a, mu, NULL, NULL, NULL) != MP_OKAY) {
  9431. WOLFSSL_MSG("mp_init_multi error");
  9432. goto cleanup;
  9433. }
  9434. if (mp_read_radix(a, ecc_sets[group->curve_idx].Af, MP_RADIX_HEX)
  9435. != MP_OKAY) {
  9436. WOLFSSL_MSG("mp_read_radix a error");
  9437. goto cleanup;
  9438. }
  9439. if (mp_read_radix(prime, ecc_sets[group->curve_idx].prime, MP_RADIX_HEX)
  9440. != MP_OKAY) {
  9441. WOLFSSL_MSG("mp_read_radix prime error");
  9442. goto cleanup;
  9443. }
  9444. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9445. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9446. goto cleanup;
  9447. }
  9448. eccP1 = (ecc_point*)p1->internal;
  9449. eccP2 = (ecc_point*)p2->internal;
  9450. if (!(montP1 = wc_ecc_new_point_h(NULL)) ||
  9451. !(montP2 = wc_ecc_new_point_h(NULL))) {
  9452. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9453. goto cleanup;
  9454. }
  9455. if ((mp_montgomery_calc_normalization(mu, prime)) != MP_OKAY) {
  9456. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9457. goto cleanup;
  9458. }
  9459. /* Convert to Montgomery form */
  9460. if (mp_cmp_d(mu, 1) == MP_EQ) {
  9461. if (wc_ecc_copy_point(eccP1, montP1) != MP_OKAY ||
  9462. wc_ecc_copy_point(eccP2, montP2) != MP_OKAY) {
  9463. WOLFSSL_MSG("wc_ecc_copy_point error");
  9464. goto cleanup;
  9465. }
  9466. } else {
  9467. if (mp_mulmod(eccP1->x, mu, prime, montP1->x) != MP_OKAY ||
  9468. mp_mulmod(eccP1->y, mu, prime, montP1->y) != MP_OKAY ||
  9469. mp_mulmod(eccP1->z, mu, prime, montP1->z) != MP_OKAY) {
  9470. WOLFSSL_MSG("mp_mulmod error");
  9471. goto cleanup;
  9472. }
  9473. if (mp_mulmod(eccP2->x, mu, prime, montP2->x) != MP_OKAY ||
  9474. mp_mulmod(eccP2->y, mu, prime, montP2->y) != MP_OKAY ||
  9475. mp_mulmod(eccP2->z, mu, prime, montP2->z) != MP_OKAY) {
  9476. WOLFSSL_MSG("mp_mulmod error");
  9477. goto cleanup;
  9478. }
  9479. }
  9480. if (ecc_projective_add_point(montP1, montP2, (ecc_point*)r->internal,
  9481. a, prime, mp) != MP_OKAY) {
  9482. WOLFSSL_MSG("ecc_projective_add_point error");
  9483. goto cleanup;
  9484. }
  9485. if (ecc_map((ecc_point*)r->internal, prime, mp) != MP_OKAY) {
  9486. WOLFSSL_MSG("ecc_map error");
  9487. goto cleanup;
  9488. }
  9489. ret = 1;
  9490. cleanup:
  9491. mp_clear(a);
  9492. mp_clear(prime);
  9493. mp_clear(mu);
  9494. wc_ecc_del_point_h(montP1, NULL);
  9495. wc_ecc_del_point_h(montP2, NULL);
  9496. #ifdef WOLFSSL_SMALL_STACK
  9497. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9498. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9499. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9500. #endif
  9501. return ret;
  9502. }
  9503. /* Calculate the value: generator * n + q * m
  9504. * return code compliant with OpenSSL :
  9505. * 1 if success, 0 if error
  9506. */
  9507. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9508. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q,
  9509. const WOLFSSL_BIGNUM *m, WOLFSSL_BN_CTX *ctx)
  9510. {
  9511. #ifdef WOLFSSL_SMALL_STACK
  9512. mp_int* a = NULL;
  9513. mp_int* prime = NULL;
  9514. #else
  9515. mp_int a[1], prime[1];
  9516. #endif
  9517. int ret = 0;
  9518. ecc_point* result = NULL;
  9519. ecc_point* tmp = NULL;
  9520. (void)ctx;
  9521. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9522. if (!group || !r) {
  9523. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9524. return 0;
  9525. }
  9526. #ifdef WOLFSSL_SMALL_STACK
  9527. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9528. if (a == NULL) {
  9529. return 0;
  9530. }
  9531. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9532. if (prime == NULL) {
  9533. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9534. return 0;
  9535. }
  9536. #endif
  9537. if (!(result = wc_ecc_new_point())) {
  9538. WOLFSSL_MSG("wolfSSL_EC_POINT_new error");
  9539. return 0;
  9540. }
  9541. /* read the curve prime and a */
  9542. if (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) != MP_OKAY) {
  9543. WOLFSSL_MSG("mp_init_multi error");
  9544. goto cleanup;
  9545. }
  9546. if (q && setupPoint(q) != 1) {
  9547. WOLFSSL_MSG("setupPoint error");
  9548. goto cleanup;
  9549. }
  9550. if (mp_read_radix(prime, ecc_sets[group->curve_idx].prime, MP_RADIX_HEX)
  9551. != MP_OKAY) {
  9552. WOLFSSL_MSG("mp_read_radix prime error");
  9553. goto cleanup;
  9554. }
  9555. if (mp_read_radix(a, ecc_sets[group->curve_idx].Af, MP_RADIX_HEX)
  9556. != MP_OKAY) {
  9557. WOLFSSL_MSG("mp_read_radix a error");
  9558. goto cleanup;
  9559. }
  9560. if (n) {
  9561. /* load generator */
  9562. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9563. if (wc_ecc_get_generator(result, group->curve_idx)
  9564. != MP_OKAY) {
  9565. WOLFSSL_MSG("wc_ecc_get_generator error");
  9566. goto cleanup;
  9567. }
  9568. #else
  9569. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9570. if (mp_read_radix(result->x, ecc_sets[group->curve_idx].Gx,
  9571. MP_RADIX_HEX) != MP_OKAY) {
  9572. WOLFSSL_MSG("mp_read_radix Gx error");
  9573. goto cleanup;
  9574. }
  9575. if (mp_read_radix(result->y, ecc_sets[group->curve_idx].Gy,
  9576. MP_RADIX_HEX) != MP_OKAY) {
  9577. WOLFSSL_MSG("mp_read_radix Gy error");
  9578. goto cleanup;
  9579. }
  9580. if (mp_set(result->z, 1) != MP_OKAY) {
  9581. WOLFSSL_MSG("mp_set Gz error");
  9582. goto cleanup;
  9583. }
  9584. #endif /* NOPT_FIPS_VERSION == 2 */
  9585. }
  9586. if (n && q && m) {
  9587. /* r = generator * n + q * m */
  9588. #ifdef ECC_SHAMIR
  9589. if (ecc_mul2add(result, (mp_int*)n->internal,
  9590. (ecc_point*)q->internal, (mp_int*)m->internal,
  9591. result, a, prime, NULL)
  9592. != MP_OKAY) {
  9593. WOLFSSL_MSG("ecc_mul2add error");
  9594. goto cleanup;
  9595. }
  9596. #else
  9597. mp_digit mp = 0;
  9598. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9599. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9600. goto cleanup;
  9601. }
  9602. if (!(tmp = wc_ecc_new_point())) {
  9603. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9604. goto cleanup;
  9605. }
  9606. /* r = generator * n */
  9607. if (wc_ecc_mulmod((mp_int*)n->internal, result, result, a, prime, 0)
  9608. != MP_OKAY) {
  9609. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9610. goto cleanup;
  9611. }
  9612. /* tmp = q * m */
  9613. if (wc_ecc_mulmod((mp_int*)m->internal, (ecc_point*)q->internal,
  9614. tmp, a, prime, 0) != MP_OKAY) {
  9615. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9616. goto cleanup;
  9617. }
  9618. /* result = result + tmp */
  9619. if (ecc_projective_add_point(tmp, result, result, a, prime, mp)
  9620. != MP_OKAY) {
  9621. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9622. goto cleanup;
  9623. }
  9624. if (ecc_map(result, prime, mp) != MP_OKAY) {
  9625. WOLFSSL_MSG("ecc_map nqm error");
  9626. goto cleanup;
  9627. }
  9628. #endif
  9629. }
  9630. else if (n) {
  9631. /* r = generator * n */
  9632. if (wc_ecc_mulmod((mp_int*)n->internal, result, result, a, prime, 1)
  9633. != MP_OKAY) {
  9634. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9635. goto cleanup;
  9636. }
  9637. }
  9638. else if (q && m) {
  9639. /* r = q * m */
  9640. if (wc_ecc_mulmod((mp_int*)m->internal, (ecc_point*)q->internal,
  9641. result, a, prime, 1) != MP_OKAY) {
  9642. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9643. goto cleanup;
  9644. }
  9645. }
  9646. /* copy to destination */
  9647. if (wc_ecc_copy_point(result, (ecc_point*)r->internal)) {
  9648. WOLFSSL_MSG("wc_ecc_copy_point error");
  9649. goto cleanup;
  9650. }
  9651. r->inSet = 1;
  9652. if (SetECPointExternal(r) != 1) {
  9653. WOLFSSL_MSG("SetECPointExternal error");
  9654. goto cleanup;
  9655. }
  9656. ret = 1;
  9657. cleanup:
  9658. mp_clear(a);
  9659. mp_clear(prime);
  9660. wc_ecc_del_point(result);
  9661. wc_ecc_del_point(tmp);
  9662. #ifdef WOLFSSL_SMALL_STACK
  9663. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9664. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9665. #endif
  9666. return ret;
  9667. }
  9668. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9669. * !WOLFSSL_SP_MATH */
  9670. /* (x, y) -> (x, -y) */
  9671. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *a,
  9672. WOLFSSL_BN_CTX *ctx)
  9673. {
  9674. ecc_point* p;
  9675. #ifdef WOLFSSL_SMALL_STACK
  9676. mp_int* prime = NULL;
  9677. #else
  9678. mp_int prime[1];
  9679. #endif
  9680. (void)ctx;
  9681. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9682. if (!group || !a || !a->internal || setupPoint(a) != 1) {
  9683. return 0;
  9684. }
  9685. p = (ecc_point*)a->internal;
  9686. #ifdef WOLFSSL_SMALL_STACK
  9687. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9688. if (prime == NULL) {
  9689. return 0;
  9690. }
  9691. #endif
  9692. /* read the curve prime and a */
  9693. if (mp_init_multi(prime, NULL, NULL, NULL, NULL, NULL) != MP_OKAY) {
  9694. WOLFSSL_MSG("mp_init_multi error");
  9695. #ifdef WOLFSSL_SMALL_STACK
  9696. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9697. #endif
  9698. return 0;
  9699. }
  9700. if (mp_sub(prime, p->y, p->y) != MP_OKAY) {
  9701. WOLFSSL_MSG("mp_sub error");
  9702. #ifdef WOLFSSL_SMALL_STACK
  9703. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9704. #endif
  9705. return 0;
  9706. }
  9707. if (SetECPointExternal(a) != 1) {
  9708. WOLFSSL_MSG("SetECPointExternal error");
  9709. #ifdef WOLFSSL_SMALL_STACK
  9710. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9711. #endif
  9712. return 0;
  9713. }
  9714. #ifdef WOLFSSL_SMALL_STACK
  9715. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9716. #endif
  9717. return 1;
  9718. }
  9719. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *p)
  9720. {
  9721. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  9722. wolfSSL_EC_POINT_free(p);
  9723. }
  9724. /* return code compliant with OpenSSL :
  9725. * 0 if equal, 1 if not and -1 in case of error
  9726. */
  9727. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  9728. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b,
  9729. WOLFSSL_BN_CTX *ctx)
  9730. {
  9731. int ret;
  9732. (void)ctx;
  9733. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  9734. if (group == NULL || a == NULL || a->internal == NULL || b == NULL ||
  9735. b->internal == NULL) {
  9736. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  9737. return -1;
  9738. }
  9739. ret = wc_ecc_cmp_point((ecc_point*)a->internal, (ecc_point*)b->internal);
  9740. if (ret == MP_EQ)
  9741. return 0;
  9742. else if (ret == MP_LT || ret == MP_GT)
  9743. return 1;
  9744. return -1;
  9745. }
  9746. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  9747. {
  9748. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  9749. if (!dest || !src) {
  9750. return 0;
  9751. }
  9752. if (setupPoint(src) != 1) {
  9753. return 0;
  9754. }
  9755. if (wc_ecc_copy_point((ecc_point*) dest->internal,
  9756. (ecc_point*) src->internal) != MP_OKAY) {
  9757. return 0;
  9758. }
  9759. dest->inSet = 1;
  9760. if (SetECPointExternal(dest) != 1) {
  9761. return 0;
  9762. }
  9763. return 1;
  9764. }
  9765. #endif /* OPENSSL_EXTRA */
  9766. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  9767. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *p)
  9768. {
  9769. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  9770. if (p != NULL) {
  9771. if (p->internal != NULL) {
  9772. wc_ecc_del_point((ecc_point*)p->internal);
  9773. p->internal = NULL;
  9774. }
  9775. wolfSSL_BN_free(p->X);
  9776. wolfSSL_BN_free(p->Y);
  9777. wolfSSL_BN_free(p->Z);
  9778. p->X = NULL;
  9779. p->Y = NULL;
  9780. p->Z = NULL;
  9781. p->inSet = p->exSet = 0;
  9782. XFREE(p, NULL, DYNAMIC_TYPE_ECC);
  9783. /* p = NULL, don't try to access or double free it */
  9784. }
  9785. }
  9786. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  9787. #ifdef OPENSSL_EXTRA
  9788. /* return code compliant with OpenSSL :
  9789. * 1 if point at infinity, 0 else
  9790. */
  9791. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  9792. const WOLFSSL_EC_POINT *point)
  9793. {
  9794. int ret;
  9795. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  9796. if (group == NULL || point == NULL || point->internal == NULL) {
  9797. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  9798. return 0;
  9799. }
  9800. if (setupPoint(point) != 1) {
  9801. return 0;
  9802. }
  9803. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  9804. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  9805. if (ret < 0) {
  9806. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  9807. return 0;
  9808. }
  9809. #else
  9810. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  9811. return 0;
  9812. #endif
  9813. return ret;
  9814. }
  9815. /* End EC_POINT */
  9816. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9817. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *r, size_t nitems)
  9818. {
  9819. size_t i, min_nitems;
  9820. #ifdef HAVE_SELFTEST
  9821. size_t ecc_sets_count;
  9822. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++);
  9823. ecc_sets_count = i;
  9824. #endif
  9825. if (r == NULL || nitems == 0)
  9826. return ecc_sets_count;
  9827. min_nitems = nitems < ecc_sets_count ? nitems : ecc_sets_count;
  9828. for (i = 0; i < min_nitems; i++) {
  9829. r[i].nid = EccEnumToNID(ecc_sets[i].id);
  9830. r[i].comment = wolfSSL_OBJ_nid2sn(r[i].nid);
  9831. }
  9832. return min_nitems;
  9833. }
  9834. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  9835. /* Start ECDSA_SIG */
  9836. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  9837. {
  9838. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  9839. if (sig) {
  9840. wolfSSL_BN_free(sig->r);
  9841. wolfSSL_BN_free(sig->s);
  9842. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  9843. }
  9844. }
  9845. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  9846. {
  9847. WOLFSSL_ECDSA_SIG *sig;
  9848. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  9849. sig = (WOLFSSL_ECDSA_SIG*) XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  9850. DYNAMIC_TYPE_ECC);
  9851. if (sig == NULL) {
  9852. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  9853. return NULL;
  9854. }
  9855. sig->s = NULL;
  9856. sig->r = wolfSSL_BN_new();
  9857. if (sig->r == NULL) {
  9858. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  9859. wolfSSL_ECDSA_SIG_free(sig);
  9860. return NULL;
  9861. }
  9862. sig->s = wolfSSL_BN_new();
  9863. if (sig->s == NULL) {
  9864. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  9865. wolfSSL_ECDSA_SIG_free(sig);
  9866. return NULL;
  9867. }
  9868. return sig;
  9869. }
  9870. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  9871. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  9872. {
  9873. if (sig == NULL) {
  9874. return;
  9875. }
  9876. if (r != NULL) {
  9877. *r = sig->r;
  9878. }
  9879. if (s != NULL) {
  9880. *s = sig->s;
  9881. }
  9882. }
  9883. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  9884. WOLFSSL_BIGNUM* s)
  9885. {
  9886. if (sig == NULL || r == NULL || s == NULL) {
  9887. return 0;
  9888. }
  9889. wolfSSL_BN_free(sig->r);
  9890. wolfSSL_BN_free(sig->s);
  9891. sig->r = r;
  9892. sig->s = s;
  9893. return 1;
  9894. }
  9895. /* return signature structure on success, NULL otherwise */
  9896. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *d, int dlen,
  9897. WOLFSSL_EC_KEY *key)
  9898. {
  9899. WOLFSSL_ECDSA_SIG *sig = NULL;
  9900. int initTmpRng = 0;
  9901. WC_RNG* rng = NULL;
  9902. #ifdef WOLFSSL_SMALL_STACK
  9903. WC_RNG* tmpRng = NULL;
  9904. byte* out = NULL;
  9905. mp_int* sig_r = NULL;
  9906. mp_int* sig_s = NULL;
  9907. #else
  9908. WC_RNG tmpRng[1];
  9909. byte out[ECC_BUFSIZE];
  9910. mp_int sig_r[1], sig_s[1];
  9911. #endif
  9912. word32 outlen = ECC_BUFSIZE;
  9913. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  9914. if (d == NULL || key == NULL || key->internal == NULL) {
  9915. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  9916. return NULL;
  9917. }
  9918. /* set internal key if not done */
  9919. if (key->inSet == 0)
  9920. {
  9921. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  9922. if (SetECKeyInternal(key) != 1) {
  9923. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  9924. return NULL;
  9925. }
  9926. }
  9927. #ifdef WOLFSSL_SMALL_STACK
  9928. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  9929. if (tmpRng == NULL)
  9930. return NULL;
  9931. out = (byte*)XMALLOC(outlen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9932. if (out == NULL) {
  9933. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  9934. return NULL;
  9935. }
  9936. sig_r = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9937. if (sig_r == NULL) {
  9938. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9939. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  9940. return NULL;
  9941. }
  9942. sig_s = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9943. if (sig_s == NULL) {
  9944. XFREE(sig_r, NULL, DYNAMIC_TYPE_BIGINT);
  9945. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9946. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  9947. return NULL;
  9948. }
  9949. #endif
  9950. if (wc_InitRng(tmpRng) == 0) {
  9951. rng = tmpRng;
  9952. initTmpRng = 1;
  9953. }
  9954. else {
  9955. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad RNG Init, trying global");
  9956. rng = wolfssl_get_global_rng();
  9957. }
  9958. if (rng) {
  9959. /* use wc_ecc_sign_hash because it supports crypto callbacks */
  9960. if (wc_ecc_sign_hash(d, dlen, out, &outlen, rng,
  9961. (ecc_key*)key->internal) == 0) {
  9962. if (mp_init_multi(sig_r, sig_s, NULL, NULL, NULL, NULL) == MP_OKAY) {
  9963. /* put signature blob in ECDSA structure */
  9964. if (DecodeECC_DSA_Sig(out, outlen, sig_r, sig_s) == 0) {
  9965. sig = wolfSSL_ECDSA_SIG_new();
  9966. if (sig == NULL) {
  9967. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new failed");
  9968. }
  9969. else if (SetIndividualExternal(&sig->r, sig_r)
  9970. != 1) {
  9971. WOLFSSL_MSG("ecdsa r key error");
  9972. wolfSSL_ECDSA_SIG_free(sig);
  9973. sig = NULL;
  9974. }
  9975. else if (SetIndividualExternal(&sig->s, sig_s)
  9976. != 1) {
  9977. WOLFSSL_MSG("ecdsa s key error");
  9978. wolfSSL_ECDSA_SIG_free(sig);
  9979. sig = NULL;
  9980. }
  9981. }
  9982. mp_free(sig_r);
  9983. mp_free(sig_s);
  9984. }
  9985. }
  9986. else {
  9987. WOLFSSL_MSG("wc_ecc_sign_hash failed");
  9988. }
  9989. }
  9990. if (initTmpRng)
  9991. wc_FreeRng(tmpRng);
  9992. #ifdef WOLFSSL_SMALL_STACK
  9993. XFREE(sig_s, NULL, DYNAMIC_TYPE_BIGINT);
  9994. XFREE(sig_r, NULL, DYNAMIC_TYPE_BIGINT);
  9995. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9996. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  9997. #endif
  9998. return sig;
  9999. }
  10000. /* return code compliant with OpenSSL :
  10001. * 1 for a valid signature, 0 for an invalid signature and -1 on error
  10002. */
  10003. int wolfSSL_ECDSA_do_verify(const unsigned char *d, int dlen,
  10004. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  10005. {
  10006. int check_sign = 0;
  10007. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  10008. byte signature[ECC_MAX_SIG_SIZE];
  10009. word32 signaturelen = (word32)sizeof(signature);
  10010. char* r;
  10011. char* s;
  10012. int ret = 0;
  10013. #endif
  10014. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  10015. if (d == NULL || sig == NULL || key == NULL || key->internal == NULL) {
  10016. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  10017. return -1;
  10018. }
  10019. /* set internal key if not done */
  10020. if (key->inSet == 0)
  10021. {
  10022. WOLFSSL_MSG("No EC key internal set, do it");
  10023. if (SetECKeyInternal(key) != 1) {
  10024. WOLFSSL_MSG("SetECKeyInternal failed");
  10025. return -1;
  10026. }
  10027. }
  10028. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10029. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  10030. (mp_int*)sig->s->internal, d, dlen, &check_sign,
  10031. (ecc_key *)key->internal) != MP_OKAY) {
  10032. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  10033. return -1;
  10034. }
  10035. else if (check_sign == 0) {
  10036. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  10037. return 0;
  10038. }
  10039. #else
  10040. /* convert big number to hex */
  10041. r = wolfSSL_BN_bn2hex(sig->r);
  10042. s = wolfSSL_BN_bn2hex(sig->s);
  10043. /* get DER-encoded ECDSA signature */
  10044. ret = wc_ecc_rs_to_sig((const char*)r, (const char*)s,
  10045. signature, &signaturelen);
  10046. /* free r and s */
  10047. if (r)
  10048. XFREE(r, NULL, DYNAMIC_TYPE_OPENSSL);
  10049. if (s)
  10050. XFREE(s, NULL, DYNAMIC_TYPE_OPENSSL);
  10051. if (ret != MP_OKAY) {
  10052. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  10053. return -1;
  10054. }
  10055. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  10056. ret = wc_ecc_verify_hash(signature, signaturelen, d, dlen, &check_sign,
  10057. (ecc_key*)key->internal);
  10058. if (ret != MP_OKAY) {
  10059. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  10060. return -1;
  10061. }
  10062. else if (check_sign == 0) {
  10063. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  10064. return 0;
  10065. }
  10066. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  10067. return 1;
  10068. }
  10069. WOLFSSL_ECDSA_SIG *wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG **sig,
  10070. const unsigned char **pp, long len)
  10071. {
  10072. WOLFSSL_ECDSA_SIG *s = NULL;
  10073. if (pp == NULL)
  10074. return NULL;
  10075. if (sig != NULL)
  10076. s = *sig;
  10077. if (s == NULL) {
  10078. s = wolfSSL_ECDSA_SIG_new();
  10079. if (s == NULL)
  10080. return NULL;
  10081. }
  10082. /* DecodeECC_DSA_Sig calls mp_init, so free these */
  10083. mp_free((mp_int*)s->r->internal);
  10084. mp_free((mp_int*)s->s->internal);
  10085. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  10086. (mp_int*)s->s->internal) != MP_OKAY) {
  10087. if (sig == NULL || *sig == NULL)
  10088. wolfSSL_ECDSA_SIG_free(s);
  10089. return NULL;
  10090. }
  10091. *pp += len;
  10092. if (sig != NULL)
  10093. *sig = s;
  10094. return s;
  10095. }
  10096. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  10097. {
  10098. word32 len;
  10099. if (sig == NULL)
  10100. return 0;
  10101. /* ASN.1: SEQ + INT + INT
  10102. * ASN.1 Integer must be a positive value - prepend zero if number has
  10103. * top bit set.
  10104. */
  10105. len = 2 + mp_leading_bit((mp_int*)sig->r->internal) +
  10106. mp_unsigned_bin_size((mp_int*)sig->r->internal) +
  10107. 2 + mp_leading_bit((mp_int*)sig->s->internal) +
  10108. mp_unsigned_bin_size((mp_int*)sig->s->internal);
  10109. /* Two bytes required for length if ASN.1 SEQ data greater than 127 bytes
  10110. * and less than 256 bytes.
  10111. */
  10112. len = 1 + ((len > 127) ? 2 : 1) + len;
  10113. if (pp != NULL && *pp != NULL) {
  10114. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  10115. (mp_int*)sig->s->internal) != MP_OKAY) {
  10116. len = 0;
  10117. }
  10118. else
  10119. *pp += len;
  10120. }
  10121. return (int)len;
  10122. }
  10123. /* End ECDSA_SIG */
  10124. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10125. /* Start ECDH */
  10126. /* return code compliant with OpenSSL :
  10127. * length of computed key if success, -1 if error
  10128. */
  10129. int wolfSSL_ECDH_compute_key(void *out, size_t outlen,
  10130. const WOLFSSL_EC_POINT *pub_key,
  10131. WOLFSSL_EC_KEY *ecdh,
  10132. void *(*KDF) (const void *in, size_t inlen,
  10133. void *out, size_t *outlen))
  10134. {
  10135. word32 len;
  10136. ecc_key* key;
  10137. int ret;
  10138. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  10139. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  10140. int setGlobalRNG = 0;
  10141. #endif
  10142. (void)KDF;
  10143. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  10144. if (out == NULL || pub_key == NULL || pub_key->internal == NULL ||
  10145. ecdh == NULL || ecdh->internal == NULL) {
  10146. WOLFSSL_MSG("Bad function arguments");
  10147. return -1;
  10148. }
  10149. /* set internal key if not done */
  10150. if (ecdh->inSet == 0)
  10151. {
  10152. WOLFSSL_MSG("No EC key internal set, do it");
  10153. if (SetECKeyInternal(ecdh) != 1) {
  10154. WOLFSSL_MSG("SetECKeyInternal failed");
  10155. return -1;
  10156. }
  10157. }
  10158. len = (word32)outlen;
  10159. key = (ecc_key*)ecdh->internal;
  10160. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  10161. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  10162. if (key->rng == NULL) {
  10163. if ((key->rng = wolfssl_get_global_rng()) == NULL) {
  10164. if (wolfSSL_RAND_Init() != 1) {
  10165. WOLFSSL_MSG("No RNG to use");
  10166. return -1;
  10167. }
  10168. key->rng = wolfssl_get_global_rng();
  10169. }
  10170. setGlobalRNG = 1;
  10171. }
  10172. #endif
  10173. PRIVATE_KEY_UNLOCK();
  10174. ret = wc_ecc_shared_secret_ssh(key, (ecc_point*)pub_key->internal,
  10175. (byte *)out, &len);
  10176. PRIVATE_KEY_LOCK();
  10177. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  10178. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  10179. if (setGlobalRNG)
  10180. key->rng = NULL;
  10181. #endif
  10182. if (ret != MP_OKAY) {
  10183. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  10184. return -1;
  10185. }
  10186. return len;
  10187. }
  10188. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  10189. /* End ECDH */
  10190. #if !defined(NO_FILESYSTEM)
  10191. #ifndef NO_BIO
  10192. #ifdef WOLFSSL_KEY_GEN
  10193. /* return code compliant with OpenSSL :
  10194. * 1 if success, 0 if error
  10195. */
  10196. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10197. {
  10198. int ret = 1;
  10199. WOLFSSL_BIO* bio = NULL;
  10200. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10201. if (fp == XBADFILE || key == NULL) {
  10202. WOLFSSL_MSG("Bad argument.");
  10203. ret = 0;
  10204. }
  10205. if (ret == 1) {
  10206. bio = wolfSSL_BIO_new_fp(fp, BIO_NOCLOSE);
  10207. if (bio == NULL) {
  10208. WOLFSSL_MSG("wolfSSL_BIO_new failed.");
  10209. ret = 0;
  10210. }
  10211. }
  10212. if (ret == 1 && wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key)
  10213. != 1) {
  10214. WOLFSSL_MSG("wolfSSL_PEM_write_bio_EC_PUBKEY failed.");
  10215. ret = 0;
  10216. }
  10217. if (bio != NULL) {
  10218. wolfSSL_BIO_free(bio);
  10219. }
  10220. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10221. return ret;
  10222. }
  10223. #endif
  10224. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  10225. * the results to be an EC key.
  10226. *
  10227. * bio structure to read EC private key from
  10228. * ec if not null is then set to the result
  10229. * cb password callback for reading PEM
  10230. * pass password string
  10231. *
  10232. * returns a pointer to a new WOLFSSL_EC_KEY struct on success and NULL on fail
  10233. */
  10234. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10235. WOLFSSL_EC_KEY** ec,
  10236. wc_pem_password_cb* cb,
  10237. void *pass)
  10238. {
  10239. WOLFSSL_EVP_PKEY* pkey;
  10240. WOLFSSL_EC_KEY* local;
  10241. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10242. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  10243. if (pkey == NULL) {
  10244. return NULL;
  10245. }
  10246. /* Since the WOLFSSL_EC_KEY structure is being taken from WOLFSSL_EVP_PKEY the
  10247. * flag indicating that the WOLFSSL_EC_KEY structure is owned should be FALSE
  10248. * flag indicating that the WOLFSSL_EC_KEY structure is owned should be FALSE
  10249. * to avoid having it free'd */
  10250. pkey->ownEcc = 0;
  10251. local = pkey->ecc;
  10252. if (ec != NULL) {
  10253. *ec = local;
  10254. }
  10255. wolfSSL_EVP_PKEY_free(pkey);
  10256. return local;
  10257. }
  10258. /* Reads a private EC key from a WOLFSSL_BIO into a WOLFSSL_EC_KEY.
  10259. * Returns 1 or 0
  10260. */
  10261. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  10262. WOLFSSL_EC_KEY** ec,
  10263. wc_pem_password_cb* cb,
  10264. void *pass)
  10265. {
  10266. WOLFSSL_EVP_PKEY* pkey;
  10267. WOLFSSL_EC_KEY* local;
  10268. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  10269. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  10270. if (pkey == NULL) {
  10271. return NULL;
  10272. }
  10273. /* Since the WOLFSSL_EC_KEY structure is being taken from WOLFSSL_EVP_PKEY the
  10274. * flag indicating that the WOLFSSL_EC_KEY structure is owned should be FALSE
  10275. * to avoid having it free'd */
  10276. pkey->ownEcc = 0;
  10277. local = pkey->ecc;
  10278. if (ec != NULL) {
  10279. *ec = local;
  10280. }
  10281. wolfSSL_EVP_PKEY_free(pkey);
  10282. return local;
  10283. }
  10284. #endif /* !NO_BIO */
  10285. #endif /* NO_FILESYSTEM */
  10286. #if defined(WOLFSSL_KEY_GEN)
  10287. #ifndef NO_BIO
  10288. /* Takes a public WOLFSSL_EC_KEY and writes it out to WOLFSSL_BIO
  10289. * Returns 1 or 0
  10290. */
  10291. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  10292. {
  10293. int ret = 0;
  10294. WOLFSSL_EVP_PKEY* pkey;
  10295. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  10296. if (bio == NULL || ec == NULL) {
  10297. WOLFSSL_MSG("Bad Function Arguments");
  10298. return 0;
  10299. }
  10300. /* Initialize pkey structure */
  10301. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  10302. if (pkey == NULL) {
  10303. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  10304. return 0;
  10305. }
  10306. /* Set pkey info */
  10307. pkey->ecc = ec;
  10308. pkey->ownEcc = 0; /* pkey does not own ECC */
  10309. pkey->type = EVP_PKEY_EC;
  10310. if ((ret = pem_write_bio_pubkey(bio, pkey)) != 1) {
  10311. WOLFSSL_MSG("wolfSSL_PEM_write_bio_PUBKEY failed");
  10312. }
  10313. wolfSSL_EVP_PKEY_free(pkey);
  10314. return ret;
  10315. }
  10316. /* return code compliant with OpenSSL :
  10317. * 1 if success, 0 if error
  10318. */
  10319. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  10320. const EVP_CIPHER* cipher,
  10321. unsigned char* passwd, int len,
  10322. wc_pem_password_cb* cb, void* arg)
  10323. {
  10324. int ret = 0, der_max_len = 0, derSz = 0;
  10325. byte *derBuf;
  10326. WOLFSSL_EVP_PKEY* pkey;
  10327. WOLFSSL_ENTER("WOLFSSL_PEM_write_bio_ECPrivateKey");
  10328. if (bio == NULL || ec == NULL) {
  10329. WOLFSSL_MSG("Bad Function Arguments");
  10330. return 0;
  10331. }
  10332. /* Initialize pkey structure */
  10333. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  10334. if (pkey == NULL) {
  10335. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  10336. return 0;
  10337. }
  10338. /* Set pkey info */
  10339. pkey->ecc = ec;
  10340. pkey->ownEcc = 0; /* pkey does not own ECC */
  10341. pkey->type = EVP_PKEY_EC;
  10342. /* 4 > size of pub, priv + ASN.1 additional informations
  10343. */
  10344. der_max_len = 4 * wc_ecc_size((ecc_key*)ec->internal) + AES_BLOCK_SIZE;
  10345. derBuf = (byte*)XMALLOC(der_max_len, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10346. if (derBuf == NULL) {
  10347. WOLFSSL_MSG("Malloc failed");
  10348. wolfSSL_EVP_PKEY_free(pkey);
  10349. return 0;
  10350. }
  10351. /* convert key to der format */
  10352. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  10353. if (derSz < 0) {
  10354. WOLFSSL_MSG("wc_EccKeyToDer failed");
  10355. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10356. wolfSSL_EVP_PKEY_free(pkey);
  10357. return 0;
  10358. }
  10359. pkey->pkey.ptr = (char*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10360. if (pkey->pkey.ptr == NULL) {
  10361. WOLFSSL_MSG("key malloc failed");
  10362. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10363. wolfSSL_EVP_PKEY_free(pkey);
  10364. return 0;
  10365. }
  10366. /* add der info to the evp key */
  10367. pkey->pkey_sz = derSz;
  10368. XMEMCPY(pkey->pkey.ptr, derBuf, derSz);
  10369. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10370. ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len,
  10371. cb, arg);
  10372. wolfSSL_EVP_PKEY_free(pkey);
  10373. return ret;
  10374. }
  10375. #endif /* !NO_BIO */
  10376. /* return code compliant with OpenSSL :
  10377. * 1 if success, 0 if error
  10378. */
  10379. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ecc,
  10380. const EVP_CIPHER* cipher,
  10381. unsigned char* passwd, int passwdSz,
  10382. unsigned char **pem, int *plen)
  10383. {
  10384. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  10385. byte *derBuf, *tmp, *cipherInfo = NULL;
  10386. int der_max_len = 0, derSz = 0;
  10387. const int type = ECC_PRIVATEKEY_TYPE;
  10388. const char* header = NULL;
  10389. const char* footer = NULL;
  10390. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  10391. if (pem == NULL || plen == NULL || ecc == NULL || ecc->internal == NULL) {
  10392. WOLFSSL_MSG("Bad function arguments");
  10393. return 0;
  10394. }
  10395. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  10396. return 0;
  10397. if (ecc->inSet == 0) {
  10398. WOLFSSL_MSG("No ECC internal set, do it");
  10399. if (SetECKeyInternal(ecc) != 1) {
  10400. WOLFSSL_MSG("SetECKeyInternal failed");
  10401. return 0;
  10402. }
  10403. }
  10404. /* 4 > size of pub, priv + ASN.1 additional information */
  10405. der_max_len = 4 * wc_ecc_size((ecc_key*)ecc->internal) + AES_BLOCK_SIZE;
  10406. derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_DER);
  10407. if (derBuf == NULL) {
  10408. WOLFSSL_MSG("malloc failed");
  10409. return 0;
  10410. }
  10411. /* Key to DER */
  10412. derSz = wc_EccKeyToDer((ecc_key*)ecc->internal, derBuf, der_max_len);
  10413. if (derSz < 0) {
  10414. WOLFSSL_MSG("wc_EccKeyToDer failed");
  10415. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10416. return 0;
  10417. }
  10418. /* encrypt DER buffer if required */
  10419. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  10420. int ret;
  10421. ret = EncryptDerKey(derBuf, &derSz, cipher,
  10422. passwd, passwdSz, &cipherInfo, der_max_len);
  10423. if (ret != 1) {
  10424. WOLFSSL_MSG("EncryptDerKey failed");
  10425. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10426. return ret;
  10427. }
  10428. /* tmp buffer with a max size */
  10429. *plen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  10430. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  10431. }
  10432. else { /* tmp buffer with a max size */
  10433. *plen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  10434. (int)XSTRLEN(footer) + 1;
  10435. }
  10436. tmp = (byte*)XMALLOC(*plen, NULL, DYNAMIC_TYPE_PEM);
  10437. if (tmp == NULL) {
  10438. WOLFSSL_MSG("malloc failed");
  10439. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10440. if (cipherInfo != NULL)
  10441. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  10442. return 0;
  10443. }
  10444. /* DER to PEM */
  10445. *plen = wc_DerToPemEx(derBuf, derSz, tmp, *plen, cipherInfo, type);
  10446. if (*plen <= 0) {
  10447. WOLFSSL_MSG("wc_DerToPemEx failed");
  10448. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10449. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  10450. if (cipherInfo != NULL)
  10451. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  10452. return 0;
  10453. }
  10454. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10455. if (cipherInfo != NULL)
  10456. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  10457. *pem = (byte*)XMALLOC((*plen)+1, NULL, DYNAMIC_TYPE_KEY);
  10458. if (*pem == NULL) {
  10459. WOLFSSL_MSG("malloc failed");
  10460. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  10461. return 0;
  10462. }
  10463. XMEMSET(*pem, 0, (*plen)+1);
  10464. if (XMEMCPY(*pem, tmp, *plen) == NULL) {
  10465. WOLFSSL_MSG("XMEMCPY failed");
  10466. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  10467. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  10468. return 0;
  10469. }
  10470. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  10471. return 1;
  10472. #else
  10473. (void)ecc;
  10474. (void)cipher;
  10475. (void)passwd;
  10476. (void)passwdSz;
  10477. (void)pem;
  10478. (void)plen;
  10479. return 0;
  10480. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  10481. }
  10482. #ifndef NO_FILESYSTEM
  10483. /* return code compliant with OpenSSL :
  10484. * 1 if success, 0 if error
  10485. */
  10486. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ecc,
  10487. const EVP_CIPHER *enc,
  10488. unsigned char *kstr, int klen,
  10489. wc_pem_password_cb *cb, void *u)
  10490. {
  10491. byte *pem;
  10492. int plen, ret;
  10493. (void)cb;
  10494. (void)u;
  10495. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  10496. if (fp == XBADFILE || ecc == NULL || ecc->internal == NULL) {
  10497. WOLFSSL_MSG("Bad function arguments");
  10498. return 0;
  10499. }
  10500. ret = wolfSSL_PEM_write_mem_ECPrivateKey(ecc, enc, kstr, klen, &pem, &plen);
  10501. if (ret != 1) {
  10502. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  10503. return 0;
  10504. }
  10505. ret = (int)XFWRITE(pem, plen, 1, fp);
  10506. if (ret != 1) {
  10507. WOLFSSL_MSG("ECC private key file write failed");
  10508. return 0;
  10509. }
  10510. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  10511. return 1;
  10512. }
  10513. #endif /* NO_FILESYSTEM */
  10514. #endif /* defined(WOLFSSL_KEY_GEN) */
  10515. #ifndef NO_BIO
  10516. /* returns a new WOLFSSL_EC_GROUP structure on success and NULL on fail */
  10517. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  10518. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  10519. {
  10520. WOLFSSL_EVP_PKEY* pkey;
  10521. WOLFSSL_EC_GROUP* ret = NULL;
  10522. /* check on if bio is null is done in wolfSSL_PEM_read_bio_PrivateKey */
  10523. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  10524. if (pkey != NULL) {
  10525. if (pkey->type != EVP_PKEY_EC) {
  10526. WOLFSSL_MSG("Unexpected key type");
  10527. }
  10528. else {
  10529. ret = (WOLFSSL_EC_GROUP*)wolfSSL_EC_KEY_get0_group(pkey->ecc);
  10530. /* set ecc group to null so it is not free'd when pkey is free'd */
  10531. pkey->ecc->group = NULL;
  10532. }
  10533. }
  10534. (void)group;
  10535. wolfSSL_EVP_PKEY_free(pkey);
  10536. return ret;
  10537. }
  10538. #endif /* !NO_BIO */
  10539. /* return 1 if success, -1 if error */
  10540. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10541. int derSz)
  10542. {
  10543. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10544. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10545. }
  10546. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10547. int derSz, int opt)
  10548. {
  10549. int ret;
  10550. word32 idx = 0;
  10551. word32 algId;
  10552. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10553. if (key == NULL || key->internal == NULL || derBuf == NULL || derSz <= 0) {
  10554. WOLFSSL_MSG("Bad function arguments");
  10555. return -1;
  10556. }
  10557. key->pkcs8HeaderSz = 0;
  10558. /* Check if input buffer has PKCS8 header. In the case that it does not
  10559. * have a PKCS8 header then do not error out. */
  10560. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  10561. &algId)) > 0) {
  10562. WOLFSSL_MSG("Found PKCS8 header");
  10563. key->pkcs8HeaderSz = (word16)idx;
  10564. }
  10565. else {
  10566. if (ret != ASN_PARSE_E) {
  10567. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10568. return -1;
  10569. }
  10570. }
  10571. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10572. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10573. derSz);
  10574. }
  10575. else {
  10576. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10577. derSz);
  10578. }
  10579. if (ret < 0) {
  10580. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10581. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10582. }
  10583. else {
  10584. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10585. }
  10586. return -1;
  10587. }
  10588. if (SetECKeyExternal(key) != 1) {
  10589. WOLFSSL_MSG("SetECKeyExternal failed");
  10590. return -1;
  10591. }
  10592. key->inSet = 1;
  10593. return 1;
  10594. }
  10595. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL*/
  10596. #endif /* HAVE_ECC */
  10597. /*******************************************************************************
  10598. * END OF EC API
  10599. ******************************************************************************/
  10600. #endif /* !WOLFSSL_PK_INCLUDED */