pk.c 476 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611
  1. /* pk.c
  2. *
  3. * Copyright (C) 2006-2024 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/internal.h>
  26. #ifndef WC_NO_RNG
  27. #include <wolfssl/wolfcrypt/random.h>
  28. #endif
  29. #ifdef HAVE_ECC
  30. #include <wolfssl/wolfcrypt/ecc.h>
  31. #ifdef HAVE_SELFTEST
  32. /* point compression types. */
  33. #define ECC_POINT_COMP_EVEN 0x02
  34. #define ECC_POINT_COMP_ODD 0x03
  35. #define ECC_POINT_UNCOMP 0x04
  36. #endif
  37. #endif
  38. #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  39. /* FIPS build has replaced ecc.h. */
  40. #define wc_ecc_key_get_priv(key) (&((key)->k))
  41. #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  42. #endif
  43. #if !defined(WOLFSSL_PK_INCLUDED)
  44. #ifndef WOLFSSL_IGNORE_FILE_WARN
  45. #warning pk.c does not need to be compiled separately from ssl.c
  46. #endif
  47. #else
  48. #ifndef NO_RSA
  49. #include <wolfssl/wolfcrypt/rsa.h>
  50. #endif
  51. /*******************************************************************************
  52. * COMMON FUNCTIONS
  53. ******************************************************************************/
  54. /* Calculate the number of bytes require to represent a length value in ASN.
  55. *
  56. * @param [in] l Length value to use.
  57. * @return Number of bytes required to represent length value.
  58. */
  59. #define ASN_LEN_SIZE(l) \
  60. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  61. #if defined(OPENSSL_EXTRA)
  62. #ifndef NO_ASN
  63. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  64. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  65. /* Convert the PEM encoding in the buffer to DER.
  66. *
  67. * @param [in] pem Buffer containing PEM encoded data.
  68. * @param [in] pemSz Size of data in buffer in bytes.
  69. * @param [in] cb Password callback when PEM encrypted.
  70. * @param [in] pass NUL terminated string for passphrase when PEM
  71. * encrypted.
  72. * @param [in] keyType Type of key to match against PEM header/footer.
  73. * @param [out] keyFormat Format of key.
  74. * @param [out] der Buffer holding DER encoding.
  75. * @return Negative on failure.
  76. * @return Number of bytes consumed on success.
  77. */
  78. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  79. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  80. {
  81. #ifdef WOLFSSL_SMALL_STACK
  82. EncryptedInfo* info = NULL;
  83. #else
  84. EncryptedInfo info[1];
  85. #endif /* WOLFSSL_SMALL_STACK */
  86. wc_pem_password_cb* localCb = NULL;
  87. int ret = 0;
  88. if (cb != NULL) {
  89. localCb = cb;
  90. }
  91. else if (pass != NULL) {
  92. localCb = wolfSSL_PEM_def_callback;
  93. }
  94. #ifdef WOLFSSL_SMALL_STACK
  95. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  96. DYNAMIC_TYPE_ENCRYPTEDINFO);
  97. if (info == NULL) {
  98. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  99. ret = MEMORY_E;
  100. }
  101. #endif /* WOLFSSL_SMALL_STACK */
  102. if (ret == 0) {
  103. XMEMSET(info, 0, sizeof(EncryptedInfo));
  104. info->passwd_cb = localCb;
  105. info->passwd_userdata = pass;
  106. /* Do not strip PKCS8 header */
  107. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  108. info, keyFormat);
  109. if (ret < 0) {
  110. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  111. }
  112. }
  113. if (ret >= 0) {
  114. ret = (int)info->consumed;
  115. }
  116. #ifdef WOLFSSL_SMALL_STACK
  117. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  118. #endif
  119. return ret;
  120. }
  121. #endif
  122. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  123. #ifndef NO_BIO
  124. /* Read PEM data from a BIO and decode to DER in a new buffer.
  125. *
  126. * @param [in, out] bio BIO object to read with.
  127. * @param [in] cb Password callback when PEM encrypted.
  128. * @param [in] pass NUL terminated string for passphrase when PEM
  129. * encrypted.
  130. * @param [in] keyType Type of key to match against PEM header/footer.
  131. * @param [out] keyFormat Format of key.
  132. * @param [out] der Buffer holding DER encoding.
  133. * @return Negative on failure.
  134. * @return Number of bytes consumed on success.
  135. */
  136. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  137. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  138. {
  139. int ret;
  140. char* mem = NULL;
  141. int memSz;
  142. int alloced = 0;
  143. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  144. if (ret == 0) {
  145. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  146. /* Write left over data back to BIO if not a file BIO */
  147. if ((ret > 0) && ((memSz - ret) > 0) &&
  148. (bio->type != WOLFSSL_BIO_FILE)) {
  149. int res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  150. if (res != memSz - ret) {
  151. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  152. if (res < 0) {
  153. ret = res;
  154. }
  155. else {
  156. ret = MEMORY_E;
  157. }
  158. }
  159. }
  160. if (alloced) {
  161. XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  162. }
  163. }
  164. return ret;
  165. }
  166. #endif /* !NO_BIO */
  167. #if !defined(NO_FILESYSTEM)
  168. /* Read PEM data from a file and decode to DER in a new buffer.
  169. *
  170. * @param [in] fp File pointer to read with.
  171. * @param [in] cb Password callback when PEM encrypted.
  172. * @param [in] pass NUL terminated string for passphrase when PEM
  173. * encrypted.
  174. * @param [in] keyType Type of key to match against PEM header/footer.
  175. * @param [out] keyFormat Format of key.
  176. * @param [out] der Buffer holding DER encoding.
  177. * @return Negative on failure.
  178. * @return Number of bytes consumed on success.
  179. */
  180. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  181. int keyType, int* keyFormat, DerBuffer** der)
  182. {
  183. int ret;
  184. char* mem = NULL;
  185. int memSz;
  186. ret = wolfssl_read_file(fp, &mem, &memSz);
  187. if (ret == 0) {
  188. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  189. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  190. }
  191. return ret;
  192. }
  193. #endif /* !NO_FILESYSTEM */
  194. #endif
  195. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) \
  196. || !defined(WOLFCRYPT_ONLY))
  197. /* Convert DER data to PEM in an allocated buffer.
  198. *
  199. * @param [in] der Buffer containing DER data.
  200. * @param [in] derSz Size of DER data in bytes.
  201. * @param [in] type Type of key being encoded.
  202. * @param [in] heap Heap hint for dynamic memory allocation.
  203. * @param [out] out Allocated buffer containing PEM.
  204. * @param [out] outSz Size of PEM encoding.
  205. * @return 1 on success.
  206. * @return 0 on error.
  207. */
  208. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  209. void* heap, byte** out, int* outSz)
  210. {
  211. int ret = 1;
  212. int pemSz;
  213. byte* pem = NULL;
  214. (void)heap;
  215. /* Convert DER to PEM - to get size. */
  216. pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
  217. if (pemSz < 0) {
  218. ret = 0;
  219. }
  220. if (ret == 1) {
  221. /* Allocate memory for PEM to be encoded into. */
  222. pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  223. if (pem == NULL) {
  224. ret = 0;
  225. }
  226. }
  227. /* Convert DER to PEM. */
  228. if ((ret == 1) && (wc_DerToPem(der, (word32)derSz, pem, (word32)pemSz,
  229. type) < 0)) {
  230. ret = 0;
  231. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  232. pem = NULL;
  233. }
  234. *out = pem;
  235. *outSz = pemSz;
  236. return ret;
  237. }
  238. #ifndef NO_BIO
  239. /* Write the DER data as PEM into BIO.
  240. *
  241. * @param [in] der Buffer containing DER data.
  242. * @param [in] derSz Size of DER data in bytes.
  243. * @param [in, out] bio BIO object to write with.
  244. * @param [in] type Type of key being encoded.
  245. * @return 1 on success.
  246. * @return 0 on error.
  247. */
  248. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  249. WOLFSSL_BIO* bio, int type)
  250. {
  251. int ret;
  252. int pemSz;
  253. byte* pem = NULL;
  254. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  255. if (ret == 1) {
  256. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  257. if (len != pemSz) {
  258. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  259. ret = 0;
  260. }
  261. }
  262. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  263. return ret;
  264. }
  265. #endif
  266. #endif
  267. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || \
  268. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  269. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  270. #if !defined(NO_FILESYSTEM)
  271. /* Write the DER data as PEM into file pointer.
  272. *
  273. * @param [in] der Buffer containing DER data.
  274. * @param [in] derSz Size of DER data in bytes.
  275. * @param [in] fp File pointer to write with.
  276. * @param [in] type Type of key being encoded.
  277. * @param [in] heap Heap hint for dynamic memory allocation.
  278. * @return 1 on success.
  279. * @return 0 on error.
  280. */
  281. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  282. XFILE fp, int type, void* heap)
  283. {
  284. int ret;
  285. int pemSz;
  286. byte* pem = NULL;
  287. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  288. if (ret == 1) {
  289. int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
  290. if (len != pemSz) {
  291. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  292. ret = 0;
  293. }
  294. }
  295. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  296. return ret;
  297. }
  298. #endif
  299. #endif
  300. #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
  301. /* Encrypt private key into PEM format.
  302. *
  303. * DER is encrypted in place.
  304. *
  305. * @param [in] der DER encoding of private key.
  306. * @param [in] derSz Size of DER in bytes.
  307. * @param [in] cipher EVP cipher.
  308. * @param [in] passwd Password to use with encryption.
  309. * @param [in] passedSz Size of password in bytes.
  310. * @param [out] cipherInfo PEM cipher information lines.
  311. * @param [in] maxDerSz Maximum size of DER buffer.
  312. * @return 1 on success.
  313. * @return 0 on error.
  314. */
  315. int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher,
  316. unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz)
  317. {
  318. int ret = 0;
  319. int paddingSz = 0;
  320. word32 idx;
  321. word32 cipherInfoSz;
  322. #ifdef WOLFSSL_SMALL_STACK
  323. EncryptedInfo* info = NULL;
  324. #else
  325. EncryptedInfo info[1];
  326. #endif
  327. WOLFSSL_ENTER("EncryptDerKey");
  328. /* Validate parameters. */
  329. if ((der == NULL) || (derSz == NULL) || (cipher == NULL) ||
  330. (passwd == NULL) || (cipherInfo == NULL)) {
  331. ret = BAD_FUNC_ARG;
  332. }
  333. #ifdef WOLFSSL_SMALL_STACK
  334. if (ret == 0) {
  335. /* Allocate encrypted info. */
  336. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  337. DYNAMIC_TYPE_ENCRYPTEDINFO);
  338. if (info == NULL) {
  339. WOLFSSL_MSG("malloc failed");
  340. ret = MEMORY_E;
  341. }
  342. }
  343. #endif
  344. if (ret == 0) {
  345. /* Clear the encrypted info and set name. */
  346. XMEMSET(info, 0, sizeof(EncryptedInfo));
  347. XSTRNCPY(info->name, cipher, NAME_SZ - 1);
  348. info->name[NAME_SZ - 1] = '\0'; /* null term */
  349. /* Get encrypted info from name. */
  350. ret = wc_EncryptedInfoGet(info, info->name);
  351. if (ret != 0) {
  352. WOLFSSL_MSG("unsupported cipher");
  353. }
  354. }
  355. if (ret == 0) {
  356. /* Generate a random salt. */
  357. if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) {
  358. WOLFSSL_MSG("generate iv failed");
  359. ret = WOLFSSL_FATAL_ERROR;
  360. }
  361. }
  362. if (ret == 0) {
  363. /* Calculate padding size - always a padding block. */
  364. paddingSz = info->ivSz - ((*derSz) % info->ivSz);
  365. /* Check der is big enough. */
  366. if (maxDerSz < (*derSz) + paddingSz) {
  367. WOLFSSL_MSG("not enough DER buffer allocated");
  368. ret = BAD_FUNC_ARG;
  369. }
  370. }
  371. if (ret == 0) {
  372. /* Set padding bytes to padding length. */
  373. XMEMSET(der + (*derSz), (byte)paddingSz, paddingSz);
  374. /* Add padding to DER size. */
  375. (*derSz) += (int)paddingSz;
  376. /* Encrypt DER buffer. */
  377. ret = wc_BufferKeyEncrypt(info, der, (word32)*derSz, passwd, passwdSz,
  378. WC_MD5);
  379. if (ret != 0) {
  380. WOLFSSL_MSG("encrypt key failed");
  381. }
  382. }
  383. if (ret == 0) {
  384. /* Create cipher info : 'cipher_name,Salt(hex)' */
  385. cipherInfoSz = (word32)(2 * info->ivSz + XSTRLEN(info->name) + 2);
  386. /* Allocate memory for PEM encryption lines. */
  387. *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, DYNAMIC_TYPE_STRING);
  388. if (*cipherInfo == NULL) {
  389. WOLFSSL_MSG("malloc failed");
  390. ret = MEMORY_E;
  391. }
  392. }
  393. if (ret == 0) {
  394. /* Copy in name and add on comma. */
  395. XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz);
  396. XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz);
  397. /* Find end of string. */
  398. idx = (word32)XSTRLEN((char*)*cipherInfo);
  399. /* Calculate remaining bytes. */
  400. cipherInfoSz -= idx;
  401. /* Encode IV into PEM encryption lines. */
  402. ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo + idx,
  403. &cipherInfoSz);
  404. if (ret != 0) {
  405. WOLFSSL_MSG("Base16_Encode failed");
  406. XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  407. *cipherInfo = NULL;
  408. }
  409. }
  410. #ifdef WOLFSSL_SMALL_STACK
  411. /* Free dynamically allocated info. */
  412. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  413. #endif
  414. return ret == 0;
  415. }
  416. #endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */
  417. #if defined(WOLFSSL_KEY_GEN) && \
  418. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  419. (!defined(NO_RSA) || defined(HAVE_ECC))
  420. /* Encrypt the DER in PEM format.
  421. *
  422. * @param [in] der DER encoded private key.
  423. * @param [in] derSz Size of DER in bytes.
  424. * @param [in] cipher EVP cipher.
  425. * @param [in] passwd Password to use in encryption.
  426. * @param [in] passwdSz Size of password in bytes.
  427. * @param [in] type PEM type of write out.
  428. * @param [in] heap Dynamic memory hint.
  429. * @param [out] out Allocated buffer containing PEM encoding.
  430. * heap was NULL and dynamic type is DYNAMIC_TYPE_KEY.
  431. * @param [out] outSz Size of PEM encoding in bytes.
  432. * @return 1 on success.
  433. * @return 0 on failure.
  434. */
  435. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  436. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  437. void* heap, byte** out, int* outSz)
  438. {
  439. int ret = 1;
  440. byte* tmp = NULL;
  441. byte* cipherInfo = NULL;
  442. int pemSz = 0;
  443. /* Macro doesn't always use it. */
  444. (void)heap;
  445. /* Encrypt DER buffer if required. */
  446. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  447. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  448. byte *tmpBuf;
  449. /* Add space for padding. */
  450. tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
  451. DYNAMIC_TYPE_TMP_BUFFER);
  452. if (tmpBuf == NULL) {
  453. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  454. ret = 0; /* der buffer is free'd at the end of the function */
  455. }
  456. else {
  457. der = tmpBuf;
  458. /* Encrypt DER inline. */
  459. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  460. &cipherInfo, derSz + blockSz);
  461. if (ret != 1) {
  462. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  463. }
  464. }
  465. }
  466. if (ret == 1) {
  467. /* Calculate PEM encoding size. */
  468. pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
  469. if (pemSz <= 0) {
  470. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  471. ret = 0;
  472. }
  473. }
  474. if (ret == 1) {
  475. /* Allocate space for PEM encoding plus a NUL terminator. */
  476. tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
  477. if (tmp == NULL) {
  478. WOLFSSL_ERROR_MSG("malloc failed");
  479. ret = 0;
  480. }
  481. }
  482. if (ret == 1) {
  483. /* DER to PEM */
  484. pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
  485. cipherInfo, type);
  486. if (pemSz <= 0) {
  487. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  488. ret = 0;
  489. }
  490. }
  491. if (ret == 1) {
  492. /* NUL terminate string - PEM. */
  493. tmp[pemSz] = 0x00;
  494. /* Return allocated buffer and size. */
  495. *out = tmp;
  496. *outSz = pemSz;
  497. /* Don't free returning buffer. */
  498. tmp = NULL;
  499. }
  500. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  501. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  502. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  503. return ret;
  504. }
  505. #endif
  506. #endif /* !NO_ASN */
  507. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  508. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  509. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  510. /* Print the number bn in hex with name field and indentation indent to file fp.
  511. *
  512. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  513. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  514. *
  515. * @param [in] fp File pointer to write to.
  516. * @param [in] indent Number of spaces to prepend to each line.
  517. * @param [in] field Name of field.
  518. * @param [in] bn Big number to print.
  519. * @return 1 on success.
  520. * @return 0 on failure.
  521. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  522. * bn or NULL.
  523. */
  524. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  525. const WOLFSSL_BIGNUM* bn)
  526. {
  527. static const int HEX_INDENT = 4;
  528. static const int MAX_DIGITS_PER_LINE = 30;
  529. int ret = 1;
  530. int i = 0;
  531. char* buf = NULL;
  532. /* Internal function - assume parameters are valid. */
  533. /* Convert BN to hexadecimal character array (allocates buffer). */
  534. buf = wolfSSL_BN_bn2hex(bn);
  535. if (buf == NULL) {
  536. ret = 0;
  537. }
  538. if (ret == 1) {
  539. /* Print leading spaces, name and spaces before data. */
  540. if (indent > 0) {
  541. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  542. ret = 0;
  543. }
  544. }
  545. if (ret == 1) {
  546. if (XFPRINTF(fp, "%s:\n", field) < 0)
  547. ret = 0;
  548. }
  549. if (ret == 1) {
  550. if (indent > 0) {
  551. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  552. ret = 0;
  553. }
  554. }
  555. if (ret == 1) {
  556. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  557. ret = 0;
  558. }
  559. if (ret == 1) {
  560. /* Print first byte - should always exist. */
  561. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  562. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  563. ret = 0;
  564. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  565. ret = 0;
  566. }
  567. }
  568. if (ret == 1) {
  569. /* Print each hexadecimal character with byte separator. */
  570. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  571. /* Byte separator every two nibbles - one byte. */
  572. if (XFPRINTF(fp, ":") < 0) {
  573. ret = 0;
  574. break;
  575. }
  576. /* New line after every 15 bytes - 30 nibbles. */
  577. if (i % MAX_DIGITS_PER_LINE == 0) {
  578. if (XFPRINTF(fp, "\n") < 0) {
  579. ret = 0;
  580. break;
  581. }
  582. if (indent > 0) {
  583. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  584. ret = 0;
  585. break;
  586. }
  587. }
  588. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  589. ret = 0;
  590. break;
  591. }
  592. }
  593. /* Print two nibbles - one byte. */
  594. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  595. ret = 0;
  596. break;
  597. }
  598. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  599. ret = 0;
  600. break;
  601. }
  602. }
  603. /* Ensure on new line after data. */
  604. if (XFPRINTF(fp, "\n") < 0) {
  605. ret = 0;
  606. }
  607. }
  608. /* Dispose of any allocated character array. */
  609. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  610. return ret;
  611. }
  612. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  613. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  614. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA)
  615. /* snprintf() must be available */
  616. /* Maximum number of extra indent spaces on each line. */
  617. #define PRINT_NUM_MAX_INDENT 48
  618. /* Maximum size of a line containing a value. */
  619. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  620. /* Number of leading spaces on each line. */
  621. #define PRINT_NUM_INDENT_CNT 4
  622. /* Indent spaces for number lines. */
  623. #define PRINT_NUM_INDENT " "
  624. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  625. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  626. /* Print indent to BIO.
  627. *
  628. * @param [in] bio BIO object to write to.
  629. * @param [in] line Buffer to put characters to before writing to BIO.
  630. * @param [in] lineLen Length of buffer.
  631. * @return 1 on success.
  632. * @return 0 on failure.
  633. */
  634. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  635. int indent)
  636. {
  637. int ret = 1;
  638. if (indent > 0) {
  639. /* Print indent spaces. */
  640. int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
  641. if (len_wanted >= lineLen) {
  642. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  643. ret = 0;
  644. }
  645. else {
  646. /* Write indents string to BIO */
  647. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  648. ret = 0;
  649. }
  650. }
  651. }
  652. return ret;
  653. }
  654. /* Print out name, and value in decimal and hex to BIO.
  655. *
  656. * @param [in] bio BIO object to write to.
  657. * @param [in] value MP integer to write.
  658. * @param [in] name Name of value.
  659. * @param [in] indent Number of leading spaces before line.
  660. * @return 1 on success.
  661. * @return 0 on failure.
  662. */
  663. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  664. const char* name, int indent)
  665. {
  666. int ret = 1;
  667. int len;
  668. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  669. /* Get the length of hex encoded value. */
  670. len = mp_unsigned_bin_size(value);
  671. /* Value must no more than 32-bits - 4 bytes. */
  672. if ((len < 0) || (len > 4)) {
  673. WOLFSSL_ERROR_MSG("Error getting exponent size");
  674. ret = 0;
  675. }
  676. if (ret == 1) {
  677. /* Print any indent spaces. */
  678. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  679. }
  680. if (ret == 1) {
  681. /* Get 32-bits of value. */
  682. word32 v = (word32)value->dp[0];
  683. /* Print the line to the string. */
  684. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  685. v);
  686. if (len >= (int)sizeof(line)) {
  687. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  688. ret = 0;
  689. } else {
  690. /* Write string to BIO */
  691. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  692. ret = 0;
  693. }
  694. }
  695. }
  696. return ret;
  697. }
  698. /* Print out name and multi-precision number to BIO.
  699. *
  700. * @param [in] bio BIO object to write to.
  701. * @param [in] num MP integer to write.
  702. * @param [in] name Name of value.
  703. * @param [in] indent Number of leading spaces before each line.
  704. * @return 1 on success.
  705. * @return 0 on failure.
  706. */
  707. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  708. int indent)
  709. {
  710. int ret = 1;
  711. int rawLen = 0;
  712. byte* rawKey = NULL;
  713. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  714. int li = 0; /* Line index. */
  715. int i;
  716. /* Allocate a buffer to hold binary encoded data. */
  717. rawLen = mp_unsigned_bin_size(num);
  718. if (rawLen == 0) {
  719. WOLFSSL_ERROR_MSG("Invalid number");
  720. ret = 0;
  721. }
  722. if (ret == 1) {
  723. rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  724. if (rawKey == NULL) {
  725. WOLFSSL_ERROR_MSG("Memory allocation error");
  726. ret = 0;
  727. }
  728. }
  729. /* Encode number as big-endian byte array. */
  730. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  731. ret = 0;
  732. }
  733. if (ret == 1) {
  734. /* Print any indent spaces. */
  735. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  736. }
  737. if (ret == 1) {
  738. /* Print header string line to string. */
  739. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  740. if (li >= (int)sizeof(line)) {
  741. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  742. ret = 0;
  743. }
  744. else {
  745. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  746. ret = 0;
  747. }
  748. }
  749. }
  750. if (ret == 1) {
  751. /* Print any indent spaces. */
  752. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  753. }
  754. if (ret == 1) {
  755. /* Start first digit line with spaces.
  756. * Writing out zeros ensures number is a positive value. */
  757. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  758. mp_leading_bit(num) ? "00:" : "");
  759. if (li >= (int)sizeof(line)) {
  760. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  761. ret = 0;
  762. }
  763. }
  764. /* Put out each line of numbers. */
  765. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  766. /* Encode another byte as 2 hex digits and append colon. */
  767. int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
  768. "%02x:", rawKey[i]);
  769. /* Check if there was room -- if not, print the current line, not
  770. * including the newest octet.
  771. */
  772. if (len_wanted >= (int)sizeof(line) - li) {
  773. /* bump current octet to the next line. */
  774. --i;
  775. /* More bytes coming so add a line break. */
  776. line[li++] = '\n';
  777. /* Write out the line. */
  778. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  779. ret = 0;
  780. }
  781. if (ret == 1) {
  782. /* Print any indent spaces. */
  783. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  784. }
  785. /* Put the leading spaces on new line. */
  786. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  787. li = PRINT_NUM_INDENT_CNT;
  788. }
  789. else {
  790. li += len_wanted;
  791. }
  792. }
  793. if (ret == 1) {
  794. /* Put out last line - replace last colon with carriage return. */
  795. line[li-1] = '\n';
  796. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  797. ret = 0;
  798. }
  799. }
  800. /* Dispose of any allocated data. */
  801. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  802. return ret;
  803. }
  804. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA */
  805. #endif /* OPENSSL_EXTRA */
  806. #if !defined(NO_CERTS) || (defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || \
  807. (!defined(NO_DH) && defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || \
  808. defined(HAVE_ECC)))
  809. /* Uses the DER SEQUENCE to determine size of DER data.
  810. *
  811. * Outer SEQUENCE encapsulates all the DER encoding.
  812. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  813. *
  814. * @param [in] seq Buffer holding DER encoded sequence.
  815. * @param [in] len Length of data in buffer (may be larger than SEQ).
  816. * @return Size of complete DER encoding on success.
  817. * @return 0 on failure.
  818. */
  819. static int wolfssl_der_length(const unsigned char* seq, int len)
  820. {
  821. int ret = 0;
  822. word32 i = 0;
  823. /* Check it is a SEQUENCE and get the length of the underlying data.
  824. * i is updated to be after SEQUENCE header bytes.
  825. */
  826. if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
  827. /* Add SEQUENCE header length to underlying data length. */
  828. ret += (int)i;
  829. }
  830. return ret;
  831. }
  832. #endif
  833. /*******************************************************************************
  834. * START OF RSA API
  835. ******************************************************************************/
  836. #ifndef NO_RSA
  837. /*
  838. * RSA METHOD
  839. * Could be used to hold function pointers to implementations of RSA operations.
  840. */
  841. #if defined(OPENSSL_EXTRA)
  842. /* Return a blank RSA method and set the name and flags.
  843. *
  844. * Only one implementation of RSA operations.
  845. * name is duplicated.
  846. *
  847. * @param [in] name Name to use in method.
  848. * @param [in] flags Flags to set into method.
  849. * @return Newly allocated RSA method on success.
  850. * @return NULL on failure.
  851. */
  852. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  853. {
  854. WOLFSSL_RSA_METHOD* meth = NULL;
  855. int name_len = 0;
  856. int err;
  857. /* Validate name is not NULL. */
  858. err = (name == NULL);
  859. if (!err) {
  860. /* Allocate an RSA METHOD to return. */
  861. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  862. DYNAMIC_TYPE_OPENSSL);
  863. err = (meth == NULL);
  864. }
  865. if (!err) {
  866. XMEMSET(meth, 0, sizeof(*meth));
  867. meth->flags = flags;
  868. meth->dynamic = 1;
  869. name_len = (int)XSTRLEN(name);
  870. meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL,
  871. DYNAMIC_TYPE_OPENSSL);
  872. err = (meth->name == NULL);
  873. }
  874. if (!err) {
  875. XMEMCPY(meth->name, name, (size_t)(name_len + 1));
  876. }
  877. if (err) {
  878. /* meth->name won't be allocated on error. */
  879. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  880. meth = NULL;
  881. }
  882. return meth;
  883. }
  884. /* Default RSA method is one with wolfSSL name and no flags.
  885. *
  886. * @return Newly allocated wolfSSL RSA method on success.
  887. * @return NULL on failure.
  888. */
  889. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  890. {
  891. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  892. 0, /* No flags. */
  893. (char*)"wolfSSL RSA",
  894. 0 /* Static definition. */
  895. };
  896. return &wolfssl_rsa_meth;
  897. }
  898. /* Dispose of RSA method and allocated data.
  899. *
  900. * @param [in] meth RSA method to free.
  901. */
  902. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  903. {
  904. /* Free method if available and dynamically allocated. */
  905. if ((meth != NULL) && meth->dynamic) {
  906. /* Name was duplicated and must be freed. */
  907. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  908. /* Dispose of RSA method. */
  909. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  910. }
  911. }
  912. #ifndef NO_WOLFSSL_STUB
  913. /* Stub function for any RSA method setting function.
  914. *
  915. * Nothing is stored - not even flags or name.
  916. *
  917. * @param [in] meth RSA method.
  918. * @param [in] p A pointer.
  919. * @return 1 to indicate success.
  920. */
  921. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  922. {
  923. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  924. (void)meth;
  925. (void)p;
  926. return 1;
  927. }
  928. #endif /* !NO_WOLFSSL_STUB */
  929. #endif /* OPENSSL_EXTRA */
  930. /*
  931. * RSA constructor/deconstructor APIs
  932. */
  933. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  934. /* Dispose of RSA key and allocated data.
  935. *
  936. * Cannot use rsa after this call.
  937. *
  938. * @param [in] rsa RSA key to free.
  939. */
  940. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  941. {
  942. int doFree = 1;
  943. WOLFSSL_ENTER("wolfSSL_RSA_free");
  944. /* Validate parameter. */
  945. if (rsa == NULL) {
  946. doFree = 0;
  947. }
  948. if (doFree) {
  949. int err;
  950. /* Decrement reference count. */
  951. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  952. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  953. (void)err;
  954. #endif
  955. }
  956. if (doFree) {
  957. void* heap = rsa->heap;
  958. /* Dispose of allocated reference counting data. */
  959. wolfSSL_RefFree(&rsa->ref);
  960. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  961. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  962. #endif
  963. if (rsa->internal != NULL) {
  964. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  965. /* Check if RNG is owned before freeing it. */
  966. if (rsa->ownRng) {
  967. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  968. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  969. wc_FreeRng(rng);
  970. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  971. }
  972. /* RNG isn't freed by wolfCrypt RSA free. */
  973. }
  974. #endif
  975. /* Dispose of allocated data in wolfCrypt RSA key. */
  976. wc_FreeRsaKey((RsaKey*)rsa->internal);
  977. /* Dispose of memory for wolfCrypt RSA key. */
  978. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  979. }
  980. /* Dispose of external representation of RSA values. */
  981. wolfSSL_BN_clear_free(rsa->iqmp);
  982. wolfSSL_BN_clear_free(rsa->dmq1);
  983. wolfSSL_BN_clear_free(rsa->dmp1);
  984. wolfSSL_BN_clear_free(rsa->q);
  985. wolfSSL_BN_clear_free(rsa->p);
  986. wolfSSL_BN_clear_free(rsa->d);
  987. wolfSSL_BN_free(rsa->e);
  988. wolfSSL_BN_free(rsa->n);
  989. #if defined(OPENSSL_EXTRA)
  990. if (rsa->meth) {
  991. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  992. }
  993. #endif
  994. /* Set back to NULLs for safety. */
  995. ForceZero(rsa, sizeof(*rsa));
  996. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  997. (void)heap;
  998. }
  999. }
  1000. /* Allocate and initialize a new RSA key.
  1001. *
  1002. * Not OpenSSL API.
  1003. *
  1004. * @param [in] heap Heap hint for dynamic memory allocation.
  1005. * @param [in] devId Device identifier value.
  1006. * @return RSA key on success.
  1007. * @return NULL on failure.
  1008. */
  1009. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  1010. {
  1011. WOLFSSL_RSA* rsa = NULL;
  1012. RsaKey* key = NULL;
  1013. int err = 0;
  1014. int rsaKeyInited = 0;
  1015. WOLFSSL_ENTER("wolfSSL_RSA_new");
  1016. /* Allocate memory for new wolfCrypt RSA key. */
  1017. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  1018. if (key == NULL) {
  1019. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  1020. err = 1;
  1021. }
  1022. if (!err) {
  1023. /* Allocate memory for new RSA key. */
  1024. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  1025. DYNAMIC_TYPE_RSA);
  1026. if (rsa == NULL) {
  1027. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  1028. err = 1;
  1029. }
  1030. }
  1031. if (!err) {
  1032. /* Clear all fields of RSA key. */
  1033. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  1034. /* Cache heap to use for all allocations. */
  1035. rsa->heap = heap;
  1036. #ifdef OPENSSL_EXTRA
  1037. /* Always have a method set. */
  1038. rsa->meth = wolfSSL_RSA_get_default_method();
  1039. #endif
  1040. /* Initialize reference counting. */
  1041. wolfSSL_RefInit(&rsa->ref, &err);
  1042. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  1043. }
  1044. if (!err) {
  1045. #endif
  1046. /* Initialize wolfCrypt RSA key. */
  1047. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  1048. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  1049. err = 1;
  1050. }
  1051. else {
  1052. rsaKeyInited = 1;
  1053. }
  1054. }
  1055. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  1056. if (!err) {
  1057. WC_RNG* rng;
  1058. /* Create a local RNG. */
  1059. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  1060. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  1061. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  1062. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  1063. rng = NULL;
  1064. }
  1065. rsa->ownRng = 1;
  1066. if (rng == NULL) {
  1067. /* Get the wolfSSL global RNG - not thread safe. */
  1068. rng = wolfssl_get_global_rng();
  1069. rsa->ownRng = 0;
  1070. }
  1071. if (rng == NULL) {
  1072. /* Couldn't create global either. */
  1073. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  1074. err = 1;
  1075. }
  1076. else {
  1077. /* Set the local or global RNG into the wolfCrypt RSA key. */
  1078. (void)wc_RsaSetRNG(key, rng);
  1079. /* Won't fail as key and rng are not NULL. */
  1080. }
  1081. }
  1082. #endif /* !HAVE_FIPS && WC_RSA_BLINDING */
  1083. if (!err) {
  1084. /* Set wolfCrypt RSA key into RSA key. */
  1085. rsa->internal = key;
  1086. /* Data from external RSA key has not been set into internal one. */
  1087. rsa->inSet = 0;
  1088. }
  1089. if (err) {
  1090. /* Dispose of any allocated data on error. */
  1091. /* No failure after RNG allocation - no need to free RNG. */
  1092. if (rsaKeyInited) {
  1093. wc_FreeRsaKey(key);
  1094. }
  1095. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  1096. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  1097. /* Return NULL. */
  1098. rsa = NULL;
  1099. }
  1100. return rsa;
  1101. }
  1102. /* Allocate and initialize a new RSA key.
  1103. *
  1104. * @return RSA key on success.
  1105. * @return NULL on failure.
  1106. */
  1107. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  1108. {
  1109. /* Call wolfSSL API to do work. */
  1110. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  1111. }
  1112. /* Increments ref count of RSA key.
  1113. *
  1114. * @param [in, out] rsa RSA key.
  1115. * @return 1 on success
  1116. * @return 0 on error
  1117. */
  1118. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  1119. {
  1120. int err = 0;
  1121. if (rsa != NULL) {
  1122. wolfSSL_RefInc(&rsa->ref, &err);
  1123. }
  1124. return !err;
  1125. }
  1126. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1127. #ifdef OPENSSL_EXTRA
  1128. #if defined(WOLFSSL_KEY_GEN)
  1129. /* Allocate a new RSA key and make it a copy.
  1130. *
  1131. * Encodes to and from DER to copy.
  1132. *
  1133. * @param [in] rsa RSA key to duplicate.
  1134. * @return RSA key on success.
  1135. * @return NULL on error.
  1136. */
  1137. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1138. {
  1139. WOLFSSL_RSA* ret = NULL;
  1140. int derSz = 0;
  1141. byte* derBuf = NULL;
  1142. int err;
  1143. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1144. err = (rsa == NULL);
  1145. if (!err) {
  1146. /* Create a new RSA key to return. */
  1147. ret = wolfSSL_RSA_new();
  1148. if (ret == NULL) {
  1149. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1150. err = 1;
  1151. }
  1152. }
  1153. if (!err) {
  1154. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1155. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1156. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1157. err = 1;
  1158. }
  1159. }
  1160. if (!err) {
  1161. /* Decode DER of the RSA public key into new key. */
  1162. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1163. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1164. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1165. err = 1;
  1166. }
  1167. }
  1168. /* Dispose of any allocated DER buffer. */
  1169. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1170. if (err) {
  1171. /* Disposes of any created RSA key - on error. */
  1172. wolfSSL_RSA_free(ret);
  1173. ret = NULL;
  1174. }
  1175. return ret;
  1176. }
  1177. /* wolfSSL_RSAPrivateKey_dup not supported */
  1178. #endif /* WOLFSSL_KEY_GEN */
  1179. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1180. void* heap);
  1181. /*
  1182. * RSA to/from bin APIs
  1183. */
  1184. /* Convert RSA public key data to internal.
  1185. *
  1186. * Creates new RSA key from the DER encoded RSA public key.
  1187. *
  1188. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1189. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1190. * @param [in] derSz Length of the data in the DER buffer.
  1191. * @return RSA key on success.
  1192. * @return NULL on failure.
  1193. */
  1194. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1195. const unsigned char **derBuf, long derSz)
  1196. {
  1197. WOLFSSL_RSA *rsa = NULL;
  1198. int err = 0;
  1199. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1200. /* Validate parameters. */
  1201. if (derBuf == NULL) {
  1202. WOLFSSL_ERROR_MSG("Bad argument");
  1203. err = 1;
  1204. }
  1205. /* Create a new RSA key to return. */
  1206. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1207. WOLFSSL_ERROR_MSG("RSA_new failed");
  1208. err = 1;
  1209. }
  1210. /* Decode RSA key from DER. */
  1211. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1212. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1213. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1214. err = 1;
  1215. }
  1216. if ((!err) && (out != NULL)) {
  1217. /* Return through parameter too. */
  1218. *out = rsa;
  1219. /* Move buffer on by the used amount. */
  1220. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1221. }
  1222. if (err) {
  1223. /* Dispose of any created RSA key. */
  1224. wolfSSL_RSA_free(rsa);
  1225. rsa = NULL;
  1226. }
  1227. return rsa;
  1228. }
  1229. /* Convert RSA private key data to internal.
  1230. *
  1231. * Create a new RSA key from the DER encoded RSA private key.
  1232. *
  1233. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1234. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1235. * @param [in] derSz Length of the data in the DER buffer.
  1236. * @return RSA key on success.
  1237. * @return NULL on failure.
  1238. */
  1239. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1240. const unsigned char **derBuf, long derSz)
  1241. {
  1242. WOLFSSL_RSA *rsa = NULL;
  1243. int err = 0;
  1244. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1245. /* Validate parameters. */
  1246. if (derBuf == NULL) {
  1247. WOLFSSL_ERROR_MSG("Bad argument");
  1248. err = 1;
  1249. }
  1250. /* Create a new RSA key to return. */
  1251. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1252. WOLFSSL_ERROR_MSG("RSA_new failed");
  1253. err = 1;
  1254. }
  1255. /* Decode RSA key from DER. */
  1256. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1257. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1258. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1259. err = 1;
  1260. }
  1261. if ((!err) && (out != NULL)) {
  1262. /* Return through parameter too. */
  1263. *out = rsa;
  1264. /* Move buffer on by the used amount. */
  1265. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1266. }
  1267. if (err) {
  1268. /* Dispose of any created RSA key. */
  1269. wolfSSL_RSA_free(rsa);
  1270. rsa = NULL;
  1271. }
  1272. return rsa;
  1273. }
  1274. /* Converts an internal RSA structure to DER format for the private key.
  1275. *
  1276. * If "pp" is null then buffer size only is returned.
  1277. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1278. * responsible for free'ing it.
  1279. *
  1280. * @param [in] rsa RSA key.
  1281. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1282. * May be NULL.
  1283. * On out, newly allocated buffer or pointer to byte after
  1284. * encoding in passed in buffer.
  1285. *
  1286. * @return Size of DER encoding on success
  1287. * @return BAD_FUNC_ARG when rsa is NULL.
  1288. * @return 0 on failure.
  1289. */
  1290. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1291. {
  1292. int ret;
  1293. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1294. /* Validate parameters. */
  1295. if (rsa == NULL) {
  1296. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1297. ret = BAD_FUNC_ARG;
  1298. }
  1299. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1300. * No heap hint as this gets returned to the user */
  1301. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1302. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1303. ret = 0;
  1304. }
  1305. /* Size of DER encoding. */
  1306. return ret;
  1307. }
  1308. /* Converts an internal RSA structure to DER format for the public key.
  1309. *
  1310. * If "pp" is null then buffer size only is returned.
  1311. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1312. * responsible for free'ing it.
  1313. *
  1314. * @param [in] rsa RSA key.
  1315. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1316. * May be NULL.
  1317. * On out, newly allocated buffer or pointer to byte after
  1318. * encoding in passed in buffer.
  1319. * @return Size of DER encoding on success
  1320. * @return BAD_FUNC_ARG when rsa is NULL.
  1321. * @return 0 on failure.
  1322. */
  1323. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1324. {
  1325. int ret;
  1326. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1327. /* check for bad functions arguments */
  1328. if (rsa == NULL) {
  1329. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1330. ret = BAD_FUNC_ARG;
  1331. }
  1332. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1333. * No heap hint as this gets returned to the user */
  1334. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1335. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1336. ret = 0;
  1337. }
  1338. return ret;
  1339. }
  1340. #endif /* OPENSSL_EXTRA */
  1341. /*
  1342. * RSA to/from BIO APIs
  1343. */
  1344. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1345. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1346. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1347. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_BIO)
  1348. /* Read DER data from a BIO.
  1349. *
  1350. * DER structures start with a constructed sequence. Use this to calculate the
  1351. * total length of the DER data.
  1352. *
  1353. * @param [in] bio BIO object to read from.
  1354. * @param [out] out Buffer holding DER encoding.
  1355. * @return Number of bytes to DER encoding on success.
  1356. * @return 0 on failure.
  1357. */
  1358. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1359. {
  1360. int err = 0;
  1361. unsigned char seq[MAX_SEQ_SZ];
  1362. unsigned char* der = NULL;
  1363. int derLen = 0;
  1364. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1365. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1366. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1367. err = 1;
  1368. }
  1369. /* Calculate complete DER encoding length. */
  1370. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1371. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1372. err = 1;
  1373. }
  1374. /* Allocate a buffer to read DER data into. */
  1375. if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap,
  1376. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1377. WOLFSSL_ERROR_MSG("Malloc failure");
  1378. err = 1;
  1379. }
  1380. if (!err) {
  1381. /* Calculate the unread amount. */
  1382. int len = derLen - (int)sizeof(seq);
  1383. /* Copy the previously read data into the buffer. */
  1384. XMEMCPY(der, seq, sizeof(seq));
  1385. /* Read rest of DER data from BIO. */
  1386. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1387. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1388. err = 1;
  1389. }
  1390. }
  1391. if (!err) {
  1392. /* Return buffer through parameter. */
  1393. *out = der;
  1394. }
  1395. if (err) {
  1396. /* Dispose of any allocated buffer on error. */
  1397. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1398. derLen = 0;
  1399. }
  1400. return derLen;
  1401. }
  1402. /* Reads the RSA private key data from a BIO to the internal form.
  1403. *
  1404. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1405. *
  1406. * @param [in] bio BIO object to read from.
  1407. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1408. * @return RSA key on success.
  1409. * @return NULL on failure.
  1410. */
  1411. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1412. {
  1413. WOLFSSL_RSA* key = NULL;
  1414. unsigned char* der = NULL;
  1415. int derLen = 0;
  1416. int err;
  1417. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1418. /* Validate parameters. */
  1419. err = (bio == NULL);
  1420. /* Read just DER encoding from BIO - buffer allocated in call. */
  1421. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1422. err = 1;
  1423. }
  1424. if (!err) {
  1425. /* Keep der for call to deallocate. */
  1426. const unsigned char* cder = der;
  1427. /* Create an RSA key from the data from the BIO. */
  1428. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1429. err = (key == NULL);
  1430. }
  1431. if ((!err) && (out != NULL)) {
  1432. /* Return the created RSA key through the parameter. */
  1433. *out = key;
  1434. }
  1435. if (err) {
  1436. /* Dispose of created key on error. */
  1437. wolfSSL_RSA_free(key);
  1438. key = NULL;
  1439. }
  1440. /* Dispose of allocated data. */
  1441. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1442. return key;
  1443. }
  1444. #endif /* defined(WOLFSSL_KEY_GEN) && !NO_BIO */
  1445. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1446. /*
  1447. * RSA DER APIs
  1448. */
  1449. #ifdef OPENSSL_EXTRA
  1450. /* Create a DER encoding of key.
  1451. *
  1452. * Not OpenSSL API.
  1453. *
  1454. * @param [in] rsa RSA key.
  1455. * @param [out] outBuf Allocated buffer containing DER encoding.
  1456. * May be NULL.
  1457. * @param [in] publicKey Whether to encode as public key.
  1458. * @param [in] heap Heap hint.
  1459. * @return Encoding size on success.
  1460. * @return Negative on failure.
  1461. */
  1462. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1463. void* heap)
  1464. {
  1465. byte* p = NULL;
  1466. int ret;
  1467. if (outBuf != NULL) {
  1468. p = *outBuf;
  1469. }
  1470. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1471. if ((ret > 0) && (p != NULL)) {
  1472. *outBuf = p;
  1473. }
  1474. return ret;
  1475. }
  1476. /* Create a DER encoding of key.
  1477. *
  1478. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1479. *
  1480. * @param [in] rsa RSA key.
  1481. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1482. * May be NULL.
  1483. * On out, newly allocated buffer or pointer to byte
  1484. * after encoding in passed in buffer.
  1485. * @param [in] publicKey Whether to encode as public key.
  1486. * @param [in] heap Heap hint.
  1487. * @return Encoding size on success.
  1488. * @return Negative on failure.
  1489. */
  1490. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1491. void* heap)
  1492. {
  1493. int ret = 1;
  1494. int derSz = 0;
  1495. byte* derBuf = NULL;
  1496. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1497. /* Unused if memory is disabled. */
  1498. (void)heap;
  1499. /* Validate parameters. */
  1500. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1501. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1502. ret = BAD_FUNC_ARG;
  1503. }
  1504. /* Push external RSA data into internal RSA key if not set. */
  1505. if ((ret == 1) && (!rsa->inSet)) {
  1506. ret = SetRsaInternal(rsa);
  1507. }
  1508. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1509. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1510. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1511. ret = BAD_FUNC_ARG;
  1512. }
  1513. if (ret == 1) {
  1514. if (publicKey) {
  1515. /* Calculate length of DER encoded RSA public key. */
  1516. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1517. if (derSz < 0) {
  1518. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1519. ret = derSz;
  1520. }
  1521. }
  1522. else {
  1523. /* Calculate length of DER encoded RSA private key. */
  1524. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1525. if (derSz < 0) {
  1526. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1527. ret = derSz;
  1528. }
  1529. }
  1530. }
  1531. if ((ret == 1) && (outBuf != NULL)) {
  1532. derBuf = *outBuf;
  1533. if (derBuf == NULL) {
  1534. /* Allocate buffer to hold DER encoded RSA key. */
  1535. derBuf = (byte*)XMALLOC((size_t)derSz, heap,
  1536. DYNAMIC_TYPE_TMP_BUFFER);
  1537. if (derBuf == NULL) {
  1538. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1539. ret = MEMORY_ERROR;
  1540. }
  1541. }
  1542. }
  1543. if ((ret == 1) && (outBuf != NULL)) {
  1544. if (publicKey > 0) {
  1545. /* RSA public key to DER. */
  1546. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf,
  1547. (word32)derSz);
  1548. }
  1549. else {
  1550. /* RSA private key to DER. */
  1551. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf,
  1552. (word32)derSz);
  1553. }
  1554. if (derSz < 0) {
  1555. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1556. ret = derSz;
  1557. }
  1558. else if ((*outBuf) != NULL) {
  1559. derBuf = NULL;
  1560. *outBuf += derSz;
  1561. }
  1562. else {
  1563. /* Return allocated buffer. */
  1564. *outBuf = derBuf;
  1565. }
  1566. }
  1567. if (ret == 1) {
  1568. /* Success - return DER encoding size. */
  1569. ret = derSz;
  1570. }
  1571. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1572. /* Not returning buffer, needs to be disposed of. */
  1573. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1574. }
  1575. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1576. return ret;
  1577. }
  1578. #endif /* OPENSSL_EXTRA */
  1579. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1580. /* Load the DER encoded private RSA key.
  1581. *
  1582. * Not OpenSSL API.
  1583. *
  1584. * @param [in] rsa RSA key.
  1585. * @param [in] derBuf Buffer holding DER encoding.
  1586. * @param [in] derSz Length of DER encoding.
  1587. * @return 1 on success.
  1588. * @return -1 on failure.
  1589. */
  1590. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1591. int derSz)
  1592. {
  1593. /* Call implementation that handles both private and public keys. */
  1594. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1595. }
  1596. /* Load the DER encoded public or private RSA key.
  1597. *
  1598. * Not OpenSSL API.
  1599. *
  1600. * @param [in] rsa RSA key.
  1601. * @param [in] derBuf Buffer holding DER encoding.
  1602. * @param [in] derSz Length of DER encoding.
  1603. * @param [in] opt Indicates public or private key.
  1604. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1605. * @return 1 on success.
  1606. * @return -1 on failure.
  1607. */
  1608. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1609. int derSz, int opt)
  1610. {
  1611. int ret = 1;
  1612. int res;
  1613. word32 idx = 0;
  1614. word32 algId;
  1615. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1616. /* Validate parameters. */
  1617. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1618. (derSz <= 0)) {
  1619. WOLFSSL_ERROR_MSG("Bad function arguments");
  1620. ret = WOLFSSL_FATAL_ERROR;
  1621. }
  1622. if (ret == 1) {
  1623. rsa->pkcs8HeaderSz = 0;
  1624. /* Check if input buffer has PKCS8 header. In the case that it does not
  1625. * have a PKCS8 header then do not error out. */
  1626. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1627. &algId);
  1628. if (res > 0) {
  1629. /* Store size of PKCS#8 header for encoding. */
  1630. WOLFSSL_MSG("Found PKCS8 header");
  1631. rsa->pkcs8HeaderSz = (word16)idx;
  1632. }
  1633. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1634. else if (res != WC_NO_ERR_TRACE(ASN_PARSE_E)) {
  1635. /* Something went wrong while decoding. */
  1636. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1637. "header");
  1638. ret = WOLFSSL_FATAL_ERROR;
  1639. }
  1640. }
  1641. if (ret == 1) {
  1642. /* Decode private or public key data. */
  1643. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1644. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1645. (word32)derSz);
  1646. }
  1647. else {
  1648. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1649. (word32)derSz);
  1650. }
  1651. /* Check for error. */
  1652. if (res < 0) {
  1653. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1654. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1655. }
  1656. else {
  1657. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1658. }
  1659. WOLFSSL_ERROR_VERBOSE(res);
  1660. ret = WOLFSSL_FATAL_ERROR;
  1661. }
  1662. }
  1663. if (ret == 1) {
  1664. /* Set external RSA key data from wolfCrypt key. */
  1665. if (SetRsaExternal(rsa) != 1) {
  1666. ret = WOLFSSL_FATAL_ERROR;
  1667. }
  1668. else {
  1669. rsa->inSet = 1;
  1670. }
  1671. }
  1672. return ret;
  1673. }
  1674. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1675. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1676. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1677. /* Load DER encoded data into WOLFSSL_RSA object.
  1678. *
  1679. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1680. *
  1681. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1682. * When rsa or *rsa is NULL a new object is created.
  1683. * When not NULL and *rsa is NULL then new object
  1684. * returned through pointer.
  1685. * @param [in] in DER encoded RSA key data.
  1686. * @param [in] inSz Size of DER encoded data in bytes.
  1687. * @param [in] opt Public or private key encoded in data. Valid values:
  1688. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1689. * @return NULL on failure.
  1690. * @return WOLFSSL_RSA object on success.
  1691. */
  1692. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1693. long inSz, int opt)
  1694. {
  1695. WOLFSSL_RSA* ret = NULL;
  1696. if ((rsa != NULL) && (*rsa != NULL)) {
  1697. ret = *rsa;
  1698. }
  1699. else {
  1700. ret = wolfSSL_RSA_new();
  1701. }
  1702. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1703. != 1)) {
  1704. if ((rsa == NULL) || (ret != *rsa)) {
  1705. wolfSSL_RSA_free(ret);
  1706. }
  1707. ret = NULL;
  1708. }
  1709. if ((rsa != NULL) && (*rsa == NULL)) {
  1710. *rsa = ret;
  1711. }
  1712. return ret;
  1713. }
  1714. #endif
  1715. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1716. /*
  1717. * RSA PEM APIs
  1718. */
  1719. #ifdef OPENSSL_EXTRA
  1720. #ifndef NO_BIO
  1721. #if defined(WOLFSSL_KEY_GEN)
  1722. /* Writes PEM encoding of an RSA public key to a BIO.
  1723. *
  1724. * @param [in] bio BIO object to write to.
  1725. * @param [in] rsa RSA key to write.
  1726. * @return 1 on success.
  1727. * @return 0 on failure.
  1728. */
  1729. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1730. {
  1731. int ret = 1;
  1732. int derSz = 0;
  1733. byte* derBuf = NULL;
  1734. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1735. /* Validate parameters. */
  1736. if ((bio == NULL) || (rsa == NULL)) {
  1737. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1738. return 0;
  1739. }
  1740. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1741. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1742. ret = 0;
  1743. }
  1744. if (derBuf == NULL) {
  1745. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1746. ret = 0;
  1747. }
  1748. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1749. PUBLICKEY_TYPE) != 1)) {
  1750. ret = 0;
  1751. }
  1752. /* Dispose of DER buffer. */
  1753. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1754. return ret;
  1755. }
  1756. #endif /* WOLFSSL_KEY_GEN */
  1757. #endif /* !NO_BIO */
  1758. #if defined(WOLFSSL_KEY_GEN)
  1759. #ifndef NO_FILESYSTEM
  1760. /* Writes PEM encoding of an RSA public key to a file pointer.
  1761. *
  1762. * @param [in] fp File pointer to write to.
  1763. * @param [in] rsa RSA key to write.
  1764. * @param [in] type PEM type to write out.
  1765. * @return 1 on success.
  1766. * @return 0 on failure.
  1767. */
  1768. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1769. int type)
  1770. {
  1771. int ret = 1;
  1772. int derSz;
  1773. byte* derBuf = NULL;
  1774. /* Validate parameters. */
  1775. if ((fp == XBADFILE) || (rsa == NULL)) {
  1776. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1777. return 0;
  1778. }
  1779. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1780. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1781. ret = 0;
  1782. }
  1783. if (derBuf == NULL) {
  1784. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1785. ret = 0;
  1786. }
  1787. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1788. rsa->heap) != 1)) {
  1789. ret = 0;
  1790. }
  1791. /* Dispose of DER buffer. */
  1792. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1793. return ret;
  1794. }
  1795. /* Writes PEM encoding of an RSA public key to a file pointer.
  1796. *
  1797. * Header/footer will contain: PUBLIC KEY
  1798. *
  1799. * @param [in] fp File pointer to write to.
  1800. * @param [in] rsa RSA key to write.
  1801. * @return 1 on success.
  1802. * @return 0 on failure.
  1803. */
  1804. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1805. {
  1806. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1807. }
  1808. /* Writes PEM encoding of an RSA public key to a file pointer.
  1809. *
  1810. * Header/footer will contain: RSA PUBLIC KEY
  1811. *
  1812. * @param [in] fp File pointer to write to.
  1813. * @param [in] rsa RSA key to write.
  1814. * @return 1 on success.
  1815. * @return 0 on failure.
  1816. */
  1817. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1818. {
  1819. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1820. }
  1821. #endif /* !NO_FILESYSTEM */
  1822. #endif /* WOLFSSL_KEY_GEN */
  1823. #ifndef NO_BIO
  1824. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1825. *
  1826. * @param [in] bio BIO object to read from.
  1827. * @param [out] out RSA key created.
  1828. * @param [in] cb Password callback when PEM encrypted.
  1829. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1830. * @return RSA key on success.
  1831. * @return NULL on failure.
  1832. */
  1833. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1834. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1835. {
  1836. WOLFSSL_RSA* rsa = NULL;
  1837. DerBuffer* der = NULL;
  1838. int keyFormat = 0;
  1839. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1840. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1841. &keyFormat, &der) >= 0)) {
  1842. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1843. WOLFSSL_RSA_LOAD_PUBLIC);
  1844. if (rsa == NULL) {
  1845. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1846. }
  1847. }
  1848. FreeDer(&der);
  1849. if ((out != NULL) && (rsa != NULL)) {
  1850. *out = rsa;
  1851. }
  1852. return rsa;
  1853. }
  1854. WOLFSSL_RSA *wolfSSL_d2i_RSA_PUBKEY_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1855. {
  1856. char* data = NULL;
  1857. int dataSz = 0;
  1858. int memAlloced = 0;
  1859. WOLFSSL_RSA* rsa = NULL;
  1860. WOLFSSL_ENTER("wolfSSL_d2i_RSA_PUBKEY_bio");
  1861. if (bio == NULL)
  1862. return NULL;
  1863. if (wolfssl_read_bio(bio, &data, &dataSz, &memAlloced) != 0) {
  1864. if (memAlloced)
  1865. XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1866. return NULL;
  1867. }
  1868. rsa = wolfssl_rsa_d2i(out, (const unsigned char*)data, dataSz,
  1869. WOLFSSL_RSA_LOAD_PUBLIC);
  1870. if (memAlloced)
  1871. XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1872. return rsa;
  1873. }
  1874. #endif /* !NO_BIO */
  1875. #ifndef NO_FILESYSTEM
  1876. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1877. *
  1878. * Header/footer should contain: PUBLIC KEY
  1879. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1880. *
  1881. * @param [in] fp File pointer to read from.
  1882. * @param [out] out RSA key created.
  1883. * @param [in] cb Password callback when PEM encrypted.
  1884. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1885. * @return RSA key on success.
  1886. * @return NULL on failure.
  1887. */
  1888. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1889. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1890. {
  1891. WOLFSSL_RSA* rsa = NULL;
  1892. DerBuffer* der = NULL;
  1893. int keyFormat = 0;
  1894. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1895. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1896. &keyFormat, &der) >= 0)) {
  1897. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1898. WOLFSSL_RSA_LOAD_PUBLIC);
  1899. if (rsa == NULL) {
  1900. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1901. }
  1902. }
  1903. FreeDer(&der);
  1904. if ((out != NULL) && (rsa != NULL)) {
  1905. *out = rsa;
  1906. }
  1907. return rsa;
  1908. }
  1909. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1910. *
  1911. * Header/footer should contain: RSA PUBLIC KEY
  1912. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1913. *
  1914. * @param [in] fp File pointer to read from.
  1915. * @param [out] rsa RSA key created.
  1916. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1917. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1918. * May be NULL.
  1919. * @return RSA key on success.
  1920. * @return NULL on failure.
  1921. */
  1922. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1923. wc_pem_password_cb* cb, void* pass)
  1924. {
  1925. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1926. }
  1927. #endif /* NO_FILESYSTEM */
  1928. #if defined(WOLFSSL_KEY_GEN) && \
  1929. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1930. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1931. *
  1932. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1933. *
  1934. * @param [in] rsa RSA key to write.
  1935. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1936. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1937. * @param [in] passwdSz Length of password string when PEM encrypted.
  1938. * @param [out] pem Allocated buffer with PEM encoding.
  1939. * @param [out] pLen Length of PEM encoding.
  1940. * @return 1 on success.
  1941. * @return 0 on failure.
  1942. */
  1943. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1944. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1945. {
  1946. int ret = 1;
  1947. byte* derBuf = NULL;
  1948. int derSz = 0;
  1949. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1950. /* Validate parameters. */
  1951. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1952. (rsa->internal == NULL)) {
  1953. WOLFSSL_ERROR_MSG("Bad function arguments");
  1954. ret = 0;
  1955. }
  1956. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1957. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1958. ret = 0;
  1959. }
  1960. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1961. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1962. rsa->heap)) < 0)) {
  1963. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1964. ret = 0;
  1965. }
  1966. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1967. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1968. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1969. ret = 0;
  1970. }
  1971. return ret;
  1972. }
  1973. #ifndef NO_BIO
  1974. /* Writes PEM encoding of an RSA private key to a BIO.
  1975. *
  1976. * @param [in] bio BIO object to write to.
  1977. * @param [in] rsa RSA key to write.
  1978. * @param [in] cipher Cipher to use when PEM encrypted.
  1979. * @param [in] passwd Password string when PEM encrypted.
  1980. * @param [in] len Length of password string when PEM encrypted.
  1981. * @param [in] cb Password callback to use when PEM encrypted.
  1982. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1983. * @return 1 on success.
  1984. * @return 0 on failure.
  1985. */
  1986. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1987. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1988. wc_pem_password_cb* cb, void* arg)
  1989. {
  1990. int ret = 1;
  1991. byte* pem = NULL;
  1992. int pLen = 0;
  1993. (void)cb;
  1994. (void)arg;
  1995. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1996. /* Validate parameters. */
  1997. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1998. WOLFSSL_ERROR_MSG("Bad function arguments");
  1999. ret = 0;
  2000. }
  2001. if (ret == 1) {
  2002. /* Write PEM to buffer that is allocated in the call. */
  2003. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  2004. &pem, &pLen);
  2005. if (ret != 1) {
  2006. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  2007. }
  2008. }
  2009. /* Write PEM to BIO. */
  2010. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  2011. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  2012. ret = 0;
  2013. }
  2014. /* Dispose of any allocated PEM buffer. */
  2015. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  2016. return ret;
  2017. }
  2018. #endif /* !NO_BIO */
  2019. #ifndef NO_FILESYSTEM
  2020. /* Writes PEM encoding of an RSA private key to a file pointer.
  2021. *
  2022. * TODO: Support use of the password callback and callback context.
  2023. *
  2024. * @param [in] fp File pointer to write to.
  2025. * @param [in] rsa RSA key to write.
  2026. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  2027. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  2028. * @param [in] passwdSz Length of password string when PEM encrypted.
  2029. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  2030. * @param [in] arg NUL terminated string for passphrase when PEM
  2031. * encrypted. Unused.
  2032. * @return 1 on success.
  2033. * @return 0 on failure.
  2034. */
  2035. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  2036. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  2037. wc_pem_password_cb *cb, void *arg)
  2038. {
  2039. int ret = 1;
  2040. byte* pem = NULL;
  2041. int pLen = 0;
  2042. (void)cb;
  2043. (void)arg;
  2044. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  2045. /* Validate parameters. */
  2046. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  2047. WOLFSSL_ERROR_MSG("Bad function arguments");
  2048. ret = 0;
  2049. }
  2050. if (ret == 1) {
  2051. /* Write PEM to buffer that is allocated in the call. */
  2052. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  2053. &pem, &pLen);
  2054. if (ret != 1) {
  2055. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  2056. }
  2057. }
  2058. /* Write PEM to file pointer. */
  2059. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  2060. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  2061. ret = 0;
  2062. }
  2063. /* Dispose of any allocated PEM buffer. */
  2064. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  2065. return ret;
  2066. }
  2067. #endif /* NO_FILESYSTEM */
  2068. #endif /* WOLFSSL_KEY_GEN && WOLFSSL_PEM_TO_DER */
  2069. #ifndef NO_BIO
  2070. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  2071. *
  2072. * @param [in] bio BIO object to read from.
  2073. * @param [out] out RSA key created.
  2074. * @param [in] cb Password callback when PEM encrypted.
  2075. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2076. * @return RSA key on success.
  2077. * @return NULL on failure.
  2078. */
  2079. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  2080. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  2081. {
  2082. WOLFSSL_RSA* rsa = NULL;
  2083. DerBuffer* der = NULL;
  2084. int keyFormat = 0;
  2085. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  2086. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  2087. &keyFormat, &der) >= 0)) {
  2088. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2089. WOLFSSL_RSA_LOAD_PRIVATE);
  2090. if (rsa == NULL) {
  2091. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2092. }
  2093. }
  2094. FreeDer(&der);
  2095. if ((out != NULL) && (rsa != NULL)) {
  2096. *out = rsa;
  2097. }
  2098. return rsa;
  2099. }
  2100. #endif /* !NO_BIO */
  2101. /* Create an RSA private key by reading the PEM encoded data from the file
  2102. * pointer.
  2103. *
  2104. * @param [in] fp File pointer to read from.
  2105. * @param [out] out RSA key created.
  2106. * @param [in] cb Password callback when PEM encrypted.
  2107. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2108. * @return RSA key on success.
  2109. * @return NULL on failure.
  2110. */
  2111. #ifndef NO_FILESYSTEM
  2112. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  2113. wc_pem_password_cb* cb, void* pass)
  2114. {
  2115. WOLFSSL_RSA* rsa = NULL;
  2116. DerBuffer* der = NULL;
  2117. int keyFormat = 0;
  2118. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  2119. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  2120. &keyFormat, &der) >= 0)) {
  2121. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2122. WOLFSSL_RSA_LOAD_PRIVATE);
  2123. if (rsa == NULL) {
  2124. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2125. }
  2126. }
  2127. FreeDer(&der);
  2128. if ((out != NULL) && (rsa != NULL)) {
  2129. *out = rsa;
  2130. }
  2131. return rsa;
  2132. }
  2133. #endif /* !NO_FILESYSTEM */
  2134. /*
  2135. * RSA print APIs
  2136. */
  2137. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  2138. !defined(NO_STDIO_FILESYSTEM)
  2139. /* Print an RSA key to a file pointer.
  2140. *
  2141. * @param [in] fp File pointer to write to.
  2142. * @param [in] rsa RSA key to write.
  2143. * @param [in] indent Number of spaces to prepend to each line.
  2144. * @return 1 on success.
  2145. * @return 0 on failure.
  2146. */
  2147. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2148. {
  2149. int ret = 1;
  2150. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2151. /* Validate parameters. */
  2152. if ((fp == XBADFILE) || (rsa == NULL)) {
  2153. ret = 0;
  2154. }
  2155. /* Set the external data from the wolfCrypt RSA key if not done. */
  2156. if ((ret == 1) && (!rsa->exSet)) {
  2157. ret = SetRsaExternal(rsa);
  2158. }
  2159. /* Get the key size from modulus if available. */
  2160. if ((ret == 1) && (rsa->n != NULL)) {
  2161. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2162. if (keySize == 0) {
  2163. ret = 0;
  2164. }
  2165. else {
  2166. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2167. ret = 0;
  2168. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2169. keySize) < 0)
  2170. ret = 0;
  2171. }
  2172. }
  2173. /* Print out any components available. */
  2174. if ((ret == 1) && (rsa->n != NULL)) {
  2175. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2176. }
  2177. if ((ret == 1) && (rsa->d != NULL)) {
  2178. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2179. }
  2180. if ((ret == 1) && (rsa->p != NULL)) {
  2181. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2182. }
  2183. if ((ret == 1) && (rsa->q != NULL)) {
  2184. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2185. }
  2186. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2187. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2188. }
  2189. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2190. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2191. }
  2192. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2193. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2194. }
  2195. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2196. return ret;
  2197. }
  2198. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2199. #if defined(XSNPRINTF) && !defined(NO_BIO)
  2200. /* snprintf() must be available */
  2201. /* Maximum size of a header line. */
  2202. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2203. /* Writes the human readable form of RSA to a BIO.
  2204. *
  2205. * @param [in] bio BIO object to write to.
  2206. * @param [in] rsa RSA key to write.
  2207. * @param [in] indent Number of spaces before each line.
  2208. * @return 1 on success.
  2209. * @return 0 on failure.
  2210. */
  2211. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2212. {
  2213. int ret = 1;
  2214. int sz = 0;
  2215. RsaKey* key = NULL;
  2216. char line[RSA_PRINT_MAX_HEADER_LINE];
  2217. int i = 0;
  2218. mp_int *num = NULL;
  2219. /* Header strings. */
  2220. const char *name[] = {
  2221. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2222. "Exponent1:", "Exponent2:", "Coefficient:"
  2223. };
  2224. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2225. /* Validate parameters. */
  2226. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2227. ret = WOLFSSL_FATAL_ERROR;
  2228. }
  2229. if (ret == 1) {
  2230. key = (RsaKey*)rsa->internal;
  2231. /* Get size in bits of key for printing out. */
  2232. sz = wolfSSL_RSA_bits(rsa);
  2233. if (sz <= 0) {
  2234. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2235. ret = 0;
  2236. }
  2237. }
  2238. if (ret == 1) {
  2239. /* Print any indent spaces. */
  2240. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2241. }
  2242. if (ret == 1) {
  2243. /* Print header line. */
  2244. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2245. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2246. if (len >= (int)sizeof(line)) {
  2247. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2248. ret = 0;
  2249. }
  2250. else {
  2251. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2252. ret = 0;
  2253. }
  2254. }
  2255. }
  2256. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2257. /* Get mp_int for index. */
  2258. switch (i) {
  2259. case 0:
  2260. /* Print out modulus */
  2261. num = &key->n;
  2262. break;
  2263. case 1:
  2264. num = &key->e;
  2265. break;
  2266. case 2:
  2267. num = &key->d;
  2268. break;
  2269. case 3:
  2270. num = &key->p;
  2271. break;
  2272. case 4:
  2273. num = &key->q;
  2274. break;
  2275. case 5:
  2276. num = &key->dP;
  2277. break;
  2278. case 6:
  2279. num = &key->dQ;
  2280. break;
  2281. case 7:
  2282. num = &key->u;
  2283. break;
  2284. default:
  2285. WOLFSSL_ERROR_MSG("Bad index value");
  2286. }
  2287. if (i == 1) {
  2288. /* Print exponent as a 32-bit value. */
  2289. ret = wolfssl_print_value(bio, num, name[i], indent);
  2290. }
  2291. else if (!mp_iszero(num)) {
  2292. /* Print name and MP integer. */
  2293. ret = wolfssl_print_number(bio, num, name[i], indent);
  2294. }
  2295. }
  2296. return ret;
  2297. }
  2298. #endif /* XSNPRINTF && !NO_BIO */
  2299. #endif /* OPENSSL_EXTRA */
  2300. /*
  2301. * RSA get/set/test APIs
  2302. */
  2303. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2304. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2305. *
  2306. * @param [in, out] rsa RSA key.
  2307. * @return 1 on success.
  2308. * @return 0 on failure.
  2309. */
  2310. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2311. {
  2312. int ret = 1;
  2313. WOLFSSL_ENTER("SetRsaExternal");
  2314. /* Validate parameters. */
  2315. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2316. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2317. ret = WOLFSSL_FATAL_ERROR;
  2318. }
  2319. if (ret == 1) {
  2320. RsaKey* key = (RsaKey*)rsa->internal;
  2321. /* Copy modulus. */
  2322. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2323. if (ret != 1) {
  2324. WOLFSSL_ERROR_MSG("rsa n error");
  2325. }
  2326. if (ret == 1) {
  2327. /* Copy public exponent. */
  2328. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2329. if (ret != 1) {
  2330. WOLFSSL_ERROR_MSG("rsa e error");
  2331. }
  2332. }
  2333. if (key->type == RSA_PRIVATE) {
  2334. if (ret == 1) {
  2335. /* Copy private exponent. */
  2336. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2337. if (ret != 1) {
  2338. WOLFSSL_ERROR_MSG("rsa d error");
  2339. }
  2340. }
  2341. if (ret == 1) {
  2342. /* Copy first prime. */
  2343. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2344. if (ret != 1) {
  2345. WOLFSSL_ERROR_MSG("rsa p error");
  2346. }
  2347. }
  2348. if (ret == 1) {
  2349. /* Copy second prime. */
  2350. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2351. if (ret != 1) {
  2352. WOLFSSL_ERROR_MSG("rsa q error");
  2353. }
  2354. }
  2355. #ifndef RSA_LOW_MEM
  2356. if (ret == 1) {
  2357. /* Copy d mod p-1. */
  2358. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2359. if (ret != 1) {
  2360. WOLFSSL_ERROR_MSG("rsa dP error");
  2361. }
  2362. }
  2363. if (ret == 1) {
  2364. /* Copy d mod q-1. */
  2365. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2366. if (ret != 1) {
  2367. WOLFSSL_ERROR_MSG("rsa dq error");
  2368. }
  2369. }
  2370. if (ret == 1) {
  2371. /* Copy 1/q mod p. */
  2372. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2373. if (ret != 1) {
  2374. WOLFSSL_ERROR_MSG("rsa u error");
  2375. }
  2376. }
  2377. #endif /* !RSA_LOW_MEM */
  2378. }
  2379. }
  2380. if (ret == 1) {
  2381. /* External values set. */
  2382. rsa->exSet = 1;
  2383. }
  2384. else {
  2385. /* Return 0 on failure. */
  2386. ret = 0;
  2387. }
  2388. return ret;
  2389. }
  2390. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2391. #ifdef OPENSSL_EXTRA
  2392. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2393. *
  2394. * @param [in, out] rsa RSA key.
  2395. * @return 1 on success.
  2396. * @return 0 on failure.
  2397. */
  2398. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2399. {
  2400. int ret = 1;
  2401. WOLFSSL_ENTER("SetRsaInternal");
  2402. /* Validate parameters. */
  2403. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2404. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2405. ret = WOLFSSL_FATAL_ERROR;
  2406. }
  2407. if (ret == 1) {
  2408. RsaKey* key = (RsaKey*)rsa->internal;
  2409. /* Copy down modulus if available. */
  2410. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2411. WOLFSSL_ERROR_MSG("rsa n key error");
  2412. ret = WOLFSSL_FATAL_ERROR;
  2413. }
  2414. /* Copy down public exponent if available. */
  2415. if ((ret == 1) && (rsa->e != NULL) &&
  2416. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2417. WOLFSSL_ERROR_MSG("rsa e key error");
  2418. ret = WOLFSSL_FATAL_ERROR;
  2419. }
  2420. /* Enough numbers for public key */
  2421. key->type = RSA_PUBLIC;
  2422. /* Copy down private exponent if available. */
  2423. if ((ret == 1) && (rsa->d != NULL)) {
  2424. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2425. WOLFSSL_ERROR_MSG("rsa d key error");
  2426. ret = WOLFSSL_FATAL_ERROR;
  2427. }
  2428. else {
  2429. /* Enough numbers for private key */
  2430. key->type = RSA_PRIVATE;
  2431. }
  2432. }
  2433. /* Copy down first prime if available. */
  2434. if ((ret == 1) && (rsa->p != NULL) &&
  2435. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2436. WOLFSSL_ERROR_MSG("rsa p key error");
  2437. ret = WOLFSSL_FATAL_ERROR;
  2438. }
  2439. /* Copy down second prime if available. */
  2440. if ((ret == 1) && (rsa->q != NULL) &&
  2441. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2442. WOLFSSL_ERROR_MSG("rsa q key error");
  2443. ret = WOLFSSL_FATAL_ERROR;
  2444. }
  2445. #ifndef RSA_LOW_MEM
  2446. /* Copy down d mod p-1 if available. */
  2447. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2448. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2449. WOLFSSL_ERROR_MSG("rsa dP key error");
  2450. ret = WOLFSSL_FATAL_ERROR;
  2451. }
  2452. /* Copy down d mod q-1 if available. */
  2453. if ((ret == 1) && (rsa->dmq1 != NULL) &&
  2454. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2455. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2456. ret = WOLFSSL_FATAL_ERROR;
  2457. }
  2458. /* Copy down 1/q mod p if available. */
  2459. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2460. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2461. WOLFSSL_ERROR_MSG("rsa u key error");
  2462. ret = WOLFSSL_FATAL_ERROR;
  2463. }
  2464. #endif /* !RSA_LOW_MEM */
  2465. if (ret == 1) {
  2466. /* All available numbers have been set down. */
  2467. rsa->inSet = 1;
  2468. }
  2469. }
  2470. return ret;
  2471. }
  2472. /* Set the RSA method into object.
  2473. *
  2474. * @param [in, out] rsa RSA key.
  2475. * @param [in] meth RSA method.
  2476. * @return 1 always.
  2477. */
  2478. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2479. {
  2480. if (rsa != NULL) {
  2481. /* Store the method into object. */
  2482. rsa->meth = meth;
  2483. /* Copy over flags. */
  2484. rsa->flags = meth->flags;
  2485. }
  2486. /* OpenSSL always assumes it will work. */
  2487. return 1;
  2488. }
  2489. /* Get the RSA method from the RSA object.
  2490. *
  2491. * @param [in] rsa RSA key.
  2492. * @return RSA method on success.
  2493. * @return NULL when RSA is NULL or no method set.
  2494. */
  2495. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2496. {
  2497. return (rsa != NULL) ? rsa->meth : NULL;
  2498. }
  2499. /* Get the size in bytes of the RSA key.
  2500. *
  2501. * Return compliant with OpenSSL
  2502. *
  2503. * @param [in] rsa RSA key.
  2504. * @return RSA modulus size in bytes.
  2505. * @return 0 on error.
  2506. */
  2507. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2508. {
  2509. int ret = 0;
  2510. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2511. if (rsa != NULL) {
  2512. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2513. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2514. /* Get key size in bytes using wolfCrypt RSA key. */
  2515. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2516. }
  2517. }
  2518. return ret;
  2519. }
  2520. /* Get the size in bits of the RSA key.
  2521. *
  2522. * Uses external modulus field.
  2523. *
  2524. * @param [in] rsa RSA key.
  2525. * @return RSA modulus size in bits.
  2526. * @return 0 on error.
  2527. */
  2528. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2529. {
  2530. int ret = 0;
  2531. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2532. if (rsa != NULL) {
  2533. /* Get number of bits in external modulus. */
  2534. ret = wolfSSL_BN_num_bits(rsa->n);
  2535. }
  2536. return ret;
  2537. }
  2538. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2539. *
  2540. * Only for those that are not NULL parameters.
  2541. *
  2542. * @param [in] rsa RSA key.
  2543. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2544. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2545. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2546. */
  2547. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2548. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2549. const WOLFSSL_BIGNUM **iqmp)
  2550. {
  2551. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2552. /* For any parameters not NULL, return the BN from the key or NULL. */
  2553. if (dmp1 != NULL) {
  2554. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2555. }
  2556. if (dmq1 != NULL) {
  2557. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2558. }
  2559. if (iqmp != NULL) {
  2560. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2561. }
  2562. }
  2563. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2564. * into RSA key.
  2565. *
  2566. * If CRT parameter is NULL then there must be one in the RSA key already.
  2567. *
  2568. * @param [in, out] rsa RSA key.
  2569. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2570. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2571. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2572. * @return 1 on success.
  2573. * @return 0 on failure.
  2574. */
  2575. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2576. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2577. {
  2578. int ret = 1;
  2579. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2580. /* If a param is NULL in rsa then it must be non-NULL in the
  2581. * corresponding user input. */
  2582. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2583. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2584. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2585. WOLFSSL_ERROR_MSG("Bad parameters");
  2586. ret = 0;
  2587. }
  2588. if (ret == 1) {
  2589. /* Replace the BNs. */
  2590. if (dmp1 != NULL) {
  2591. wolfSSL_BN_clear_free(rsa->dmp1);
  2592. rsa->dmp1 = dmp1;
  2593. }
  2594. if (dmq1 != NULL) {
  2595. wolfSSL_BN_clear_free(rsa->dmq1);
  2596. rsa->dmq1 = dmq1;
  2597. }
  2598. if (iqmp != NULL) {
  2599. wolfSSL_BN_clear_free(rsa->iqmp);
  2600. rsa->iqmp = iqmp;
  2601. }
  2602. /* Set the values into the wolfCrypt RSA key. */
  2603. if (SetRsaInternal(rsa) != 1) {
  2604. if (dmp1 != NULL) {
  2605. rsa->dmp1 = NULL;
  2606. }
  2607. if (dmq1 != NULL) {
  2608. rsa->dmq1 = NULL;
  2609. }
  2610. if (iqmp != NULL) {
  2611. rsa->iqmp = NULL;
  2612. }
  2613. ret = 0;
  2614. }
  2615. }
  2616. return ret;
  2617. }
  2618. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2619. *
  2620. * @param [in] rsa RSA key.
  2621. * @param [out] p BN that is first prime. May be NULL.
  2622. * @param [out] q BN that is second prime. May be NULL.
  2623. */
  2624. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2625. const WOLFSSL_BIGNUM **q)
  2626. {
  2627. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2628. /* For any primes not NULL, return the BN from the key or NULL. */
  2629. if (p != NULL) {
  2630. *p = (rsa != NULL) ? rsa->p : NULL;
  2631. }
  2632. if (q != NULL) {
  2633. *q = (rsa != NULL) ? rsa->q : NULL;
  2634. }
  2635. }
  2636. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2637. *
  2638. * If factor parameter is NULL then there must be one in the RSA key already.
  2639. *
  2640. * @param [in, out] rsa RSA key.
  2641. * @param [in] p BN that is first prime. May be NULL.
  2642. * @param [in] q BN that is second prime. May be NULL.
  2643. * @return 1 on success.
  2644. * @return 0 on failure.
  2645. */
  2646. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2647. WOLFSSL_BIGNUM *q)
  2648. {
  2649. int ret = 1;
  2650. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2651. /* If a param is null in r then it must be non-null in the
  2652. * corresponding user input. */
  2653. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2654. ((rsa->q == NULL) && (q == NULL))) {
  2655. WOLFSSL_ERROR_MSG("Bad parameters");
  2656. ret = 0;
  2657. }
  2658. if (ret == 1) {
  2659. /* Replace the BNs. */
  2660. if (p != NULL) {
  2661. wolfSSL_BN_clear_free(rsa->p);
  2662. rsa->p = p;
  2663. }
  2664. if (q != NULL) {
  2665. wolfSSL_BN_clear_free(rsa->q);
  2666. rsa->q = q;
  2667. }
  2668. /* Set the values into the wolfCrypt RSA key. */
  2669. if (SetRsaInternal(rsa) != 1) {
  2670. if (p != NULL) {
  2671. rsa->p = NULL;
  2672. }
  2673. if (q != NULL) {
  2674. rsa->q = NULL;
  2675. }
  2676. ret = 0;
  2677. }
  2678. }
  2679. return ret;
  2680. }
  2681. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2682. * exponent, private exponent).
  2683. *
  2684. * @param [in] rsa RSA key.
  2685. * @param [out] n BN that is the modulus. May be NULL.
  2686. * @param [out] e BN that is the public exponent. May be NULL.
  2687. * @param [out] d BN that is the private exponent. May be NULL.
  2688. */
  2689. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2690. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2691. {
  2692. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2693. /* For any parameters not NULL, return the BN from the key or NULL. */
  2694. if (n != NULL) {
  2695. *n = (rsa != NULL) ? rsa->n : NULL;
  2696. }
  2697. if (e != NULL) {
  2698. *e = (rsa != NULL) ? rsa->e : NULL;
  2699. }
  2700. if (d != NULL) {
  2701. *d = (rsa != NULL) ? rsa->d : NULL;
  2702. }
  2703. }
  2704. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2705. * public exponent, private exponent).
  2706. *
  2707. * If BN parameter is NULL then there must be one in the RSA key already.
  2708. *
  2709. * @param [in,out] rsa RSA key.
  2710. * @param [in] n BN that is the modulus. May be NULL.
  2711. * @param [in] e BN that is the public exponent. May be NULL.
  2712. * @param [in] d BN that is the private exponent. May be NULL.
  2713. * @return 1 on success.
  2714. * @return 0 on failure.
  2715. */
  2716. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2717. WOLFSSL_BIGNUM *d)
  2718. {
  2719. int ret = 1;
  2720. /* If the fields n and e in r are NULL, the corresponding input
  2721. * parameters MUST be non-NULL for n and e. d may be
  2722. * left NULL (in case only the public key is used).
  2723. */
  2724. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2725. ((rsa->e == NULL) && (e == NULL))) {
  2726. ret = 0;
  2727. }
  2728. if (ret == 1) {
  2729. /* Replace the BNs. */
  2730. if (n != NULL) {
  2731. wolfSSL_BN_free(rsa->n);
  2732. rsa->n = n;
  2733. }
  2734. if (e != NULL) {
  2735. wolfSSL_BN_free(rsa->e);
  2736. rsa->e = e;
  2737. }
  2738. if (d != NULL) {
  2739. /* Private key is sensitive data. */
  2740. wolfSSL_BN_clear_free(rsa->d);
  2741. rsa->d = d;
  2742. }
  2743. /* Set the values into the wolfCrypt RSA key. */
  2744. if (SetRsaInternal(rsa) != 1) {
  2745. if (n != NULL) {
  2746. rsa->n = NULL;
  2747. }
  2748. if (e != NULL) {
  2749. rsa->e = NULL;
  2750. }
  2751. if (d != NULL) {
  2752. rsa->d = NULL;
  2753. }
  2754. ret = 0;
  2755. }
  2756. }
  2757. return ret;
  2758. }
  2759. /* Get the flags of the RSA key.
  2760. *
  2761. * @param [in] rsa RSA key.
  2762. * @return Flags set in RSA key on success.
  2763. * @return 0 when RSA key is NULL.
  2764. */
  2765. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2766. {
  2767. int ret = 0;
  2768. /* Get flags from the RSA key if available. */
  2769. if (rsa != NULL) {
  2770. ret = rsa->flags;
  2771. }
  2772. return ret;
  2773. }
  2774. /* Set the flags into the RSA key.
  2775. *
  2776. * @param [in, out] rsa RSA key.
  2777. * @param [in] flags Flags to set.
  2778. */
  2779. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2780. {
  2781. /* Add the flags into RSA key if available. */
  2782. if (rsa != NULL) {
  2783. rsa->flags |= flags;
  2784. }
  2785. }
  2786. /* Clear the flags in the RSA key.
  2787. *
  2788. * @param [in, out] rsa RSA key.
  2789. * @param [in] flags Flags to clear.
  2790. */
  2791. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2792. {
  2793. /* Clear the flags passed in that are on the RSA key if available. */
  2794. if (rsa != NULL) {
  2795. rsa->flags &= ~flags;
  2796. }
  2797. }
  2798. /* Test the flags in the RSA key.
  2799. *
  2800. * @param [in] rsa RSA key.
  2801. * @return Matching flags of RSA key on success.
  2802. * @return 0 when RSA key is NULL.
  2803. */
  2804. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2805. {
  2806. /* Return the flags passed in that are set on the RSA key if available. */
  2807. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2808. }
  2809. /* Get the extra data, by index, associated with the RSA key.
  2810. *
  2811. * @param [in] rsa RSA key.
  2812. * @param [in] idx Index of extra data.
  2813. * @return Extra data (anonymous type) on success.
  2814. * @return NULL on failure.
  2815. */
  2816. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2817. {
  2818. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2819. #ifdef HAVE_EX_DATA
  2820. return (rsa == NULL) ? NULL :
  2821. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2822. #else
  2823. (void)rsa;
  2824. (void)idx;
  2825. return NULL;
  2826. #endif
  2827. }
  2828. /* Set extra data against the RSA key at an index.
  2829. *
  2830. * @param [in, out] rsa RSA key.
  2831. * @param [in] idx Index set set extra data at.
  2832. * @param [in] data Extra data of anonymous type.
  2833. * @return 1 on success.
  2834. * @return 0 on failure.
  2835. */
  2836. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2837. {
  2838. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2839. #ifdef HAVE_EX_DATA
  2840. return (rsa == NULL) ? 0 :
  2841. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2842. #else
  2843. (void)rsa;
  2844. (void)idx;
  2845. (void)data;
  2846. return 0;
  2847. #endif
  2848. }
  2849. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2850. /* Set the extra data and cleanup callback against the RSA key at an index.
  2851. *
  2852. * Not OpenSSL API.
  2853. *
  2854. * @param [in, out] rsa RSA key.
  2855. * @param [in] idx Index set set extra data at.
  2856. * @param [in] data Extra data of anonymous type.
  2857. * @param [in] freeCb Callback function to free extra data.
  2858. * @return 1 on success.
  2859. * @return 0 on failure.
  2860. */
  2861. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2862. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2863. {
  2864. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2865. return (rsa == NULL) ? 0 :
  2866. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2867. freeCb);
  2868. }
  2869. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2870. /*
  2871. * RSA check key APIs
  2872. */
  2873. #ifdef WOLFSSL_RSA_KEY_CHECK
  2874. /* Check that the RSA key is valid using wolfCrypt.
  2875. *
  2876. * @param [in] rsa RSA key.
  2877. * @return 1 on success.
  2878. * @return 0 on failure.
  2879. */
  2880. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2881. {
  2882. int ret = 1;
  2883. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2884. /* Validate parameters. */
  2885. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2886. ret = 0;
  2887. }
  2888. /* Constant RSA - assume internal data has been set. */
  2889. /* Check wolfCrypt RSA key. */
  2890. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2891. ret = 0;
  2892. }
  2893. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2894. return ret;
  2895. }
  2896. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2897. /*
  2898. * RSA generate APIs
  2899. */
  2900. /* Get a random number generator associated with the RSA key.
  2901. *
  2902. * If not able, then get the global if possible.
  2903. * *tmpRng must not be an initialized RNG.
  2904. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2905. * associated with the wolfCrypt RSA key.
  2906. *
  2907. * @param [in] rsa RSA key.
  2908. * @param [out] tmpRng Temporary random number generator.
  2909. * @param [out] initTmpRng Temporary random number generator was initialized.
  2910. *
  2911. * @return A wolfCrypt RNG to use on success.
  2912. * @return NULL on error.
  2913. */
  2914. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2915. {
  2916. WC_RNG* rng = NULL;
  2917. int err = 0;
  2918. /* Check validity of parameters. */
  2919. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2920. err = 1;
  2921. }
  2922. if (!err) {
  2923. /* Haven't initialized any RNG passed through tmpRng. */
  2924. *initTmpRng = 0;
  2925. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2926. /* Use wolfCrypt RSA key's RNG if available/set. */
  2927. rng = ((RsaKey*)rsa->internal)->rng;
  2928. #endif
  2929. }
  2930. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2931. /* Make an RNG with tmpRng or get global. */
  2932. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2933. if ((rng != NULL) && *initTmpRng) {
  2934. *tmpRng = rng;
  2935. }
  2936. }
  2937. return rng;
  2938. }
  2939. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2940. *
  2941. * @param [in, out] rsa RSA key.
  2942. * @param [in] bits Number of bits that the modulus must have.
  2943. * @param [in] e A BN object holding the public exponent to use.
  2944. * @param [in] cb Status callback. Unused.
  2945. * @return 0 on success.
  2946. * @return wolfSSL native error code on error.
  2947. */
  2948. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2949. WOLFSSL_BIGNUM* e, void* cb)
  2950. {
  2951. #ifdef WOLFSSL_KEY_GEN
  2952. int ret = 0;
  2953. #ifdef WOLFSSL_SMALL_STACK
  2954. WC_RNG* tmpRng = NULL;
  2955. #else
  2956. WC_RNG _tmpRng[1];
  2957. WC_RNG* tmpRng = _tmpRng;
  2958. #endif
  2959. int initTmpRng = 0;
  2960. WC_RNG* rng = NULL;
  2961. long en;
  2962. #endif
  2963. (void)cb;
  2964. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2965. #ifdef WOLFSSL_KEY_GEN
  2966. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2967. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2968. if (rng == NULL) {
  2969. /* Something went wrong so return memory error. */
  2970. ret = MEMORY_E;
  2971. }
  2972. if ((ret == 0) && ((en = (long)wolfSSL_BN_get_word(e)) <= 0)) {
  2973. ret = BAD_FUNC_ARG;
  2974. }
  2975. if (ret == 0) {
  2976. /* Generate an RSA key. */
  2977. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits, en, rng);
  2978. if (ret != MP_OKAY) {
  2979. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2980. }
  2981. }
  2982. if (ret == 0) {
  2983. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2984. ret = SetRsaExternal(rsa);
  2985. if (ret == 1) {
  2986. /* Internal matches external. */
  2987. rsa->inSet = 1;
  2988. /* Return success. */
  2989. ret = 0;
  2990. }
  2991. else {
  2992. /* Something went wrong so return memory error. */
  2993. ret = MEMORY_E;
  2994. }
  2995. }
  2996. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2997. if (initTmpRng) {
  2998. wc_FreeRng(tmpRng);
  2999. }
  3000. #ifdef WOLFSSL_SMALL_STACK
  3001. /* Dispose of any allocated RNG. */
  3002. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3003. #endif
  3004. return ret;
  3005. #else
  3006. WOLFSSL_ERROR_MSG("No Key Gen built in");
  3007. (void)rsa;
  3008. (void)e;
  3009. (void)bits;
  3010. return NOT_COMPILED_IN;
  3011. #endif
  3012. }
  3013. /* Generate an RSA key that has the specified modulus size and public exponent.
  3014. *
  3015. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  3016. * down to nearest multiple of 8. For example generating a key of size
  3017. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  3018. *
  3019. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  3020. * @param [in] e Public exponent to use i.e. 65537.
  3021. * @param [in] cb Status callback. Unused.
  3022. * @param [in] data Data to pass to status callback. Unused.
  3023. * @return A new RSA key on success.
  3024. * @return NULL on failure.
  3025. */
  3026. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  3027. void(*cb)(int, int, void*), void* data)
  3028. {
  3029. WOLFSSL_RSA* rsa = NULL;
  3030. WOLFSSL_BIGNUM* bn = NULL;
  3031. int err = 0;
  3032. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  3033. (void)cb;
  3034. (void)data;
  3035. /* Validate bits. */
  3036. if (bits < 0) {
  3037. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  3038. err = 1;
  3039. }
  3040. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  3041. * longer values. */
  3042. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  3043. WOLFSSL_ERROR_MSG("Error creating big number");
  3044. err = 1;
  3045. }
  3046. /* Set public exponent. */
  3047. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  3048. WOLFSSL_ERROR_MSG("Error using e value");
  3049. err = 1;
  3050. }
  3051. /* Create an RSA key object to hold generated key. */
  3052. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  3053. WOLFSSL_ERROR_MSG("memory error");
  3054. err = 1;
  3055. }
  3056. while (!err) {
  3057. int ret;
  3058. /* Use wolfCrypt to generate RSA key. */
  3059. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  3060. #ifdef HAVE_FIPS
  3061. /* Keep trying if failed to find a prime. */
  3062. if (ret == WC_NO_ERR_TRACE(PRIME_GEN_E)) {
  3063. continue;
  3064. }
  3065. #endif
  3066. if (ret != WOLFSSL_ERROR_NONE) {
  3067. /* Unrecoverable error in generation. */
  3068. err = 1;
  3069. }
  3070. /* Done generating - unrecoverable error or success. */
  3071. break;
  3072. }
  3073. if (err) {
  3074. /* Dispose of RSA key object if generation didn't work. */
  3075. wolfSSL_RSA_free(rsa);
  3076. /* Returning NULL on error. */
  3077. rsa = NULL;
  3078. }
  3079. /* Dispose of the temporary BN used for the public exponent. */
  3080. wolfSSL_BN_free(bn);
  3081. return rsa;
  3082. }
  3083. /* Generate an RSA key that has the specified modulus size and public exponent.
  3084. *
  3085. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  3086. * down to nearest multiple of 8. For example generating a key of size
  3087. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  3088. *
  3089. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  3090. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  3091. * @param [in] cb Status callback. Unused.
  3092. * @return 1 on success.
  3093. * @return 0 on failure.
  3094. */
  3095. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  3096. void* cb)
  3097. {
  3098. int ret = 1;
  3099. /* Validate parameters. */
  3100. if ((rsa == NULL) || (rsa->internal == NULL)) {
  3101. WOLFSSL_ERROR_MSG("bad arguments");
  3102. ret = 0;
  3103. }
  3104. else {
  3105. for (;;) {
  3106. /* Use wolfCrypt to generate RSA key. */
  3107. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  3108. #ifdef HAVE_FIPS
  3109. /* Keep trying again if public key value didn't work. */
  3110. if (gen_ret == WC_NO_ERR_TRACE(PRIME_GEN_E)) {
  3111. continue;
  3112. }
  3113. #endif
  3114. if (gen_ret != WOLFSSL_ERROR_NONE) {
  3115. /* Unrecoverable error in generation. */
  3116. ret = 0;
  3117. }
  3118. /* Done generating - unrecoverable error or success. */
  3119. break;
  3120. }
  3121. }
  3122. return ret;
  3123. }
  3124. #endif /* OPENSSL_EXTRA */
  3125. /*
  3126. * RSA padding APIs
  3127. */
  3128. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  3129. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  3130. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  3131. /* Add PKCS#1 PSS padding to hash.
  3132. *
  3133. *
  3134. * +-----------+
  3135. * | M |
  3136. * +-----------+
  3137. * |
  3138. * V
  3139. * Hash
  3140. * |
  3141. * V
  3142. * +--------+----------+----------+
  3143. * M' = |Padding1| mHash | salt |
  3144. * +--------+----------+----------+
  3145. * |
  3146. * +--------+----------+ V
  3147. * DB = |Padding2|maskedseed| Hash
  3148. * +--------+----------+ |
  3149. * | |
  3150. * V | +--+
  3151. * xor <--- MGF <---| |bc|
  3152. * | | +--+
  3153. * | | |
  3154. * V V V
  3155. * +-------------------+----------+--+
  3156. * EM = | maskedDB |maskedseed|bc|
  3157. * +-------------------+----------+--+
  3158. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3159. *
  3160. * @param [in] rsa RSA key.
  3161. * @param [out] em Encoded message.
  3162. * @param [in[ mHash Message hash.
  3163. * @param [in] hashAlg Hash algorithm.
  3164. * @param [in] saltLen Length of salt to generate.
  3165. * @return 1 on success.
  3166. * @return 0 on failure.
  3167. */
  3168. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3169. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3170. {
  3171. int ret = 1;
  3172. enum wc_HashType hashType;
  3173. int hashLen = 0;
  3174. int emLen = 0;
  3175. int mgf = 0;
  3176. int initTmpRng = 0;
  3177. WC_RNG *rng = NULL;
  3178. #ifdef WOLFSSL_SMALL_STACK
  3179. WC_RNG* tmpRng = NULL;
  3180. #else
  3181. WC_RNG _tmpRng[1];
  3182. WC_RNG* tmpRng = _tmpRng;
  3183. #endif
  3184. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3185. /* Validate parameters. */
  3186. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3187. ret = 0;
  3188. }
  3189. if (ret == 1) {
  3190. /* Get/create an RNG. */
  3191. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3192. if (rng == NULL) {
  3193. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3194. ret = 0;
  3195. }
  3196. }
  3197. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3198. /* Set the external data from the wolfCrypt RSA key if not done. */
  3199. if ((ret == 1) && (!rsa->exSet)) {
  3200. ret = SetRsaExternal(rsa);
  3201. }
  3202. if (ret == 1) {
  3203. /* Get the wolfCrypt hash algorithm type. */
  3204. hashType = EvpMd2MacType(hashAlg);
  3205. if (hashType > WC_HASH_TYPE_MAX) {
  3206. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3207. ret = 0;
  3208. }
  3209. }
  3210. if (ret == 1) {
  3211. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3212. mgf = wc_hash2mgf(hashType);
  3213. if (mgf == WC_MGF1NONE) {
  3214. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3215. ret = 0;
  3216. }
  3217. }
  3218. if (ret == 1) {
  3219. /* Get the length of the hash output. */
  3220. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3221. if (hashLen < 0) {
  3222. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3223. ret = 0;
  3224. }
  3225. }
  3226. if (ret == 1) {
  3227. /* Get length of RSA key - encrypted message length. */
  3228. emLen = wolfSSL_RSA_size(rsa);
  3229. if (emLen <= 0) {
  3230. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3231. ret = 0;
  3232. }
  3233. }
  3234. if (ret == 1) {
  3235. /* Calculate the salt length to use for special cases. */
  3236. /* TODO: use special case wolfCrypt values? */
  3237. switch (saltLen) {
  3238. /* Negative saltLen values are treated differently. */
  3239. case RSA_PSS_SALTLEN_DIGEST:
  3240. saltLen = hashLen;
  3241. break;
  3242. case RSA_PSS_SALTLEN_MAX_SIGN:
  3243. case RSA_PSS_SALTLEN_MAX:
  3244. #ifdef WOLFSSL_PSS_LONG_SALT
  3245. saltLen = emLen - hashLen - 2;
  3246. #else
  3247. saltLen = hashLen;
  3248. #endif
  3249. break;
  3250. default:
  3251. if (saltLen < 0) {
  3252. /* No other negative values implemented. */
  3253. WOLFSSL_ERROR_MSG("invalid saltLen");
  3254. ret = 0;
  3255. }
  3256. }
  3257. }
  3258. if (ret == 1) {
  3259. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3260. if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen,
  3261. RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0,
  3262. saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3263. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3264. ret = 0;
  3265. }
  3266. }
  3267. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3268. if (initTmpRng) {
  3269. wc_FreeRng(tmpRng);
  3270. }
  3271. #ifdef WOLFSSL_SMALL_STACK
  3272. /* Dispose of any allocated RNG. */
  3273. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3274. #endif
  3275. return ret;
  3276. }
  3277. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3278. *
  3279. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3280. *
  3281. * @param [in] rsa RSA key.
  3282. * @param [in[ mHash Message hash.
  3283. * @param [in] hashAlg Hash algorithm.
  3284. * @param [in] em Encoded message.
  3285. * @param [in] saltLen Length of salt to generate.
  3286. * @return 1 on success.
  3287. * @return 0 on failure.
  3288. */
  3289. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3290. const WOLFSSL_EVP_MD *hashAlg,
  3291. const unsigned char *em, int saltLen)
  3292. {
  3293. int ret = 1;
  3294. int hashLen = 0;
  3295. int mgf = 0;
  3296. int emLen = 0;
  3297. int mPrimeLen = 0;
  3298. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3299. byte *mPrime = NULL;
  3300. byte *buf = NULL;
  3301. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3302. /* Validate parameters. */
  3303. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3304. ret = 0;
  3305. }
  3306. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3307. /* Set the external data from the wolfCrypt RSA key if not done. */
  3308. if ((ret == 1) && (!rsa->exSet)) {
  3309. ret = SetRsaExternal(rsa);
  3310. }
  3311. if (ret == 1) {
  3312. /* Get hash length for hash algorithm. */
  3313. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3314. if (hashLen < 0) {
  3315. ret = 0;
  3316. }
  3317. }
  3318. if (ret == 1) {
  3319. /* Get length of RSA key - encrypted message length. */
  3320. emLen = wolfSSL_RSA_size(rsa);
  3321. if (emLen <= 0) {
  3322. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3323. ret = 0;
  3324. }
  3325. }
  3326. if (ret == 1) {
  3327. /* Calculate the salt length to use for special cases. */
  3328. switch (saltLen) {
  3329. /* Negative saltLen values are treated differently */
  3330. case RSA_PSS_SALTLEN_DIGEST:
  3331. saltLen = hashLen;
  3332. break;
  3333. case RSA_PSS_SALTLEN_AUTO:
  3334. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3335. saltLen = RSA_PSS_SALT_LEN_DISCOVER;
  3336. break;
  3337. #endif
  3338. case RSA_PSS_SALTLEN_MAX:
  3339. #ifdef WOLFSSL_PSS_LONG_SALT
  3340. saltLen = emLen - hashLen - 2;
  3341. #else
  3342. saltLen = hashLen;
  3343. #endif
  3344. break;
  3345. default:
  3346. if (saltLen < 0) {
  3347. /* No other negative values implemented. */
  3348. WOLFSSL_ERROR_MSG("invalid saltLen");
  3349. ret = 0;
  3350. }
  3351. }
  3352. }
  3353. if (ret == 1) {
  3354. /* Get the wolfCrypt hash algorithm type. */
  3355. hashType = EvpMd2MacType(hashAlg);
  3356. if (hashType > WC_HASH_TYPE_MAX) {
  3357. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3358. ret = 0;
  3359. }
  3360. }
  3361. if (ret == 1) {
  3362. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3363. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3364. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3365. ret = 0;
  3366. }
  3367. }
  3368. if (ret == 1) {
  3369. /* Allocate buffer to unpad inline with. */
  3370. buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3371. if (buf == NULL) {
  3372. WOLFSSL_ERROR_MSG("malloc error");
  3373. ret = 0;
  3374. }
  3375. }
  3376. if (ret == 1) {
  3377. /* Copy encrypted message to temp for inline unpadding. */
  3378. XMEMCPY(buf, em, (size_t)emLen);
  3379. /* Remove and verify the PSS padding. */
  3380. mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime,
  3381. RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3382. wolfSSL_BN_num_bits(rsa->n), NULL);
  3383. if (mPrimeLen < 0) {
  3384. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3385. ret = 0;
  3386. }
  3387. }
  3388. if (ret == 1) {
  3389. /* Verify the hash is correct. */
  3390. if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime,
  3391. (word32)mPrimeLen, hashType, saltLen,
  3392. wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3393. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3394. ret = 0;
  3395. }
  3396. }
  3397. /* Dispose of any allocated buffer. */
  3398. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3399. return ret;
  3400. }
  3401. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3402. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3403. * WOLFSSL_NGINX) */
  3404. /*
  3405. * RSA sign/verify APIs
  3406. */
  3407. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3408. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3409. #else
  3410. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3411. #endif
  3412. #if defined(OPENSSL_EXTRA)
  3413. /* Encode the message hash.
  3414. *
  3415. * Used by signing and verification.
  3416. *
  3417. * @param [in] hashAlg Hash algorithm OID.
  3418. * @param [in] hash Hash of message to encode for signing.
  3419. * @param [in] hLen Length of hash of message.
  3420. * @param [out] enc Encoded message hash.
  3421. * @param [out] encLen Length of encoded message hash.
  3422. * @param [in] padding Which padding scheme is being used.
  3423. * @return 1 on success.
  3424. * @return 0 on failure.
  3425. */
  3426. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3427. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3428. {
  3429. int ret = 1;
  3430. int hType = WC_HASH_TYPE_NONE;
  3431. /* Validate parameters. */
  3432. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3433. ret = 0;
  3434. }
  3435. if ((ret == 1) && (hashAlg != NID_undef) &&
  3436. (padding == RSA_PKCS1_PADDING)) {
  3437. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3438. hType = (int)nid2oid(hashAlg, oidHashType);
  3439. if (hType == -1) {
  3440. ret = 0;
  3441. }
  3442. }
  3443. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3444. /* PKCS#1.5 encoding. */
  3445. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3446. if (encSz == 0) {
  3447. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3448. ret = 0;
  3449. }
  3450. else {
  3451. *encLen = (unsigned int)encSz;
  3452. }
  3453. }
  3454. /* Other padding schemes require the hash as is. */
  3455. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3456. XMEMCPY(enc, hash, hLen);
  3457. *encLen = hLen;
  3458. }
  3459. return ret;
  3460. }
  3461. /* Sign the message hash using hash algorithm and RSA key.
  3462. *
  3463. * @param [in] hashAlg Hash algorithm OID.
  3464. * @param [in] hash Hash of message to encode for signing.
  3465. * @param [in] hLen Length of hash of message.
  3466. * @param [out] enc Encoded message hash.
  3467. * @param [out] encLen Length of encoded message hash.
  3468. * @param [in] rsa RSA key.
  3469. * @return 1 on success.
  3470. * @return 0 on failure.
  3471. */
  3472. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3473. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3474. {
  3475. if (sigLen != NULL) {
  3476. /* No size checking in this API */
  3477. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3478. }
  3479. /* flag is 1: output complete signature. */
  3480. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3481. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3482. }
  3483. /* Sign the message hash using hash algorithm and RSA key.
  3484. *
  3485. * Not OpenSSL API.
  3486. *
  3487. * @param [in] hashAlg Hash algorithm NID.
  3488. * @param [in] hash Hash of message to encode for signing.
  3489. * @param [in] hLen Length of hash of message.
  3490. * @param [out] enc Encoded message hash.
  3491. * @param [out] encLen Length of encoded message hash.
  3492. * @param [in] rsa RSA key.
  3493. * @param [in] flag When 1: Output encrypted signature.
  3494. * When 0: Output encoded hash.
  3495. * @return 1 on success.
  3496. * @return 0 on failure.
  3497. */
  3498. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3499. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3500. WOLFSSL_RSA* rsa, int flag)
  3501. {
  3502. int ret = 0;
  3503. if ((flag == 0) || (flag == 1)) {
  3504. if (sigLen != NULL) {
  3505. /* No size checking in this API */
  3506. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3507. }
  3508. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3509. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3510. }
  3511. return ret;
  3512. }
  3513. /**
  3514. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3515. *
  3516. * Not OpenSSL API.
  3517. *
  3518. * @param [in] hashAlg Hash NID
  3519. * @param [in] hash Message hash to sign.
  3520. * @param [in] mLen Length of message hash to sign.
  3521. * @param [out] sigRet Output buffer.
  3522. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3523. * On Output: length of data written to sigRet.
  3524. * @param [in] rsa RSA key used to sign the input.
  3525. * @param [in] flag 1: Output the signature.
  3526. * 0: Output the value that the unpadded signature
  3527. * should be compared to.
  3528. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3529. * RSA_PKCS1_PADDING are currently supported for
  3530. * signing.
  3531. * @return 1 on success.
  3532. * @return 0 on failure.
  3533. */
  3534. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3535. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3536. WOLFSSL_RSA* rsa, int flag, int padding)
  3537. {
  3538. int ret = 1;
  3539. word32 outLen = 0;
  3540. int signSz = 0;
  3541. WC_RNG* rng = NULL;
  3542. int initTmpRng = 0;
  3543. #ifdef WOLFSSL_SMALL_STACK
  3544. WC_RNG* tmpRng = NULL;
  3545. byte* encodedSig = NULL;
  3546. #else
  3547. WC_RNG _tmpRng[1];
  3548. WC_RNG* tmpRng = _tmpRng;
  3549. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3550. #endif
  3551. unsigned int encSz = 0;
  3552. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3553. if (flag == 0) {
  3554. /* Only encode message. */
  3555. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3556. padding);
  3557. }
  3558. /* Validate parameters. */
  3559. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3560. WOLFSSL_ERROR_MSG("Bad function arguments");
  3561. ret = 0;
  3562. }
  3563. /* Set wolfCrypt RSA key data from external if not already done. */
  3564. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3565. ret = 0;
  3566. }
  3567. if (ret == 1) {
  3568. /* Get the maximum signature length. */
  3569. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3570. /* Check not an error return. */
  3571. if (outLen == 0) {
  3572. WOLFSSL_ERROR_MSG("Bad RSA size");
  3573. ret = 0;
  3574. }
  3575. /* Check signature buffer is big enough. */
  3576. else if (outLen > *sigLen) {
  3577. WOLFSSL_ERROR_MSG("Output buffer too small");
  3578. ret = 0;
  3579. }
  3580. }
  3581. #ifdef WOLFSSL_SMALL_STACK
  3582. if (ret == 1) {
  3583. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3584. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3585. DYNAMIC_TYPE_SIGNATURE);
  3586. if (encodedSig == NULL) {
  3587. ret = 0;
  3588. }
  3589. }
  3590. #endif
  3591. if (ret == 1) {
  3592. /* Get/create an RNG. */
  3593. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3594. if (rng == NULL) {
  3595. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3596. ret = 0;
  3597. }
  3598. }
  3599. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3600. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3601. &encSz, padding) == 0)) {
  3602. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3603. ret = 0;
  3604. }
  3605. if (ret == 1) {
  3606. switch (padding) {
  3607. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3608. case RSA_NO_PADDING:
  3609. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3610. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3611. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3612. ret = 0;
  3613. }
  3614. break;
  3615. #endif
  3616. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3617. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3618. case RSA_PKCS1_PSS_PADDING:
  3619. {
  3620. enum wc_HashType hType =
  3621. wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3622. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3623. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3624. "OpenSSL uses max length by default.");
  3625. #endif
  3626. /* Create RSA PSS signature. */
  3627. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3628. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3629. (RsaKey*)rsa->internal, rng)) <= 0) {
  3630. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3631. ret = 0;
  3632. }
  3633. break;
  3634. }
  3635. #endif
  3636. #ifndef WC_NO_RSA_OAEP
  3637. case RSA_PKCS1_OAEP_PADDING:
  3638. /* Not a signature padding scheme. */
  3639. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3640. "signing");
  3641. ret = 0;
  3642. break;
  3643. #endif
  3644. case RSA_PKCS1_PADDING:
  3645. {
  3646. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3647. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3648. (RsaKey*)rsa->internal, rng)) <= 0) {
  3649. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3650. ret = 0;
  3651. }
  3652. break;
  3653. }
  3654. default:
  3655. WOLFSSL_ERROR_MSG("Unsupported padding");
  3656. ret = 0;
  3657. break;
  3658. }
  3659. }
  3660. if (ret == 1) {
  3661. /* Return the size of signature generated. */
  3662. *sigLen = (unsigned int)signSz;
  3663. }
  3664. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3665. if (initTmpRng) {
  3666. wc_FreeRng(tmpRng);
  3667. }
  3668. #ifdef WOLFSSL_SMALL_STACK
  3669. /* Dispose of any allocated RNG and encoded signature. */
  3670. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3671. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3672. #endif
  3673. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3674. return ret;
  3675. }
  3676. /**
  3677. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3678. *
  3679. * @param [in] hashAlg Hash NID
  3680. * @param [in] hash Message hash.
  3681. * @param [in] mLen Length of message hash.
  3682. * @param [in] sigRet Signature data.
  3683. * @param [in] sigLen Length of signature data.
  3684. * @param [in] rsa RSA key used to sign the input
  3685. * @return 1 on success.
  3686. * @return 0 on failure.
  3687. */
  3688. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3689. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3690. WOLFSSL_RSA* rsa)
  3691. {
  3692. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3693. RSA_PKCS1_PADDING);
  3694. }
  3695. /**
  3696. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3697. *
  3698. * Not OpenSSL API.
  3699. *
  3700. * @param [in] hashAlg Hash NID
  3701. * @param [in] hash Message hash.
  3702. * @param [in] mLen Length of message hash.
  3703. * @param [in] sigRet Signature data.
  3704. * @param [in] sigLen Length of signature data.
  3705. * @param [in] rsa RSA key used to sign the input
  3706. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3707. * RSA_PKCS1_PADDING are currently supported for
  3708. * signing.
  3709. * @return 1 on success.
  3710. * @return 0 on failure.
  3711. */
  3712. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3713. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3714. WOLFSSL_RSA* rsa, int padding)
  3715. {
  3716. int ret = 1;
  3717. #ifdef WOLFSSL_SMALL_STACK
  3718. unsigned char* encodedSig = NULL;
  3719. #else
  3720. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3721. #endif
  3722. unsigned char* sigDec = NULL;
  3723. unsigned int len = MAX_ENCODED_SIG_SZ;
  3724. int verLen = 0;
  3725. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3726. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3727. #endif
  3728. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3729. /* Validate parameters. */
  3730. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3731. WOLFSSL_ERROR_MSG("Bad function arguments");
  3732. ret = 0;
  3733. }
  3734. if (ret == 1) {
  3735. /* Allocate memory for decrypted signature. */
  3736. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3737. DYNAMIC_TYPE_TMP_BUFFER);
  3738. if (sigDec == NULL) {
  3739. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3740. ret = 0;
  3741. }
  3742. }
  3743. #ifdef WOLFSSL_SMALL_STACK
  3744. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3745. /* Allocate memory for encoded signature. */
  3746. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3747. DYNAMIC_TYPE_TMP_BUFFER);
  3748. if (encodedSig == NULL) {
  3749. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3750. ret = 0;
  3751. }
  3752. }
  3753. #endif
  3754. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3755. /* Make encoded signature to compare with decrypted signature. */
  3756. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3757. padding) <= 0) {
  3758. WOLFSSL_ERROR_MSG("Message Digest Error");
  3759. ret = 0;
  3760. }
  3761. }
  3762. if (ret == 1) {
  3763. /* Decrypt signature */
  3764. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3765. !defined(HAVE_SELFTEST)
  3766. hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3767. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3768. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3769. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3770. ret = 0;
  3771. }
  3772. #else
  3773. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3774. (RsaKey*)rsa->internal);
  3775. if (verLen < 0) {
  3776. ret = 0;
  3777. }
  3778. #endif
  3779. }
  3780. if (ret == 1) {
  3781. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3782. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3783. if (padding == RSA_PKCS1_PSS_PADDING) {
  3784. /* Check PSS padding is valid. */
  3785. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen,
  3786. hType, DEF_PSS_SALT_LEN,
  3787. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3788. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3789. ret = 0;
  3790. }
  3791. }
  3792. else
  3793. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3794. * FIPS_VERSION >= 5.1) */
  3795. /* Compare decrypted signature to encoded signature. */
  3796. if (((int)len != verLen) ||
  3797. (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) {
  3798. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3799. ret = 0;
  3800. }
  3801. }
  3802. /* Dispose of any allocated data. */
  3803. #ifdef WOLFSSL_SMALL_STACK
  3804. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3805. #endif
  3806. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3807. return ret;
  3808. }
  3809. /*
  3810. * RSA public/private encrypt/decrypt APIs
  3811. */
  3812. /* Encrypt with the RSA public key.
  3813. *
  3814. * Return compliant with OpenSSL.
  3815. *
  3816. * @param [in] len Length of data to encrypt.
  3817. * @param [in] from Data to encrypt.
  3818. * @param [out] to Encrypted data.
  3819. * @param [in] rsa RSA key.
  3820. * @param [in] padding Type of padding to place around plaintext.
  3821. * @return Size of encrypted data on success.
  3822. * @return -1 on failure.
  3823. */
  3824. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3825. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3826. {
  3827. int ret = 0;
  3828. int initTmpRng = 0;
  3829. WC_RNG *rng = NULL;
  3830. #ifdef WOLFSSL_SMALL_STACK
  3831. WC_RNG* tmpRng = NULL;
  3832. #else
  3833. WC_RNG _tmpRng[1];
  3834. WC_RNG* tmpRng = _tmpRng;
  3835. #endif
  3836. #if !defined(HAVE_FIPS)
  3837. int mgf = WC_MGF1NONE;
  3838. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3839. int pad_type = WC_RSA_NO_PAD;
  3840. #endif
  3841. int outLen = 0;
  3842. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3843. /* Validate parameters. */
  3844. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3845. (from == NULL)) {
  3846. WOLFSSL_ERROR_MSG("Bad function arguments");
  3847. ret = WOLFSSL_FATAL_ERROR;
  3848. }
  3849. if (ret == 0) {
  3850. #if !defined(HAVE_FIPS)
  3851. /* Convert to wolfCrypt padding, hash and MGF. */
  3852. switch (padding) {
  3853. case RSA_PKCS1_PADDING:
  3854. pad_type = WC_RSA_PKCSV15_PAD;
  3855. break;
  3856. case RSA_PKCS1_OAEP_PADDING:
  3857. pad_type = WC_RSA_OAEP_PAD;
  3858. hash = WC_HASH_TYPE_SHA;
  3859. mgf = WC_MGF1SHA1;
  3860. break;
  3861. case RSA_NO_PADDING:
  3862. pad_type = WC_RSA_NO_PAD;
  3863. break;
  3864. default:
  3865. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3866. "scheme");
  3867. ret = WOLFSSL_FATAL_ERROR;
  3868. }
  3869. #else
  3870. /* Check for supported padding schemes in FIPS. */
  3871. /* TODO: Do we support more schemes in later versions of FIPS? */
  3872. if (padding != RSA_PKCS1_PADDING) {
  3873. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3874. "FIPS");
  3875. ret = WOLFSSL_FATAL_ERROR;
  3876. }
  3877. #endif
  3878. }
  3879. /* Set wolfCrypt RSA key data from external if not already done. */
  3880. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3881. ret = WOLFSSL_FATAL_ERROR;
  3882. }
  3883. if (ret == 0) {
  3884. /* Calculate maximum length of encrypted data. */
  3885. outLen = wolfSSL_RSA_size(rsa);
  3886. if (outLen == 0) {
  3887. WOLFSSL_ERROR_MSG("Bad RSA size");
  3888. ret = WOLFSSL_FATAL_ERROR;
  3889. }
  3890. }
  3891. if (ret == 0) {
  3892. /* Get an RNG. */
  3893. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3894. if (rng == NULL) {
  3895. ret = WOLFSSL_FATAL_ERROR;
  3896. }
  3897. }
  3898. if (ret == 0) {
  3899. /* Use wolfCrypt to public-encrypt with RSA key. */
  3900. #if !defined(HAVE_FIPS)
  3901. ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen,
  3902. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3903. #else
  3904. ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen,
  3905. (RsaKey*)rsa->internal, rng);
  3906. #endif
  3907. }
  3908. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3909. if (initTmpRng) {
  3910. wc_FreeRng(tmpRng);
  3911. }
  3912. #ifdef WOLFSSL_SMALL_STACK
  3913. /* Dispose of any allocated RNG. */
  3914. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3915. #endif
  3916. /* wolfCrypt error means return -1. */
  3917. if (ret <= 0) {
  3918. ret = WOLFSSL_FATAL_ERROR;
  3919. }
  3920. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3921. return ret;
  3922. }
  3923. /* Decrypt with the RSA public key.
  3924. *
  3925. * Return compliant with OpenSSL.
  3926. *
  3927. * @param [in] len Length of encrypted data.
  3928. * @param [in] from Encrypted data.
  3929. * @param [out] to Decrypted data.
  3930. * @param [in] rsa RSA key.
  3931. * @param [in] padding Type of padding to around plaintext to remove.
  3932. * @return Size of decrypted data on success.
  3933. * @return -1 on failure.
  3934. */
  3935. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3936. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3937. {
  3938. int ret = 0;
  3939. #if !defined(HAVE_FIPS)
  3940. int mgf = WC_MGF1NONE;
  3941. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3942. int pad_type = WC_RSA_NO_PAD;
  3943. #endif
  3944. int outLen = 0;
  3945. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3946. /* Validate parameters. */
  3947. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3948. (from == NULL)) {
  3949. WOLFSSL_ERROR_MSG("Bad function arguments");
  3950. ret = WOLFSSL_FATAL_ERROR;
  3951. }
  3952. if (ret == 0) {
  3953. #if !defined(HAVE_FIPS)
  3954. switch (padding) {
  3955. case RSA_PKCS1_PADDING:
  3956. pad_type = WC_RSA_PKCSV15_PAD;
  3957. break;
  3958. case RSA_PKCS1_OAEP_PADDING:
  3959. pad_type = WC_RSA_OAEP_PAD;
  3960. hash = WC_HASH_TYPE_SHA;
  3961. mgf = WC_MGF1SHA1;
  3962. break;
  3963. case RSA_NO_PADDING:
  3964. pad_type = WC_RSA_NO_PAD;
  3965. break;
  3966. default:
  3967. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3968. ret = WOLFSSL_FATAL_ERROR;
  3969. }
  3970. #else
  3971. /* Check for supported padding schemes in FIPS. */
  3972. /* TODO: Do we support more schemes in later versions of FIPS? */
  3973. if (padding != RSA_PKCS1_PADDING) {
  3974. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3975. "FIPS");
  3976. ret = WOLFSSL_FATAL_ERROR;
  3977. }
  3978. #endif
  3979. }
  3980. /* Set wolfCrypt RSA key data from external if not already done. */
  3981. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3982. ret = WOLFSSL_FATAL_ERROR;
  3983. }
  3984. if (ret == 0) {
  3985. /* Calculate maximum length of decrypted data. */
  3986. outLen = wolfSSL_RSA_size(rsa);
  3987. if (outLen == 0) {
  3988. WOLFSSL_ERROR_MSG("Bad RSA size");
  3989. ret = WOLFSSL_FATAL_ERROR;
  3990. }
  3991. }
  3992. if (ret == 0) {
  3993. /* Use wolfCrypt to private-decrypt with RSA key.
  3994. * Size of 'to' buffer must be size of RSA key */
  3995. #if !defined(HAVE_FIPS)
  3996. ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen,
  3997. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3998. #else
  3999. ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen,
  4000. (RsaKey*)rsa->internal);
  4001. #endif
  4002. }
  4003. /* wolfCrypt error means return -1. */
  4004. if (ret <= 0) {
  4005. ret = WOLFSSL_FATAL_ERROR;
  4006. }
  4007. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  4008. return ret;
  4009. }
  4010. /* Decrypt with the RSA public key.
  4011. *
  4012. * @param [in] len Length of encrypted data.
  4013. * @param [in] from Encrypted data.
  4014. * @param [out] to Decrypted data.
  4015. * @param [in] rsa RSA key.
  4016. * @param [in] padding Type of padding to around plaintext to remove.
  4017. * @return Size of decrypted data on success.
  4018. * @return -1 on failure.
  4019. */
  4020. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  4021. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  4022. {
  4023. int ret = 0;
  4024. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4025. int pad_type = WC_RSA_NO_PAD;
  4026. #endif
  4027. int outLen = 0;
  4028. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  4029. /* Validate parameters. */
  4030. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4031. (from == NULL)) {
  4032. WOLFSSL_ERROR_MSG("Bad function arguments");
  4033. ret = WOLFSSL_FATAL_ERROR;
  4034. }
  4035. if (ret == 0) {
  4036. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4037. switch (padding) {
  4038. case RSA_PKCS1_PADDING:
  4039. pad_type = WC_RSA_PKCSV15_PAD;
  4040. break;
  4041. case RSA_NO_PADDING:
  4042. pad_type = WC_RSA_NO_PAD;
  4043. break;
  4044. /* TODO: RSA_X931_PADDING not supported */
  4045. default:
  4046. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  4047. ret = WOLFSSL_FATAL_ERROR;
  4048. }
  4049. #else
  4050. if (padding != RSA_PKCS1_PADDING) {
  4051. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  4052. "FIPS");
  4053. ret = WOLFSSL_FATAL_ERROR;
  4054. }
  4055. #endif
  4056. }
  4057. /* Set wolfCrypt RSA key data from external if not already done. */
  4058. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4059. ret = WOLFSSL_FATAL_ERROR;
  4060. }
  4061. if (ret == 0) {
  4062. /* Calculate maximum length of encrypted data. */
  4063. outLen = wolfSSL_RSA_size(rsa);
  4064. if (outLen == 0) {
  4065. WOLFSSL_ERROR_MSG("Bad RSA size");
  4066. ret = WOLFSSL_FATAL_ERROR;
  4067. }
  4068. }
  4069. if (ret == 0) {
  4070. /* Use wolfCrypt to public-decrypt with RSA key. */
  4071. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4072. /* Size of 'to' buffer must be size of RSA key. */
  4073. ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen,
  4074. (RsaKey*)rsa->internal, pad_type);
  4075. #else
  4076. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  4077. ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen,
  4078. (RsaKey*)rsa->internal);
  4079. #endif
  4080. }
  4081. /* wolfCrypt error means return -1. */
  4082. if (ret <= 0) {
  4083. ret = WOLFSSL_FATAL_ERROR;
  4084. }
  4085. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  4086. return ret;
  4087. }
  4088. /* Encrypt with the RSA private key.
  4089. *
  4090. * Calls wc_RsaSSL_Sign.
  4091. *
  4092. * @param [in] len Length of data to encrypt.
  4093. * @param [in] from Data to encrypt.
  4094. * @param [out] to Encrypted data.
  4095. * @param [in] rsa RSA key.
  4096. * @param [in] padding Type of padding to place around plaintext.
  4097. * @return Size of encrypted data on success.
  4098. * @return -1 on failure.
  4099. */
  4100. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  4101. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  4102. {
  4103. int ret = 0;
  4104. int initTmpRng = 0;
  4105. WC_RNG *rng = NULL;
  4106. #ifdef WOLFSSL_SMALL_STACK
  4107. WC_RNG* tmpRng = NULL;
  4108. #else
  4109. WC_RNG _tmpRng[1];
  4110. WC_RNG* tmpRng = _tmpRng;
  4111. #endif
  4112. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  4113. /* Validate parameters. */
  4114. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4115. (from == NULL)) {
  4116. WOLFSSL_ERROR_MSG("Bad function arguments");
  4117. ret = WOLFSSL_FATAL_ERROR;
  4118. }
  4119. if (ret == 0) {
  4120. switch (padding) {
  4121. case RSA_PKCS1_PADDING:
  4122. #ifdef WC_RSA_NO_PADDING
  4123. case RSA_NO_PADDING:
  4124. #endif
  4125. break;
  4126. /* TODO: RSA_X931_PADDING not supported */
  4127. default:
  4128. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  4129. ret = WOLFSSL_FATAL_ERROR;
  4130. }
  4131. }
  4132. /* Set wolfCrypt RSA key data from external if not already done. */
  4133. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4134. ret = WOLFSSL_FATAL_ERROR;
  4135. }
  4136. if (ret == 0) {
  4137. /* Get an RNG. */
  4138. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  4139. if (rng == NULL) {
  4140. ret = WOLFSSL_FATAL_ERROR;
  4141. }
  4142. }
  4143. if (ret == 0) {
  4144. /* Use wolfCrypt to private-encrypt with RSA key.
  4145. * Size of output buffer must be size of RSA key. */
  4146. if (padding == RSA_PKCS1_PADDING) {
  4147. ret = wc_RsaSSL_Sign(from, (word32)len, to,
  4148. (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng);
  4149. }
  4150. #ifdef WC_RSA_NO_PADDING
  4151. else if (padding == RSA_NO_PADDING) {
  4152. word32 outLen = (word32)wolfSSL_RSA_size(rsa);
  4153. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  4154. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  4155. if (ret == 0)
  4156. ret = (int)outLen;
  4157. }
  4158. #endif
  4159. }
  4160. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4161. if (initTmpRng) {
  4162. wc_FreeRng(tmpRng);
  4163. }
  4164. #ifdef WOLFSSL_SMALL_STACK
  4165. /* Dispose of any allocated RNG. */
  4166. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4167. #endif
  4168. /* wolfCrypt error means return -1. */
  4169. if (ret <= 0) {
  4170. ret = WOLFSSL_FATAL_ERROR;
  4171. }
  4172. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4173. return ret;
  4174. }
  4175. /*
  4176. * RSA misc operation APIs
  4177. */
  4178. /* Calculate d mod p-1 and q-1 into BNs.
  4179. *
  4180. * Not OpenSSL API.
  4181. *
  4182. * @param [in, out] rsa RSA key.
  4183. * @return 1 on success.
  4184. * @return -1 on failure.
  4185. */
  4186. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4187. {
  4188. int ret = 1;
  4189. int err;
  4190. mp_int* t = NULL;
  4191. #ifdef WOLFSSL_SMALL_STACK
  4192. mp_int *tmp = NULL;
  4193. #else
  4194. mp_int tmp[1];
  4195. #endif
  4196. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4197. /* Validate parameters. */
  4198. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4199. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4200. WOLFSSL_ERROR_MSG("rsa no init error");
  4201. ret = WOLFSSL_FATAL_ERROR;
  4202. }
  4203. #ifdef WOLFSSL_SMALL_STACK
  4204. if (ret == 1) {
  4205. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4206. DYNAMIC_TYPE_TMP_BUFFER);
  4207. if (tmp == NULL) {
  4208. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4209. ret = WOLFSSL_FATAL_ERROR;
  4210. }
  4211. }
  4212. #endif
  4213. if (ret == 1) {
  4214. /* Initialize temp MP integer. */
  4215. if (mp_init(tmp) != MP_OKAY) {
  4216. WOLFSSL_ERROR_MSG("mp_init error");
  4217. ret = WOLFSSL_FATAL_ERROR;
  4218. }
  4219. }
  4220. if (ret == 1) {
  4221. t = tmp;
  4222. /* Sub 1 from p into temp. */
  4223. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4224. if (err != MP_OKAY) {
  4225. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4226. ret = WOLFSSL_FATAL_ERROR;
  4227. }
  4228. }
  4229. if (ret == 1) {
  4230. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4231. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4232. (mp_int*)rsa->dmp1->internal);
  4233. if (err != MP_OKAY) {
  4234. WOLFSSL_ERROR_MSG("mp_mod error");
  4235. ret = WOLFSSL_FATAL_ERROR;
  4236. }
  4237. }
  4238. if (ret == 1) {
  4239. /* Sub 1 from q into temp. */
  4240. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4241. if (err != MP_OKAY) {
  4242. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4243. ret = WOLFSSL_FATAL_ERROR;
  4244. }
  4245. }
  4246. if (ret == 1) {
  4247. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4248. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4249. (mp_int*)rsa->dmq1->internal);
  4250. if (err != MP_OKAY) {
  4251. WOLFSSL_ERROR_MSG("mp_mod error");
  4252. ret = WOLFSSL_FATAL_ERROR;
  4253. }
  4254. }
  4255. mp_clear(t);
  4256. #ifdef WOLFSSL_SMALL_STACK
  4257. if (rsa != NULL) {
  4258. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4259. }
  4260. #endif
  4261. return ret;
  4262. }
  4263. #ifndef NO_WOLFSSL_STUB
  4264. /* Enable blinding for RSA key operations.
  4265. *
  4266. * Blinding is a compile time option in wolfCrypt.
  4267. *
  4268. * @param [in] rsa RSA key. Unused.
  4269. * @param [in] bnCtx BN context to use for blinding. Unused.
  4270. * @return 1 always.
  4271. */
  4272. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4273. {
  4274. WOLFSSL_STUB("RSA_blinding_on");
  4275. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4276. (void)rsa;
  4277. (void)bnCtx;
  4278. return 1; /* on by default */
  4279. }
  4280. #endif
  4281. #endif /* OPENSSL_EXTRA */
  4282. #endif /* !NO_RSA */
  4283. /*******************************************************************************
  4284. * END OF RSA API
  4285. ******************************************************************************/
  4286. /*******************************************************************************
  4287. * START OF DSA API
  4288. ******************************************************************************/
  4289. #ifndef NO_DSA
  4290. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4291. !defined(NO_STDIO_FILESYSTEM)
  4292. /* return code compliant with OpenSSL :
  4293. * 1 if success, 0 if error
  4294. */
  4295. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4296. {
  4297. int ret = 1;
  4298. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4299. if (fp == XBADFILE || dsa == NULL) {
  4300. ret = 0;
  4301. }
  4302. if (ret == 1 && dsa->p != NULL) {
  4303. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4304. if (pBits == 0) {
  4305. ret = 0;
  4306. }
  4307. else {
  4308. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4309. ret = 0;
  4310. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4311. ret = 0;
  4312. }
  4313. }
  4314. if (ret == 1 && dsa->priv_key != NULL) {
  4315. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4316. }
  4317. if (ret == 1 && dsa->pub_key != NULL) {
  4318. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4319. }
  4320. if (ret == 1 && dsa->p != NULL) {
  4321. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4322. }
  4323. if (ret == 1 && dsa->q != NULL) {
  4324. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4325. }
  4326. if (ret == 1 && dsa->g != NULL) {
  4327. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4328. }
  4329. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4330. return ret;
  4331. }
  4332. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4333. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4334. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4335. {
  4336. if (dsa) {
  4337. dsa->p = NULL;
  4338. dsa->q = NULL;
  4339. dsa->g = NULL;
  4340. dsa->pub_key = NULL;
  4341. dsa->priv_key = NULL;
  4342. dsa->internal = NULL;
  4343. dsa->inSet = 0;
  4344. dsa->exSet = 0;
  4345. }
  4346. }
  4347. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4348. {
  4349. WOLFSSL_DSA* external;
  4350. DsaKey* key;
  4351. WOLFSSL_MSG("wolfSSL_DSA_new");
  4352. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4353. if (key == NULL) {
  4354. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4355. return NULL;
  4356. }
  4357. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4358. DYNAMIC_TYPE_DSA);
  4359. if (external == NULL) {
  4360. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4361. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4362. return NULL;
  4363. }
  4364. InitwolfSSL_DSA(external);
  4365. if (wc_InitDsaKey(key) != 0) {
  4366. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4367. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4368. wolfSSL_DSA_free(external);
  4369. return NULL;
  4370. }
  4371. external->internal = key;
  4372. return external;
  4373. }
  4374. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4375. {
  4376. WOLFSSL_MSG("wolfSSL_DSA_free");
  4377. if (dsa) {
  4378. if (dsa->internal) {
  4379. FreeDsaKey((DsaKey*)dsa->internal);
  4380. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4381. dsa->internal = NULL;
  4382. }
  4383. wolfSSL_BN_free(dsa->priv_key);
  4384. wolfSSL_BN_free(dsa->pub_key);
  4385. wolfSSL_BN_free(dsa->g);
  4386. wolfSSL_BN_free(dsa->q);
  4387. wolfSSL_BN_free(dsa->p);
  4388. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4389. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4390. /* dsa = NULL, don't try to access or double free it */
  4391. }
  4392. }
  4393. /* wolfSSL -> OpenSSL */
  4394. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4395. {
  4396. DsaKey* key;
  4397. WOLFSSL_MSG("Entering SetDsaExternal");
  4398. if (dsa == NULL || dsa->internal == NULL) {
  4399. WOLFSSL_MSG("dsa key NULL error");
  4400. return WOLFSSL_FATAL_ERROR;
  4401. }
  4402. key = (DsaKey*)dsa->internal;
  4403. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4404. WOLFSSL_MSG("dsa p key error");
  4405. return WOLFSSL_FATAL_ERROR;
  4406. }
  4407. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4408. WOLFSSL_MSG("dsa q key error");
  4409. return WOLFSSL_FATAL_ERROR;
  4410. }
  4411. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4412. WOLFSSL_MSG("dsa g key error");
  4413. return WOLFSSL_FATAL_ERROR;
  4414. }
  4415. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4416. WOLFSSL_MSG("dsa y key error");
  4417. return WOLFSSL_FATAL_ERROR;
  4418. }
  4419. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4420. WOLFSSL_MSG("dsa x key error");
  4421. return WOLFSSL_FATAL_ERROR;
  4422. }
  4423. dsa->exSet = 1;
  4424. return 1;
  4425. }
  4426. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4427. #ifdef OPENSSL_EXTRA
  4428. /* Openssl -> WolfSSL */
  4429. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4430. {
  4431. DsaKey* key;
  4432. WOLFSSL_MSG("Entering SetDsaInternal");
  4433. if (dsa == NULL || dsa->internal == NULL) {
  4434. WOLFSSL_MSG("dsa key NULL error");
  4435. return WOLFSSL_FATAL_ERROR;
  4436. }
  4437. key = (DsaKey*)dsa->internal;
  4438. if (dsa->p != NULL &&
  4439. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4440. WOLFSSL_MSG("rsa p key error");
  4441. return WOLFSSL_FATAL_ERROR;
  4442. }
  4443. if (dsa->q != NULL &&
  4444. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4445. WOLFSSL_MSG("rsa q key error");
  4446. return WOLFSSL_FATAL_ERROR;
  4447. }
  4448. if (dsa->g != NULL &&
  4449. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4450. WOLFSSL_MSG("rsa g key error");
  4451. return WOLFSSL_FATAL_ERROR;
  4452. }
  4453. if (dsa->pub_key != NULL) {
  4454. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4455. WOLFSSL_MSG("rsa pub_key error");
  4456. return WOLFSSL_FATAL_ERROR;
  4457. }
  4458. /* public key */
  4459. key->type = DSA_PUBLIC;
  4460. }
  4461. if (dsa->priv_key != NULL) {
  4462. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4463. WOLFSSL_MSG("rsa priv_key error");
  4464. return WOLFSSL_FATAL_ERROR;
  4465. }
  4466. /* private key */
  4467. key->type = DSA_PRIVATE;
  4468. }
  4469. dsa->inSet = 1;
  4470. return 1;
  4471. }
  4472. /* return code compliant with OpenSSL :
  4473. * 1 if success, 0 if error
  4474. */
  4475. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4476. {
  4477. int ret = 0;
  4478. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4479. if (dsa == NULL || dsa->internal == NULL) {
  4480. WOLFSSL_MSG("Bad arguments");
  4481. return 0;
  4482. }
  4483. if (dsa->inSet == 0) {
  4484. WOLFSSL_MSG("No DSA internal set, do it");
  4485. if (SetDsaInternal(dsa) != 1) {
  4486. WOLFSSL_MSG("SetDsaInternal failed");
  4487. return ret;
  4488. }
  4489. }
  4490. #ifdef WOLFSSL_KEY_GEN
  4491. {
  4492. int initTmpRng = 0;
  4493. WC_RNG *rng = NULL;
  4494. #ifdef WOLFSSL_SMALL_STACK
  4495. WC_RNG *tmpRng;
  4496. #else
  4497. WC_RNG tmpRng[1];
  4498. #endif
  4499. #ifdef WOLFSSL_SMALL_STACK
  4500. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4501. if (tmpRng == NULL)
  4502. return WOLFSSL_FATAL_ERROR;
  4503. #endif
  4504. if (wc_InitRng(tmpRng) == 0) {
  4505. rng = tmpRng;
  4506. initTmpRng = 1;
  4507. }
  4508. else {
  4509. WOLFSSL_MSG("Bad RNG Init, trying global");
  4510. rng = wolfssl_get_global_rng();
  4511. }
  4512. if (rng) {
  4513. /* These were allocated above by SetDsaInternal(). They should
  4514. * be cleared before wc_MakeDsaKey() which reinitializes
  4515. * x and y. */
  4516. mp_clear(&((DsaKey*)dsa->internal)->x);
  4517. mp_clear(&((DsaKey*)dsa->internal)->y);
  4518. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4519. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4520. else if (SetDsaExternal(dsa) != 1)
  4521. WOLFSSL_MSG("SetDsaExternal failed");
  4522. else
  4523. ret = 1;
  4524. }
  4525. if (initTmpRng)
  4526. wc_FreeRng(tmpRng);
  4527. #ifdef WOLFSSL_SMALL_STACK
  4528. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4529. #endif
  4530. }
  4531. #else /* WOLFSSL_KEY_GEN */
  4532. WOLFSSL_MSG("No Key Gen built in");
  4533. #endif
  4534. return ret;
  4535. }
  4536. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4537. */
  4538. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4539. int seedLen, int* counterRet, unsigned long* hRet,
  4540. WOLFSSL_BN_CB cb, void* CBArg)
  4541. {
  4542. WOLFSSL_DSA* dsa;
  4543. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4544. (void)cb;
  4545. (void)CBArg;
  4546. dsa = wolfSSL_DSA_new();
  4547. if (dsa == NULL) {
  4548. return NULL;
  4549. }
  4550. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4551. counterRet, hRet, NULL) != 1) {
  4552. wolfSSL_DSA_free(dsa);
  4553. return NULL;
  4554. }
  4555. return dsa;
  4556. }
  4557. /* return code compliant with OpenSSL :
  4558. * 1 if success, 0 if error
  4559. */
  4560. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4561. unsigned char* seed, int seedLen,
  4562. int* counterRet,
  4563. unsigned long* hRet, void* cb)
  4564. {
  4565. int ret = 0;
  4566. (void)bits;
  4567. (void)seed;
  4568. (void)seedLen;
  4569. (void)counterRet;
  4570. (void)hRet;
  4571. (void)cb;
  4572. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4573. if (dsa == NULL || dsa->internal == NULL) {
  4574. WOLFSSL_MSG("Bad arguments");
  4575. return 0;
  4576. }
  4577. #ifdef WOLFSSL_KEY_GEN
  4578. {
  4579. int initTmpRng = 0;
  4580. WC_RNG *rng = NULL;
  4581. #ifdef WOLFSSL_SMALL_STACK
  4582. WC_RNG *tmpRng;
  4583. #else
  4584. WC_RNG tmpRng[1];
  4585. #endif
  4586. #ifdef WOLFSSL_SMALL_STACK
  4587. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4588. if (tmpRng == NULL)
  4589. return WOLFSSL_FATAL_ERROR;
  4590. #endif
  4591. if (wc_InitRng(tmpRng) == 0) {
  4592. rng = tmpRng;
  4593. initTmpRng = 1;
  4594. }
  4595. else {
  4596. WOLFSSL_MSG("Bad RNG Init, trying global");
  4597. rng = wolfssl_get_global_rng();
  4598. }
  4599. if (rng) {
  4600. if (wc_MakeDsaParameters(rng, bits,
  4601. (DsaKey*)dsa->internal) != MP_OKAY)
  4602. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4603. else if (SetDsaExternal(dsa) != 1)
  4604. WOLFSSL_MSG("SetDsaExternal failed");
  4605. else
  4606. ret = 1;
  4607. }
  4608. if (initTmpRng)
  4609. wc_FreeRng(tmpRng);
  4610. #ifdef WOLFSSL_SMALL_STACK
  4611. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4612. #endif
  4613. }
  4614. #else /* WOLFSSL_KEY_GEN */
  4615. WOLFSSL_MSG("No Key Gen built in");
  4616. #endif
  4617. return ret;
  4618. }
  4619. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4620. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4621. {
  4622. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4623. if (d != NULL) {
  4624. if (p != NULL)
  4625. *p = d->p;
  4626. if (q != NULL)
  4627. *q = d->q;
  4628. if (g != NULL)
  4629. *g = d->g;
  4630. }
  4631. }
  4632. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4633. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4634. {
  4635. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4636. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4637. WOLFSSL_MSG("Bad parameter");
  4638. return 0;
  4639. }
  4640. wolfSSL_BN_free(d->p);
  4641. wolfSSL_BN_free(d->q);
  4642. wolfSSL_BN_free(d->g);
  4643. d->p = p;
  4644. d->q = q;
  4645. d->g = g;
  4646. return 1;
  4647. }
  4648. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4649. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4650. {
  4651. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4652. if (d != NULL) {
  4653. if (pub_key != NULL)
  4654. *pub_key = d->pub_key;
  4655. if (priv_key != NULL)
  4656. *priv_key = d->priv_key;
  4657. }
  4658. }
  4659. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4660. WOLFSSL_BIGNUM *priv_key)
  4661. {
  4662. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4663. /* The private key may be NULL */
  4664. if (d->pub_key == NULL && pub_key == NULL) {
  4665. WOLFSSL_MSG("Bad parameter");
  4666. return 0;
  4667. }
  4668. if (pub_key != NULL) {
  4669. wolfSSL_BN_free(d->pub_key);
  4670. d->pub_key = pub_key;
  4671. }
  4672. if (priv_key != NULL) {
  4673. wolfSSL_BN_free(d->priv_key);
  4674. d->priv_key = priv_key;
  4675. }
  4676. return 1;
  4677. }
  4678. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4679. {
  4680. WOLFSSL_DSA_SIG* sig;
  4681. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4682. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4683. DYNAMIC_TYPE_OPENSSL);
  4684. if (sig)
  4685. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4686. return sig;
  4687. }
  4688. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4689. {
  4690. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4691. if (sig) {
  4692. if (sig->r) {
  4693. wolfSSL_BN_free(sig->r);
  4694. }
  4695. if (sig->s) {
  4696. wolfSSL_BN_free(sig->s);
  4697. }
  4698. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4699. }
  4700. }
  4701. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4702. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4703. {
  4704. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4705. if (sig != NULL) {
  4706. *r = sig->r;
  4707. *s = sig->s;
  4708. }
  4709. }
  4710. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4711. WOLFSSL_BIGNUM *s)
  4712. {
  4713. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4714. if (r == NULL || s == NULL) {
  4715. WOLFSSL_MSG("Bad parameter");
  4716. return 0;
  4717. }
  4718. wolfSSL_BN_clear_free(sig->r);
  4719. wolfSSL_BN_clear_free(sig->s);
  4720. sig->r = r;
  4721. sig->s = s;
  4722. return 1;
  4723. }
  4724. #ifndef HAVE_SELFTEST
  4725. /**
  4726. *
  4727. * @param sig The input signature to encode
  4728. * @param out The output buffer. If *out is NULL then a new buffer is
  4729. * allocated. Otherwise the output is written to the buffer.
  4730. * @return length on success and -1 on error
  4731. */
  4732. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4733. {
  4734. /* Space for sequence + two asn ints */
  4735. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4736. word32 bufLen = sizeof(buf);
  4737. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4738. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4739. out == NULL) {
  4740. WOLFSSL_MSG("Bad function arguments");
  4741. return WOLFSSL_FATAL_ERROR;
  4742. }
  4743. if (StoreECC_DSA_Sig(buf, &bufLen,
  4744. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4745. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4746. return WOLFSSL_FATAL_ERROR;
  4747. }
  4748. if (*out == NULL) {
  4749. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4750. if (tmp == NULL) {
  4751. WOLFSSL_MSG("malloc error");
  4752. return WOLFSSL_FATAL_ERROR;
  4753. }
  4754. *out = tmp;
  4755. }
  4756. XMEMCPY(*out, buf, bufLen);
  4757. return (int)bufLen;
  4758. }
  4759. /**
  4760. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4761. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4762. */
  4763. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4764. {
  4765. WOLFSSL_DSA_SIG* ret;
  4766. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4767. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4768. return NULL;
  4769. }
  4770. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4771. WOLFSSL_MSG("wolfSSL_BN_new error");
  4772. wolfSSL_DSA_SIG_free(ret);
  4773. return NULL;
  4774. }
  4775. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4776. WOLFSSL_MSG("wolfSSL_BN_new error");
  4777. wolfSSL_DSA_SIG_free(ret);
  4778. return NULL;
  4779. }
  4780. return ret;
  4781. }
  4782. /**
  4783. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4784. * ASN1_SEQUENCE
  4785. * ASN1_INTEGER (DSA r)
  4786. * ASN1_INTEGER (DSA s)
  4787. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4788. * length then this API interprets this as two unsigned binary numbers.
  4789. * @param sig If non-null then free'd first and then newly created
  4790. * WOLFSSL_DSA_SIG is assigned
  4791. * @param pp Input buffer that is moved forward on success
  4792. * @param length Length of input buffer
  4793. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4794. */
  4795. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4796. const unsigned char **pp, long length)
  4797. {
  4798. WOLFSSL_DSA_SIG* ret;
  4799. mp_int* r;
  4800. mp_int* s;
  4801. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4802. if (pp == NULL || *pp == NULL || length < 0) {
  4803. WOLFSSL_MSG("Bad function arguments");
  4804. return NULL;
  4805. }
  4806. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4807. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4808. return NULL;
  4809. }
  4810. r = (mp_int*)ret->r->internal;
  4811. s = (mp_int*)ret->s->internal;
  4812. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4813. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4814. /* Two raw numbers of length/2 size each */
  4815. if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) {
  4816. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4817. wolfSSL_DSA_SIG_free(ret);
  4818. return NULL;
  4819. }
  4820. if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) !=
  4821. 0) {
  4822. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4823. wolfSSL_DSA_SIG_free(ret);
  4824. return NULL;
  4825. }
  4826. *pp += length;
  4827. }
  4828. else {
  4829. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4830. wolfSSL_DSA_SIG_free(ret);
  4831. return NULL;
  4832. }
  4833. }
  4834. else {
  4835. /* DecodeECC_DSA_Sig success move pointer forward */
  4836. #ifndef NO_STRICT_ECDSA_LEN
  4837. *pp += length;
  4838. #else
  4839. {
  4840. /* We need to figure out how much to move by ourselves */
  4841. word32 idx = 0;
  4842. int len = 0;
  4843. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4844. WOLFSSL_MSG("GetSequence error");
  4845. wolfSSL_DSA_SIG_free(ret);
  4846. return NULL;
  4847. }
  4848. *pp += len;
  4849. }
  4850. #endif
  4851. }
  4852. if (sig != NULL) {
  4853. if (*sig != NULL)
  4854. wolfSSL_DSA_SIG_free(*sig);
  4855. *sig = ret;
  4856. }
  4857. return ret;
  4858. }
  4859. #endif /* HAVE_SELFTEST */
  4860. /* return 1 on success, < 0 otherwise */
  4861. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4862. WOLFSSL_DSA* dsa)
  4863. {
  4864. int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
  4865. int initTmpRng = 0;
  4866. WC_RNG* rng = NULL;
  4867. #ifdef WOLFSSL_SMALL_STACK
  4868. WC_RNG* tmpRng = NULL;
  4869. #else
  4870. WC_RNG tmpRng[1];
  4871. #endif
  4872. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4873. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4874. WOLFSSL_MSG("Bad function arguments");
  4875. return WOLFSSL_FATAL_ERROR;
  4876. }
  4877. if (dsa->inSet == 0) {
  4878. WOLFSSL_MSG("No DSA internal set, do it");
  4879. if (SetDsaInternal(dsa) != 1) {
  4880. WOLFSSL_MSG("SetDsaInternal failed");
  4881. return WOLFSSL_FATAL_ERROR;
  4882. }
  4883. }
  4884. #ifdef WOLFSSL_SMALL_STACK
  4885. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4886. if (tmpRng == NULL)
  4887. return WOLFSSL_FATAL_ERROR;
  4888. #endif
  4889. if (wc_InitRng(tmpRng) == 0) {
  4890. rng = tmpRng;
  4891. initTmpRng = 1;
  4892. }
  4893. else {
  4894. WOLFSSL_MSG("Bad RNG Init, trying global");
  4895. #ifdef WOLFSSL_SMALL_STACK
  4896. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4897. tmpRng = NULL;
  4898. #endif
  4899. rng = wolfssl_get_global_rng();
  4900. if (! rng)
  4901. return WOLFSSL_FATAL_ERROR;
  4902. }
  4903. if (rng) {
  4904. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0) {
  4905. WOLFSSL_MSG("DsaSign failed");
  4906. ret = WOLFSSL_FATAL_ERROR;
  4907. }
  4908. else
  4909. ret = WOLFSSL_SUCCESS;
  4910. }
  4911. if (initTmpRng)
  4912. wc_FreeRng(tmpRng);
  4913. #ifdef WOLFSSL_SMALL_STACK
  4914. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4915. #endif
  4916. return ret;
  4917. }
  4918. #ifndef HAVE_SELFTEST
  4919. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4920. int inLen, WOLFSSL_DSA* dsa)
  4921. {
  4922. byte sigBin[DSA_MAX_SIG_SIZE];
  4923. const byte *tmp = sigBin;
  4924. int sigLen;
  4925. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4926. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4927. WOLFSSL_MSG("Bad function arguments");
  4928. return NULL;
  4929. }
  4930. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4931. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4932. return NULL;
  4933. }
  4934. if (dsa->internal == NULL) {
  4935. WOLFSSL_MSG("dsa->internal is null");
  4936. return NULL;
  4937. }
  4938. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4939. if (sigLen <= 0) {
  4940. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4941. return NULL;
  4942. }
  4943. /* 2 * sigLen for the two points r and s */
  4944. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4945. }
  4946. #endif /* !HAVE_SELFTEST */
  4947. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4948. WOLFSSL_DSA* dsa, int *dsacheck)
  4949. {
  4950. int ret;
  4951. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4952. if (d == NULL || sig == NULL || dsa == NULL) {
  4953. WOLFSSL_MSG("Bad function arguments");
  4954. return WOLFSSL_FATAL_ERROR;
  4955. }
  4956. if (dsa->inSet == 0)
  4957. {
  4958. WOLFSSL_MSG("No DSA internal set, do it");
  4959. if (SetDsaInternal(dsa) != 1) {
  4960. WOLFSSL_MSG("SetDsaInternal failed");
  4961. return WOLFSSL_FATAL_ERROR;
  4962. }
  4963. }
  4964. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4965. if (ret != 0 || *dsacheck != 1) {
  4966. WOLFSSL_MSG("DsaVerify failed");
  4967. return ret;
  4968. }
  4969. return 1;
  4970. }
  4971. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4972. {
  4973. if (!d)
  4974. return 0;
  4975. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4976. return 0;
  4977. return wolfSSL_BN_num_bits(d->p);
  4978. }
  4979. #ifndef HAVE_SELFTEST
  4980. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4981. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4982. {
  4983. int dsacheck, sz;
  4984. byte sigBin[DSA_MAX_SIG_SIZE];
  4985. byte* sigBinPtr = sigBin;
  4986. DsaKey* key;
  4987. int qSz;
  4988. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4989. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4990. WOLFSSL_MSG("Bad function arguments");
  4991. return 0;
  4992. }
  4993. if (!sig->r || !sig->s) {
  4994. WOLFSSL_MSG("No signature found in DSA_SIG");
  4995. return 0;
  4996. }
  4997. if (dsa->inSet == 0) {
  4998. WOLFSSL_MSG("No DSA internal set, do it");
  4999. if (SetDsaInternal(dsa) != 1) {
  5000. WOLFSSL_MSG("SetDsaInternal failed");
  5001. return 0;
  5002. }
  5003. }
  5004. key = (DsaKey*)dsa->internal;
  5005. if (key == NULL) {
  5006. WOLFSSL_MSG("dsa->internal is null");
  5007. return 0;
  5008. }
  5009. qSz = mp_unsigned_bin_size(&key->q);
  5010. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  5011. WOLFSSL_MSG("mp_unsigned_bin_size error");
  5012. return 0;
  5013. }
  5014. /* read r */
  5015. /* front pad with zeros */
  5016. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  5017. return 0;
  5018. while (sz++ < qSz)
  5019. *sigBinPtr++ = 0;
  5020. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  5021. return 0;
  5022. /* Move to s */
  5023. sigBinPtr = sigBin + qSz;
  5024. /* read s */
  5025. /* front pad with zeros */
  5026. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  5027. return 0;
  5028. while (sz++ < qSz)
  5029. *sigBinPtr++ = 0;
  5030. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  5031. return 0;
  5032. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  5033. != 1) || dsacheck != 1) {
  5034. return 0;
  5035. }
  5036. return 1;
  5037. }
  5038. #endif /* !HAVE_SELFTEST */
  5039. int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  5040. unsigned char** out)
  5041. {
  5042. int ret = 0;
  5043. word32 derLen = 0;
  5044. int preAllocated = 1;
  5045. DsaKey* key = NULL;
  5046. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  5047. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  5048. ret = BAD_FUNC_ARG;
  5049. }
  5050. if (ret == 0) {
  5051. key = (DsaKey*)dsa->internal;
  5052. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  5053. if (ret == WC_NO_ERR_TRACE(LENGTH_ONLY_E)) {
  5054. ret = 0;
  5055. }
  5056. }
  5057. if (ret == 0 && *out == NULL) {
  5058. /* If we're allocating out for the caller, we don't increment out just
  5059. past the end of the DER buffer. If out is already allocated, we do.
  5060. (OpenSSL convention) */
  5061. preAllocated = 0;
  5062. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  5063. if (*out == NULL) {
  5064. ret = MEMORY_E;
  5065. }
  5066. }
  5067. if (ret == 0) {
  5068. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  5069. }
  5070. if (ret >= 0 && preAllocated == 1) {
  5071. *out += derLen;
  5072. }
  5073. if (ret < 0 && preAllocated == 0) {
  5074. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  5075. }
  5076. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  5077. return ret;
  5078. }
  5079. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  5080. long derLen)
  5081. {
  5082. WOLFSSL_DSA* ret = NULL;
  5083. int err = 0;
  5084. word32 idx = 0;
  5085. int asnLen;
  5086. DsaKey* internalKey = NULL;
  5087. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  5088. if (der == NULL || *der == NULL || derLen <= 0) {
  5089. err = 1;
  5090. }
  5091. if (err == 0) {
  5092. ret = wolfSSL_DSA_new();
  5093. err = ret == NULL;
  5094. }
  5095. if (err == 0) {
  5096. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  5097. }
  5098. if (err == 0) {
  5099. internalKey = (DsaKey*)ret->internal;
  5100. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  5101. }
  5102. if (err == 0) {
  5103. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  5104. }
  5105. if (err == 0) {
  5106. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  5107. }
  5108. if (err == 0) {
  5109. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  5110. != 1;
  5111. }
  5112. if (err == 0) {
  5113. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  5114. != 1;
  5115. }
  5116. if (err == 0) {
  5117. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  5118. != 1;
  5119. }
  5120. if (err == 0 && dsa != NULL) {
  5121. *dsa = ret;
  5122. }
  5123. if (err != 0 && ret != NULL) {
  5124. wolfSSL_DSA_free(ret);
  5125. ret = NULL;
  5126. }
  5127. return ret;
  5128. }
  5129. #if defined(WOLFSSL_KEY_GEN)
  5130. #ifndef NO_BIO
  5131. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  5132. * Returns 1 or 0
  5133. */
  5134. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  5135. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  5136. wc_pem_password_cb* cb, void* arg)
  5137. {
  5138. int ret = 1;
  5139. byte *pem = NULL;
  5140. int pLen = 0;
  5141. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  5142. (void)cb;
  5143. (void)arg;
  5144. /* Validate parameters. */
  5145. if ((bio == NULL) || (dsa == NULL)) {
  5146. WOLFSSL_MSG("Bad Function Arguments");
  5147. ret = 0;
  5148. }
  5149. if (ret == 1) {
  5150. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, cipher, passwd, passwdSz,
  5151. &pem, &pLen);
  5152. }
  5153. /* Write PEM to BIO. */
  5154. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  5155. WOLFSSL_ERROR_MSG("DSA private key BIO write failed");
  5156. ret = 0;
  5157. }
  5158. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5159. return ret;
  5160. }
  5161. #ifndef HAVE_SELFTEST
  5162. /* Encode the DSA public key as DER.
  5163. *
  5164. * @param [in] key DSA key to encode.
  5165. * @param [out] der Pointer through which buffer is returned.
  5166. * @param [in] heap Heap hint.
  5167. * @return Size of encoding on success.
  5168. * @return 0 on error.
  5169. */
  5170. static int wolfssl_dsa_key_to_pubkey_der(WOLFSSL_DSA* key, unsigned char** der,
  5171. void* heap)
  5172. {
  5173. int sz;
  5174. unsigned char* buf = NULL;
  5175. /* Use maximum encoded size to allocate. */
  5176. sz = MAX_DSA_PUBKEY_SZ;
  5177. /* Allocate memory to hold encoding. */
  5178. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5179. if (buf == NULL) {
  5180. WOLFSSL_MSG("malloc failed");
  5181. sz = 0;
  5182. }
  5183. if (sz > 0) {
  5184. /* Encode public key to DER using wolfSSL. */
  5185. sz = wc_DsaKeyToPublicDer((DsaKey*)key->internal, buf, (word32)sz);
  5186. if (sz < 0) {
  5187. WOLFSSL_MSG("wc_DsaKeyToPublicDer failed");
  5188. sz = 0;
  5189. }
  5190. }
  5191. /* Return buffer on success. */
  5192. if (sz > 0) {
  5193. *der = buf;
  5194. }
  5195. else {
  5196. /* Dispose of any dynamically allocated data not returned. */
  5197. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5198. }
  5199. return sz;
  5200. }
  5201. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5202. * Returns 1 or 0
  5203. */
  5204. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5205. {
  5206. int ret = 1;
  5207. unsigned char* derBuf = NULL;
  5208. int derSz = 0;
  5209. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5210. /* Validate parameters. */
  5211. if ((bio == NULL) || (dsa == NULL)) {
  5212. WOLFSSL_MSG("Bad Function Arguments");
  5213. return 0;
  5214. }
  5215. /* Encode public key in EC key as DER. */
  5216. derSz = wolfssl_dsa_key_to_pubkey_der(dsa, &derBuf, bio->heap);
  5217. if (derSz == 0) {
  5218. ret = 0;
  5219. }
  5220. /* Write out to BIO the PEM encoding of the DSA public key. */
  5221. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  5222. PUBLICKEY_TYPE) != 1)) {
  5223. ret = 0;
  5224. }
  5225. /* Dispose of any dynamically allocated data. */
  5226. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5227. return ret;
  5228. }
  5229. #endif /* HAVE_SELFTEST */
  5230. #endif /* !NO_BIO */
  5231. /* return code compliant with OpenSSL :
  5232. * 1 if success, 0 if error
  5233. */
  5234. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5235. const EVP_CIPHER* cipher,
  5236. unsigned char* passwd, int passwdSz,
  5237. unsigned char **pem, int *pLen)
  5238. {
  5239. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5240. byte *derBuf, *tmp, *cipherInfo = NULL;
  5241. int der_max_len = 0, derSz = 0;
  5242. const int type = DSA_PRIVATEKEY_TYPE;
  5243. const char* header = NULL;
  5244. const char* footer = NULL;
  5245. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5246. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5247. WOLFSSL_MSG("Bad function arguments");
  5248. return 0;
  5249. }
  5250. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5251. return 0;
  5252. if (dsa->inSet == 0) {
  5253. WOLFSSL_MSG("No DSA internal set, do it");
  5254. if (SetDsaInternal(dsa) != 1) {
  5255. WOLFSSL_MSG("SetDsaInternal failed");
  5256. return 0;
  5257. }
  5258. }
  5259. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5260. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER);
  5261. if (derBuf == NULL) {
  5262. WOLFSSL_MSG("malloc failed");
  5263. return 0;
  5264. }
  5265. /* Key to DER */
  5266. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5267. if (derSz < 0) {
  5268. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5269. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5270. return 0;
  5271. }
  5272. /* encrypt DER buffer if required */
  5273. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5274. int ret;
  5275. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5276. passwd, passwdSz, &cipherInfo, der_max_len);
  5277. if (ret != 1) {
  5278. WOLFSSL_MSG("EncryptDerKey failed");
  5279. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5280. return ret;
  5281. }
  5282. /* tmp buffer with a max size */
  5283. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5284. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5285. }
  5286. else { /* tmp buffer with a max size */
  5287. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5288. (int)XSTRLEN(footer) + 1;
  5289. }
  5290. tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM);
  5291. if (tmp == NULL) {
  5292. WOLFSSL_MSG("malloc failed");
  5293. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5294. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5295. return 0;
  5296. }
  5297. /* DER to PEM */
  5298. *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo,
  5299. type);
  5300. if (*pLen <= 0) {
  5301. WOLFSSL_MSG("wc_DerToPemEx failed");
  5302. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5303. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5304. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5305. return 0;
  5306. }
  5307. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5308. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5309. *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY);
  5310. if (*pem == NULL) {
  5311. WOLFSSL_MSG("malloc failed");
  5312. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5313. return 0;
  5314. }
  5315. XMEMSET(*pem, 0, (size_t)((*pLen)+1));
  5316. if (XMEMCPY(*pem, tmp, (size_t)*pLen) == NULL) {
  5317. WOLFSSL_MSG("XMEMCPY failed");
  5318. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5319. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5320. return 0;
  5321. }
  5322. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5323. return 1;
  5324. #else
  5325. (void)dsa;
  5326. (void)cipher;
  5327. (void)passwd;
  5328. (void)passwdSz;
  5329. (void)pem;
  5330. (void)pLen;
  5331. return 0;
  5332. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5333. }
  5334. #ifndef NO_FILESYSTEM
  5335. /* return code compliant with OpenSSL :
  5336. * 1 if success, 0 if error
  5337. */
  5338. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5339. const EVP_CIPHER *enc,
  5340. unsigned char *kstr, int klen,
  5341. wc_pem_password_cb *cb, void *u)
  5342. {
  5343. byte *pem;
  5344. int pLen, ret;
  5345. (void)cb;
  5346. (void)u;
  5347. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5348. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5349. WOLFSSL_MSG("Bad function arguments");
  5350. return 0;
  5351. }
  5352. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5353. &pLen);
  5354. if (ret != 1) {
  5355. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5356. return 0;
  5357. }
  5358. ret = (int)XFWRITE(pem, (size_t)pLen, 1, fp);
  5359. if (ret != 1) {
  5360. WOLFSSL_MSG("DSA private key file write failed");
  5361. return 0;
  5362. }
  5363. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5364. return 1;
  5365. }
  5366. #endif /* NO_FILESYSTEM */
  5367. #endif /* defined(WOLFSSL_KEY_GEN) */
  5368. #ifndef NO_FILESYSTEM
  5369. /* return code compliant with OpenSSL :
  5370. * 1 if success, 0 if error
  5371. */
  5372. #ifndef NO_WOLFSSL_STUB
  5373. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5374. {
  5375. (void)fp;
  5376. (void)x;
  5377. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5378. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5379. return 0;
  5380. }
  5381. #endif
  5382. #endif /* NO_FILESYSTEM */
  5383. #ifndef NO_BIO
  5384. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5385. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5386. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5387. * the results to be an DSA key.
  5388. *
  5389. * bio structure to read DSA private key from
  5390. * dsa if not null is then set to the result
  5391. * cb password callback for reading PEM
  5392. * pass password string
  5393. *
  5394. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5395. */
  5396. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5397. WOLFSSL_DSA** dsa,
  5398. wc_pem_password_cb* cb,
  5399. void* pass)
  5400. {
  5401. WOLFSSL_EVP_PKEY* pkey = NULL;
  5402. WOLFSSL_DSA* local;
  5403. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5404. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5405. if (pkey == NULL) {
  5406. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5407. return NULL;
  5408. }
  5409. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5410. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5411. * to avoid having it free'd */
  5412. pkey->ownDsa = 0;
  5413. local = pkey->dsa;
  5414. if (dsa != NULL) {
  5415. *dsa = local;
  5416. }
  5417. wolfSSL_EVP_PKEY_free(pkey);
  5418. return local;
  5419. }
  5420. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5421. * Returns 1 or 0
  5422. */
  5423. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5424. wc_pem_password_cb* cb, void* pass)
  5425. {
  5426. WOLFSSL_EVP_PKEY* pkey;
  5427. WOLFSSL_DSA* local;
  5428. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5429. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5430. if (pkey == NULL) {
  5431. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5432. return NULL;
  5433. }
  5434. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5435. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5436. * to avoid having it free'd */
  5437. pkey->ownDsa = 0;
  5438. local = pkey->dsa;
  5439. if (dsa != NULL) {
  5440. *dsa = local;
  5441. }
  5442. wolfSSL_EVP_PKEY_free(pkey);
  5443. return local;
  5444. }
  5445. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5446. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5447. #endif /* NO_BIO */
  5448. #endif /* OPENSSL_EXTRA */
  5449. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5450. /* return 1 if success, -1 if error */
  5451. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5452. {
  5453. word32 idx = 0;
  5454. int ret;
  5455. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5456. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5457. WOLFSSL_MSG("Bad function arguments");
  5458. return WOLFSSL_FATAL_ERROR;
  5459. }
  5460. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5461. (word32)derSz);
  5462. if (ret < 0) {
  5463. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5464. return WOLFSSL_FATAL_ERROR;
  5465. }
  5466. if (SetDsaExternal(dsa) != 1) {
  5467. WOLFSSL_MSG("SetDsaExternal failed");
  5468. return WOLFSSL_FATAL_ERROR;
  5469. }
  5470. dsa->inSet = 1;
  5471. return 1;
  5472. }
  5473. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5474. returns 1 on success, or 0 on failure. */
  5475. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5476. int derSz, int opt)
  5477. {
  5478. word32 idx = 0;
  5479. int ret;
  5480. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5481. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5482. WOLFSSL_MSG("Bad function arguments");
  5483. return WOLFSSL_FATAL_ERROR;
  5484. }
  5485. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5486. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5487. (word32)derSz);
  5488. }
  5489. else {
  5490. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5491. (word32)derSz);
  5492. }
  5493. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5494. WOLFSSL_ERROR_VERBOSE(ret);
  5495. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5496. return WOLFSSL_FATAL_ERROR;
  5497. }
  5498. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5499. WOLFSSL_ERROR_VERBOSE(ret);
  5500. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5501. return WOLFSSL_FATAL_ERROR;
  5502. }
  5503. if (SetDsaExternal(dsa) != 1) {
  5504. WOLFSSL_MSG("SetDsaExternal failed");
  5505. return WOLFSSL_FATAL_ERROR;
  5506. }
  5507. dsa->inSet = 1;
  5508. return 1;
  5509. }
  5510. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5511. #ifdef OPENSSL_EXTRA
  5512. #ifndef NO_BIO
  5513. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5514. wc_pem_password_cb *cb, void *u)
  5515. {
  5516. WOLFSSL_DSA* dsa;
  5517. DsaKey* key;
  5518. int length;
  5519. unsigned char* buf;
  5520. word32 bufSz;
  5521. int ret;
  5522. word32 idx = 0;
  5523. DerBuffer* pDer;
  5524. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5525. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5526. if (ret <= 0) {
  5527. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5528. return NULL;
  5529. }
  5530. bufSz = (word32)ret;
  5531. if (cb != NULL || u != NULL) {
  5532. /*
  5533. * cb is for a call back when encountering encrypted PEM files
  5534. * if cb == NULL and u != NULL then u = null terminated password string
  5535. */
  5536. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5537. }
  5538. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5539. NULL) < 0 ) {
  5540. WOLFSSL_MSG("Issue converting from PEM to DER");
  5541. return NULL;
  5542. }
  5543. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5544. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5545. FreeDer(&pDer);
  5546. return NULL;
  5547. }
  5548. dsa = wolfSSL_DSA_new();
  5549. if (dsa == NULL) {
  5550. FreeDer(&pDer);
  5551. WOLFSSL_MSG("Error creating DSA struct");
  5552. return NULL;
  5553. }
  5554. key = (DsaKey*)dsa->internal;
  5555. if (key == NULL) {
  5556. FreeDer(&pDer);
  5557. wolfSSL_DSA_free(dsa);
  5558. WOLFSSL_MSG("Error finding DSA key struct");
  5559. return NULL;
  5560. }
  5561. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5562. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5563. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5564. WOLFSSL_MSG("dsa key error");
  5565. FreeDer(&pDer);
  5566. wolfSSL_DSA_free(dsa);
  5567. return NULL;
  5568. }
  5569. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5570. WOLFSSL_MSG("dsa p key error");
  5571. FreeDer(&pDer);
  5572. wolfSSL_DSA_free(dsa);
  5573. return NULL;
  5574. }
  5575. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5576. WOLFSSL_MSG("dsa q key error");
  5577. FreeDer(&pDer);
  5578. wolfSSL_DSA_free(dsa);
  5579. return NULL;
  5580. }
  5581. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5582. WOLFSSL_MSG("dsa g key error");
  5583. FreeDer(&pDer);
  5584. wolfSSL_DSA_free(dsa);
  5585. return NULL;
  5586. }
  5587. if (x != NULL) {
  5588. *x = dsa;
  5589. }
  5590. FreeDer(&pDer);
  5591. return dsa;
  5592. }
  5593. #endif /* !NO_BIO */
  5594. #if !defined(NO_DH)
  5595. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5596. {
  5597. WOLFSSL_DH* dh;
  5598. DhKey* key;
  5599. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5600. if (dsa == NULL) {
  5601. return NULL;
  5602. }
  5603. dh = wolfSSL_DH_new();
  5604. if (dh == NULL) {
  5605. return NULL;
  5606. }
  5607. key = (DhKey*)dh->internal;
  5608. if (dsa->p != NULL &&
  5609. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5610. != 1) {
  5611. WOLFSSL_MSG("rsa p key error");
  5612. wolfSSL_DH_free(dh);
  5613. return NULL;
  5614. }
  5615. if (dsa->g != NULL &&
  5616. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5617. != 1) {
  5618. WOLFSSL_MSG("rsa g key error");
  5619. wolfSSL_DH_free(dh);
  5620. return NULL;
  5621. }
  5622. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5623. WOLFSSL_MSG("dsa p key error");
  5624. wolfSSL_DH_free(dh);
  5625. return NULL;
  5626. }
  5627. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5628. WOLFSSL_MSG("dsa g key error");
  5629. wolfSSL_DH_free(dh);
  5630. return NULL;
  5631. }
  5632. return dh;
  5633. }
  5634. #endif /* !NO_DH */
  5635. #endif /* OPENSSL_EXTRA */
  5636. #endif /* !NO_DSA */
  5637. /*******************************************************************************
  5638. * END OF DSA API
  5639. ******************************************************************************/
  5640. /*******************************************************************************
  5641. * START OF DH API
  5642. ******************************************************************************/
  5643. #ifndef NO_DH
  5644. #ifdef OPENSSL_EXTRA
  5645. /*
  5646. * DH constructor/deconstructor APIs
  5647. */
  5648. /* Allocate and initialize a new DH key.
  5649. *
  5650. * @return DH key on success.
  5651. * @return NULL on failure.
  5652. */
  5653. WOLFSSL_DH* wolfSSL_DH_new(void)
  5654. {
  5655. int err = 0;
  5656. WOLFSSL_DH* dh = NULL;
  5657. DhKey* key = NULL;
  5658. WOLFSSL_ENTER("wolfSSL_DH_new");
  5659. /* Allocate OpenSSL DH key. */
  5660. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5661. if (dh == NULL) {
  5662. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5663. err = 1;
  5664. }
  5665. if (!err) {
  5666. /* Clear key data. */
  5667. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5668. /* Initialize reference counting. */
  5669. wolfSSL_RefInit(&dh->ref, &err);
  5670. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5671. }
  5672. if (!err) {
  5673. #endif
  5674. /* Allocate wolfSSL DH key. */
  5675. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5676. if (key == NULL) {
  5677. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5678. err = 1;
  5679. }
  5680. }
  5681. if (!err) {
  5682. /* Set and initialize wolfSSL DH key. */
  5683. dh->internal = key;
  5684. if (wc_InitDhKey(key) != 0) {
  5685. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5686. err = 1;
  5687. }
  5688. }
  5689. if (err && (dh != NULL)) {
  5690. /* Dispose of the allocated memory. */
  5691. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5692. wolfSSL_RefFree(&dh->ref);
  5693. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5694. dh = NULL;
  5695. }
  5696. return dh;
  5697. }
  5698. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5699. /* Set the DH parameters based on the NID.
  5700. *
  5701. * @param [in, out] dh DH key to set.
  5702. * @param [in] nid Numeric ID of predefined DH parameters.
  5703. * @return 0 on success.
  5704. * @return 1 on failure.
  5705. */
  5706. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5707. {
  5708. int err = 0;
  5709. const DhParams* params = NULL;
  5710. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5711. * FIPS v2 module */
  5712. switch (nid) {
  5713. #ifdef HAVE_FFDHE_2048
  5714. case NID_ffdhe2048:
  5715. params = wc_Dh_ffdhe2048_Get();
  5716. break;
  5717. #endif /* HAVE_FFDHE_2048 */
  5718. #ifdef HAVE_FFDHE_3072
  5719. case NID_ffdhe3072:
  5720. params = wc_Dh_ffdhe3072_Get();
  5721. break;
  5722. #endif /* HAVE_FFDHE_3072 */
  5723. #ifdef HAVE_FFDHE_4096
  5724. case NID_ffdhe4096:
  5725. params = wc_Dh_ffdhe4096_Get();
  5726. break;
  5727. #endif /* HAVE_FFDHE_4096 */
  5728. default:
  5729. break;
  5730. }
  5731. if (params == NULL) {
  5732. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5733. err = 1;
  5734. }
  5735. if (!err) {
  5736. /* Set prime from data retrieved. */
  5737. dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL);
  5738. if (dh->p == NULL) {
  5739. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5740. err = 1;
  5741. }
  5742. }
  5743. if (!err) {
  5744. /* Set generator from data retrieved. */
  5745. dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL);
  5746. if (dh->g == NULL) {
  5747. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5748. err = 1;
  5749. }
  5750. }
  5751. #ifdef HAVE_FFDHE_Q
  5752. if (!err) {
  5753. /* Set order from data retrieved. */
  5754. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5755. if (dh->q == NULL) {
  5756. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5757. err = 1;
  5758. }
  5759. }
  5760. #endif
  5761. /* Synchronize the external into internal DH key's parameters. */
  5762. if ((!err) && (SetDhInternal(dh) != 1)) {
  5763. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5764. err = 1;
  5765. }
  5766. if (!err) {
  5767. /* External DH key parameters were set. */
  5768. dh->exSet = 1;
  5769. }
  5770. if (err == 1) {
  5771. /* Dispose of any external parameters. */
  5772. #ifdef HAVE_FFDHE_Q
  5773. wolfSSL_BN_free(dh->q);
  5774. dh->q = NULL;
  5775. #endif
  5776. wolfSSL_BN_free(dh->p);
  5777. dh->p = NULL;
  5778. wolfSSL_BN_free(dh->g);
  5779. dh->g = NULL;
  5780. }
  5781. return err;
  5782. }
  5783. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5784. FIPS_VERSION_GT(2,0))
  5785. /* Set the DH parameters based on the NID.
  5786. *
  5787. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5788. *
  5789. * @param [in, out] dh DH key to set.
  5790. * @param [in] nid Numeric ID of predefined DH parameters.
  5791. * @return 0 on success.
  5792. * @return 1 on failure.
  5793. */
  5794. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5795. {
  5796. int err = 0;
  5797. int name = 0;
  5798. #ifdef HAVE_FFDHE_Q
  5799. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5800. #else
  5801. int elements = ELEMENT_P | ELEMENT_G;
  5802. #endif /* HAVE_FFDHE_Q */
  5803. switch (nid) {
  5804. #ifdef HAVE_FFDHE_2048
  5805. case NID_ffdhe2048:
  5806. name = WC_FFDHE_2048;
  5807. break;
  5808. #endif /* HAVE_FFDHE_2048 */
  5809. #ifdef HAVE_FFDHE_3072
  5810. case NID_ffdhe3072:
  5811. name = WC_FFDHE_3072;
  5812. break;
  5813. #endif /* HAVE_FFDHE_3072 */
  5814. #ifdef HAVE_FFDHE_4096
  5815. case NID_ffdhe4096:
  5816. name = WC_FFDHE_4096;
  5817. break;
  5818. #endif /* HAVE_FFDHE_4096 */
  5819. default:
  5820. err = 1;
  5821. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5822. break;
  5823. }
  5824. /* Set the internal DH key's parameters based on name. */
  5825. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5826. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5827. err = 1;
  5828. }
  5829. /* Synchronize the internal into external DH key's parameters. */
  5830. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5831. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5832. err = 1;
  5833. }
  5834. return err;
  5835. }
  5836. #else
  5837. /* Set the DH parameters based on the NID.
  5838. *
  5839. * Pre-defined DH parameters not available.
  5840. *
  5841. * @param [in, out] dh DH key to set.
  5842. * @param [in] nid Numeric ID of predefined DH parameters.
  5843. * @return 1 for failure.
  5844. */
  5845. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5846. {
  5847. return 1;
  5848. }
  5849. #endif
  5850. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5851. *
  5852. * @param [in] nid Numeric ID of DH parameters.
  5853. *
  5854. * @return DH key on success.
  5855. * @return NULL on failure.
  5856. */
  5857. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5858. {
  5859. WOLFSSL_DH* dh = NULL;
  5860. int err = 0;
  5861. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5862. /* Allocate a new DH key. */
  5863. dh = wolfSSL_DH_new();
  5864. if (dh == NULL) {
  5865. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5866. err = 1;
  5867. }
  5868. if (!err) {
  5869. /* Set the parameters based on NID. */
  5870. err = wolfssl_dh_set_nid(dh, nid);
  5871. }
  5872. if (err && (dh != NULL)) {
  5873. /* Dispose of the key on failure to set. */
  5874. wolfSSL_DH_free(dh);
  5875. dh = NULL;
  5876. }
  5877. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5878. return dh;
  5879. }
  5880. /* Dispose of DH key and allocated data.
  5881. *
  5882. * Cannot use dh after this call.
  5883. *
  5884. * @param [in] dh DH key to free.
  5885. */
  5886. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5887. {
  5888. int doFree = 0;
  5889. WOLFSSL_ENTER("wolfSSL_DH_free");
  5890. if (dh != NULL) {
  5891. int err;
  5892. /* Only free if all references to it are done */
  5893. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5894. /* Ignore errors - doFree will be 0 on error. */
  5895. (void)err;
  5896. }
  5897. if (doFree) {
  5898. /* Dispose of allocated reference counting data. */
  5899. wolfSSL_RefFree(&dh->ref);
  5900. /* Dispose of wolfSSL DH key. */
  5901. if (dh->internal) {
  5902. wc_FreeDhKey((DhKey*)dh->internal);
  5903. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5904. dh->internal = NULL;
  5905. }
  5906. /* Dispose of any allocated BNs. */
  5907. wolfSSL_BN_free(dh->priv_key);
  5908. wolfSSL_BN_free(dh->pub_key);
  5909. wolfSSL_BN_free(dh->g);
  5910. wolfSSL_BN_free(dh->p);
  5911. wolfSSL_BN_free(dh->q);
  5912. /* Set back to NULLs for safety. */
  5913. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5914. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5915. }
  5916. }
  5917. /* Increments ref count of DH key.
  5918. *
  5919. * @param [in, out] dh DH key.
  5920. * @return 1 on success
  5921. * @return 0 on error
  5922. */
  5923. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5924. {
  5925. int err = 1;
  5926. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5927. if (dh != NULL) {
  5928. wolfSSL_RefInc(&dh->ref, &err);
  5929. }
  5930. return !err;
  5931. }
  5932. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5933. defined(OPENSSL_EXTRA)
  5934. #ifdef WOLFSSL_DH_EXTRA
  5935. /* Duplicate the DH key.
  5936. *
  5937. * Internal DH key in 'dh' is updated if necessary.
  5938. *
  5939. * @param [in, out] dh DH key to duplicate.
  5940. * @return NULL on failure.
  5941. * @return DH key on success.
  5942. */
  5943. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5944. {
  5945. WOLFSSL_DH* ret = NULL;
  5946. int err = 0;
  5947. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5948. /* Validate parameters. */
  5949. if (dh == NULL) {
  5950. WOLFSSL_ERROR_MSG("Bad parameter");
  5951. err = 1;
  5952. }
  5953. /* Ensure internal DH key is set. */
  5954. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5955. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5956. err = 1;
  5957. }
  5958. /* Create a new DH key object. */
  5959. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5960. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5961. err = 1;
  5962. }
  5963. /* Copy internal DH key from original to new. */
  5964. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5965. MP_OKAY)) {
  5966. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5967. err = 1;
  5968. }
  5969. if (!err) {
  5970. ret->inSet = 1;
  5971. /* Synchronize the internal into external DH key's parameters. */
  5972. if (SetDhExternal(ret) != 1) {
  5973. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5974. err = 1;
  5975. }
  5976. }
  5977. /* Dispose of any allocated DH key on error. */
  5978. if (err && (ret != NULL)) {
  5979. wolfSSL_DH_free(ret);
  5980. ret = NULL;
  5981. }
  5982. return ret;
  5983. }
  5984. #endif /* WOLFSSL_DH_EXTRA */
  5985. #endif
  5986. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5987. *
  5988. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5989. * Subgroup."
  5990. *
  5991. * @return NULL on failure.
  5992. * @return DH Key on success.
  5993. */
  5994. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5995. {
  5996. WOLFSSL_DH* dh;
  5997. int err = 0;
  5998. static const byte pHex[] = {
  5999. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  6000. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  6001. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  6002. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  6003. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  6004. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  6005. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  6006. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  6007. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  6008. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  6009. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  6010. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  6011. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  6012. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  6013. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  6014. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  6015. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  6016. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  6017. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  6018. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  6019. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  6020. 0x1E, 0x1A, 0x15, 0x97
  6021. };
  6022. static const byte gHex[] = {
  6023. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  6024. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  6025. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  6026. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  6027. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  6028. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  6029. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  6030. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  6031. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  6032. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  6033. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  6034. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  6035. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  6036. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  6037. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  6038. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  6039. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  6040. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  6041. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  6042. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  6043. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  6044. 0x6C, 0xC4, 0x16, 0x59
  6045. };
  6046. static const byte qHex[] = {
  6047. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  6048. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  6049. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  6050. };
  6051. /* Create a new DH key to return. */
  6052. dh = wolfSSL_DH_new();
  6053. if (dh == NULL) {
  6054. err = 1;
  6055. }
  6056. if (!err) {
  6057. /* Set prime. */
  6058. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  6059. if (dh->p == NULL) {
  6060. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  6061. err = 1;
  6062. }
  6063. }
  6064. if (!err) {
  6065. /* Set generator. */
  6066. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  6067. if (dh->g == NULL) {
  6068. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  6069. err = 1;
  6070. }
  6071. }
  6072. if (!err) {
  6073. /* Set order. */
  6074. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  6075. if (dh->q == NULL) {
  6076. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  6077. err = 1;
  6078. }
  6079. }
  6080. /* Set values into wolfSSL DH key. */
  6081. if ((!err) && (SetDhInternal(dh) != 1)) {
  6082. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  6083. err = 1;
  6084. }
  6085. if (!err) {
  6086. /* External DH key parameters were set. */
  6087. dh->exSet = 1;
  6088. }
  6089. /* Dispose of any allocated DH key on error. */
  6090. if (err && (dh != NULL)) {
  6091. wolfSSL_DH_free(dh);
  6092. dh = NULL;
  6093. }
  6094. return dh;
  6095. }
  6096. /* TODO: consider changing strings to byte arrays. */
  6097. /* Returns a big number with the 768-bit prime from RFC 2409.
  6098. *
  6099. * @param [in, out] bn If not NULL then this BN is set and returned.
  6100. * If NULL then a new BN is created, set and returned.
  6101. *
  6102. * @return NULL on failure.
  6103. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  6104. */
  6105. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  6106. {
  6107. #if WOLFSSL_MAX_BN_BITS >= 768
  6108. static const char prm[] = {
  6109. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6110. "C4C6628B80DC1CD129024E088A67CC74"
  6111. "020BBEA63B139B22514A08798E3404DD"
  6112. "EF9519B3CD3A431B302B0A6DF25F1437"
  6113. "4FE1356D6D51C245E485B576625E7EC6"
  6114. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  6115. };
  6116. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  6117. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6118. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6119. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  6120. bn = NULL;
  6121. }
  6122. return bn;
  6123. #else
  6124. (void)bn;
  6125. return NULL;
  6126. #endif
  6127. }
  6128. /* Returns a big number with the 1024-bit prime from RFC 2409.
  6129. *
  6130. * @param [in, out] bn If not NULL then this BN is set and returned.
  6131. * If NULL then a new BN is created, set and returned.
  6132. *
  6133. * @return NULL on failure.
  6134. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  6135. */
  6136. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  6137. {
  6138. #if WOLFSSL_MAX_BN_BITS >= 1024
  6139. static const char prm[] = {
  6140. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6141. "C4C6628B80DC1CD129024E088A67CC74"
  6142. "020BBEA63B139B22514A08798E3404DD"
  6143. "EF9519B3CD3A431B302B0A6DF25F1437"
  6144. "4FE1356D6D51C245E485B576625E7EC6"
  6145. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6146. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6147. "49286651ECE65381FFFFFFFFFFFFFFFF"
  6148. };
  6149. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  6150. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6151. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6152. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  6153. bn = NULL;
  6154. }
  6155. return bn;
  6156. #else
  6157. (void)bn;
  6158. return NULL;
  6159. #endif
  6160. }
  6161. /* Returns a big number with the 1536-bit prime from RFC 3526.
  6162. *
  6163. * @param [in, out] bn If not NULL then this BN is set and returned.
  6164. * If NULL then a new BN is created, set and returned.
  6165. *
  6166. * @return NULL on failure.
  6167. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  6168. */
  6169. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  6170. {
  6171. #if WOLFSSL_MAX_BN_BITS >= 1536
  6172. static const char prm[] = {
  6173. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6174. "C4C6628B80DC1CD129024E088A67CC74"
  6175. "020BBEA63B139B22514A08798E3404DD"
  6176. "EF9519B3CD3A431B302B0A6DF25F1437"
  6177. "4FE1356D6D51C245E485B576625E7EC6"
  6178. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6179. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6180. "49286651ECE45B3DC2007CB8A163BF05"
  6181. "98DA48361C55D39A69163FA8FD24CF5F"
  6182. "83655D23DCA3AD961C62F356208552BB"
  6183. "9ED529077096966D670C354E4ABC9804"
  6184. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6185. };
  6186. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6187. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6188. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6189. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6190. bn = NULL;
  6191. }
  6192. return bn;
  6193. #else
  6194. (void)bn;
  6195. return NULL;
  6196. #endif
  6197. }
  6198. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6199. *
  6200. * @param [in, out] bn If not NULL then this BN is set and returned.
  6201. * If NULL then a new BN is created, set and returned.
  6202. *
  6203. * @return NULL on failure.
  6204. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6205. */
  6206. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6207. {
  6208. #if WOLFSSL_MAX_BN_BITS >= 2048
  6209. static const char prm[] = {
  6210. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6211. "C4C6628B80DC1CD129024E088A67CC74"
  6212. "020BBEA63B139B22514A08798E3404DD"
  6213. "EF9519B3CD3A431B302B0A6DF25F1437"
  6214. "4FE1356D6D51C245E485B576625E7EC6"
  6215. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6216. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6217. "49286651ECE45B3DC2007CB8A163BF05"
  6218. "98DA48361C55D39A69163FA8FD24CF5F"
  6219. "83655D23DCA3AD961C62F356208552BB"
  6220. "9ED529077096966D670C354E4ABC9804"
  6221. "F1746C08CA18217C32905E462E36CE3B"
  6222. "E39E772C180E86039B2783A2EC07A28F"
  6223. "B5C55DF06F4C52C9DE2BCBF695581718"
  6224. "3995497CEA956AE515D2261898FA0510"
  6225. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6226. };
  6227. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6228. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6229. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6230. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6231. bn = NULL;
  6232. }
  6233. return bn;
  6234. #else
  6235. (void)bn;
  6236. return NULL;
  6237. #endif
  6238. }
  6239. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6240. *
  6241. * @param [in, out] bn If not NULL then this BN is set and returned.
  6242. * If NULL then a new BN is created, set and returned.
  6243. *
  6244. * @return NULL on failure.
  6245. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6246. */
  6247. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6248. {
  6249. #if WOLFSSL_MAX_BN_BITS >= 3072
  6250. static const char prm[] = {
  6251. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6252. "C4C6628B80DC1CD129024E088A67CC74"
  6253. "020BBEA63B139B22514A08798E3404DD"
  6254. "EF9519B3CD3A431B302B0A6DF25F1437"
  6255. "4FE1356D6D51C245E485B576625E7EC6"
  6256. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6257. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6258. "49286651ECE45B3DC2007CB8A163BF05"
  6259. "98DA48361C55D39A69163FA8FD24CF5F"
  6260. "83655D23DCA3AD961C62F356208552BB"
  6261. "9ED529077096966D670C354E4ABC9804"
  6262. "F1746C08CA18217C32905E462E36CE3B"
  6263. "E39E772C180E86039B2783A2EC07A28F"
  6264. "B5C55DF06F4C52C9DE2BCBF695581718"
  6265. "3995497CEA956AE515D2261898FA0510"
  6266. "15728E5A8AAAC42DAD33170D04507A33"
  6267. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6268. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6269. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6270. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6271. "D87602733EC86A64521F2B18177B200C"
  6272. "BBE117577A615D6C770988C0BAD946E2"
  6273. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6274. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6275. };
  6276. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6277. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6278. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6279. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6280. bn = NULL;
  6281. }
  6282. return bn;
  6283. #else
  6284. (void)bn;
  6285. return NULL;
  6286. #endif
  6287. }
  6288. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6289. *
  6290. * @param [in, out] bn If not NULL then this BN is set and returned.
  6291. * If NULL then a new BN is created, set and returned.
  6292. *
  6293. * @return NULL on failure.
  6294. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6295. */
  6296. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6297. {
  6298. #if WOLFSSL_MAX_BN_BITS >= 4096
  6299. static const char prm[] = {
  6300. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6301. "C4C6628B80DC1CD129024E088A67CC74"
  6302. "020BBEA63B139B22514A08798E3404DD"
  6303. "EF9519B3CD3A431B302B0A6DF25F1437"
  6304. "4FE1356D6D51C245E485B576625E7EC6"
  6305. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6306. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6307. "49286651ECE45B3DC2007CB8A163BF05"
  6308. "98DA48361C55D39A69163FA8FD24CF5F"
  6309. "83655D23DCA3AD961C62F356208552BB"
  6310. "9ED529077096966D670C354E4ABC9804"
  6311. "F1746C08CA18217C32905E462E36CE3B"
  6312. "E39E772C180E86039B2783A2EC07A28F"
  6313. "B5C55DF06F4C52C9DE2BCBF695581718"
  6314. "3995497CEA956AE515D2261898FA0510"
  6315. "15728E5A8AAAC42DAD33170D04507A33"
  6316. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6317. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6318. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6319. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6320. "D87602733EC86A64521F2B18177B200C"
  6321. "BBE117577A615D6C770988C0BAD946E2"
  6322. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6323. "4B82D120A92108011A723C12A787E6D7"
  6324. "88719A10BDBA5B2699C327186AF4E23C"
  6325. "1A946834B6150BDA2583E9CA2AD44CE8"
  6326. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6327. "287C59474E6BC05D99B2964FA090C3A2"
  6328. "233BA186515BE7ED1F612970CEE2D7AF"
  6329. "B81BDD762170481CD0069127D5B05AA9"
  6330. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6331. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6332. };
  6333. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6334. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6335. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6336. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6337. bn = NULL;
  6338. }
  6339. return bn;
  6340. #else
  6341. (void)bn;
  6342. return NULL;
  6343. #endif
  6344. }
  6345. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6346. *
  6347. * @param [in, out] bn If not NULL then this BN is set and returned.
  6348. * If NULL then a new BN is created, set and returned.
  6349. *
  6350. * @return NULL on failure.
  6351. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6352. */
  6353. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6354. {
  6355. #if WOLFSSL_MAX_BN_BITS >= 6144
  6356. static const char prm[] = {
  6357. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6358. "C4C6628B80DC1CD129024E088A67CC74"
  6359. "020BBEA63B139B22514A08798E3404DD"
  6360. "EF9519B3CD3A431B302B0A6DF25F1437"
  6361. "4FE1356D6D51C245E485B576625E7EC6"
  6362. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6363. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6364. "49286651ECE45B3DC2007CB8A163BF05"
  6365. "98DA48361C55D39A69163FA8FD24CF5F"
  6366. "83655D23DCA3AD961C62F356208552BB"
  6367. "9ED529077096966D670C354E4ABC9804"
  6368. "F1746C08CA18217C32905E462E36CE3B"
  6369. "E39E772C180E86039B2783A2EC07A28F"
  6370. "B5C55DF06F4C52C9DE2BCBF695581718"
  6371. "3995497CEA956AE515D2261898FA0510"
  6372. "15728E5A8AAAC42DAD33170D04507A33"
  6373. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6374. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6375. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6376. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6377. "D87602733EC86A64521F2B18177B200C"
  6378. "BBE117577A615D6C770988C0BAD946E2"
  6379. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6380. "4B82D120A92108011A723C12A787E6D7"
  6381. "88719A10BDBA5B2699C327186AF4E23C"
  6382. "1A946834B6150BDA2583E9CA2AD44CE8"
  6383. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6384. "287C59474E6BC05D99B2964FA090C3A2"
  6385. "233BA186515BE7ED1F612970CEE2D7AF"
  6386. "B81BDD762170481CD0069127D5B05AA9"
  6387. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6388. "4DF435C93402849236C3FAB4D27C7026"
  6389. "C1D4DCB2602646DEC9751E763DBA37BD"
  6390. "F8FF9406AD9E530EE5DB382F413001AE"
  6391. "B06A53ED9027D831179727B0865A8918"
  6392. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6393. "DB7F1447E6CC254B332051512BD7AF42"
  6394. "6FB8F401378CD2BF5983CA01C64B92EC"
  6395. "F032EA15D1721D03F482D7CE6E74FEF6"
  6396. "D55E702F46980C82B5A84031900B1C9E"
  6397. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6398. "0F1D45B7FF585AC54BD407B22B4154AA"
  6399. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6400. "A79715EEF29BE32806A1D58BB7C5DA76"
  6401. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6402. "DA56C9EC2EF29632387FE8D76E3C0468"
  6403. "043E8F663F4860EE12BF2D5B0B7474D6"
  6404. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6405. };
  6406. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6407. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6408. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6409. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6410. bn = NULL;
  6411. }
  6412. return bn;
  6413. #else
  6414. (void)bn;
  6415. return NULL;
  6416. #endif
  6417. }
  6418. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6419. *
  6420. * @param [in, out] bn If not NULL then this BN is set and returned.
  6421. * If NULL then a new BN is created, set and returned.
  6422. *
  6423. * @return NULL on failure.
  6424. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6425. */
  6426. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6427. {
  6428. #if WOLFSSL_MAX_BN_BITS >= 8192
  6429. static const char prm[] = {
  6430. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6431. "C4C6628B80DC1CD129024E088A67CC74"
  6432. "020BBEA63B139B22514A08798E3404DD"
  6433. "EF9519B3CD3A431B302B0A6DF25F1437"
  6434. "4FE1356D6D51C245E485B576625E7EC6"
  6435. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6436. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6437. "49286651ECE45B3DC2007CB8A163BF05"
  6438. "98DA48361C55D39A69163FA8FD24CF5F"
  6439. "83655D23DCA3AD961C62F356208552BB"
  6440. "9ED529077096966D670C354E4ABC9804"
  6441. "F1746C08CA18217C32905E462E36CE3B"
  6442. "E39E772C180E86039B2783A2EC07A28F"
  6443. "B5C55DF06F4C52C9DE2BCBF695581718"
  6444. "3995497CEA956AE515D2261898FA0510"
  6445. "15728E5A8AAAC42DAD33170D04507A33"
  6446. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6447. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6448. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6449. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6450. "D87602733EC86A64521F2B18177B200C"
  6451. "BBE117577A615D6C770988C0BAD946E2"
  6452. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6453. "4B82D120A92108011A723C12A787E6D7"
  6454. "88719A10BDBA5B2699C327186AF4E23C"
  6455. "1A946834B6150BDA2583E9CA2AD44CE8"
  6456. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6457. "287C59474E6BC05D99B2964FA090C3A2"
  6458. "233BA186515BE7ED1F612970CEE2D7AF"
  6459. "B81BDD762170481CD0069127D5B05AA9"
  6460. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6461. "4DF435C93402849236C3FAB4D27C7026"
  6462. "C1D4DCB2602646DEC9751E763DBA37BD"
  6463. "F8FF9406AD9E530EE5DB382F413001AE"
  6464. "B06A53ED9027D831179727B0865A8918"
  6465. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6466. "DB7F1447E6CC254B332051512BD7AF42"
  6467. "6FB8F401378CD2BF5983CA01C64B92EC"
  6468. "F032EA15D1721D03F482D7CE6E74FEF6"
  6469. "D55E702F46980C82B5A84031900B1C9E"
  6470. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6471. "0F1D45B7FF585AC54BD407B22B4154AA"
  6472. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6473. "A79715EEF29BE32806A1D58BB7C5DA76"
  6474. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6475. "DA56C9EC2EF29632387FE8D76E3C0468"
  6476. "043E8F663F4860EE12BF2D5B0B7474D6"
  6477. "E694F91E6DBE115974A3926F12FEE5E4"
  6478. "38777CB6A932DF8CD8BEC4D073B931BA"
  6479. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6480. "2576F6936BA424663AAB639C5AE4F568"
  6481. "3423B4742BF1C978238F16CBE39D652D"
  6482. "E3FDB8BEFC848AD922222E04A4037C07"
  6483. "13EB57A81A23F0C73473FC646CEA306B"
  6484. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6485. "79683303ED5BDD3A062B3CF5B3A278A6"
  6486. "6D2A13F83F44F82DDF310EE074AB6A36"
  6487. "4597E899A0255DC164F31CC50846851D"
  6488. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6489. "FAF36BC31ECFA268359046F4EB879F92"
  6490. "4009438B481C6CD7889A002ED5EE382B"
  6491. "C9190DA6FC026E479558E4475677E9AA"
  6492. "9E3050E2765694DFC81F56E880B96E71"
  6493. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6494. };
  6495. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6496. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6497. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6498. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6499. bn = NULL;
  6500. }
  6501. return bn;
  6502. #else
  6503. (void)bn;
  6504. return NULL;
  6505. #endif
  6506. }
  6507. /*
  6508. * DH to/from bin APIs
  6509. */
  6510. #ifndef NO_CERTS
  6511. /* Load the DER encoded DH parameters into DH key.
  6512. *
  6513. * @param [in, out] dh DH key to load parameters into.
  6514. * @param [in] der Buffer holding DER encoded parameters data.
  6515. * @param [in, out] idx On in, index at which DH key DER data starts.
  6516. * On out, index after DH key DER data.
  6517. * @param [in] derSz Size of DER buffer in bytes.
  6518. *
  6519. * @return 0 on success.
  6520. * @return 1 when decoding DER or setting the external key fails.
  6521. */
  6522. static int wolfssl_dh_load_params(WOLFSSL_DH* dh, const unsigned char* der,
  6523. word32* idx, word32 derSz)
  6524. {
  6525. int err = 0;
  6526. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6527. int ret;
  6528. /* Decode DH parameters/key from DER. */
  6529. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6530. if (ret != 0) {
  6531. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6532. err = 1;
  6533. }
  6534. if (!err) {
  6535. /* wolfSSL DH key set. */
  6536. dh->inSet = 1;
  6537. /* Set the external DH key based on wolfSSL DH key. */
  6538. if (SetDhExternal(dh) != 1) {
  6539. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6540. err = 1;
  6541. }
  6542. }
  6543. #else
  6544. byte* p;
  6545. byte* g;
  6546. word32 pSz = MAX_DH_SIZE;
  6547. word32 gSz = MAX_DH_SIZE;
  6548. /* Only DH parameters supported. */
  6549. /* Load external and set internal. */
  6550. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6551. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6552. if ((p == NULL) || (g == NULL)) {
  6553. err = 1;
  6554. }
  6555. /* Extract the p and g as data from the DER encoded DH parameters. */
  6556. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6557. &gSz) < 0)) {
  6558. err = 1;
  6559. }
  6560. if (!err) {
  6561. /* Put p and g in as big numbers - free existing BNs. */
  6562. if (dh->p != NULL) {
  6563. wolfSSL_BN_free(dh->p);
  6564. dh->p = NULL;
  6565. }
  6566. if (dh->g != NULL) {
  6567. wolfSSL_BN_free(dh->g);
  6568. dh->g = NULL;
  6569. }
  6570. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6571. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6572. if (dh->p == NULL || dh->g == NULL) {
  6573. err = 1;
  6574. }
  6575. else {
  6576. /* External DH key parameters were set. */
  6577. dh->exSet = 1;
  6578. }
  6579. }
  6580. /* Set internal as the outside has been updated. */
  6581. if ((!err) && (SetDhInternal(dh) != 1)) {
  6582. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6583. err = 1;
  6584. }
  6585. if (!err) {
  6586. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6587. }
  6588. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6589. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6590. #endif
  6591. return err;
  6592. }
  6593. #ifdef OPENSSL_ALL
  6594. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6595. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6596. *
  6597. * @param [out] dh DH key to put parameters into. May be NULL.
  6598. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6599. * Value updated to end of data when dh is not NULL.
  6600. * @param [in] length Length of data available in bytes.
  6601. *
  6602. * @return DH key on success.
  6603. * @return NULL on failure.
  6604. */
  6605. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6606. long length)
  6607. {
  6608. WOLFSSL_DH *newDh = NULL;
  6609. word32 idx = 0;
  6610. int err = 0;
  6611. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6612. /* Validate parameters. */
  6613. if ((pp == NULL) || (length <= 0)) {
  6614. WOLFSSL_ERROR_MSG("bad argument");
  6615. err = 1;
  6616. }
  6617. /* Create new DH key to return. */
  6618. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6619. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6620. err = 1;
  6621. }
  6622. if ((!err) && (wolfssl_dh_load_params(newDh, *pp, &idx,
  6623. (word32)length) != 0)) {
  6624. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6625. err = 1;
  6626. }
  6627. if ((!err) && (dh != NULL)) {
  6628. /* Return through parameter too. */
  6629. *dh = newDh;
  6630. /* Move buffer on by the used amount. */
  6631. *pp += idx;
  6632. }
  6633. if (err && (newDh != NULL)) {
  6634. /* Dispose of any created DH key. */
  6635. wolfSSL_DH_free(newDh);
  6636. newDh = NULL;
  6637. }
  6638. return newDh;
  6639. }
  6640. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6641. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6642. *
  6643. * @params [in] dh DH key with parameters to encode.
  6644. * @params [in, out] out Pointer to buffer to encode into.
  6645. * When NULL or pointer to NULL, only length returned.
  6646. * @return 0 on error.
  6647. * @return Size of DER encoding in bytes on success.
  6648. */
  6649. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6650. {
  6651. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6652. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6653. word32 len = (word32)-1;
  6654. int err = 0;
  6655. /* Validate parameters. */
  6656. if (dh == NULL) {
  6657. WOLFSSL_ERROR_MSG("Bad parameters");
  6658. err = 1;
  6659. }
  6660. /* Push external DH data into internal DH key if not set. */
  6661. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6662. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6663. err = 1;
  6664. }
  6665. if (!err) {
  6666. int ret;
  6667. unsigned char* der = NULL;
  6668. /* Use *out when available otherwise NULL. */
  6669. if (out != NULL) {
  6670. der = *out;
  6671. }
  6672. /* Get length and/or encode. */
  6673. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6674. /* Length of encoded data is returned on success. */
  6675. if (ret > 0) {
  6676. *out += len;
  6677. }
  6678. /* An error occurred unless only length returned. */
  6679. else if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) {
  6680. err = 1;
  6681. }
  6682. }
  6683. /* Set return to 0 on error. */
  6684. if (err) {
  6685. len = 0;
  6686. }
  6687. return (int)len;
  6688. #else
  6689. word32 len;
  6690. int ret = 0;
  6691. int pSz;
  6692. int gSz;
  6693. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6694. /* Validate parameters. */
  6695. if (dh == NULL) {
  6696. WOLFSSL_ERROR_MSG("Bad parameters");
  6697. len = 0;
  6698. }
  6699. else {
  6700. /* SEQ <len>
  6701. * INT <len> [0x00] <prime>
  6702. * INT <len> [0x00] <generator>
  6703. * Integers have 0x00 prepended if the top bit of positive number is
  6704. * set.
  6705. */
  6706. /* Get total length of prime including any prepended zeros. */
  6707. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6708. mp_leading_bit((mp_int*)dh->p->internal);
  6709. /* Get total length of generator including any prepended zeros. */
  6710. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6711. mp_leading_bit((mp_int*)dh->g->internal);
  6712. /* Calculate length of data in sequence. */
  6713. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6714. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6715. /* Add in the length of the SEQUENCE. */
  6716. len += 1 + ASN_LEN_SIZE(len);
  6717. if ((out != NULL) && (*out != NULL)) {
  6718. /* Encode parameters. */
  6719. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6720. (mp_int*)dh->g->internal);
  6721. if (ret != MP_OKAY) {
  6722. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6723. len = 0;
  6724. }
  6725. else {
  6726. /* Move pointer on if encoded. */
  6727. *out += len;
  6728. }
  6729. }
  6730. }
  6731. return (int)len;
  6732. #endif
  6733. }
  6734. #endif /* OPENSSL_ALL */
  6735. #endif /* !NO_CERTS */
  6736. #endif /* OPENSSL_EXTRA */
  6737. #if defined(OPENSSL_EXTRA) || \
  6738. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6739. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6740. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6741. /* Load the DER encoded DH parameters into DH key.
  6742. *
  6743. * @param [in, out] dh DH key to load parameters into.
  6744. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6745. * @param [in] derSz Size of DER data in buffer in bytes.
  6746. *
  6747. * @return 1 on success.
  6748. * @return -1 when DH or derBuf is NULL,
  6749. * internal DH key in DH is NULL,
  6750. * derSz is 0 or less,
  6751. * error decoding DER data or
  6752. * setting external parameter values fails.
  6753. */
  6754. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6755. {
  6756. int ret = 1;
  6757. word32 idx = 0;
  6758. /* Validate parameters. */
  6759. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6760. (derSz <= 0)) {
  6761. WOLFSSL_ERROR_MSG("Bad function arguments");
  6762. ret = WOLFSSL_FATAL_ERROR;
  6763. }
  6764. if ((ret == 1) && (wolfssl_dh_load_params(dh, derBuf, &idx,
  6765. (word32)derSz) != 0)) {
  6766. WOLFSSL_ERROR_MSG("DH key decode failed");
  6767. ret = WOLFSSL_FATAL_ERROR;
  6768. }
  6769. return ret;
  6770. }
  6771. #endif
  6772. /*
  6773. * DH PEM APIs
  6774. */
  6775. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6776. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6777. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6778. /* Create a DH key by reading the PEM encoded data from the BIO.
  6779. *
  6780. * @param [in] bio BIO object to read from.
  6781. * @param [in, out] dh DH key to use. May be NULL.
  6782. * @param [in] pem PEM data to decode.
  6783. * @param [in] pemSz Size of PEM data in bytes.
  6784. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6785. * freed after use.
  6786. * @return DH key on success.
  6787. * @return NULL on failure.
  6788. */
  6789. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6790. unsigned char* pem, int pemSz, int memAlloced)
  6791. {
  6792. WOLFSSL_DH* localDh = NULL;
  6793. DerBuffer *der = NULL;
  6794. int err = 0;
  6795. /* Convert PEM to DER assuming DH Parameter format. */
  6796. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6797. NULL) < 0)) {
  6798. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6799. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6800. != 0) {
  6801. err = 1;
  6802. }
  6803. /* If Success on X9.42 DH format, clear error from failed DH format */
  6804. else {
  6805. unsigned long error;
  6806. CLEAR_ASN_NO_PEM_HEADER_ERROR(error);
  6807. }
  6808. }
  6809. if (memAlloced) {
  6810. /* PEM data no longer needed. */
  6811. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6812. }
  6813. if (!err) {
  6814. /* Use the DH key passed in or allocate a new one. */
  6815. if (dh != NULL) {
  6816. localDh = *dh;
  6817. }
  6818. if (localDh == NULL) {
  6819. localDh = wolfSSL_DH_new();
  6820. if (localDh == NULL) {
  6821. err = 1;
  6822. }
  6823. }
  6824. }
  6825. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6826. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length)
  6827. != 1)) {
  6828. /* Free an allocated DH key. */
  6829. if ((dh == NULL) || (localDh != *dh)) {
  6830. wolfSSL_DH_free(localDh);
  6831. }
  6832. localDh = NULL;
  6833. err = 1;
  6834. }
  6835. /* Return the DH key on success. */
  6836. if ((!err) && (dh != NULL)) {
  6837. *dh = localDh;
  6838. }
  6839. /* Dispose of DER data. */
  6840. if (der != NULL) {
  6841. FreeDer(&der);
  6842. }
  6843. return localDh;
  6844. }
  6845. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6846. #ifndef NO_BIO
  6847. /* Create a DH key by reading the PEM encoded data from the BIO.
  6848. *
  6849. * DH parameters are public data and are not expected to be encrypted.
  6850. *
  6851. * @param [in] bio BIO object to read from.
  6852. * @param [in, out] dh DH key to When pointer to
  6853. * NULL, a new DH key is created.
  6854. * @param [in] cb Password callback when PEM encrypted. Not used.
  6855. * @param [in] pass NUL terminated string for passphrase when PEM
  6856. * encrypted. Not used.
  6857. * @return DH key on success.
  6858. * @return NULL on failure.
  6859. */
  6860. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6861. wc_pem_password_cb *cb, void *pass)
  6862. {
  6863. WOLFSSL_DH* localDh = NULL;
  6864. int err = 0;
  6865. unsigned char* mem = NULL;
  6866. int size = 0;
  6867. int memAlloced = 0;
  6868. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6869. (void)cb;
  6870. (void)pass;
  6871. /* Validate parameters. */
  6872. if (bio == NULL) {
  6873. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6874. err = 1;
  6875. }
  6876. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6877. */
  6878. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6879. != 0)) {
  6880. err = 1;
  6881. }
  6882. if (!err) {
  6883. /* Create a DH key from the PEM - try two different headers. */
  6884. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6885. }
  6886. return localDh;
  6887. }
  6888. #endif /* !NO_BIO */
  6889. #ifndef NO_FILESYSTEM
  6890. /* Read DH parameters from a file pointer into DH key.
  6891. *
  6892. * DH parameters are public data and are not expected to be encrypted.
  6893. *
  6894. * @param [in] fp File pointer to read DH parameter file from.
  6895. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6896. * NULL, a new DH key is created.
  6897. * @param [in] cb Password callback when PEM encrypted. Not used.
  6898. * @param [in] pass NUL terminated string for passphrase when PEM
  6899. * encrypted. Not used.
  6900. *
  6901. * @return NULL on failure.
  6902. * @return DH key with parameters set on success.
  6903. */
  6904. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6905. wc_pem_password_cb* cb, void* pass)
  6906. {
  6907. WOLFSSL_DH* localDh = NULL;
  6908. int err = 0;
  6909. unsigned char* mem = NULL;
  6910. int size = 0;
  6911. (void)cb;
  6912. (void)pass;
  6913. /* Read data from file pointer. */
  6914. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6915. err = 1;
  6916. }
  6917. if (!err) {
  6918. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6919. }
  6920. return localDh;
  6921. }
  6922. #endif /* !NO_FILESYSTEM */
  6923. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6924. /* Encoded parameter data in DH key as DER.
  6925. *
  6926. * @param [in, out] dh DH key object to encode.
  6927. * @param [out] out Buffer containing DER encoding.
  6928. * @param [in] heap Heap hint.
  6929. * @return <0 on error.
  6930. * @return Length of DER encoded DH parameters in bytes.
  6931. */
  6932. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6933. void* heap)
  6934. {
  6935. int ret = WC_NO_ERR_TRACE(WOLFSSL_FATAL_ERROR);
  6936. int err = 0;
  6937. byte* der = NULL;
  6938. word32 derSz;
  6939. DhKey* key = NULL;
  6940. (void)heap;
  6941. /* Set internal parameters based on external parameters. */
  6942. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6943. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6944. err = 1;
  6945. }
  6946. if (!err) {
  6947. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6948. key = (DhKey*)dh->internal;
  6949. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6950. if (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) {
  6951. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6952. err = 1;
  6953. }
  6954. }
  6955. if (!err) {
  6956. /* Allocate memory for DER encoding. */
  6957. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6958. if (der == NULL) {
  6959. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6960. err = 1;
  6961. }
  6962. }
  6963. if (!err) {
  6964. /* Encode DH parameters into DER buffer. */
  6965. ret = wc_DhParamsToDer(key, der, &derSz);
  6966. if (ret < 0) {
  6967. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6968. err = 1;
  6969. }
  6970. }
  6971. if (!err) {
  6972. *out = der;
  6973. der = NULL;
  6974. }
  6975. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6976. return ret;
  6977. }
  6978. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6979. * passed in.
  6980. *
  6981. * @param [in] fp File pointer to write to.
  6982. * @param [in] dh DH key to write.
  6983. * @return 1 on success.
  6984. * @return 0 on failure.
  6985. */
  6986. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6987. {
  6988. int ret = 1;
  6989. int derSz;
  6990. byte* derBuf = NULL;
  6991. void* heap = NULL;
  6992. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6993. /* Validate parameters. */
  6994. if ((fp == XBADFILE) || (dh == NULL)) {
  6995. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6996. ret = 0;
  6997. }
  6998. if (ret == 1) {
  6999. DhKey* key = (DhKey*)dh->internal;
  7000. if (key)
  7001. heap = key->heap;
  7002. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  7003. WOLFSSL_ERROR_MSG("DER encoding failed");
  7004. ret = 0;
  7005. }
  7006. if (derBuf == NULL) {
  7007. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  7008. ret = 0;
  7009. }
  7010. }
  7011. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  7012. DH_PARAM_TYPE, NULL) != 1)) {
  7013. ret = 0;
  7014. }
  7015. /* Dispose of DER buffer. */
  7016. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  7017. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  7018. return ret;
  7019. }
  7020. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  7021. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  7022. * OPENSSL_EXTRA */
  7023. /*
  7024. * DH get/set APIs
  7025. */
  7026. #ifdef OPENSSL_EXTRA
  7027. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  7028. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  7029. /* Set the members of DhKey into WOLFSSL_DH
  7030. * Specify elements to set via the 2nd parameter
  7031. *
  7032. * @param [in, out] dh DH key to synchronize.
  7033. * @param [in] elm Elements to synchronize.
  7034. * @return 1 on success.
  7035. * @return -1 on failure.
  7036. */
  7037. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  7038. {
  7039. int ret = 1;
  7040. DhKey *key = NULL;
  7041. WOLFSSL_ENTER("SetDhExternal_ex");
  7042. /* Validate parameters. */
  7043. if ((dh == NULL) || (dh->internal == NULL)) {
  7044. WOLFSSL_ERROR_MSG("dh key NULL error");
  7045. ret = WOLFSSL_FATAL_ERROR;
  7046. }
  7047. if (ret == 1) {
  7048. /* Get the wolfSSL DH key. */
  7049. key = (DhKey*)dh->internal;
  7050. }
  7051. if ((ret == 1) && (elm & ELEMENT_P)) {
  7052. /* Set the prime. */
  7053. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  7054. WOLFSSL_ERROR_MSG("dh param p error");
  7055. ret = WOLFSSL_FATAL_ERROR;
  7056. }
  7057. }
  7058. if ((ret == 1) && (elm & ELEMENT_G)) {
  7059. /* Set the generator. */
  7060. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  7061. WOLFSSL_ERROR_MSG("dh param g error");
  7062. ret = WOLFSSL_FATAL_ERROR;
  7063. }
  7064. }
  7065. if ((ret == 1) && (elm & ELEMENT_Q)) {
  7066. /* Set the order. */
  7067. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  7068. WOLFSSL_ERROR_MSG("dh param q error");
  7069. ret = WOLFSSL_FATAL_ERROR;
  7070. }
  7071. }
  7072. #ifdef WOLFSSL_DH_EXTRA
  7073. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  7074. /* Set the private key. */
  7075. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  7076. WOLFSSL_ERROR_MSG("No DH Private Key");
  7077. ret = WOLFSSL_FATAL_ERROR;
  7078. }
  7079. }
  7080. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  7081. /* Set the public key. */
  7082. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  7083. WOLFSSL_ERROR_MSG("No DH Public Key");
  7084. ret = WOLFSSL_FATAL_ERROR;
  7085. }
  7086. }
  7087. #endif /* WOLFSSL_DH_EXTRA */
  7088. if (ret == 1) {
  7089. /* On success record that the external values have been set. */
  7090. dh->exSet = 1;
  7091. }
  7092. return ret;
  7093. }
  7094. /* Set the members of DhKey into WOLFSSL_DH
  7095. * DhKey was populated from wc_DhKeyDecode
  7096. * p, g, pub_key and priv_key are set.
  7097. *
  7098. * @param [in, out] dh DH key to synchronize.
  7099. * @return 1 on success.
  7100. * @return -1 on failure.
  7101. */
  7102. int SetDhExternal(WOLFSSL_DH *dh)
  7103. {
  7104. /* Assuming Q not required when using this API. */
  7105. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  7106. WOLFSSL_ENTER("SetDhExternal");
  7107. return SetDhExternal_ex(dh, elements);
  7108. }
  7109. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  7110. /* Set the internal/wolfSSL DH key with data from the external parts.
  7111. *
  7112. * @param [in, out] dh DH key to synchronize.
  7113. * @return 1 on success.
  7114. * @return -1 on failure.
  7115. */
  7116. int SetDhInternal(WOLFSSL_DH* dh)
  7117. {
  7118. int ret = 1;
  7119. DhKey *key = NULL;
  7120. WOLFSSL_ENTER("SetDhInternal");
  7121. /* Validate parameters. */
  7122. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7123. WOLFSSL_ERROR_MSG("Bad function arguments");
  7124. ret = WOLFSSL_FATAL_ERROR;
  7125. }
  7126. if (ret == 1) {
  7127. /* Get the wolfSSL DH key. */
  7128. key = (DhKey*)dh->internal;
  7129. /* Clear out key and initialize. */
  7130. wc_FreeDhKey(key);
  7131. if (wc_InitDhKey(key) != 0) {
  7132. ret = WOLFSSL_FATAL_ERROR;
  7133. }
  7134. }
  7135. if (ret == 1) {
  7136. /* Transfer prime. */
  7137. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  7138. ret = WOLFSSL_FATAL_ERROR;
  7139. }
  7140. }
  7141. if (ret == 1) {
  7142. /* Transfer generator. */
  7143. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  7144. ret = WOLFSSL_FATAL_ERROR;
  7145. }
  7146. }
  7147. #ifdef HAVE_FFDHE_Q
  7148. /* Transfer order if available. */
  7149. if ((ret == 1) && (dh->q != NULL)) {
  7150. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  7151. ret = WOLFSSL_FATAL_ERROR;
  7152. }
  7153. }
  7154. #endif
  7155. #ifdef WOLFSSL_DH_EXTRA
  7156. /* Transfer private key if available. */
  7157. if ((ret == 1) && (dh->priv_key != NULL) &&
  7158. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  7159. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7160. ret = WOLFSSL_FATAL_ERROR;
  7161. }
  7162. }
  7163. /* Transfer public key if available. */
  7164. if ((ret == 1) && (dh->pub_key != NULL) &&
  7165. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  7166. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7167. ret = WOLFSSL_FATAL_ERROR;
  7168. }
  7169. }
  7170. #endif /* WOLFSSL_DH_EXTRA */
  7171. if (ret == 1) {
  7172. /* On success record that the internal values have been set. */
  7173. dh->inSet = 1;
  7174. }
  7175. return ret;
  7176. }
  7177. /* Get the size, in bytes, of the DH key.
  7178. *
  7179. * Return code compliant with OpenSSL.
  7180. *
  7181. * @param [in] dh DH key.
  7182. * @return -1 on error.
  7183. * @return Size of DH key in bytes on success.
  7184. */
  7185. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7186. {
  7187. WOLFSSL_ENTER("wolfSSL_DH_size");
  7188. if (dh == NULL)
  7189. return WOLFSSL_FATAL_ERROR;
  7190. /* Validate parameter. */
  7191. /* Size of key is size of prime in bytes. */
  7192. return wolfSSL_BN_num_bytes(dh->p);
  7193. }
  7194. /**
  7195. * Return parameters p, q and/or g of the DH key.
  7196. *
  7197. * @param [in] dh DH key to retrieve parameters from.
  7198. * @param [out] p Pointer to return prime in. May be NULL.
  7199. * @param [out] q Pointer to return order in. May be NULL.
  7200. * @param [out] g Pointer to return generator in. May be NULL.
  7201. */
  7202. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7203. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7204. {
  7205. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7206. if (dh != NULL) {
  7207. /* Return prime if required. */
  7208. if (p != NULL) {
  7209. *p = dh->p;
  7210. }
  7211. /* Return order if required. */
  7212. if (q != NULL) {
  7213. *q = dh->q;
  7214. }
  7215. /* Return generator if required. */
  7216. if (g != NULL) {
  7217. *g = dh->g;
  7218. }
  7219. }
  7220. }
  7221. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7222. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7223. #if defined(OPENSSL_ALL) || \
  7224. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7225. /* Sets the parameters p, g and optionally q into the DH key.
  7226. *
  7227. * Ownership of p, q and g get taken over by "dh" on success and should be
  7228. * free'd with a call to wolfSSL_DH_free -- not individually.
  7229. *
  7230. * @param [in, out] dh DH key to set.
  7231. * @param [in] p Prime value to set. May be NULL when value already
  7232. * present.
  7233. * @param [in] q Order value to set. May be NULL.
  7234. * @param [in] g Generator value to set. May be NULL when value already
  7235. * present.
  7236. * @return 1 on success.
  7237. * @return 0 on failure.
  7238. */
  7239. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7240. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7241. {
  7242. int ret = 1;
  7243. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7244. /* Validate parameters - q is optional. */
  7245. if (dh == NULL) {
  7246. WOLFSSL_ERROR_MSG("Bad function arguments");
  7247. ret = 0;
  7248. }
  7249. /* p can be NULL if we already have one set. */
  7250. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7251. WOLFSSL_ERROR_MSG("Bad function arguments");
  7252. ret = 0;
  7253. }
  7254. /* g can be NULL if we already have one set. */
  7255. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7256. WOLFSSL_ERROR_MSG("Bad function arguments");
  7257. ret = 0;
  7258. }
  7259. if (ret == 1) {
  7260. /* Invalidate internal key. */
  7261. dh->inSet = 0;
  7262. /* Free external representation of parameters and set with those passed
  7263. * in. */
  7264. if (p != NULL) {
  7265. wolfSSL_BN_free(dh->p);
  7266. dh->p = p;
  7267. }
  7268. if (q != NULL) {
  7269. wolfSSL_BN_free(dh->q);
  7270. dh->q = q;
  7271. }
  7272. if (g != NULL) {
  7273. wolfSSL_BN_free(dh->g);
  7274. dh->g = g;
  7275. }
  7276. /* External DH key parameters were set. */
  7277. dh->exSet = 1;
  7278. /* Set internal/wolfSSL DH key as well. */
  7279. if (SetDhInternal(dh) != 1) {
  7280. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7281. /* Don't keep parameters on failure. */
  7282. dh->p = NULL;
  7283. dh->q = NULL;
  7284. dh->g = NULL;
  7285. /* Internal and external DH key not set. */
  7286. dh->inSet = 0;
  7287. dh->exSet = 0;
  7288. ret = 0;
  7289. }
  7290. }
  7291. return ret;
  7292. }
  7293. /* Set the length of the DH private key in bits.
  7294. *
  7295. * Length field is checked at generation.
  7296. *
  7297. * @param [in, out] dh DH key to set.
  7298. * @param [in] len Length of DH private key in bytes.
  7299. * @return 0 on failure.
  7300. * @return 1 on success.
  7301. */
  7302. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7303. {
  7304. int ret = 1;
  7305. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7306. /* Validate parameter. */
  7307. if (dh == NULL) {
  7308. WOLFSSL_ERROR_MSG("Bad function arguments");
  7309. ret = 0;
  7310. }
  7311. else {
  7312. /* Store length. */
  7313. dh->length = (int)len;
  7314. }
  7315. return ret;
  7316. }
  7317. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7318. #endif
  7319. /* Get the public and private keys requested.
  7320. *
  7321. * @param [in] dh DH key to get keys from.
  7322. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7323. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7324. */
  7325. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7326. const WOLFSSL_BIGNUM **priv_key)
  7327. {
  7328. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7329. /* Get only when valid DH passed in. */
  7330. if (dh != NULL) {
  7331. /* Return public key if required and available. */
  7332. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7333. *pub_key = dh->pub_key;
  7334. }
  7335. /* Return private key if required and available. */
  7336. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7337. *priv_key = dh->priv_key;
  7338. }
  7339. }
  7340. }
  7341. /* Set the public and/or private key.
  7342. *
  7343. * @param [in, out] dh DH key to have keys set into.
  7344. * @param [in] pub_key Public key to set. May be NULL.
  7345. * @param [in] priv_key Private key to set. May be NULL.
  7346. * @return 0 on failure.
  7347. * @return 1 on success.
  7348. */
  7349. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7350. WOLFSSL_BIGNUM *priv_key)
  7351. {
  7352. int ret = 1;
  7353. #ifdef WOLFSSL_DH_EXTRA
  7354. DhKey *key = NULL;
  7355. #endif
  7356. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7357. /* Validate parameters. */
  7358. if (dh == NULL) {
  7359. ret = 0;
  7360. }
  7361. #ifdef WOLFSSL_DH_EXTRA
  7362. else {
  7363. key = (DhKey*)dh->internal;
  7364. }
  7365. #endif
  7366. /* Replace public key when one passed in. */
  7367. if ((ret == 1) && (pub_key != NULL)) {
  7368. wolfSSL_BN_free(dh->pub_key);
  7369. dh->pub_key = pub_key;
  7370. #ifdef WOLFSSL_DH_EXTRA
  7371. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7372. ret = 0;
  7373. }
  7374. #endif
  7375. }
  7376. /* Replace private key when one passed in. */
  7377. if ((ret == 1) && (priv_key != NULL)) {
  7378. wolfSSL_BN_clear_free(dh->priv_key);
  7379. dh->priv_key = priv_key;
  7380. #ifdef WOLFSSL_DH_EXTRA
  7381. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7382. ret = 0;
  7383. }
  7384. #endif
  7385. }
  7386. return ret;
  7387. }
  7388. #endif /* OPENSSL_EXTRA */
  7389. /*
  7390. * DH check APIs
  7391. */
  7392. #ifdef OPENSSL_EXTRA
  7393. #ifndef NO_CERTS
  7394. #ifdef OPENSSL_ALL
  7395. /* Check whether BN number is a prime.
  7396. *
  7397. * @param [in] n Number to check.
  7398. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7399. * @return 1 on success.
  7400. * @return 0 on error.
  7401. */
  7402. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7403. {
  7404. int ret = 1;
  7405. #ifdef WOLFSSL_SMALL_STACK
  7406. WC_RNG* tmpRng = NULL;
  7407. #else
  7408. WC_RNG tmpRng[1];
  7409. #endif
  7410. WC_RNG* rng;
  7411. int localRng;
  7412. /* Make an RNG with tmpRng or get global. */
  7413. rng = wolfssl_make_rng(tmpRng, &localRng);
  7414. if (rng == NULL) {
  7415. ret = 0;
  7416. }
  7417. if (ret == 1) {
  7418. mp_int* prime = (mp_int*)n->internal;
  7419. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7420. ret = 0;
  7421. }
  7422. /* Free local random number generator if created. */
  7423. if (localRng) {
  7424. wc_FreeRng(rng);
  7425. #ifdef WOLFSSL_SMALL_STACK
  7426. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7427. #endif
  7428. }
  7429. }
  7430. return ret;
  7431. }
  7432. /* Checks the Diffie-Hellman parameters.
  7433. *
  7434. * Checks that the generator and prime are available.
  7435. * Checks that the prime is prime.
  7436. * OpenSSL expects codes to be non-NULL.
  7437. *
  7438. * @param [in] dh DH key to check.
  7439. * @param [out] codes Codes of checks that failed.
  7440. * @return 1 on success.
  7441. * @return 0 when DH is NULL, there were errors or failed to create a random
  7442. * number generator.
  7443. */
  7444. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7445. {
  7446. int ret = 1;
  7447. int errors = 0;
  7448. WOLFSSL_ENTER("wolfSSL_DH_check");
  7449. /* Validate parameters. */
  7450. if (dh == NULL) {
  7451. ret = 0;
  7452. }
  7453. /* Check generator available. */
  7454. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7455. errors |= DH_NOT_SUITABLE_GENERATOR;
  7456. }
  7457. if (ret == 1) {
  7458. /* Check prime available. */
  7459. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7460. errors |= DH_CHECK_P_NOT_PRIME;
  7461. }
  7462. else {
  7463. /* Test if dh->p is prime. */
  7464. int isPrime = MP_NO;
  7465. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7466. /* Set error code if parameter p is not prime. */
  7467. if ((ret == 1) && (isPrime != MP_YES)) {
  7468. errors |= DH_CHECK_P_NOT_PRIME;
  7469. }
  7470. }
  7471. }
  7472. /* Return errors when user wants exact issues. */
  7473. if (codes != NULL) {
  7474. *codes = errors;
  7475. }
  7476. else if (errors) {
  7477. ret = 0;
  7478. }
  7479. return ret;
  7480. }
  7481. #endif /* OPENSSL_ALL */
  7482. #endif /* !NO_CERTS */
  7483. #endif /* OPENSSL_EXTRA */
  7484. /*
  7485. * DH generate APIs
  7486. */
  7487. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7488. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7489. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7490. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7491. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7492. /* Generate DH parameters.
  7493. *
  7494. * @param [in] prime_len Length of prime in bits.
  7495. * @param [in] generator Generator value to use.
  7496. * @param [in] callback Called with progress information. Unused.
  7497. * @param [in] cb_arg User callback argument. Unused.
  7498. * @return NULL on failure.
  7499. * @return DH key on success.
  7500. */
  7501. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7502. void (*callback) (int, int, void *), void *cb_arg)
  7503. {
  7504. WOLFSSL_DH* dh = NULL;
  7505. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7506. /* Not supported by wolfSSl APIs. */
  7507. (void)callback;
  7508. (void)cb_arg;
  7509. /* Create an empty DH key. */
  7510. if ((dh = wolfSSL_DH_new()) == NULL) {
  7511. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7512. }
  7513. /* Generate parameters into DH key. */
  7514. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7515. != 1) {
  7516. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7517. wolfSSL_DH_free(dh);
  7518. dh = NULL;
  7519. }
  7520. return dh;
  7521. }
  7522. /* Generate DH parameters.
  7523. *
  7524. * @param [in] dh DH key to generate parameters into.
  7525. * @param [in] prime_len Length of prime in bits.
  7526. * @param [in] generator Generator value to use.
  7527. * @param [in] callback Called with progress information. Unused.
  7528. * @param [in] cb_arg User callback argument. Unused.
  7529. * @return 0 on failure.
  7530. * @return 1 on success.
  7531. */
  7532. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7533. int generator, void (*callback) (int, int, void *))
  7534. {
  7535. int ret = 1;
  7536. DhKey* key = NULL;
  7537. #ifdef WOLFSSL_SMALL_STACK
  7538. WC_RNG* tmpRng = NULL;
  7539. #else
  7540. WC_RNG tmpRng[1];
  7541. #endif
  7542. WC_RNG* rng = NULL;
  7543. int localRng = 0;
  7544. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7545. /* Not supported by wolfSSL APIs. */
  7546. (void)callback;
  7547. (void)generator;
  7548. /* Validate parameters. */
  7549. if (dh == NULL) {
  7550. WOLFSSL_ERROR_MSG("Bad parameter");
  7551. ret = 0;
  7552. }
  7553. if (ret == 1) {
  7554. /* Make an RNG with tmpRng or get global. */
  7555. rng = wolfssl_make_rng(tmpRng, &localRng);
  7556. if (rng == NULL) {
  7557. WOLFSSL_ERROR_MSG("No RNG to use");
  7558. ret = 0;
  7559. }
  7560. }
  7561. if (ret == 1) {
  7562. /* Get internal/wolfSSL DH key. */
  7563. key = (DhKey*)dh->internal;
  7564. /* Clear out data from internal DH key. */
  7565. wc_FreeDhKey(key);
  7566. /* Re-initialize internal DH key. */
  7567. if (wc_InitDhKey(key) != 0) {
  7568. ret = 0;
  7569. }
  7570. }
  7571. if (ret == 1) {
  7572. /* Generate parameters into internal DH key. */
  7573. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7574. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7575. ret = 0;
  7576. }
  7577. }
  7578. /* Free local random number generator if created. */
  7579. if (localRng) {
  7580. wc_FreeRng(rng);
  7581. #ifdef WOLFSSL_SMALL_STACK
  7582. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7583. #endif
  7584. }
  7585. if (ret == 1) {
  7586. /* Internal parameters set by generation. */
  7587. dh->inSet = 1;
  7588. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7589. /* Synchronize the external to the internal parameters. */
  7590. if (SetDhExternal(dh) != 1) {
  7591. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7592. ret = 0;
  7593. }
  7594. }
  7595. return ret;
  7596. }
  7597. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7598. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7599. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7600. * HAVE_SBLIM_SFCB)) */
  7601. #ifdef OPENSSL_EXTRA
  7602. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7603. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7604. /* Generate a public/private key pair base on parameters.
  7605. *
  7606. * @param [in, out] dh DH key to generate keys into.
  7607. * @return 1 on success.
  7608. * @return 0 on error.
  7609. */
  7610. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7611. {
  7612. int ret = 1;
  7613. word32 pubSz = 0;
  7614. word32 privSz = 0;
  7615. int localRng = 0;
  7616. WC_RNG* rng = NULL;
  7617. #ifdef WOLFSSL_SMALL_STACK
  7618. WC_RNG* tmpRng = NULL;
  7619. #else
  7620. WC_RNG tmpRng[1];
  7621. #endif
  7622. unsigned char* pub = NULL;
  7623. unsigned char* priv = NULL;
  7624. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7625. /* Validate parameters. */
  7626. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7627. WOLFSSL_ERROR_MSG("Bad function arguments");
  7628. ret = 0;
  7629. }
  7630. /* Synchronize the external and internal parameters. */
  7631. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7632. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7633. ret = 0;
  7634. }
  7635. if (ret == 1) {
  7636. /* Make a new RNG or use global. */
  7637. rng = wolfssl_make_rng(tmpRng, &localRng);
  7638. /* Check we have a random number generator. */
  7639. if (rng == NULL) {
  7640. ret = 0;
  7641. }
  7642. }
  7643. if (ret == 1) {
  7644. /* Get the size of the prime in bytes. */
  7645. pubSz = (word32)wolfSSL_BN_num_bytes(dh->p);
  7646. if (pubSz == 0) {
  7647. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7648. ret = 0;
  7649. }
  7650. }
  7651. if (ret == 1) {
  7652. /* Private key size can be as much as the size of the prime. */
  7653. if (dh->length) {
  7654. privSz = (word32)(dh->length / 8); /* to bytes */
  7655. }
  7656. else {
  7657. privSz = pubSz;
  7658. }
  7659. /* Allocate public and private key arrays. */
  7660. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7661. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7662. if (pub == NULL || priv == NULL) {
  7663. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7664. ret = 0;
  7665. }
  7666. }
  7667. if (ret == 1) {
  7668. /* Dispose of old public and private keys. */
  7669. wolfSSL_BN_free(dh->pub_key);
  7670. wolfSSL_BN_free(dh->priv_key);
  7671. /* Allocate new public and private keys. */
  7672. dh->pub_key = wolfSSL_BN_new();
  7673. dh->priv_key = wolfSSL_BN_new();
  7674. if (dh->pub_key == NULL) {
  7675. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7676. ret = 0;
  7677. }
  7678. if (dh->priv_key == NULL) {
  7679. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7680. ret = 0;
  7681. }
  7682. }
  7683. PRIVATE_KEY_UNLOCK();
  7684. /* Generate public and private keys into arrays. */
  7685. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7686. &privSz, pub, &pubSz) < 0)) {
  7687. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7688. ret = 0;
  7689. }
  7690. /* Set public key from array. */
  7691. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) ==
  7692. NULL)) {
  7693. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7694. ret = 0;
  7695. }
  7696. /* Set private key from array. */
  7697. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) ==
  7698. NULL)) {
  7699. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7700. ret = 0;
  7701. }
  7702. PRIVATE_KEY_LOCK();
  7703. if (localRng) {
  7704. /* Free an initialized local random number generator. */
  7705. wc_FreeRng(rng);
  7706. #ifdef WOLFSSL_SMALL_STACK
  7707. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7708. #endif
  7709. }
  7710. /* Dispose of allocated data. */
  7711. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7712. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7713. return ret;
  7714. }
  7715. static int _DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7716. WOLFSSL_DH* dh, int ct)
  7717. {
  7718. int ret = 0;
  7719. word32 keySz = 0;
  7720. int pubSz = MAX_DHKEY_SZ;
  7721. int privSz = MAX_DHKEY_SZ;
  7722. int sz = 0;
  7723. #ifdef WOLFSSL_SMALL_STACK
  7724. unsigned char* pub = NULL;
  7725. unsigned char* priv = NULL;
  7726. #else
  7727. unsigned char pub [MAX_DHKEY_SZ];
  7728. unsigned char priv[MAX_DHKEY_SZ];
  7729. #endif
  7730. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7731. /* Validate parameters. */
  7732. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7733. WOLFSSL_ERROR_MSG("Bad function arguments");
  7734. ret = WOLFSSL_FATAL_ERROR;
  7735. }
  7736. /* Get the maximum size of computed DH key. */
  7737. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7738. WOLFSSL_ERROR_MSG("Bad DH_size");
  7739. ret = WOLFSSL_FATAL_ERROR;
  7740. }
  7741. if (ret == 0) {
  7742. /* Validate the size of the private key. */
  7743. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7744. if (sz > (int)privSz) {
  7745. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7746. ret = WOLFSSL_FATAL_ERROR;
  7747. }
  7748. }
  7749. if (ret == 0) {
  7750. #ifdef WOLFSSL_SMALL_STACK
  7751. /* Keep real private key size to minimize amount allocated. */
  7752. privSz = sz;
  7753. #endif
  7754. /* Validate the size of the public key. */
  7755. sz = wolfSSL_BN_num_bytes(otherPub);
  7756. if (sz > pubSz) {
  7757. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7758. ret = WOLFSSL_FATAL_ERROR;
  7759. }
  7760. }
  7761. if (ret == 0) {
  7762. #ifdef WOLFSSL_SMALL_STACK
  7763. /* Allocate memory for the public key array. */
  7764. pub = (unsigned char*)XMALLOC((size_t)sz, NULL,
  7765. DYNAMIC_TYPE_PUBLIC_KEY);
  7766. if (pub == NULL)
  7767. ret = WOLFSSL_FATAL_ERROR;
  7768. }
  7769. if (ret == 0) {
  7770. /* Allocate memory for the private key array. */
  7771. priv = (unsigned char*)XMALLOC((size_t)privSz, NULL,
  7772. DYNAMIC_TYPE_PRIVATE_KEY);
  7773. if (priv == NULL) {
  7774. ret = WOLFSSL_FATAL_ERROR;
  7775. }
  7776. }
  7777. if (ret == 0) {
  7778. #endif
  7779. /* Get the private key into the array. */
  7780. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7781. if (privSz <= 0) {
  7782. ret = WOLFSSL_FATAL_ERROR;
  7783. }
  7784. }
  7785. if (ret == 0) {
  7786. /* Get the public key into the array. */
  7787. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7788. if (pubSz <= 0) {
  7789. ret = WOLFSSL_FATAL_ERROR;
  7790. }
  7791. }
  7792. /* Synchronize the external into the internal parameters. */
  7793. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7794. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7795. ret = WOLFSSL_FATAL_ERROR;
  7796. }
  7797. PRIVATE_KEY_UNLOCK();
  7798. /* Calculate shared secret from private and public keys. */
  7799. if (ret == 0) {
  7800. word32 padded_keySz = keySz;
  7801. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(7,0)) && !defined(HAVE_SELFTEST)
  7802. if (ct) {
  7803. if (wc_DhAgree_ct((DhKey*)dh->internal, key, &keySz, priv,
  7804. (word32)privSz, pub, (word32)pubSz) < 0) {
  7805. WOLFSSL_ERROR_MSG("wc_DhAgree_ct failed");
  7806. ret = WOLFSSL_FATAL_ERROR;
  7807. }
  7808. }
  7809. else
  7810. #endif /* (!HAVE_FIPS || FIPS_VERSION_GE(7,0)) && !HAVE_SELFTEST */
  7811. {
  7812. if (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7813. (word32)privSz, pub, (word32)pubSz) < 0) {
  7814. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7815. ret = WOLFSSL_FATAL_ERROR;
  7816. }
  7817. }
  7818. if ((ret == 0) && ct) {
  7819. /* Arrange for correct fixed-length, right-justified key, even if
  7820. * the crypto back end doesn't support it. With some crypto back
  7821. * ends this forgoes formal constant-timeness on the key agreement,
  7822. * but assured that wolfSSL_DH_compute_key_padded() functions
  7823. * correctly.
  7824. */
  7825. if (keySz < padded_keySz) {
  7826. XMEMMOVE(key, key + (padded_keySz - keySz),
  7827. padded_keySz - keySz);
  7828. XMEMSET(key, 0, padded_keySz - keySz);
  7829. }
  7830. }
  7831. }
  7832. if (ret == 0) {
  7833. /* Return actual length. */
  7834. ret = (int)keySz;
  7835. }
  7836. PRIVATE_KEY_LOCK();
  7837. #ifdef WOLFSSL_SMALL_STACK
  7838. if (priv != NULL)
  7839. #endif
  7840. {
  7841. /* Zeroize sensitive data. */
  7842. ForceZero(priv, (word32)privSz);
  7843. }
  7844. #ifdef WOLFSSL_SMALL_STACK
  7845. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7846. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7847. #endif
  7848. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7849. return ret;
  7850. }
  7851. /* Compute the shared key from the private key and peer's public key.
  7852. *
  7853. * Return code compliant with OpenSSL.
  7854. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7855. * supported.
  7856. *
  7857. * @param [out] key Buffer to place shared key.
  7858. * @param [in] otherPub Peer's public key.
  7859. * @param [in] dh DH key containing private key.
  7860. * @return -1 on error.
  7861. * @return Size of shared secret in bytes on success.
  7862. */
  7863. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7864. WOLFSSL_DH* dh)
  7865. {
  7866. return _DH_compute_key(key, otherPub, dh, 0);
  7867. }
  7868. /* Compute the shared key from the private key and peer's public key as in
  7869. * wolfSSL_DH_compute_key, but using constant time processing, with an output
  7870. * key length fixed at the nominal DH key size. Leading zeros are retained.
  7871. *
  7872. * Return code compliant with OpenSSL.
  7873. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7874. * supported.
  7875. *
  7876. * @param [out] key Buffer to place shared key.
  7877. * @param [in] otherPub Peer's public key.
  7878. * @param [in] dh DH key containing private key.
  7879. * @return -1 on error.
  7880. * @return Size of shared secret in bytes on success.
  7881. */
  7882. int wolfSSL_DH_compute_key_padded(unsigned char* key,
  7883. const WOLFSSL_BIGNUM* otherPub, WOLFSSL_DH* dh)
  7884. {
  7885. return _DH_compute_key(key, otherPub, dh, 1);
  7886. }
  7887. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7888. * HAVE_FIPS_VERSION > 2 */
  7889. #endif /* OPENSSL_EXTRA */
  7890. #endif /* NO_DH */
  7891. /*******************************************************************************
  7892. * END OF DH API
  7893. ******************************************************************************/
  7894. /*******************************************************************************
  7895. * START OF EC API
  7896. ******************************************************************************/
  7897. #ifdef HAVE_ECC
  7898. #if defined(OPENSSL_EXTRA)
  7899. /* Start EC_curve */
  7900. /* Get the NIST name for the numeric ID.
  7901. *
  7902. * @param [in] nid Numeric ID of an EC curve.
  7903. * @return String representing NIST name of EC curve on success.
  7904. * @return NULL on error.
  7905. */
  7906. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7907. {
  7908. const char* name = NULL;
  7909. const WOLF_EC_NIST_NAME* nist_name;
  7910. /* Attempt to find the curve info matching the NID passed in. */
  7911. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7912. if (nist_name->nid == nid) {
  7913. /* NID found - return name. */
  7914. name = nist_name->name;
  7915. break;
  7916. }
  7917. }
  7918. return name;
  7919. }
  7920. /* Get the numeric ID for the NIST name.
  7921. *
  7922. * @param [in] name NIST name of EC curve.
  7923. * @return NID matching NIST name on success.
  7924. * @return 0 on error.
  7925. */
  7926. int wolfSSL_EC_curve_nist2nid(const char* name)
  7927. {
  7928. int nid = 0;
  7929. const WOLF_EC_NIST_NAME* nist_name;
  7930. /* Attempt to find the curve info matching the NIST name passed in. */
  7931. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7932. if (XSTRCMP(nist_name->name, name) == 0) {
  7933. /* Name found - return NID. */
  7934. nid = nist_name->nid;
  7935. break;
  7936. }
  7937. }
  7938. return nid;
  7939. }
  7940. #endif /* OPENSSL_EXTRA */
  7941. /* End EC_curve */
  7942. /* Start EC_METHOD */
  7943. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7944. /* Get the EC method of the EC group object.
  7945. *
  7946. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7947. * the NID.
  7948. *
  7949. * @param [in] group EC group object.
  7950. * @return EC method.
  7951. */
  7952. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7953. const WOLFSSL_EC_GROUP *group)
  7954. {
  7955. /* No method table used so just return the same object. */
  7956. return group;
  7957. }
  7958. /* Get field type for method.
  7959. *
  7960. * Only prime fields are supported.
  7961. *
  7962. * @param [in] meth EC method.
  7963. * @return X9.63 prime field NID on success.
  7964. * @return 0 on error.
  7965. */
  7966. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7967. {
  7968. int nid = 0;
  7969. if (meth != NULL) {
  7970. /* Only field type supported by code base. */
  7971. nid = NID_X9_62_prime_field;
  7972. }
  7973. return nid;
  7974. }
  7975. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7976. /* End EC_METHOD */
  7977. /* Start EC_GROUP */
  7978. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7979. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7980. * value.
  7981. *
  7982. * @param [in] n ECC curve id.
  7983. * @return ECC curve NID (OpenSSL compatible value).
  7984. */
  7985. int EccEnumToNID(int n)
  7986. {
  7987. WOLFSSL_ENTER("EccEnumToNID");
  7988. switch(n) {
  7989. case ECC_SECP192R1:
  7990. return NID_X9_62_prime192v1;
  7991. case ECC_PRIME192V2:
  7992. return NID_X9_62_prime192v2;
  7993. case ECC_PRIME192V3:
  7994. return NID_X9_62_prime192v3;
  7995. case ECC_PRIME239V1:
  7996. return NID_X9_62_prime239v1;
  7997. case ECC_PRIME239V2:
  7998. return NID_X9_62_prime239v2;
  7999. case ECC_PRIME239V3:
  8000. return NID_X9_62_prime239v3;
  8001. case ECC_SECP256R1:
  8002. return NID_X9_62_prime256v1;
  8003. case ECC_SECP112R1:
  8004. return NID_secp112r1;
  8005. case ECC_SECP112R2:
  8006. return NID_secp112r2;
  8007. case ECC_SECP128R1:
  8008. return NID_secp128r1;
  8009. case ECC_SECP128R2:
  8010. return NID_secp128r2;
  8011. case ECC_SECP160R1:
  8012. return NID_secp160r1;
  8013. case ECC_SECP160R2:
  8014. return NID_secp160r2;
  8015. case ECC_SECP224R1:
  8016. return NID_secp224r1;
  8017. case ECC_SECP384R1:
  8018. return NID_secp384r1;
  8019. case ECC_SECP521R1:
  8020. return NID_secp521r1;
  8021. case ECC_SECP160K1:
  8022. return NID_secp160k1;
  8023. case ECC_SECP192K1:
  8024. return NID_secp192k1;
  8025. case ECC_SECP224K1:
  8026. return NID_secp224k1;
  8027. case ECC_SECP256K1:
  8028. return NID_secp256k1;
  8029. case ECC_BRAINPOOLP160R1:
  8030. return NID_brainpoolP160r1;
  8031. case ECC_BRAINPOOLP192R1:
  8032. return NID_brainpoolP192r1;
  8033. case ECC_BRAINPOOLP224R1:
  8034. return NID_brainpoolP224r1;
  8035. case ECC_BRAINPOOLP256R1:
  8036. return NID_brainpoolP256r1;
  8037. case ECC_BRAINPOOLP320R1:
  8038. return NID_brainpoolP320r1;
  8039. case ECC_BRAINPOOLP384R1:
  8040. return NID_brainpoolP384r1;
  8041. case ECC_BRAINPOOLP512R1:
  8042. return NID_brainpoolP512r1;
  8043. #ifdef WOLFSSL_SM2
  8044. case ECC_SM2P256V1:
  8045. return NID_sm2;
  8046. #endif
  8047. default:
  8048. WOLFSSL_MSG("NID not found");
  8049. return WOLFSSL_FATAL_ERROR;
  8050. }
  8051. }
  8052. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8053. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8054. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  8055. *
  8056. * Used by ecc_sets[].
  8057. *
  8058. * @param [in] n OpenSSL NID of EC curve.
  8059. * @return wolfCrypt EC curve id.
  8060. * @return -1 on error.
  8061. */
  8062. int NIDToEccEnum(int nid)
  8063. {
  8064. int id;
  8065. WOLFSSL_ENTER("NIDToEccEnum");
  8066. switch (nid) {
  8067. case NID_X9_62_prime192v1:
  8068. id = ECC_SECP192R1;
  8069. break;
  8070. case NID_X9_62_prime192v2:
  8071. id = ECC_PRIME192V2;
  8072. break;
  8073. case NID_X9_62_prime192v3:
  8074. id = ECC_PRIME192V3;
  8075. break;
  8076. case NID_X9_62_prime239v1:
  8077. id = ECC_PRIME239V1;
  8078. break;
  8079. case NID_X9_62_prime239v2:
  8080. id = ECC_PRIME239V2;
  8081. break;
  8082. case NID_X9_62_prime239v3:
  8083. id = ECC_PRIME239V3;
  8084. break;
  8085. case NID_X9_62_prime256v1:
  8086. id = ECC_SECP256R1;
  8087. break;
  8088. case NID_secp112r1:
  8089. id = ECC_SECP112R1;
  8090. break;
  8091. case NID_secp112r2:
  8092. id = ECC_SECP112R2;
  8093. break;
  8094. case NID_secp128r1:
  8095. id = ECC_SECP128R1;
  8096. break;
  8097. case NID_secp128r2:
  8098. id = ECC_SECP128R2;
  8099. break;
  8100. case NID_secp160r1:
  8101. id = ECC_SECP160R1;
  8102. break;
  8103. case NID_secp160r2:
  8104. id = ECC_SECP160R2;
  8105. break;
  8106. case NID_secp224r1:
  8107. id = ECC_SECP224R1;
  8108. break;
  8109. case NID_secp384r1:
  8110. id = ECC_SECP384R1;
  8111. break;
  8112. case NID_secp521r1:
  8113. id = ECC_SECP521R1;
  8114. break;
  8115. case NID_secp160k1:
  8116. id = ECC_SECP160K1;
  8117. break;
  8118. case NID_secp192k1:
  8119. id = ECC_SECP192K1;
  8120. break;
  8121. case NID_secp224k1:
  8122. id = ECC_SECP224K1;
  8123. break;
  8124. case NID_secp256k1:
  8125. id = ECC_SECP256K1;
  8126. break;
  8127. case NID_brainpoolP160r1:
  8128. id = ECC_BRAINPOOLP160R1;
  8129. break;
  8130. case NID_brainpoolP192r1:
  8131. id = ECC_BRAINPOOLP192R1;
  8132. break;
  8133. case NID_brainpoolP224r1:
  8134. id = ECC_BRAINPOOLP224R1;
  8135. break;
  8136. case NID_brainpoolP256r1:
  8137. id = ECC_BRAINPOOLP256R1;
  8138. break;
  8139. case NID_brainpoolP320r1:
  8140. id = ECC_BRAINPOOLP320R1;
  8141. break;
  8142. case NID_brainpoolP384r1:
  8143. id = ECC_BRAINPOOLP384R1;
  8144. break;
  8145. case NID_brainpoolP512r1:
  8146. id = ECC_BRAINPOOLP512R1;
  8147. break;
  8148. default:
  8149. WOLFSSL_MSG("NID not found");
  8150. /* -1 on error. */
  8151. id = WOLFSSL_FATAL_ERROR;
  8152. }
  8153. return id;
  8154. }
  8155. /* Set the fields of the EC group based on numeric ID.
  8156. *
  8157. * @param [in, out] group EC group.
  8158. * @param [in] nid Numeric ID of an EC curve.
  8159. */
  8160. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  8161. {
  8162. int eccEnum;
  8163. int realNid;
  8164. /* Convert ecc_curve_id enum to NID. */
  8165. if ((realNid = EccEnumToNID(nid)) != -1) {
  8166. /* ecc_curve_id enum passed in - have real NID value set. */
  8167. eccEnum = nid;
  8168. }
  8169. else {
  8170. /* NID passed in is OpenSSL type. */
  8171. realNid = nid;
  8172. /* Convert NID to ecc_curve_id enum. */
  8173. eccEnum = NIDToEccEnum(nid);
  8174. }
  8175. /* Set the numeric ID of the curve */
  8176. group->curve_nid = realNid;
  8177. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  8178. group->curve_idx = -1;
  8179. /* Find index and OID sum for curve if wolfCrypt supports it. */
  8180. if (eccEnum != -1) {
  8181. int i;
  8182. /* Find id and set the internal curve idx and OID sum. */
  8183. for (i = 0; ecc_sets[i].size != 0; i++) {
  8184. if (ecc_sets[i].id == eccEnum) {
  8185. /* Found id in wolfCrypt supported EC curves. */
  8186. group->curve_idx = i;
  8187. group->curve_oid = (int)ecc_sets[i].oidSum;
  8188. break;
  8189. }
  8190. }
  8191. }
  8192. }
  8193. /* Create a new EC group with the numeric ID for an EC curve.
  8194. *
  8195. * @param [in] nid Numeric ID of an EC curve.
  8196. * @return New, allocated EC group on success.
  8197. * @return NULL on error.
  8198. */
  8199. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  8200. {
  8201. int err = 0;
  8202. WOLFSSL_EC_GROUP* group;
  8203. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  8204. /* Allocate EC group. */
  8205. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  8206. DYNAMIC_TYPE_ECC);
  8207. if (group == NULL) {
  8208. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  8209. err = 1;
  8210. }
  8211. if (!err) {
  8212. /* Reset all fields. */
  8213. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  8214. /* Set the fields of group based on the numeric ID. */
  8215. ec_group_set_nid(group, nid);
  8216. }
  8217. return group;
  8218. }
  8219. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8220. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8221. /* Dispose of the EC group.
  8222. *
  8223. * Cannot use group after this call.
  8224. *
  8225. * @param [in] group EC group to free.
  8226. */
  8227. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8228. {
  8229. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8230. /* Dispose of EC group. */
  8231. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8232. }
  8233. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8234. #ifdef OPENSSL_EXTRA
  8235. #ifndef NO_BIO
  8236. /* Creates an EC group from the DER encoding.
  8237. *
  8238. * Only named curves supported.
  8239. *
  8240. * @param [out] group Reference to EC group object.
  8241. * @param [in] in Buffer holding DER encoding of curve.
  8242. * @param [in] inSz Length of data in buffer.
  8243. * @return EC group on success.
  8244. * @return NULL on error.
  8245. */
  8246. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  8247. const unsigned char** in_pp, long inSz)
  8248. {
  8249. int err = 0;
  8250. WOLFSSL_EC_GROUP* ret = NULL;
  8251. word32 idx = 0;
  8252. word32 oid = 0;
  8253. int id = 0;
  8254. const unsigned char* in;
  8255. if (in_pp == NULL || *in_pp == NULL)
  8256. return NULL;
  8257. in = *in_pp;
  8258. /* Use the group passed in. */
  8259. if ((group != NULL) && (*group != NULL)) {
  8260. ret = *group;
  8261. }
  8262. /* Only support named curves. */
  8263. if (in[0] != ASN_OBJECT_ID) {
  8264. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8265. err = 1;
  8266. }
  8267. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8268. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8269. 0)) {
  8270. err = 1;
  8271. }
  8272. if (!err) {
  8273. /* Get the internal ID for OID. */
  8274. id = wc_ecc_get_oid(oid, NULL, NULL);
  8275. if (id < 0) {
  8276. err = 1;
  8277. }
  8278. }
  8279. if (!err) {
  8280. /* Get the NID for the internal ID. */
  8281. int nid = EccEnumToNID(id);
  8282. if (ret == NULL) {
  8283. /* Create a new EC group with the numeric ID. */
  8284. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8285. if (ret == NULL) {
  8286. err = 1;
  8287. }
  8288. }
  8289. else {
  8290. ec_group_set_nid(ret, nid);
  8291. }
  8292. }
  8293. if ((!err) && (group != NULL)) {
  8294. /* Return the EC group through reference. */
  8295. *group = ret;
  8296. }
  8297. if (err) {
  8298. if ((ret != NULL) && (ret != *group)) {
  8299. wolfSSL_EC_GROUP_free(ret);
  8300. }
  8301. ret = NULL;
  8302. }
  8303. else {
  8304. *in_pp += idx;
  8305. }
  8306. return ret;
  8307. }
  8308. /* Creates a new EC group from the PEM encoding in the BIO.
  8309. *
  8310. * @param [in] bio BIO to read PEM encoding from.
  8311. * @param [out] group Reference to EC group object.
  8312. * @param [in] cb Password callback when PEM encrypted.
  8313. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8314. * @return EC group on success.
  8315. * @return NULL on error.
  8316. */
  8317. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8318. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8319. {
  8320. int err = 0;
  8321. WOLFSSL_EC_GROUP* ret = NULL;
  8322. DerBuffer* der = NULL;
  8323. int keyFormat = 0;
  8324. if (bio == NULL) {
  8325. err = 1;
  8326. }
  8327. /* Read parameters from BIO and convert PEM to DER. */
  8328. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8329. &keyFormat, &der) < 0)) {
  8330. err = 1;
  8331. }
  8332. if (!err) {
  8333. /* Create EC group from DER encoding. */
  8334. const byte** p = (const byte**)&der->buffer;
  8335. ret = wolfssl_ec_group_d2i(group, p, der->length);
  8336. if (ret == NULL) {
  8337. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8338. }
  8339. }
  8340. /* Dispose of any allocated data. */
  8341. FreeDer(&der);
  8342. return ret;
  8343. }
  8344. WOLFSSL_EC_GROUP *wolfSSL_d2i_ECPKParameters(WOLFSSL_EC_GROUP **out,
  8345. const unsigned char **in, long len)
  8346. {
  8347. return wolfssl_ec_group_d2i(out, in, len);
  8348. }
  8349. #endif /* !NO_BIO */
  8350. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8351. /* Copy an EC group.
  8352. *
  8353. * Only used by wolfSSL_EC_KEY_dup at this time.
  8354. *
  8355. * @param [in, out] dst Destination EC group.
  8356. * @param [in] src Source EC group.
  8357. * @return 0 on success.
  8358. */
  8359. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8360. const WOLFSSL_EC_GROUP* src)
  8361. {
  8362. /* Copy the fields. */
  8363. dst->curve_idx = src->curve_idx;
  8364. dst->curve_nid = src->curve_nid;
  8365. dst->curve_oid = src->curve_oid;
  8366. return 0;
  8367. }
  8368. #endif /* OPENSSL_ALL && !NO_CERTS */
  8369. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8370. *
  8371. * @param [in] src EC group to duplicate.
  8372. *
  8373. * @return EC group on success.
  8374. * @return NULL on error.
  8375. */
  8376. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8377. {
  8378. WOLFSSL_EC_GROUP* newGroup = NULL;
  8379. if (src != NULL) {
  8380. /* Create new group base on NID in original EC group. */
  8381. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8382. }
  8383. return newGroup;
  8384. }
  8385. /* Compare two EC groups.
  8386. *
  8387. * Return code compliant with OpenSSL.
  8388. *
  8389. * @param [in] a First EC group.
  8390. * @param [in] b Second EC group.
  8391. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8392. *
  8393. * @return 0 if equal.
  8394. * @return 1 if not equal.
  8395. * @return -1 on error.
  8396. */
  8397. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8398. WOLFSSL_BN_CTX *ctx)
  8399. {
  8400. int ret;
  8401. /* No BN operations performed. */
  8402. (void)ctx;
  8403. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8404. /* Validate parameters. */
  8405. if ((a == NULL) || (b == NULL)) {
  8406. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8407. /* Return error value. */
  8408. ret = WOLFSSL_FATAL_ERROR;
  8409. }
  8410. /* Compare NID and wolfSSL curve index. */
  8411. else {
  8412. /* 0 when same, 1 when not. */
  8413. ret = ((a->curve_nid == b->curve_nid) &&
  8414. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8415. }
  8416. return ret;
  8417. }
  8418. #ifndef NO_WOLFSSL_STUB
  8419. /* Set the ASN.1 flag that indicate encoding of curve.
  8420. *
  8421. * Stub function - flag not used elsewhere.
  8422. * Always encoded as named curve.
  8423. *
  8424. * @param [in] group EC group to modify.
  8425. * @param [in] flag ASN.1 flag to set. Valid values:
  8426. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8427. */
  8428. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8429. {
  8430. (void)group;
  8431. (void)flag;
  8432. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8433. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8434. }
  8435. #endif
  8436. /* Get the curve NID of the group.
  8437. *
  8438. * Return code compliant with OpenSSL.
  8439. *
  8440. * @param [in] group EC group.
  8441. * @return Curve NID on success.
  8442. * @return 0 on error.
  8443. */
  8444. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8445. {
  8446. int nid = 0;
  8447. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8448. if (group == NULL) {
  8449. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8450. }
  8451. else {
  8452. nid = group->curve_nid;
  8453. }
  8454. return nid;
  8455. }
  8456. /* Get the degree (curve size in bits) of the EC group.
  8457. *
  8458. * Return code compliant with OpenSSL.
  8459. *
  8460. * @return Degree of the curve on success.
  8461. * @return 0 on error.
  8462. */
  8463. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8464. {
  8465. int degree = 0;
  8466. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8467. if (group == NULL) {
  8468. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8469. }
  8470. else {
  8471. switch (group->curve_nid) {
  8472. case NID_secp112r1:
  8473. case NID_secp112r2:
  8474. degree = 112;
  8475. break;
  8476. case NID_secp128r1:
  8477. case NID_secp128r2:
  8478. degree = 128;
  8479. break;
  8480. case NID_secp160k1:
  8481. case NID_secp160r1:
  8482. case NID_secp160r2:
  8483. case NID_brainpoolP160r1:
  8484. degree = 160;
  8485. break;
  8486. case NID_secp192k1:
  8487. case NID_brainpoolP192r1:
  8488. case NID_X9_62_prime192v1:
  8489. case NID_X9_62_prime192v2:
  8490. case NID_X9_62_prime192v3:
  8491. degree = 192;
  8492. break;
  8493. case NID_secp224k1:
  8494. case NID_secp224r1:
  8495. case NID_brainpoolP224r1:
  8496. degree = 224;
  8497. break;
  8498. case NID_X9_62_prime239v1:
  8499. case NID_X9_62_prime239v2:
  8500. case NID_X9_62_prime239v3:
  8501. degree = 239;
  8502. break;
  8503. case NID_secp256k1:
  8504. case NID_brainpoolP256r1:
  8505. case NID_X9_62_prime256v1:
  8506. degree = 256;
  8507. break;
  8508. case NID_brainpoolP320r1:
  8509. degree = 320;
  8510. break;
  8511. case NID_secp384r1:
  8512. case NID_brainpoolP384r1:
  8513. degree = 384;
  8514. break;
  8515. case NID_brainpoolP512r1:
  8516. degree = 512;
  8517. break;
  8518. case NID_secp521r1:
  8519. degree = 521;
  8520. break;
  8521. }
  8522. }
  8523. return degree;
  8524. }
  8525. #endif /* OPENSSL_EXTRA */
  8526. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8527. /* Get the length of the order in bits of the EC group.
  8528. *
  8529. * TODO: consider switch statement or calculating directly from hex string
  8530. * array instead of using mp_int.
  8531. *
  8532. * @param [in] group EC group.
  8533. * @return Length of order in bits on success.
  8534. * @return 0 on error.
  8535. */
  8536. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8537. {
  8538. int ret = 0;
  8539. #ifdef WOLFSSL_SMALL_STACK
  8540. mp_int *order = NULL;
  8541. #else
  8542. mp_int order[1];
  8543. #endif
  8544. /* Validate parameter. */
  8545. if ((group == NULL) || (group->curve_idx < 0)) {
  8546. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8547. ret = WOLFSSL_FATAL_ERROR;
  8548. }
  8549. #ifdef WOLFSSL_SMALL_STACK
  8550. if (ret == 0) {
  8551. /* Allocate memory for mp_int that will hold order value. */
  8552. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8553. DYNAMIC_TYPE_TMP_BUFFER);
  8554. if (order == NULL) {
  8555. ret = WOLFSSL_FATAL_ERROR;
  8556. }
  8557. }
  8558. #endif
  8559. if (ret == 0) {
  8560. /* Initialize mp_int. */
  8561. ret = mp_init(order);
  8562. }
  8563. if (ret == 0) {
  8564. /* Read hex string of order from wolfCrypt array of curves. */
  8565. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8566. MP_RADIX_HEX);
  8567. if (ret == 0) {
  8568. /* Get bits of order. */
  8569. ret = mp_count_bits(order);
  8570. }
  8571. /* Clear and free mp_int. */
  8572. mp_clear(order);
  8573. }
  8574. #ifdef WOLFSSL_SMALL_STACK
  8575. /* Deallocate order. */
  8576. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8577. #endif
  8578. /* Convert error code to length of 0. */
  8579. if (ret < 0) {
  8580. ret = 0;
  8581. }
  8582. return ret;
  8583. }
  8584. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8585. #if defined(OPENSSL_EXTRA)
  8586. /* Get the order of the group as a BN.
  8587. *
  8588. * Return code compliant with OpenSSL.
  8589. *
  8590. * @param [in] group EC group.
  8591. * @param [in, out] order BN to hold order value.
  8592. * @param [in] ctx Context to use for BN operations. Unused.
  8593. * @return 1 on success.
  8594. * @return 0 on error.
  8595. */
  8596. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8597. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8598. {
  8599. int ret = 1;
  8600. mp_int* mp = NULL;
  8601. /* No BN operations performed - done with mp_int in BN. */
  8602. (void)ctx;
  8603. /* Validate parameters. */
  8604. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8605. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8606. ret = 0;
  8607. }
  8608. if (ret == 1) {
  8609. mp = (mp_int*)order->internal;
  8610. }
  8611. /* Initialize */
  8612. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8613. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8614. ret = 0;
  8615. }
  8616. /* Read hex string of order from wolfCrypt array of curves. */
  8617. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8618. MP_RADIX_HEX) != MP_OKAY)) {
  8619. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8620. /* Zero out any partial value but don't free. */
  8621. mp_zero(mp);
  8622. ret = 0;
  8623. }
  8624. return ret;
  8625. }
  8626. #endif /* OPENSSL_EXTRA */
  8627. /* End EC_GROUP */
  8628. /* Start EC_POINT */
  8629. #if defined(OPENSSL_EXTRA)
  8630. /* Set data of EC point into internal, wolfCrypt EC point object.
  8631. *
  8632. * EC_POINT Openssl -> WolfSSL
  8633. *
  8634. * @param [in, out] p EC point to update.
  8635. * @return 1 on success.
  8636. * @return -1 on failure.
  8637. */
  8638. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8639. {
  8640. int ret = 1;
  8641. WOLFSSL_ENTER("ec_point_internal_set");
  8642. /* Validate parameter. */
  8643. if ((p == NULL) || (p->internal == NULL)) {
  8644. WOLFSSL_MSG("ECPoint NULL error");
  8645. ret = WOLFSSL_FATAL_ERROR;
  8646. }
  8647. else {
  8648. /* Get internal point as a wolfCrypt EC point. */
  8649. ecc_point* point = (ecc_point*)p->internal;
  8650. /* Set X ordinate if available. */
  8651. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8652. WOLFSSL_MSG("ecc point X error");
  8653. ret = WOLFSSL_FATAL_ERROR;
  8654. }
  8655. /* Set Y ordinate if available. */
  8656. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8657. point->y) != 1)) {
  8658. WOLFSSL_MSG("ecc point Y error");
  8659. ret = WOLFSSL_FATAL_ERROR;
  8660. }
  8661. /* Set Z ordinate if available. */
  8662. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8663. point->z) != 1)) {
  8664. WOLFSSL_MSG("ecc point Z error");
  8665. ret = WOLFSSL_FATAL_ERROR;
  8666. }
  8667. /* Internal values set when operations succeeded. */
  8668. p->inSet = (ret == 1);
  8669. }
  8670. return ret;
  8671. }
  8672. /* Set data of internal, wolfCrypt EC point object into EC point.
  8673. *
  8674. * EC_POINT WolfSSL -> OpenSSL
  8675. *
  8676. * @param [in, out] p EC point to update.
  8677. * @return 1 on success.
  8678. * @return -1 on failure.
  8679. */
  8680. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8681. {
  8682. int ret = 1;
  8683. WOLFSSL_ENTER("ec_point_external_set");
  8684. /* Validate parameter. */
  8685. if ((p == NULL) || (p->internal == NULL)) {
  8686. WOLFSSL_MSG("ECPoint NULL error");
  8687. ret = WOLFSSL_FATAL_ERROR;
  8688. }
  8689. else {
  8690. /* Get internal point as a wolfCrypt EC point. */
  8691. ecc_point* point = (ecc_point*)p->internal;
  8692. /* Set X ordinate. */
  8693. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8694. WOLFSSL_MSG("ecc point X error");
  8695. ret = WOLFSSL_FATAL_ERROR;
  8696. }
  8697. /* Set Y ordinate. */
  8698. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8699. WOLFSSL_MSG("ecc point Y error");
  8700. ret = WOLFSSL_FATAL_ERROR;
  8701. }
  8702. /* Set Z ordinate. */
  8703. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8704. WOLFSSL_MSG("ecc point Z error");
  8705. ret = WOLFSSL_FATAL_ERROR;
  8706. }
  8707. /* External values set when operations succeeded. */
  8708. p->exSet = (ret == 1);
  8709. }
  8710. return ret;
  8711. }
  8712. /* Setup internals of EC point.
  8713. *
  8714. * Assumes point is not NULL.
  8715. *
  8716. * @param [in, out] point EC point to update.
  8717. * @return 1 on success.
  8718. * @return 0 on failure.
  8719. */
  8720. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8721. int ret = 1;
  8722. /* Check if internal values need setting. */
  8723. if (!point->inSet) {
  8724. WOLFSSL_MSG("No ECPoint internal set, do it");
  8725. /* Forcing to non-constant type to update internals. */
  8726. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8727. WOLFSSL_MSG("ec_point_internal_set failed");
  8728. ret = 0;
  8729. }
  8730. }
  8731. return ret;
  8732. }
  8733. /* Create a new EC point from the group.
  8734. *
  8735. * @param [in] group EC group.
  8736. * @return EC point on success.
  8737. * @return NULL on error.
  8738. */
  8739. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8740. {
  8741. int err = 0;
  8742. WOLFSSL_EC_POINT* point = NULL;
  8743. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8744. /* Validate parameter. */
  8745. if (group == NULL) {
  8746. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8747. err = 1;
  8748. }
  8749. if (!err) {
  8750. /* Allocate memory for new EC point. */
  8751. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8752. DYNAMIC_TYPE_ECC);
  8753. if (point == NULL) {
  8754. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8755. err = 1;
  8756. }
  8757. }
  8758. if (!err) {
  8759. /* Clear fields of EC point. */
  8760. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8761. /* Allocate internal EC point. */
  8762. point->internal = wc_ecc_new_point();
  8763. if (point->internal == NULL) {
  8764. WOLFSSL_MSG("ecc_new_point failure");
  8765. err = 1;
  8766. }
  8767. }
  8768. if (err) {
  8769. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8770. point = NULL;
  8771. }
  8772. return point;
  8773. }
  8774. #endif /* OPENSSL_EXTRA */
  8775. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8776. /* Dispose of the EC point.
  8777. *
  8778. * Cannot use point after this call.
  8779. *
  8780. * @param [in, out] point EC point to free.
  8781. */
  8782. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8783. {
  8784. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8785. if (point != NULL) {
  8786. if (point->internal != NULL) {
  8787. wc_ecc_del_point((ecc_point*)point->internal);
  8788. point->internal = NULL;
  8789. }
  8790. /* Free ordinates. */
  8791. wolfSSL_BN_free(point->X);
  8792. wolfSSL_BN_free(point->Y);
  8793. wolfSSL_BN_free(point->Z);
  8794. /* Clear fields. */
  8795. point->X = NULL;
  8796. point->Y = NULL;
  8797. point->Z = NULL;
  8798. point->inSet = 0;
  8799. point->exSet = 0;
  8800. /* Dispose of EC point. */
  8801. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8802. }
  8803. }
  8804. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8805. #ifdef OPENSSL_EXTRA
  8806. /* Clear and dispose of the EC point.
  8807. *
  8808. * Cannot use point after this call.
  8809. *
  8810. * @param [in, out] point EC point to free.
  8811. */
  8812. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8813. {
  8814. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8815. if (point != NULL) {
  8816. if (point->internal != NULL) {
  8817. /* Force internal point to be zeros. */
  8818. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8819. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8820. #else
  8821. ecc_point* p = (ecc_point*)point->internal;
  8822. mp_forcezero(p->x);
  8823. mp_forcezero(p->y);
  8824. mp_forcezero(p->z);
  8825. #endif
  8826. wc_ecc_del_point((ecc_point*)point->internal);
  8827. point->internal = NULL;
  8828. }
  8829. /* Clear the ordinates before freeing. */
  8830. wolfSSL_BN_clear_free(point->X);
  8831. wolfSSL_BN_clear_free(point->Y);
  8832. wolfSSL_BN_clear_free(point->Z);
  8833. /* Clear fields. */
  8834. point->X = NULL;
  8835. point->Y = NULL;
  8836. point->Z = NULL;
  8837. point->inSet = 0;
  8838. point->exSet = 0;
  8839. /* Dispose of EC point. */
  8840. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8841. }
  8842. }
  8843. /* Print out the internals of EC point in debug and when logging callback set.
  8844. *
  8845. * Not an OpenSSL API.
  8846. *
  8847. * TODO: Use WOLFSSL_MSG_EX()?
  8848. *
  8849. * @param [in] msg Message to prepend.
  8850. * @param [in] point EC point to print.
  8851. */
  8852. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8853. {
  8854. #if defined(DEBUG_WOLFSSL)
  8855. char *num;
  8856. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8857. /* Only print when debugging on. */
  8858. if (WOLFSSL_IS_DEBUG_ON()) {
  8859. if (point == NULL) {
  8860. /* No point passed in so just put out "NULL". */
  8861. WOLFSSL_MSG_EX("%s = NULL\n", msg);
  8862. }
  8863. else {
  8864. /* Put out message and status of internal/external data set. */
  8865. WOLFSSL_MSG_EX("%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8866. point->exSet);
  8867. /* Get x-ordinate as a hex string and print. */
  8868. num = wolfSSL_BN_bn2hex(point->X);
  8869. WOLFSSL_MSG_EX("\tX = %s\n", num);
  8870. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8871. /* Get x-ordinate as a hex string and print. */
  8872. num = wolfSSL_BN_bn2hex(point->Y);
  8873. WOLFSSL_MSG_EX("\tY = %s\n", num);
  8874. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8875. /* Get z-ordinate as a hex string and print. */
  8876. num = wolfSSL_BN_bn2hex(point->Z);
  8877. WOLFSSL_MSG_EX("\tZ = %s\n", num);
  8878. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8879. }
  8880. }
  8881. #else
  8882. (void)msg;
  8883. (void)point;
  8884. #endif
  8885. }
  8886. /* Convert EC point to hex string that as either uncompressed or compressed.
  8887. *
  8888. * ECC point compression types were not included in selftest ecc.h
  8889. *
  8890. * @param [in] group EC group for point.
  8891. * @param [in] point EC point to encode.
  8892. * @param [in] form Format of encoding. Valid values:
  8893. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8894. * @param [in] ctx Context to use for BN operations. Unused.
  8895. * @return Allocated hex string on success.
  8896. * @return NULL on error.
  8897. */
  8898. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8899. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8900. {
  8901. static const char* hexDigit = "0123456789ABCDEF";
  8902. char* hex = NULL;
  8903. int i;
  8904. int sz = 0;
  8905. int len = 0;
  8906. int err = 0;
  8907. /* No BN operations performed. */
  8908. (void)ctx;
  8909. /* Validate parameters. */
  8910. if ((group == NULL) || (point == NULL)) {
  8911. err = 1;
  8912. }
  8913. /* Get curve id expects a positive index. */
  8914. if ((!err) && (group->curve_idx < 0)) {
  8915. err = 1;
  8916. }
  8917. if (!err) {
  8918. /* Get curve id to look up ordinate size. */
  8919. int id = wc_ecc_get_curve_id(group->curve_idx);
  8920. /* Get size of ordinate. */
  8921. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8922. err = 1;
  8923. }
  8924. }
  8925. if (!err) {
  8926. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8927. len = sz + 1;
  8928. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8929. /* Include y ordinate when uncompressed. */
  8930. len += sz;
  8931. }
  8932. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8933. */
  8934. hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC);
  8935. if (hex == NULL) {
  8936. err = 1;
  8937. }
  8938. }
  8939. if (!err) {
  8940. /* Make bytes all zeros to allow for ordinate values less than max size.
  8941. */
  8942. XMEMSET(hex, 0, (size_t)(2 * len + 1));
  8943. /* Calculate offset as leading zeros not encoded. */
  8944. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8945. /* Put in x-ordinate after format byte. */
  8946. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8947. 0) {
  8948. err = 1;
  8949. }
  8950. }
  8951. if (!err) {
  8952. if (form == POINT_CONVERSION_COMPRESSED) {
  8953. /* Compressed format byte value dependent on whether y-ordinate is
  8954. * odd.
  8955. */
  8956. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8957. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8958. /* No y-ordinate. */
  8959. }
  8960. else {
  8961. /* Put in uncompressed format byte. */
  8962. hex[0] = ECC_POINT_UNCOMP;
  8963. /* Calculate offset as leading zeros not encoded. */
  8964. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8965. /* Put in y-ordinate after x-ordinate. */
  8966. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8967. (byte*)(hex + i)) < 0) {
  8968. err = 1;
  8969. }
  8970. }
  8971. }
  8972. if (!err) {
  8973. /* Convert binary encoding to hex string. */
  8974. /* Start at end so as not to overwrite. */
  8975. for (i = len-1; i >= 0; i--) {
  8976. /* Get byte value and store has hex string. */
  8977. byte b = (byte)hex[i];
  8978. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8979. hex[i * 2 ] = hexDigit[b >> 4];
  8980. }
  8981. /* Memset put trailing zero or '\0' on end of string. */
  8982. }
  8983. if (err && (hex != NULL)) {
  8984. /* Dispose of allocated data not being returned. */
  8985. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8986. hex = NULL;
  8987. }
  8988. /* Return hex string encoding. */
  8989. return hex;
  8990. }
  8991. static size_t hex_to_bytes(const char *hex, unsigned char *output, size_t sz)
  8992. {
  8993. word32 i;
  8994. for (i = 0; i < sz; i++) {
  8995. signed char ch1, ch2;
  8996. ch1 = HexCharToByte(hex[i * 2]);
  8997. ch2 = HexCharToByte(hex[i * 2 + 1]);
  8998. if ((ch1 < 0) || (ch2 < 0)) {
  8999. WOLFSSL_MSG("hex_to_bytes: syntax error");
  9000. return 0;
  9001. }
  9002. output[i] = (unsigned char)((ch1 << 4) + ch2);
  9003. }
  9004. return sz;
  9005. }
  9006. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_hex2point(const EC_GROUP *group,
  9007. const char *hex, WOLFSSL_EC_POINT*p, WOLFSSL_BN_CTX *ctx)
  9008. {
  9009. /* for uncompressed mode */
  9010. size_t str_sz;
  9011. BIGNUM *Gx = NULL;
  9012. BIGNUM *Gy = NULL;
  9013. char strGx[MAX_ECC_BYTES * 2 + 1];
  9014. /* for compressed mode */
  9015. int key_sz;
  9016. byte *octGx = (byte *)strGx; /* octGx[MAX_ECC_BYTES] */
  9017. int p_alloc = 0;
  9018. int ret;
  9019. WOLFSSL_ENTER("wolfSSL_EC_POINT_hex2point");
  9020. if (group == NULL || hex == NULL || ctx == NULL)
  9021. return NULL;
  9022. if (p == NULL) {
  9023. if ((p = wolfSSL_EC_POINT_new(group)) == NULL) {
  9024. WOLFSSL_MSG("wolfSSL_EC_POINT_new");
  9025. goto err;
  9026. }
  9027. p_alloc = 1;
  9028. }
  9029. key_sz = (wolfSSL_EC_GROUP_get_degree(group) + 7) / 8;
  9030. if (hex[0] == '0' && hex[1] == '4') { /* uncompressed mode */
  9031. str_sz = key_sz * 2;
  9032. XMEMSET(strGx, 0x0, str_sz + 1);
  9033. XMEMCPY(strGx, hex + 2, str_sz);
  9034. if (wolfSSL_BN_hex2bn(&Gx, strGx) == 0)
  9035. goto err;
  9036. if (wolfSSL_BN_hex2bn(&Gy, hex + 2 + str_sz) == 0)
  9037. goto err;
  9038. ret = wolfSSL_EC_POINT_set_affine_coordinates_GFp
  9039. (group, p, Gx, Gy, ctx);
  9040. if (ret != WOLFSSL_SUCCESS) {
  9041. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9042. goto err;
  9043. }
  9044. }
  9045. else if (hex[0] == '0' && (hex[1] == '2' || hex[1] == '3')) {
  9046. size_t sz = XSTRLEN(hex + 2) / 2;
  9047. /* compressed mode */
  9048. octGx[0] = ECC_POINT_COMP_ODD;
  9049. if (hex_to_bytes(hex + 2, octGx + 1, sz) != sz) {
  9050. goto err;
  9051. }
  9052. if (wolfSSL_ECPoint_d2i(octGx, key_sz + 1, group, p)
  9053. != WOLFSSL_SUCCESS) {
  9054. goto err;
  9055. }
  9056. }
  9057. else
  9058. goto err;
  9059. wolfSSL_BN_free(Gx);
  9060. wolfSSL_BN_free(Gy);
  9061. return p;
  9062. err:
  9063. wolfSSL_BN_free(Gx);
  9064. wolfSSL_BN_free(Gy);
  9065. if (p_alloc) {
  9066. EC_POINT_free(p);
  9067. }
  9068. return NULL;
  9069. }
  9070. /* Encode the EC point as an uncompressed point in DER.
  9071. *
  9072. * Return code compliant with OpenSSL.
  9073. * Not OpenSSL API.
  9074. *
  9075. * @param [in] group EC group point belongs to.
  9076. * @param [in] point EC point to encode.
  9077. * @param [out] out Buffer to encode into. May be NULL.
  9078. * @param [in, out] len On in, length of buffer in bytes.
  9079. * On out, length of encoding in bytes.
  9080. * @return 1 on success.
  9081. * @return 0 on error.
  9082. */
  9083. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  9084. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  9085. {
  9086. int res = 1;
  9087. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  9088. /* Validate parameters. */
  9089. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  9090. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  9091. res = 0;
  9092. }
  9093. /* Ensure points internals are set up. */
  9094. if ((res == 1) && (ec_point_setup(point) != 1)) {
  9095. res = 0;
  9096. }
  9097. /* Dump the point if encoding. */
  9098. if ((res == 1) && (out != NULL)) {
  9099. wolfSSL_EC_POINT_dump("i2d p", point);
  9100. }
  9101. if (res == 1) {
  9102. /* DER encode point in uncompressed format. */
  9103. int ret = wc_ecc_export_point_der(group->curve_idx,
  9104. (ecc_point*)point->internal, out, len);
  9105. /* Check return. When out is NULL, return will be length only error. */
  9106. if ((ret != MP_OKAY) && ((out != NULL) ||
  9107. (ret != WC_NO_ERR_TRACE(LENGTH_ONLY_E)))) {
  9108. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  9109. res = 0;
  9110. }
  9111. }
  9112. return res;
  9113. }
  9114. /* Decode the uncompressed point in DER into EC point.
  9115. *
  9116. * Return code compliant with OpenSSL.
  9117. * Not OpenSSL API.
  9118. *
  9119. * @param [in] in Buffer containing DER encoded point.
  9120. * @param [in] len Length of data in bytes.
  9121. * @param [in] group EC group associated with point.
  9122. * @param [in, out] point EC point to set data into.
  9123. * @return 1 on success.
  9124. * @return 0 on error.
  9125. */
  9126. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  9127. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  9128. {
  9129. int ret = 1;
  9130. WOLFSSL_BIGNUM* x = NULL;
  9131. WOLFSSL_BIGNUM* y = NULL;
  9132. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  9133. /* Validate parameters. */
  9134. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  9135. (point->internal == NULL)) {
  9136. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  9137. ret = 0;
  9138. }
  9139. if (ret == 1) {
  9140. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9141. /* Import point into internal EC point. */
  9142. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  9143. (ecc_point*)point->internal, 0) != MP_OKAY) {
  9144. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  9145. ret = 0;
  9146. }
  9147. #else
  9148. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  9149. if (in[0] == 0x04) {
  9150. /* Import point into internal EC point. */
  9151. if (wc_ecc_import_point_der((unsigned char *)in, len,
  9152. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  9153. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  9154. ret = 0;
  9155. }
  9156. }
  9157. else {
  9158. WOLFSSL_MSG("Only uncompressed points supported with "
  9159. "HAVE_SELFTEST");
  9160. ret = 0;
  9161. }
  9162. #endif
  9163. }
  9164. if (ret == 1)
  9165. point->inSet = 1;
  9166. /* Set new external point. */
  9167. if (ret == 1 && ec_point_external_set(point) != 1) {
  9168. WOLFSSL_MSG("ec_point_external_set failed");
  9169. ret = 0;
  9170. }
  9171. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  9172. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9173. x = wolfSSL_BN_new();
  9174. y = wolfSSL_BN_new();
  9175. if (x == NULL || y == NULL)
  9176. ret = 0;
  9177. if (ret == 1 && wolfSSL_EC_POINT_get_affine_coordinates_GFp(group,
  9178. point, x, y, NULL) != 1) {
  9179. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp failed");
  9180. ret = 0;
  9181. }
  9182. /* wolfSSL_EC_POINT_set_affine_coordinates_GFp check that the point is
  9183. * on the curve. */
  9184. if (ret == 1 && wolfSSL_EC_POINT_set_affine_coordinates_GFp(group,
  9185. point, x, y, NULL) != 1) {
  9186. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp failed");
  9187. ret = 0;
  9188. }
  9189. #else
  9190. WOLFSSL_MSG("Importing non-affine point. This may cause issues in math "
  9191. "operations later on.");
  9192. #endif
  9193. }
  9194. if (ret == 1) {
  9195. /* Dump new point. */
  9196. wolfSSL_EC_POINT_dump("d2i p", point);
  9197. }
  9198. wolfSSL_BN_free(x);
  9199. wolfSSL_BN_free(y);
  9200. return ret;
  9201. }
  9202. /* Encode point as octet string.
  9203. *
  9204. * HYBRID not supported.
  9205. *
  9206. * @param [in] group EC group that point belongs to.
  9207. * @param [in] point EC point to encode.
  9208. * @param [in] form Format of encoding. Valid values:
  9209. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  9210. * @param [out] buf Buffer to write encoding into.
  9211. * @param [in] len Length of buffer.
  9212. * @param [in] ctx Context to use for BN operations. Unused.
  9213. * @return Length of encoded data on success.
  9214. * @return 0 on error.
  9215. */
  9216. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  9217. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  9218. WOLFSSL_BN_CTX *ctx)
  9219. {
  9220. int err = 0;
  9221. word32 enc_len = (word32)len;
  9222. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9223. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  9224. #endif /* !HAVE_SELFTEST */
  9225. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  9226. /* No BN operations performed. */
  9227. (void)ctx;
  9228. /* Validate parameters. */
  9229. if ((group == NULL) || (point == NULL)) {
  9230. err = 1;
  9231. }
  9232. /* Ensure points internals are set up. */
  9233. if ((!err) && (ec_point_setup(point) != 1)) {
  9234. err = 1;
  9235. }
  9236. /* Special case when point is infinity. */
  9237. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9238. /* Encoding is a single octet: 0x00. */
  9239. enc_len = 1;
  9240. if (buf != NULL) {
  9241. /* Check whether buffer has space. */
  9242. if (len < 1) {
  9243. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  9244. err = 1;
  9245. }
  9246. else {
  9247. /* Put in encoding of infinity. */
  9248. buf[0] = 0x00;
  9249. }
  9250. }
  9251. }
  9252. /* Not infinity. */
  9253. else if (!err) {
  9254. /* Validate format. */
  9255. if (form != POINT_CONVERSION_UNCOMPRESSED
  9256. #ifndef HAVE_SELFTEST
  9257. && form != POINT_CONVERSION_COMPRESSED
  9258. #endif /* !HAVE_SELFTEST */
  9259. ) {
  9260. WOLFSSL_MSG("Unsupported point form");
  9261. err = 1;
  9262. }
  9263. if (!err) {
  9264. int ret;
  9265. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9266. /* Encode as compressed or uncompressed. */
  9267. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  9268. (ecc_point*)point->internal, buf, &enc_len, compressed);
  9269. #else
  9270. /* Encode uncompressed point in DER format. */
  9271. ret = wc_ecc_export_point_der(group->curve_idx,
  9272. (ecc_point*)point->internal, buf, &enc_len);
  9273. #endif /* !HAVE_SELFTEST */
  9274. /* Check return. When buf is NULL, return will be length only
  9275. * error.
  9276. */
  9277. if (ret != ((buf != NULL) ? MP_OKAY : WC_NO_ERR_TRACE(LENGTH_ONLY_E))) {
  9278. err = 1;
  9279. }
  9280. }
  9281. }
  9282. #if defined(DEBUG_WOLFSSL)
  9283. if (!err) {
  9284. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_point2oct point", point);
  9285. WOLFSSL_MSG("\twolfSSL_EC_POINT_point2oct output:");
  9286. WOLFSSL_BUFFER(buf, enc_len);
  9287. }
  9288. #endif
  9289. /* On error, return encoding length of 0. */
  9290. if (err) {
  9291. enc_len = 0;
  9292. }
  9293. return (size_t)enc_len;
  9294. }
  9295. /* Convert octet string to EC point.
  9296. *
  9297. * @param [in] group EC group.
  9298. * @param [in, out] point EC point to set data into.
  9299. * @param [in] buf Buffer holding octet string.
  9300. * @param [in] len Length of data in buffer in bytes.
  9301. * @param [in] ctx Context to use for BN operations. Unused.
  9302. */
  9303. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  9304. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  9305. WOLFSSL_BN_CTX *ctx)
  9306. {
  9307. int ret;
  9308. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9309. /* No BN operations performed. */
  9310. (void)ctx;
  9311. /* Validate parameters. */
  9312. if ((group == NULL) || (point == NULL)) {
  9313. ret = 0;
  9314. }
  9315. else {
  9316. /* Decode DER encoding into EC point. */
  9317. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  9318. point);
  9319. }
  9320. return ret;
  9321. }
  9322. /* Convert an EC point to a single BN.
  9323. *
  9324. * @param [in] group EC group.
  9325. * @param [in] point EC point.
  9326. * @param [in] form Format of encoding. Valid values:
  9327. * POINT_CONVERSION_UNCOMPRESSED,
  9328. * POINT_CONVERSION_COMPRESSED.
  9329. * @param [in, out] bn BN to hold point value.
  9330. * When NULL a new BN is allocated otherwise this is
  9331. * returned on success.
  9332. * @param [in] ctx Context to use for BN operations. Unused.
  9333. * @return BN object with point as a value on success.
  9334. * @return NULL on error.
  9335. */
  9336. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  9337. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  9338. WOLFSSL_BN_CTX* ctx)
  9339. {
  9340. int err = 0;
  9341. size_t len = 0;
  9342. byte *buf = NULL;
  9343. WOLFSSL_BIGNUM *ret = NULL;
  9344. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9345. /* Validate parameters. */
  9346. if ((group == NULL) || (point == NULL)) {
  9347. err = 1;
  9348. }
  9349. /* Calculate length of octet encoding. */
  9350. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  9351. 0, ctx)) == 0)) {
  9352. err = 1;
  9353. }
  9354. /* Allocate buffer to hold octet encoding. */
  9355. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  9356. NULL)) {
  9357. WOLFSSL_MSG("malloc failed");
  9358. err = 1;
  9359. }
  9360. /* Encode EC point as an octet string. */
  9361. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  9362. ctx) != len)) {
  9363. err = 1;
  9364. }
  9365. /* Load BN with octet string data. */
  9366. if (!err) {
  9367. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  9368. }
  9369. /* Dispose of any allocated data. */
  9370. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9371. return ret;
  9372. }
  9373. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9374. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9375. /* Check if EC point is on the the curve defined by the EC group.
  9376. *
  9377. * @param [in] group EC group defining curve.
  9378. * @param [in] point EC point to check.
  9379. * @param [in] ctx Context to use for BN operations. Unused.
  9380. * @return 1 when point is on curve.
  9381. * @return 0 when point is not on curve or error.
  9382. */
  9383. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9384. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9385. {
  9386. int err = 0;
  9387. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9388. /* No BN operations performed. */
  9389. (void)ctx;
  9390. /* Validate parameters. */
  9391. if ((group == NULL) || (point == NULL)) {
  9392. WOLFSSL_MSG("Invalid arguments");
  9393. err = 1;
  9394. }
  9395. /* Ensure internal EC point set. */
  9396. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9397. (WOLFSSL_EC_POINT*)point) != 1) {
  9398. WOLFSSL_MSG("ec_point_internal_set error");
  9399. err = 1;
  9400. }
  9401. /* Check point is on curve from group. */
  9402. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9403. group->curve_idx) != MP_OKAY)) {
  9404. err = 1;
  9405. }
  9406. /* Return boolean of on curve. No error means on curve. */
  9407. return !err;
  9408. }
  9409. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9410. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9411. /* Convert Jacobian ordinates to affine.
  9412. *
  9413. * @param [in] group EC group.
  9414. * @param [in] point EC point to get coordinates from.
  9415. * @return 1 on success.
  9416. * @return 0 on error.
  9417. */
  9418. int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9419. WOLFSSL_EC_POINT *point)
  9420. {
  9421. int err = 0;
  9422. mp_digit mp = 0;
  9423. #ifdef WOLFSSL_SMALL_STACK
  9424. mp_int* modulus;
  9425. #else
  9426. mp_int modulus[1];
  9427. #endif
  9428. #ifdef WOLFSSL_SMALL_STACK
  9429. /* Allocate memory for curve's prime modulus. */
  9430. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9431. if (modulus == NULL) {
  9432. err = 1;
  9433. }
  9434. #endif
  9435. /* Initialize the MP integer. */
  9436. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9437. WOLFSSL_MSG("mp_init failed");
  9438. err = 1;
  9439. }
  9440. if (!err) {
  9441. /* Get the modulus from the hex string in the EC curve set. */
  9442. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9443. MP_RADIX_HEX) != MP_OKAY) {
  9444. WOLFSSL_MSG("mp_read_radix failed");
  9445. err = 1;
  9446. }
  9447. /* Get Montgomery multiplier for the modulus as ordinates in
  9448. * Montgomery form.
  9449. */
  9450. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9451. WOLFSSL_MSG("mp_montgomery_setup failed");
  9452. err = 1;
  9453. }
  9454. /* Map internal EC point from Jacobian to affine. */
  9455. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9456. MP_OKAY)) {
  9457. WOLFSSL_MSG("ecc_map failed");
  9458. err = 1;
  9459. }
  9460. /* Set new ordinates into external EC point. */
  9461. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9462. WOLFSSL_MSG("ec_point_external_set failed");
  9463. err = 1;
  9464. }
  9465. point->exSet = !err;
  9466. mp_clear(modulus);
  9467. }
  9468. #ifdef WOLFSSL_SMALL_STACK
  9469. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9470. #endif
  9471. return err;
  9472. }
  9473. /* Get the affine coordinates of the EC point on a Prime curve.
  9474. *
  9475. * When z-ordinate is not one then coordinates are Jacobian and need to be
  9476. * converted to affine before storing in BNs.
  9477. *
  9478. * Return code compliant with OpenSSL.
  9479. *
  9480. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9481. *
  9482. * @param [in] group EC group.
  9483. * @param [in] point EC point to get coordinates from.
  9484. * @param [in, out] x BN to hold x-ordinate.
  9485. * @param [in, out] y BN to hold y-ordinate.
  9486. * @param [in] ctx Context to use for BN operations. Unused.
  9487. * @return 1 on success.
  9488. * @return 0 on error.
  9489. */
  9490. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9491. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9492. WOLFSSL_BN_CTX* ctx)
  9493. {
  9494. int ret = 1;
  9495. /* BN operations don't need context. */
  9496. (void)ctx;
  9497. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9498. /* Validate parameters. */
  9499. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9500. (x == NULL) || (y == NULL)) {
  9501. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9502. ret = 0;
  9503. }
  9504. /* Don't return point at infinity. */
  9505. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9506. ret = 0;
  9507. }
  9508. /* Ensure internal EC point has values of external EC point. */
  9509. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9510. ret = 0;
  9511. }
  9512. /* Check whether ordinates are in Jacobian form. */
  9513. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9514. /* Convert from Jacobian to affine. */
  9515. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9516. ret = 0;
  9517. }
  9518. }
  9519. /* Copy the externally set x and y ordinates. */
  9520. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9521. ret = 0;
  9522. }
  9523. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9524. ret = 0;
  9525. }
  9526. return ret;
  9527. }
  9528. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9529. /* Sets the affine coordinates that belong on a prime curve.
  9530. *
  9531. * @param [in] group EC group.
  9532. * @param [in, out] point EC point to set coordinates into.
  9533. * @param [in] x BN holding x-ordinate.
  9534. * @param [in] y BN holding y-ordinate.
  9535. * @param [in] ctx Context to use for BN operations. Unused.
  9536. * @return 1 on success.
  9537. * @return 0 on error.
  9538. */
  9539. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9540. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9541. WOLFSSL_BN_CTX* ctx)
  9542. {
  9543. int ret = 1;
  9544. /* BN operations don't need context. */
  9545. (void)ctx;
  9546. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9547. /* Validate parameters. */
  9548. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9549. (x == NULL) || (y == NULL)) {
  9550. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9551. ret = 0;
  9552. }
  9553. /* Ensure we have a object for x-ordinate. */
  9554. if ((ret == 1) && (point->X == NULL) &&
  9555. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9556. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9557. ret = 0;
  9558. }
  9559. /* Ensure we have a object for y-ordinate. */
  9560. if ((ret == 1) && (point->Y == NULL) &&
  9561. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9562. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9563. ret = 0;
  9564. }
  9565. /* Ensure we have a object for z-ordinate. */
  9566. if ((ret == 1) && (point->Z == NULL) &&
  9567. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9568. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9569. ret = 0;
  9570. }
  9571. /* Copy the x-ordinate. */
  9572. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9573. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9574. ret = 0;
  9575. }
  9576. /* Copy the y-ordinate. */
  9577. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9578. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9579. ret = 0;
  9580. }
  9581. /* z-ordinate is one for affine coordinates. */
  9582. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9583. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9584. ret = 0;
  9585. }
  9586. /* Copy the new point data to internal object. */
  9587. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9588. WOLFSSL_MSG("ec_point_internal_set failed");
  9589. ret = 0;
  9590. }
  9591. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9592. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9593. /* Check that the point is valid. */
  9594. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9595. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9596. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9597. ret = 0;
  9598. }
  9599. #endif
  9600. return ret;
  9601. }
  9602. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9603. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9604. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9605. /* Add two points on the same together.
  9606. *
  9607. * @param [in] curveIdx Index of curve in ecc_set.
  9608. * @param [out] r Result point.
  9609. * @param [in] p1 First point to add.
  9610. * @param [in] p2 Second point to add.
  9611. * @return 1 on success.
  9612. * @return 0 on error.
  9613. */
  9614. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9615. ecc_point* p2)
  9616. {
  9617. int ret = 1;
  9618. #ifdef WOLFSSL_SMALL_STACK
  9619. mp_int* a = NULL;
  9620. mp_int* prime = NULL;
  9621. mp_int* mu = NULL;
  9622. #else
  9623. mp_int a[1];
  9624. mp_int prime[1];
  9625. mp_int mu[1];
  9626. #endif
  9627. mp_digit mp = 0;
  9628. ecc_point* montP1 = NULL;
  9629. ecc_point* montP2 = NULL;
  9630. #ifdef WOLFSSL_SMALL_STACK
  9631. if (ret == 1) {
  9632. /* Allocate memory for curve parameter: a. */
  9633. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9634. if (a == NULL) {
  9635. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9636. ret = 0;
  9637. }
  9638. }
  9639. if (ret == 1) {
  9640. /* Allocate memory for curve parameter: prime. */
  9641. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9642. if (prime == NULL) {
  9643. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9644. ret = 0;
  9645. }
  9646. }
  9647. if (ret == 1) {
  9648. /* Allocate memory for mu (Montgomery normalizer). */
  9649. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9650. if (mu == NULL) {
  9651. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9652. ret = 0;
  9653. }
  9654. }
  9655. if (ret == 1) {
  9656. /* Zero out all MP int data in case initialization fails. */
  9657. XMEMSET(a, 0, sizeof(mp_int));
  9658. XMEMSET(prime, 0, sizeof(mp_int));
  9659. XMEMSET(mu, 0, sizeof(mp_int));
  9660. }
  9661. #endif
  9662. /* Initialize the MP ints. */
  9663. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9664. MP_OKAY)) {
  9665. WOLFSSL_MSG("mp_init_multi error");
  9666. ret = 0;
  9667. }
  9668. /* Read the curve parameter: a. */
  9669. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9670. MP_OKAY)) {
  9671. WOLFSSL_MSG("mp_read_radix a error");
  9672. ret = 0;
  9673. }
  9674. /* Read the curve parameter: prime. */
  9675. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9676. MP_RADIX_HEX) != MP_OKAY)) {
  9677. WOLFSSL_MSG("mp_read_radix prime error");
  9678. ret = 0;
  9679. }
  9680. /* Calculate the Montgomery product. */
  9681. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9682. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9683. ret = 0;
  9684. }
  9685. /* TODO: use the heap filed of one of the points? */
  9686. /* Allocate new points to hold the Montgomery form values. */
  9687. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9688. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9689. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9690. ret = 0;
  9691. }
  9692. /* Calculate the Montgomery normalizer. */
  9693. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9694. MP_OKAY)) {
  9695. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9696. ret = 0;
  9697. }
  9698. /* Convert to Montgomery form. */
  9699. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9700. /* Copy the points if the normalizer is 1. */
  9701. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9702. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9703. WOLFSSL_MSG("wc_ecc_copy_point error");
  9704. ret = 0;
  9705. }
  9706. }
  9707. else if (ret == 1) {
  9708. /* Multiply each ordinate by the Montgomery normalizer. */
  9709. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9710. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9711. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9712. WOLFSSL_MSG("mp_mulmod error");
  9713. ret = 0;
  9714. }
  9715. /* Multiply each ordinate by the Montgomery normalizer. */
  9716. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9717. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9718. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9719. WOLFSSL_MSG("mp_mulmod error");
  9720. ret = 0;
  9721. }
  9722. }
  9723. /* Perform point addition with internal EC point objects - Jacobian form
  9724. * result.
  9725. */
  9726. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9727. mp) != MP_OKAY)) {
  9728. WOLFSSL_MSG("ecc_projective_add_point error");
  9729. ret = 0;
  9730. }
  9731. /* Map point back to affine coordinates. Converts from Montogomery form. */
  9732. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9733. WOLFSSL_MSG("ecc_map error");
  9734. ret = 0;
  9735. }
  9736. /* Dispose of allocated memory. */
  9737. mp_clear(a);
  9738. mp_clear(prime);
  9739. mp_clear(mu);
  9740. wc_ecc_del_point_h(montP1, NULL);
  9741. wc_ecc_del_point_h(montP2, NULL);
  9742. #ifdef WOLFSSL_SMALL_STACK
  9743. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9744. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9745. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9746. #endif
  9747. return ret;
  9748. }
  9749. /* Add two points on the same curve together.
  9750. *
  9751. * @param [in] group EC group.
  9752. * @param [out] r EC point that is result of point addition.
  9753. * @param [in] p1 First EC point to add.
  9754. * @param [in] p2 Second EC point to add.
  9755. * @param [in] ctx Context to use for BN operations. Unused.
  9756. * @return 1 on success.
  9757. * @return 0 on error.
  9758. */
  9759. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9760. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9761. {
  9762. int ret = 1;
  9763. /* No BN operations performed. */
  9764. (void)ctx;
  9765. /* Validate parameters. */
  9766. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9767. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9768. ret = 0;
  9769. }
  9770. /* Ensure the internal objects of the EC points are setup. */
  9771. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9772. (ec_point_setup(p2) != 1))) {
  9773. WOLFSSL_MSG("ec_point_setup error");
  9774. ret = 0;
  9775. }
  9776. #ifdef DEBUG_WOLFSSL
  9777. if (ret == 1) {
  9778. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9779. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9780. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9781. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p1", p1);
  9782. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p2", p2);
  9783. if (curve != NULL)
  9784. WOLFSSL_MSG_EX("curve name: %s", curve);
  9785. if (nistName != NULL)
  9786. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9787. }
  9788. #endif
  9789. if (ret == 1) {
  9790. /* Add points using wolfCrypt objects. */
  9791. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9792. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9793. }
  9794. /* Copy internal EC point values out to external EC point. */
  9795. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9796. WOLFSSL_MSG("ec_point_external_set error");
  9797. ret = 0;
  9798. }
  9799. #ifdef DEBUG_WOLFSSL
  9800. if (ret == 1) {
  9801. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add result", r);
  9802. }
  9803. #endif
  9804. return ret;
  9805. }
  9806. /* Sum the scalar multiplications of the base point and n, and q and m.
  9807. *
  9808. * r = base point * n + q * m
  9809. *
  9810. * @param [out] r EC point that is result of operation.
  9811. * @param [in] b Base point of curve.
  9812. * @param [in] n Scalar to multiply by base point.
  9813. * @param [in] q EC point to be scalar multiplied.
  9814. * @param [in] m Scalar to multiply q by.
  9815. * @param [in] a Parameter A of curve.
  9816. * @param [in] prime Prime (modulus) of curve.
  9817. * @return 1 on success.
  9818. * @return 0 on error.
  9819. */
  9820. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9821. mp_int* m, mp_int* a, mp_int* prime)
  9822. {
  9823. int ret = 1;
  9824. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9825. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9826. WOLFSSL_MSG("ecc_mul2add error");
  9827. ret = 0;
  9828. }
  9829. #else
  9830. ecc_point* tmp = NULL;
  9831. mp_digit mp = 0;
  9832. /* Calculate Montgomery product. */
  9833. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9834. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9835. ret = 0;
  9836. }
  9837. /* Create temporary point to hold: q * m */
  9838. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9839. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9840. ret = 0;
  9841. }
  9842. /* r = base point * n */
  9843. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9844. MP_OKAY)) {
  9845. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9846. ret = 0;
  9847. }
  9848. /* tmp = q * m */
  9849. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9850. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9851. ret = 0;
  9852. }
  9853. /* r = r + tmp */
  9854. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9855. MP_OKAY)) {
  9856. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9857. ret = 0;
  9858. }
  9859. /* Map point back to affine coordinates. Converts from Montogomery
  9860. * form. */
  9861. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9862. WOLFSSL_MSG("ecc_map nqm error");
  9863. ret = 0;
  9864. }
  9865. /* Dispose of allocated temporary point. */
  9866. wc_ecc_del_point(tmp);
  9867. #endif
  9868. return ret;
  9869. }
  9870. /* Sum the scalar multiplications of the base point and n, and q and m.
  9871. *
  9872. * r = base point * n + q * m
  9873. *
  9874. * @param [in] curveIdx Index of curve in ecc_set.
  9875. * @param [out] r EC point that is result of operation.
  9876. * @param [in] n Scalar to multiply by base point. May be NULL.
  9877. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9878. * @param [in] m Scalar to multiply q by. May be NULL.
  9879. * @return 1 on success.
  9880. * @return 0 on error.
  9881. */
  9882. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9883. ecc_point* q, mp_int* m)
  9884. {
  9885. int ret = 1;
  9886. #ifdef WOLFSSL_SMALL_STACK
  9887. mp_int* a = NULL;
  9888. mp_int* prime = NULL;
  9889. #else
  9890. mp_int a[1], prime[1];
  9891. #endif
  9892. #ifdef WOLFSSL_SMALL_STACK
  9893. /* Allocate MP integer for curve parameter: a. */
  9894. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9895. if (a == NULL) {
  9896. ret = 0;
  9897. }
  9898. if (ret == 1) {
  9899. /* Allocate MP integer for curve parameter: prime. */
  9900. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9901. if (prime == NULL) {
  9902. ret = 0;
  9903. }
  9904. }
  9905. #endif
  9906. /* Initialize the MP ints. */
  9907. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9908. MP_OKAY)) {
  9909. WOLFSSL_MSG("mp_init_multi error");
  9910. ret = 0;
  9911. }
  9912. /* Read the curve parameter: prime. */
  9913. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9914. MP_RADIX_HEX) != MP_OKAY)) {
  9915. WOLFSSL_MSG("mp_read_radix prime error");
  9916. ret = 0;
  9917. }
  9918. /* Read the curve parameter: a. */
  9919. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9920. MP_RADIX_HEX) != MP_OKAY)) {
  9921. WOLFSSL_MSG("mp_read_radix a error");
  9922. ret = 0;
  9923. }
  9924. if ((ret == 1) && (n != NULL)) {
  9925. /* Get generator - base point. */
  9926. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9927. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9928. WOLFSSL_MSG("wc_ecc_get_generator error");
  9929. ret = 0;
  9930. }
  9931. #else
  9932. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9933. /* Read generator (base point) x-ordinate. */
  9934. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9935. MP_RADIX_HEX) != MP_OKAY)) {
  9936. WOLFSSL_MSG("mp_read_radix Gx error");
  9937. ret = 0;
  9938. }
  9939. /* Read generator (base point) y-ordinate. */
  9940. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9941. MP_RADIX_HEX) != MP_OKAY)) {
  9942. WOLFSSL_MSG("mp_read_radix Gy error");
  9943. ret = 0;
  9944. }
  9945. /* z-ordinate is one as point is affine. */
  9946. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9947. WOLFSSL_MSG("mp_set Gz error");
  9948. ret = 0;
  9949. }
  9950. #endif /* NOPT_FIPS_VERSION == 2 */
  9951. }
  9952. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9953. /* r = base point * n + q * m */
  9954. ret = ec_mul2add(r, r, n, q, m, a, prime);
  9955. }
  9956. /* Not all values present, see if we are only doing base point * n. */
  9957. else if ((ret == 1) && (n != NULL)) {
  9958. /* r = base point * n */
  9959. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9960. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9961. ret = 0;
  9962. }
  9963. }
  9964. /* Not all values present, see if we are only doing q * m. */
  9965. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9966. /* r = q * m */
  9967. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9968. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9969. ret = 0;
  9970. }
  9971. }
  9972. /* No values to use. */
  9973. else if (ret == 1) {
  9974. /* Set result to infinity as no values passed in. */
  9975. mp_zero(r->x);
  9976. mp_zero(r->y);
  9977. mp_zero(r->z);
  9978. }
  9979. mp_clear(a);
  9980. mp_clear(prime);
  9981. #ifdef WOLFSSL_SMALL_STACK
  9982. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9983. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9984. #endif
  9985. return ret;
  9986. }
  9987. /* Sum the scalar multiplications of the base point and n, and q and m.
  9988. *
  9989. * r = base point * n + q * m
  9990. *
  9991. * Return code compliant with OpenSSL.
  9992. *
  9993. * @param [in] group EC group.
  9994. * @param [out] r EC point that is result of operation.
  9995. * @param [in] n Scalar to multiply by base point. May be NULL.
  9996. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9997. * @param [in] m Scalar to multiply q by. May be NULL.
  9998. * @param [in] ctx Context to use for BN operations. Unused.
  9999. * @return 1 on success.
  10000. * @return 0 on error.
  10001. */
  10002. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  10003. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  10004. WOLFSSL_BN_CTX *ctx)
  10005. {
  10006. int ret = 1;
  10007. /* No BN operations performed. */
  10008. (void)ctx;
  10009. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  10010. /* Validate parameters. */
  10011. if ((group == NULL) || (r == NULL)) {
  10012. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  10013. ret = 0;
  10014. }
  10015. /* Ensure the internal representation of the EC point q is setup. */
  10016. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  10017. WOLFSSL_MSG("ec_point_setup error");
  10018. ret = 0;
  10019. }
  10020. #ifdef DEBUG_WOLFSSL
  10021. if (ret == 1) {
  10022. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  10023. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  10024. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  10025. char* num;
  10026. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul input q", q);
  10027. num = wolfSSL_BN_bn2hex(n);
  10028. WOLFSSL_MSG_EX("\tn = %s", num);
  10029. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  10030. num = wolfSSL_BN_bn2hex(m);
  10031. WOLFSSL_MSG_EX("\tm = %s", num);
  10032. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  10033. if (curve != NULL)
  10034. WOLFSSL_MSG_EX("curve name: %s", curve);
  10035. if (nistName != NULL)
  10036. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  10037. }
  10038. #endif
  10039. if (ret == 1) {
  10040. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  10041. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  10042. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  10043. /* Perform multiplication with wolfCrypt objects. */
  10044. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  10045. ni, qi, mi);
  10046. }
  10047. /* Only on success is the internal point guaranteed to be set. */
  10048. if (r != NULL) {
  10049. r->inSet = (ret == 1);
  10050. }
  10051. /* Copy internal EC point values out to external EC point. */
  10052. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  10053. WOLFSSL_MSG("ec_point_external_set error");
  10054. ret = 0;
  10055. }
  10056. #ifdef DEBUG_WOLFSSL
  10057. if (ret == 1) {
  10058. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul result", r);
  10059. }
  10060. #endif
  10061. return ret;
  10062. }
  10063. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  10064. * !WOLFSSL_SP_MATH */
  10065. /* Invert the point on the curve.
  10066. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  10067. *
  10068. * @param [in] curveIdx Index of curve in ecc_set.
  10069. * @param [in, out] point EC point to invert.
  10070. * @return 1 on success.
  10071. * @return 0 on error.
  10072. */
  10073. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  10074. {
  10075. int ret = 1;
  10076. #ifdef WOLFSSL_SMALL_STACK
  10077. mp_int* prime = NULL;
  10078. #else
  10079. mp_int prime[1];
  10080. #endif
  10081. #ifdef WOLFSSL_SMALL_STACK
  10082. /* Allocate memory for an MP int to hold the prime of the curve. */
  10083. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  10084. if (prime == NULL) {
  10085. ret = 0;
  10086. }
  10087. #endif
  10088. /* Initialize MP int. */
  10089. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  10090. WOLFSSL_MSG("mp_init_multi error");
  10091. ret = 0;
  10092. }
  10093. /* Read the curve parameter: prime. */
  10094. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  10095. MP_RADIX_HEX) != MP_OKAY)) {
  10096. WOLFSSL_MSG("mp_read_radix prime error");
  10097. ret = 0;
  10098. }
  10099. /* y = (prime - y) mod prime. */
  10100. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  10101. point->y) != MP_OKAY)) {
  10102. WOLFSSL_MSG("mp_sub error");
  10103. ret = 0;
  10104. }
  10105. /* Dispose of memory associated with MP. */
  10106. mp_free(prime);
  10107. #ifdef WOLFSSL_SMALL_STACK
  10108. /* Dispose of dynamically allocated temporaries. */
  10109. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  10110. #endif
  10111. return ret;
  10112. }
  10113. /* Invert the point on the curve.
  10114. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  10115. *
  10116. * @param [in] group EC group.
  10117. * @param [in, out] point EC point to invert.
  10118. * @param [in] ctx Context to use for BN operations. Unused.
  10119. * @return 1 on success.
  10120. * @return 0 on error.
  10121. */
  10122. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  10123. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  10124. {
  10125. int ret = 1;
  10126. /* No BN operations performed. */
  10127. (void)ctx;
  10128. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  10129. /* Validate parameters. */
  10130. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10131. ret = 0;
  10132. }
  10133. /* Ensure internal representation of point is setup. */
  10134. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10135. ret = 0;
  10136. }
  10137. #ifdef DEBUG_WOLFSSL
  10138. if (ret == 1) {
  10139. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  10140. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  10141. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  10142. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert input", point);
  10143. if (curve != NULL)
  10144. WOLFSSL_MSG_EX("curve name: %s", curve);
  10145. if (nistName != NULL)
  10146. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  10147. }
  10148. #endif
  10149. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  10150. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  10151. if (ec_point_convert_to_affine(group, point) != 0)
  10152. ret = 0;
  10153. #else
  10154. WOLFSSL_MSG("wolfSSL_EC_POINT_invert called on non-affine point");
  10155. ret = 0;
  10156. #endif
  10157. }
  10158. if (ret == 1) {
  10159. /* Perform inversion using wolfCrypt objects. */
  10160. ret = wolfssl_ec_point_invert(group->curve_idx,
  10161. (ecc_point*)point->internal);
  10162. }
  10163. /* Set the external EC point representation based on internal. */
  10164. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  10165. WOLFSSL_MSG("ec_point_external_set error");
  10166. ret = 0;
  10167. }
  10168. #ifdef DEBUG_WOLFSSL
  10169. if (ret == 1) {
  10170. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert result", point);
  10171. }
  10172. #endif
  10173. return ret;
  10174. }
  10175. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10176. /* Compare two points on a the same curve.
  10177. *
  10178. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  10179. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10180. * When equal:
  10181. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10182. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  10183. *
  10184. * @param [in] group EC group.
  10185. * @param [in] a EC point to compare.
  10186. * @param [in] b EC point to compare.
  10187. * @return 0 when equal.
  10188. * @return 1 when different.
  10189. * @return -1 on error.
  10190. */
  10191. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  10192. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10193. {
  10194. int ret = 0;
  10195. BIGNUM* at = BN_new();
  10196. BIGNUM* bt = BN_new();
  10197. BIGNUM* az = BN_new();
  10198. BIGNUM* bz = BN_new();
  10199. BIGNUM* mod = BN_new();
  10200. /* Check that the big numbers were allocated. */
  10201. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  10202. (mod == NULL)) {
  10203. ret = WOLFSSL_FATAL_ERROR;
  10204. }
  10205. /* Get the modulus for the curve. */
  10206. if ((ret == 0) &&
  10207. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  10208. ret = WOLFSSL_FATAL_ERROR;
  10209. }
  10210. if (ret == 0) {
  10211. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  10212. if (BN_is_one(a->Z)) {
  10213. if (BN_copy(bt, b->X) == NULL) {
  10214. ret = WOLFSSL_FATAL_ERROR;
  10215. }
  10216. }
  10217. /* az = Az ^ 2 */
  10218. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  10219. ret = WOLFSSL_FATAL_ERROR;
  10220. }
  10221. /* bt = Bx * az = Bx * (Az ^ 2) */
  10222. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  10223. ret = WOLFSSL_FATAL_ERROR;
  10224. }
  10225. }
  10226. if (ret == 0) {
  10227. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  10228. if (BN_is_one(b->Z)) {
  10229. if (BN_copy(at, a->X) == NULL) {
  10230. ret = WOLFSSL_FATAL_ERROR;
  10231. }
  10232. }
  10233. /* bz = Bz ^ 2 */
  10234. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  10235. ret = WOLFSSL_FATAL_ERROR;
  10236. }
  10237. /* at = Ax * bz = Ax * (Bz ^ 2) */
  10238. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  10239. ret = WOLFSSL_FATAL_ERROR;
  10240. }
  10241. }
  10242. /* Compare x-ordinates. */
  10243. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10244. ret = 1;
  10245. }
  10246. if (ret == 0) {
  10247. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  10248. if (BN_is_one(a->Z)) {
  10249. if (BN_copy(bt, b->Y) == NULL) {
  10250. ret = WOLFSSL_FATAL_ERROR;
  10251. }
  10252. }
  10253. /* az = az * Az = Az ^ 3 */
  10254. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  10255. ret = WOLFSSL_FATAL_ERROR;
  10256. }
  10257. /* bt = By * az = By * (Az ^ 3) */
  10258. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  10259. ret = WOLFSSL_FATAL_ERROR;
  10260. }
  10261. }
  10262. if (ret == 0) {
  10263. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  10264. if (BN_is_one(b->Z)) {
  10265. if (BN_copy(at, a->Y) == NULL) {
  10266. ret = WOLFSSL_FATAL_ERROR;
  10267. }
  10268. }
  10269. /* bz = bz * Bz = Bz ^ 3 */
  10270. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  10271. ret = WOLFSSL_FATAL_ERROR;
  10272. }
  10273. /* at = Ay * bz = Ay * (Bz ^ 3) */
  10274. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  10275. ret = WOLFSSL_FATAL_ERROR;
  10276. }
  10277. }
  10278. /* Compare y-ordinates. */
  10279. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10280. ret = 1;
  10281. }
  10282. BN_free(mod);
  10283. BN_free(bz);
  10284. BN_free(az);
  10285. BN_free(bt);
  10286. BN_free(at);
  10287. return ret;
  10288. }
  10289. #endif
  10290. /* Compare two points on a the same curve.
  10291. *
  10292. * Return code compliant with OpenSSL.
  10293. *
  10294. * @param [in] group EC group.
  10295. * @param [in] a EC point to compare.
  10296. * @param [in] b EC point to compare.
  10297. * @param [in] ctx Context to use for BN operations. Unused.
  10298. * @return 0 when equal.
  10299. * @return 1 when different.
  10300. * @return -1 on error.
  10301. */
  10302. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  10303. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10304. {
  10305. int ret = 0;
  10306. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  10307. /* Validate parameters. */
  10308. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  10309. (b == NULL) || (b->internal == NULL)) {
  10310. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  10311. ret = WOLFSSL_FATAL_ERROR;
  10312. }
  10313. if (ret != -1) {
  10314. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10315. /* If same Z ordinate then no need to convert to affine. */
  10316. if (BN_cmp(a->Z, b->Z) == 0) {
  10317. /* Compare */
  10318. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  10319. }
  10320. else {
  10321. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  10322. }
  10323. #else
  10324. /* No BN operations performed. */
  10325. (void)ctx;
  10326. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  10327. (ecc_point*)b->internal) != MP_EQ);
  10328. #endif
  10329. }
  10330. return ret;
  10331. }
  10332. /* Copy EC point.
  10333. *
  10334. * @param [out] dest EC point to copy into.
  10335. * @param [in] src EC point to copy.
  10336. * @return 1 on success.
  10337. * @return 0 on error.
  10338. */
  10339. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  10340. {
  10341. int ret = 1;
  10342. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  10343. /* Validate parameters. */
  10344. if ((dest == NULL) || (src == NULL)) {
  10345. ret = 0;
  10346. }
  10347. /* Ensure internal EC point of src is setup. */
  10348. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  10349. ret = 0;
  10350. }
  10351. /* Copy internal EC points. */
  10352. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  10353. (ecc_point*)dest->internal) != MP_OKAY)) {
  10354. ret = 0;
  10355. }
  10356. if (ret == 1) {
  10357. /* Destinatation internal point is set. */
  10358. dest->inSet = 1;
  10359. /* Set the external EC point of dest based on internal. */
  10360. if (ec_point_external_set(dest) != 1) {
  10361. ret = 0;
  10362. }
  10363. }
  10364. return ret;
  10365. }
  10366. /* Checks whether point is at infinity.
  10367. *
  10368. * Return code compliant with OpenSSL.
  10369. *
  10370. * @param [in] group EC group.
  10371. * @param [in] point EC point to check.
  10372. * @return 1 when at infinity.
  10373. * @return 0 when not at infinity.
  10374. */
  10375. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  10376. const WOLFSSL_EC_POINT *point)
  10377. {
  10378. int ret = 1;
  10379. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  10380. /* Validate parameters. */
  10381. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10382. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  10383. ret = 0;
  10384. }
  10385. /* Ensure internal EC point is setup. */
  10386. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10387. ret = 0;
  10388. }
  10389. if (ret == 1) {
  10390. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10391. /* Check for infinity. */
  10392. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  10393. if (ret < 0) {
  10394. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  10395. /* Error return is 0 by OpenSSL. */
  10396. ret = 0;
  10397. }
  10398. #else
  10399. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  10400. ret = 0;
  10401. #endif
  10402. }
  10403. return ret;
  10404. }
  10405. #endif /* OPENSSL_EXTRA */
  10406. /* End EC_POINT */
  10407. /* Start EC_KEY */
  10408. #ifdef OPENSSL_EXTRA
  10409. /*
  10410. * EC key constructor/deconstructor APIs
  10411. */
  10412. /* Allocate a new EC key.
  10413. *
  10414. * Not OpenSSL API.
  10415. *
  10416. * @param [in] heap Heap hint for dynamic memory allocation.
  10417. * @param [in] devId Device identifier value.
  10418. * @return New, allocated EC key on success.
  10419. * @return NULL on error.
  10420. */
  10421. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  10422. {
  10423. WOLFSSL_EC_KEY *key = NULL;
  10424. int err = 0;
  10425. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  10426. /* Allocate memory for EC key. */
  10427. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  10428. DYNAMIC_TYPE_ECC);
  10429. if (key == NULL) {
  10430. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  10431. err = 1;
  10432. }
  10433. if (!err) {
  10434. /* Reset all fields to 0. */
  10435. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  10436. /* Cache heap hint. */
  10437. key->heap = heap;
  10438. /* Initialize fields to defaults. */
  10439. key->form = POINT_CONVERSION_UNCOMPRESSED;
  10440. /* Initialize reference count. */
  10441. wolfSSL_RefInit(&key->ref, &err);
  10442. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  10443. }
  10444. if (!err) {
  10445. #endif
  10446. /* Allocate memory for internal EC key representation. */
  10447. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  10448. DYNAMIC_TYPE_ECC);
  10449. if (key->internal == NULL) {
  10450. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10451. err = 1;
  10452. }
  10453. }
  10454. if (!err) {
  10455. /* Initialize wolfCrypt EC key. */
  10456. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10457. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10458. err = 1;
  10459. }
  10460. }
  10461. if (!err) {
  10462. /* Group unknown at creation */
  10463. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10464. if (key->group == NULL) {
  10465. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10466. err = 1;
  10467. }
  10468. }
  10469. if (!err) {
  10470. /* Allocate a point as public key. */
  10471. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10472. if (key->pub_key == NULL) {
  10473. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10474. err = 1;
  10475. }
  10476. }
  10477. if (!err) {
  10478. /* Allocate a BN as private key. */
  10479. key->priv_key = wolfSSL_BN_new();
  10480. if (key->priv_key == NULL) {
  10481. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10482. err = 1;
  10483. }
  10484. }
  10485. if (err) {
  10486. /* Dispose of EC key on error. */
  10487. wolfSSL_EC_KEY_free(key);
  10488. key = NULL;
  10489. }
  10490. /* Return new EC key object. */
  10491. return key;
  10492. }
  10493. /* Allocate a new EC key.
  10494. *
  10495. * @return New, allocated EC key on success.
  10496. * @return NULL on error.
  10497. */
  10498. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10499. {
  10500. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10501. }
  10502. /* Create new EC key with the group having the specified numeric ID.
  10503. *
  10504. * @param [in] nid Numeric ID.
  10505. * @return New, allocated EC key on success.
  10506. * @return NULL on error.
  10507. */
  10508. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10509. {
  10510. WOLFSSL_EC_KEY *key;
  10511. int err = 0;
  10512. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10513. /* Allocate empty, EC key. */
  10514. key = wolfSSL_EC_KEY_new();
  10515. if (key == NULL) {
  10516. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10517. err = 1;
  10518. }
  10519. if (!err) {
  10520. /* Set group to be nid. */
  10521. ec_group_set_nid(key->group, nid);
  10522. if (key->group->curve_idx == -1) {
  10523. wolfSSL_EC_KEY_free(key);
  10524. key = NULL;
  10525. }
  10526. }
  10527. /* Return the new EC key object. */
  10528. return key;
  10529. }
  10530. /* Dispose of the EC key and allocated data.
  10531. *
  10532. * Cannot use key after this call.
  10533. *
  10534. * @param [in] key EC key to free.
  10535. */
  10536. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10537. {
  10538. int doFree = 0;
  10539. int err;
  10540. (void)err;
  10541. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10542. if (key != NULL) {
  10543. void* heap = key->heap;
  10544. /* Decrement reference count. */
  10545. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10546. if (doFree) {
  10547. /* Dispose of allocated reference counting data. */
  10548. wolfSSL_RefFree(&key->ref);
  10549. /* Dispose of private key. */
  10550. wolfSSL_BN_free(key->priv_key);
  10551. wolfSSL_EC_POINT_free(key->pub_key);
  10552. wolfSSL_EC_GROUP_free(key->group);
  10553. if (key->internal != NULL) {
  10554. /* Dispose of wolfCrypt representation of EC key. */
  10555. wc_ecc_free((ecc_key*)key->internal);
  10556. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10557. }
  10558. /* Set back to NULLs for safety. */
  10559. ForceZero(key, sizeof(*key));
  10560. /* Dispose of the memory associated with the EC key. */
  10561. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10562. (void)heap;
  10563. }
  10564. }
  10565. }
  10566. /* Increments ref count of EC key.
  10567. *
  10568. * @param [in, out] key EC key.
  10569. * @return 1 on success
  10570. * @return 0 on error
  10571. */
  10572. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10573. {
  10574. int err = 1;
  10575. if (key != NULL) {
  10576. wolfSSL_RefInc(&key->ref, &err);
  10577. }
  10578. return !err;
  10579. }
  10580. #ifndef NO_CERTS
  10581. #if defined(OPENSSL_ALL)
  10582. /* Copy the internal, wolfCrypt EC key.
  10583. *
  10584. * @param [in, out] dst Destination wolfCrypt EC key.
  10585. * @param [in] src Source wolfCrypt EC key.
  10586. * @return 0 on success.
  10587. * @return Negative on error.
  10588. */
  10589. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10590. {
  10591. int ret;
  10592. /* Copy public key. */
  10593. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10594. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10595. #else
  10596. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10597. #endif
  10598. if (ret != MP_OKAY) {
  10599. WOLFSSL_MSG("wc_ecc_copy_point error");
  10600. }
  10601. if (ret == 0) {
  10602. /* Copy private key. */
  10603. ret = mp_copy(wc_ecc_key_get_priv((ecc_key*)src),
  10604. wc_ecc_key_get_priv(dst));
  10605. if (ret != MP_OKAY) {
  10606. WOLFSSL_MSG("mp_copy error");
  10607. }
  10608. }
  10609. if (ret == 0) {
  10610. /* Copy domain parameters. */
  10611. if (src->dp) {
  10612. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10613. if (ret != 0) {
  10614. WOLFSSL_MSG("wc_ecc_set_curve error");
  10615. }
  10616. }
  10617. }
  10618. if (ret == 0) {
  10619. /* Copy the other components. */
  10620. dst->type = src->type;
  10621. dst->idx = src->idx;
  10622. dst->state = src->state;
  10623. dst->flags = src->flags;
  10624. }
  10625. return ret;
  10626. }
  10627. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10628. *
  10629. * Copies the internal representation as well.
  10630. *
  10631. * @param [in] src EC key to duplicate.
  10632. *
  10633. * @return EC key on success.
  10634. * @return NULL on error.
  10635. */
  10636. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10637. {
  10638. int err = 0;
  10639. WOLFSSL_EC_KEY* newKey = NULL;
  10640. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10641. /* Validate EC key. */
  10642. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10643. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10644. WOLFSSL_MSG("src NULL error");
  10645. err = 1;
  10646. }
  10647. if (!err) {
  10648. /* Create a new, empty key. */
  10649. newKey = wolfSSL_EC_KEY_new();
  10650. if (newKey == NULL) {
  10651. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10652. err = 1;
  10653. }
  10654. }
  10655. if (!err) {
  10656. /* Copy internal EC key. */
  10657. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10658. (ecc_key*)src->internal) != 0) {
  10659. WOLFSSL_MSG("Copying internal EC key error");
  10660. err = 1;
  10661. }
  10662. }
  10663. if (!err) {
  10664. /* Internal key set. */
  10665. newKey->inSet = 1;
  10666. /* Copy group */
  10667. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10668. }
  10669. /* Copy public key. */
  10670. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10671. WOLFSSL_MSG("Copying EC public key error");
  10672. err = 1;
  10673. }
  10674. if (!err) {
  10675. /* Set header size of private key in PKCS#8 format.*/
  10676. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10677. /* Copy private key. */
  10678. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10679. WOLFSSL_MSG("Copying EC private key error");
  10680. err = 1;
  10681. }
  10682. }
  10683. if (err) {
  10684. /* Dispose of EC key on error. */
  10685. wolfSSL_EC_KEY_free(newKey);
  10686. newKey = NULL;
  10687. }
  10688. /* Return the new EC key. */
  10689. return newKey;
  10690. }
  10691. #endif /* OPENSSL_ALL */
  10692. #endif /* !NO_CERTS */
  10693. /*
  10694. * EC key to/from bin/octet APIs
  10695. */
  10696. /* Create an EC key from the octet encoded public key.
  10697. *
  10698. * Behaviour checked against OpenSSL.
  10699. *
  10700. * @param [out] key Reference to EC key. Must pass in a valid object with
  10701. * group set.
  10702. * @param [in, out] in On in, reference to buffer that contains data.
  10703. * On out, reference to buffer after public key data.
  10704. * @param [in] len Length of data in the buffer. Must be length of the
  10705. * encoded public key.
  10706. * @return Allocated EC key on success.
  10707. * @return NULL on error.
  10708. */
  10709. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10710. const unsigned char **in, long len)
  10711. {
  10712. int err = 0;
  10713. WOLFSSL_EC_KEY* ret = NULL;
  10714. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10715. /* Validate parameters: EC group needed to perform import. */
  10716. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10717. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10718. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10719. err = 1;
  10720. }
  10721. if (!err) {
  10722. /* Return the EC key object passed in. */
  10723. ret = *key;
  10724. /* Import point into public key field. */
  10725. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in,
  10726. (size_t)len, NULL) != 1) {
  10727. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10728. ret = NULL;
  10729. err = 1;
  10730. }
  10731. }
  10732. if (!err) {
  10733. /* Assumed length passed in is all the data. */
  10734. *in += len;
  10735. }
  10736. return ret;
  10737. }
  10738. /* Puts the encoded public key into out.
  10739. *
  10740. * Passing in NULL for out returns length only.
  10741. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10742. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10743. *
  10744. * @param [in] key EC key to encode.
  10745. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10746. * point to NULL.
  10747. * @return Length of encoding in bytes on success.
  10748. * @return 0 on error.
  10749. */
  10750. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10751. {
  10752. int ret = 1;
  10753. size_t len = 0;
  10754. int form = POINT_CONVERSION_UNCOMPRESSED;
  10755. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10756. /* Validate parameters. */
  10757. if (key == NULL) {
  10758. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10759. ret = 0;
  10760. }
  10761. /* Ensure the external key data is set from the internal EC key. */
  10762. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10763. key) != 1)) {
  10764. WOLFSSL_MSG("SetECKeyExternal failure");
  10765. ret = 0;
  10766. }
  10767. if (ret == 1) {
  10768. #ifdef HAVE_COMP_KEY
  10769. /* Default to compressed form if not set */
  10770. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10771. POINT_CONVERSION_UNCOMPRESSED :
  10772. POINT_CONVERSION_COMPRESSED;
  10773. #endif
  10774. /* Calculate length of point encoding. */
  10775. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10776. 0, NULL);
  10777. }
  10778. /* Encode if length calculated and pointer supplied to update. */
  10779. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10780. unsigned char *tmp = NULL;
  10781. /* Allocate buffer for encoding if no buffer supplied. */
  10782. if (*out == NULL) {
  10783. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10784. if (tmp == NULL) {
  10785. WOLFSSL_MSG("malloc failed");
  10786. ret = 0;
  10787. }
  10788. }
  10789. else {
  10790. /* Get buffer to encode into. */
  10791. tmp = *out;
  10792. }
  10793. /* Encode public key into buffer. */
  10794. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10795. form, tmp, len, NULL) == 0)) {
  10796. ret = 0;
  10797. }
  10798. if (ret == 1) {
  10799. /* Return buffer if allocated. */
  10800. if (*out == NULL) {
  10801. *out = tmp;
  10802. }
  10803. else {
  10804. /* Step over encoded data if not allocated. */
  10805. *out += len;
  10806. }
  10807. }
  10808. else if (*out == NULL) {
  10809. /* Dispose of allocated buffer. */
  10810. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10811. }
  10812. }
  10813. if (ret == 1) {
  10814. /* Return length on success. */
  10815. ret = (int)len;
  10816. }
  10817. return ret;
  10818. }
  10819. #ifdef HAVE_ECC_KEY_IMPORT
  10820. /* Create a EC key from the DER encoded private key.
  10821. *
  10822. * @param [out] key Reference to EC key.
  10823. * @param [in, out] in On in, reference to buffer that contains DER data.
  10824. * On out, reference to buffer after private key data.
  10825. * @param [in] long Length of data in the buffer. May be larger than the
  10826. * length of the encoded private key.
  10827. * @return Allocated EC key on success.
  10828. * @return NULL on error.
  10829. */
  10830. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10831. const unsigned char** in, long len)
  10832. {
  10833. int err = 0;
  10834. word32 idx = 0;
  10835. WOLFSSL_EC_KEY* ret = NULL;
  10836. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10837. /* Validate parameters. */
  10838. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10839. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10840. err = 1;
  10841. }
  10842. /* Create a new, empty EC key. */
  10843. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10844. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10845. err = 1;
  10846. }
  10847. /* Decode the private key DER data into internal EC key. */
  10848. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10849. (word32)len) != 0)) {
  10850. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10851. err = 1;
  10852. }
  10853. if (!err) {
  10854. /* Internal EC key setup. */
  10855. ret->inSet = 1;
  10856. /* Set the EC key from the internal values. */
  10857. if (SetECKeyExternal(ret) != 1) {
  10858. WOLFSSL_MSG("SetECKeyExternal error");
  10859. err = 1;
  10860. }
  10861. }
  10862. if (!err) {
  10863. /* Move buffer on to next byte after data used. */
  10864. *in += idx;
  10865. if (key) {
  10866. /* Return new EC key through reference. */
  10867. *key = ret;
  10868. }
  10869. }
  10870. if (err && (ret != NULL)) {
  10871. /* Dispose of allocated EC key. */
  10872. wolfSSL_EC_KEY_free(ret);
  10873. ret = NULL;
  10874. }
  10875. return ret;
  10876. }
  10877. #endif /* HAVE_ECC_KEY_IMPORT */
  10878. /* Enecode the private key of the EC key into the buffer as DER.
  10879. *
  10880. * @param [in] key EC key to encode.
  10881. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10882. * On out, reference to buffer adter the encoding.
  10883. * May be NULL.
  10884. * @return Length of DER encoding on success.
  10885. * @return 0 on error.
  10886. */
  10887. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10888. {
  10889. int err = 0;
  10890. word32 len = 0;
  10891. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10892. /* Validate parameters. */
  10893. if (key == NULL) {
  10894. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10895. err = 1;
  10896. }
  10897. /* Update the internal EC key if not set. */
  10898. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10899. 1)) {
  10900. WOLFSSL_MSG("SetECKeyInternal error");
  10901. err = 1;
  10902. }
  10903. /* Calculate the length of the private key DER encoding using internal EC
  10904. * key. */
  10905. if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal,
  10906. 0)) <= 0)) {
  10907. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10908. err = 1;
  10909. }
  10910. /* Only return length when out is NULL. */
  10911. if ((!err) && (out != NULL)) {
  10912. unsigned char* buf = NULL;
  10913. /* Must have a buffer to encode into. */
  10914. if (*out == NULL) {
  10915. /* Allocate a new buffer of appropriate length. */
  10916. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10917. if (buf == NULL) {
  10918. /* Error and return 0. */
  10919. err = 1;
  10920. len = 0;
  10921. }
  10922. else {
  10923. /* Return the allocated buffer. */
  10924. *out = buf;
  10925. }
  10926. }
  10927. /* Encode the internal EC key as a private key in DER format. */
  10928. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10929. len) < 0) {
  10930. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10931. err = 1;
  10932. }
  10933. else if (buf != *out) {
  10934. /* Move the reference to byte past encoded private key. */
  10935. *out += len;
  10936. }
  10937. /* Dispose of any allocated buffer on error. */
  10938. if (err && (*out == buf)) {
  10939. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10940. *out = NULL;
  10941. }
  10942. }
  10943. return (int)len;
  10944. }
  10945. /* Load private key into EC key from DER encoding.
  10946. *
  10947. * Not an OpenSSL compatibility API.
  10948. *
  10949. * @param [in, out] key EC key to put private key values into.
  10950. * @param [in] derBuf Buffer holding DER encoding.
  10951. * @param [in] derSz Size of DER encoding in bytes.
  10952. * @return 1 on success.
  10953. * @return -1 on error.
  10954. */
  10955. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10956. int derSz)
  10957. {
  10958. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10959. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10960. }
  10961. /* Load private/public key into EC key from DER encoding.
  10962. *
  10963. * Not an OpenSSL compatibility API.
  10964. *
  10965. * @param [in, out] key EC key to put private/public key values into.
  10966. * @param [in] derBuf Buffer holding DER encoding.
  10967. * @param [in] derSz Size of DER encoding in bytes.
  10968. * @param [in] opt Key type option. Valid values:
  10969. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10970. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10971. * @return 1 on success.
  10972. * @return -1 on error.
  10973. */
  10974. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10975. int derSz, int opt)
  10976. {
  10977. int res = 1;
  10978. int ret;
  10979. word32 idx = 0;
  10980. word32 algId;
  10981. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10982. /* Validate parameters. */
  10983. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10984. (derSz <= 0)) {
  10985. WOLFSSL_MSG("Bad function arguments");
  10986. res = WOLFSSL_FATAL_ERROR;
  10987. }
  10988. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10989. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10990. res = WOLFSSL_FATAL_ERROR;
  10991. }
  10992. if (res == 1) {
  10993. /* Assume no PKCS#8 header. */
  10994. key->pkcs8HeaderSz = 0;
  10995. /* Check if input buffer has PKCS8 header. In the case that it does not
  10996. * have a PKCS8 header then do not error out.
  10997. */
  10998. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10999. (word32)derSz, &algId)) > 0) {
  11000. WOLFSSL_MSG("Found PKCS8 header");
  11001. key->pkcs8HeaderSz = (word16)idx;
  11002. res = 1;
  11003. }
  11004. /* Error out on parsing error. */
  11005. else if (ret != WC_NO_ERR_TRACE(ASN_PARSE_E)) {
  11006. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  11007. res = WOLFSSL_FATAL_ERROR;
  11008. }
  11009. }
  11010. if (res == 1) {
  11011. /* Load into internal EC key based on key type option. */
  11012. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  11013. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  11014. (word32)derSz);
  11015. }
  11016. else {
  11017. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  11018. (word32)derSz);
  11019. if (ret < 0) {
  11020. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  11021. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  11022. if (tmp == NULL) {
  11023. ret = WOLFSSL_FATAL_ERROR;
  11024. }
  11025. else {
  11026. /* We now try again as x.963 [point type][x][opt y]. */
  11027. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  11028. INVALID_DEVID);
  11029. if (ret == 0) {
  11030. ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp);
  11031. if (ret == 0) {
  11032. /* Take ownership of new key - set tmp to the old
  11033. * key which will then be freed below. */
  11034. ecc_key *old = (ecc_key *)key->internal;
  11035. key->internal = tmp;
  11036. tmp = old;
  11037. idx = (word32)derSz;
  11038. }
  11039. wc_ecc_free(tmp);
  11040. }
  11041. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  11042. DYNAMIC_TYPE_ECC);
  11043. }
  11044. }
  11045. }
  11046. if (ret < 0) {
  11047. /* Error returned from wolfSSL. */
  11048. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  11049. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  11050. }
  11051. else {
  11052. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  11053. }
  11054. res = WOLFSSL_FATAL_ERROR;
  11055. }
  11056. /* Internal key updated - update whether it is a valid key. */
  11057. key->inSet = (res == 1);
  11058. }
  11059. /* Set the external EC key based on value in internal. */
  11060. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11061. WOLFSSL_MSG("SetECKeyExternal failed");
  11062. res = WOLFSSL_FATAL_ERROR;
  11063. }
  11064. return res;
  11065. }
  11066. #ifndef NO_BIO
  11067. WOLFSSL_EC_KEY *wolfSSL_d2i_EC_PUBKEY_bio(WOLFSSL_BIO *bio,
  11068. WOLFSSL_EC_KEY **out)
  11069. {
  11070. char* data = NULL;
  11071. int dataSz = 0;
  11072. int memAlloced = 0;
  11073. WOLFSSL_EC_KEY* ec = NULL;
  11074. int err = 0;
  11075. WOLFSSL_ENTER("wolfSSL_d2i_EC_PUBKEY_bio");
  11076. if (bio == NULL)
  11077. return NULL;
  11078. if (err == 0 && wolfssl_read_bio(bio, &data, &dataSz, &memAlloced) != 0) {
  11079. WOLFSSL_ERROR_MSG("wolfssl_read_bio failed");
  11080. err = 1;
  11081. }
  11082. if (err == 0 && (ec = wolfSSL_EC_KEY_new()) == NULL) {
  11083. WOLFSSL_ERROR_MSG("wolfSSL_EC_KEY_new failed");
  11084. err = 1;
  11085. }
  11086. /* Load the EC key with the public key from the DER encoding. */
  11087. if (err == 0 && wolfSSL_EC_KEY_LoadDer_ex(ec, (const unsigned char*)data,
  11088. dataSz, WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1) {
  11089. WOLFSSL_ERROR_MSG("wolfSSL_EC_KEY_LoadDer_ex failed");
  11090. err = 1;
  11091. }
  11092. if (memAlloced)
  11093. XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11094. if (err) { /* on error */
  11095. wolfSSL_EC_KEY_free(ec);
  11096. ec = NULL;
  11097. }
  11098. else { /* on success */
  11099. if (out != NULL)
  11100. *out = ec;
  11101. }
  11102. return ec;
  11103. }
  11104. #endif /* !NO_BIO */
  11105. /*
  11106. * EC key PEM APIs
  11107. */
  11108. #ifdef HAVE_ECC_KEY_EXPORT
  11109. #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_FILESYSTEM) || !defined(NO_BIO))
  11110. /* Encode the EC public key as DER.
  11111. *
  11112. * @param [in] key EC key to encode.
  11113. * @param [out] der Pointer through which buffer is returned.
  11114. * @param [in] heap Heap hint.
  11115. * @return Size of encoding on success.
  11116. * @return 0 on error.
  11117. */
  11118. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  11119. unsigned char** der, void* heap)
  11120. {
  11121. int sz;
  11122. unsigned char* buf = NULL;
  11123. (void)heap;
  11124. /* Calculate encoded size to allocate. */
  11125. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  11126. if (sz <= 0) {
  11127. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  11128. sz = 0;
  11129. }
  11130. if (sz > 0) {
  11131. /* Allocate memory to hold encoding. */
  11132. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  11133. if (buf == NULL) {
  11134. WOLFSSL_MSG("malloc failed");
  11135. sz = 0;
  11136. }
  11137. }
  11138. if (sz > 0) {
  11139. /* Encode public key to DER using wolfSSL. */
  11140. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1);
  11141. if (sz < 0) {
  11142. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  11143. sz = 0;
  11144. }
  11145. }
  11146. /* Return buffer on success. */
  11147. if (sz > 0) {
  11148. *der = buf;
  11149. }
  11150. else {
  11151. /* Dispose of any dynamically allocated data not returned. */
  11152. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  11153. }
  11154. return sz;
  11155. }
  11156. #endif
  11157. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  11158. /*
  11159. * Return code compliant with OpenSSL.
  11160. *
  11161. * @param [in] fp File pointer to write PEM encoding to.
  11162. * @param [in] key EC key to encode and write.
  11163. * @return 1 on success.
  11164. * @return 0 on error.
  11165. */
  11166. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  11167. {
  11168. int ret = 1;
  11169. unsigned char* derBuf = NULL;
  11170. int derSz = 0;
  11171. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  11172. /* Validate parameters. */
  11173. if ((fp == XBADFILE) || (key == NULL)) {
  11174. WOLFSSL_MSG("Bad argument.");
  11175. return 0;
  11176. }
  11177. /* Encode public key in EC key as DER. */
  11178. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  11179. if (derSz == 0) {
  11180. ret = 0;
  11181. }
  11182. /* Write out to file the PEM encoding of the DER. */
  11183. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  11184. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  11185. ret = 0;
  11186. }
  11187. /* Dispose of any dynamically allocated data. */
  11188. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11189. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  11190. return ret;
  11191. }
  11192. #endif
  11193. #endif
  11194. #ifndef NO_BIO
  11195. /* Read a PEM encoded EC public key from a BIO.
  11196. *
  11197. * @param [in] bio BIO to read EC public key from.
  11198. * @param [out] out Pointer to return EC key object through. May be NULL.
  11199. * @param [in] cb Password callback when PEM encrypted.
  11200. * @param [in] pass NUL terminated string for passphrase when PEM
  11201. * encrypted.
  11202. * @return New EC key object on success.
  11203. * @return NULL on error.
  11204. */
  11205. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  11206. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  11207. {
  11208. int err = 0;
  11209. WOLFSSL_EC_KEY* ec = NULL;
  11210. DerBuffer* der = NULL;
  11211. int keyFormat = 0;
  11212. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  11213. /* Validate parameters. */
  11214. if (bio == NULL) {
  11215. err = 1;
  11216. }
  11217. if (!err) {
  11218. /* Create an empty EC key. */
  11219. ec = wolfSSL_EC_KEY_new();
  11220. if (ec == NULL) {
  11221. err = 1;
  11222. }
  11223. }
  11224. /* Read a PEM key in to a new DER buffer. */
  11225. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  11226. &keyFormat, &der) <= 0)) {
  11227. err = 1;
  11228. }
  11229. /* Load the EC key with the public key from the DER encoding. */
  11230. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11231. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  11232. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11233. err = 1;
  11234. }
  11235. /* Dispose of dynamically allocated data not needed anymore. */
  11236. FreeDer(&der);
  11237. if (err) {
  11238. wolfSSL_EC_KEY_free(ec);
  11239. ec = NULL;
  11240. }
  11241. /* Return EC key through out if required. */
  11242. if ((out != NULL) && (ec != NULL)) {
  11243. *out = ec;
  11244. }
  11245. return ec;
  11246. }
  11247. /* Read a PEM encoded EC private key from a BIO.
  11248. *
  11249. * @param [in] bio BIO to read EC private key from.
  11250. * @param [out] out Pointer to return EC key object through. May be NULL.
  11251. * @param [in] cb Password callback when PEM encrypted.
  11252. * @param [in] pass NUL terminated string for passphrase when PEM
  11253. * encrypted.
  11254. * @return New EC key object on success.
  11255. * @return NULL on error.
  11256. */
  11257. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  11258. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  11259. {
  11260. int err = 0;
  11261. WOLFSSL_EC_KEY* ec = NULL;
  11262. DerBuffer* der = NULL;
  11263. int keyFormat = 0;
  11264. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  11265. /* Validate parameters. */
  11266. if (bio == NULL) {
  11267. err = 1;
  11268. }
  11269. if (!err) {
  11270. /* Create an empty EC key. */
  11271. ec = wolfSSL_EC_KEY_new();
  11272. if (ec == NULL) {
  11273. err = 1;
  11274. }
  11275. }
  11276. /* Read a PEM key in to a new DER buffer.
  11277. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  11278. * pem_read_bio_key(), and then check key format if it is EC.
  11279. */
  11280. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  11281. &keyFormat, &der) <= 0)) {
  11282. err = 1;
  11283. }
  11284. if (keyFormat != ECDSAk) {
  11285. WOLFSSL_ERROR_MSG("Error not EC key format");
  11286. err = 1;
  11287. }
  11288. /* Load the EC key with the private key from the DER encoding. */
  11289. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11290. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  11291. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11292. err = 1;
  11293. }
  11294. /* Dispose of dynamically allocated data not needed anymore. */
  11295. FreeDer(&der);
  11296. if (err) {
  11297. wolfSSL_EC_KEY_free(ec);
  11298. ec = NULL;
  11299. }
  11300. /* Return EC key through out if required. */
  11301. if ((out != NULL) && (ec != NULL)) {
  11302. *out = ec;
  11303. }
  11304. return ec;
  11305. }
  11306. #endif /* !NO_BIO */
  11307. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC_KEY_EXPORT)
  11308. #ifndef NO_BIO
  11309. /* Write out the EC public key as PEM to the BIO.
  11310. *
  11311. * @param [in] bio BIO to write PEM encoding to.
  11312. * @param [in] ec EC public key to encode.
  11313. * @return 1 on success.
  11314. * @return 0 on error.
  11315. */
  11316. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  11317. {
  11318. int ret = 1;
  11319. unsigned char* derBuf = NULL;
  11320. int derSz = 0;
  11321. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  11322. /* Validate parameters. */
  11323. if ((bio == NULL) || (ec == NULL)) {
  11324. WOLFSSL_MSG("Bad Function Arguments");
  11325. return 0;
  11326. }
  11327. /* Encode public key in EC key as DER. */
  11328. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  11329. if (derSz == 0) {
  11330. ret = 0;
  11331. }
  11332. /* Write out to BIO the PEM encoding of the EC public key. */
  11333. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  11334. ECC_PUBLICKEY_TYPE) != 1)) {
  11335. ret = 0;
  11336. }
  11337. /* Dispose of any dynamically allocated data. */
  11338. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11339. return ret;
  11340. }
  11341. /* Write out the EC private key as PEM to the BIO.
  11342. *
  11343. * Return code compliant with OpenSSL.
  11344. *
  11345. * @param [in] bio BIO to write PEM encoding to.
  11346. * @param [in] ec EC private key to encode.
  11347. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11348. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11349. * @param [in] passwdSz Length of password string when PEM encrypted.
  11350. * @param [in] cb Password callback when PEM encrypted. Unused.
  11351. * @param [in] pass NUL terminated string for passphrase when PEM
  11352. * encrypted. Unused.
  11353. * @return 1 on success.
  11354. * @return 0 on error.
  11355. */
  11356. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  11357. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11358. wc_pem_password_cb* cb, void* arg)
  11359. {
  11360. int ret = 1;
  11361. unsigned char* pem = NULL;
  11362. int pLen = 0;
  11363. (void)cb;
  11364. (void)arg;
  11365. /* Validate parameters. */
  11366. if ((bio == NULL) || (ec == NULL)) {
  11367. ret = 0;
  11368. }
  11369. /* Write EC private key to PEM. */
  11370. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11371. passwdSz, &pem, &pLen) != 1)) {
  11372. ret = 0;
  11373. }
  11374. /* Write PEM to BIO. */
  11375. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  11376. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  11377. ret = 0;
  11378. }
  11379. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11380. return ret;
  11381. }
  11382. #endif /* !NO_BIO */
  11383. /* Encode the EC private key as PEM into buffer.
  11384. *
  11385. * Return code compliant with OpenSSL.
  11386. * Not an OpenSSL API.
  11387. *
  11388. * @param [in] ec EC private key to encode.
  11389. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11390. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11391. * @param [in] passwdSz Length of password string when PEM encrypted.
  11392. * @param [out] pem Newly allocated buffer holding PEM encoding.
  11393. * @param [out] pLen Length of PEM encoding in bytes.
  11394. * @return 1 on success.
  11395. * @return 0 on error.
  11396. */
  11397. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  11398. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11399. unsigned char **pem, int *pLen)
  11400. {
  11401. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  11402. int ret = 1;
  11403. byte* derBuf = NULL;
  11404. word32 der_max_len = 0;
  11405. int derSz = 0;
  11406. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  11407. /* Validate parameters. */
  11408. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  11409. (ec->internal == NULL)) {
  11410. WOLFSSL_MSG("Bad function arguments");
  11411. ret = 0;
  11412. }
  11413. /* Ensure internal EC key is set from external. */
  11414. if ((ret == 1) && (ec->inSet == 0)) {
  11415. WOLFSSL_MSG("No ECC internal set, do it");
  11416. if (SetECKeyInternal(ec) != 1) {
  11417. WOLFSSL_MSG("SetECKeyInternal failed");
  11418. ret = 0;
  11419. }
  11420. }
  11421. if (ret == 1) {
  11422. /* Calculate maximum size of DER encoding.
  11423. * 4 > size of pub, priv + ASN.1 additional information */
  11424. der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) +
  11425. AES_BLOCK_SIZE;
  11426. /* Allocate buffer big enough to hold encoding. */
  11427. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL,
  11428. DYNAMIC_TYPE_TMP_BUFFER);
  11429. if (derBuf == NULL) {
  11430. WOLFSSL_MSG("malloc failed");
  11431. ret = 0;
  11432. }
  11433. }
  11434. if (ret == 1) {
  11435. /* Encode EC private key as DER. */
  11436. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  11437. if (derSz < 0) {
  11438. WOLFSSL_MSG("wc_EccKeyToDer failed");
  11439. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  11440. ret = 0;
  11441. }
  11442. }
  11443. /* Convert DER to PEM - possibly encrypting. */
  11444. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  11445. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  11446. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  11447. ret = 0;
  11448. }
  11449. return ret;
  11450. #else
  11451. (void)ec;
  11452. (void)cipher;
  11453. (void)passwd;
  11454. (void)passwdSz;
  11455. (void)pem;
  11456. (void)pLen;
  11457. return 0;
  11458. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  11459. }
  11460. #ifndef NO_FILESYSTEM
  11461. /* Write out the EC private key as PEM to file.
  11462. *
  11463. * Return code compliant with OpenSSL.
  11464. *
  11465. * @param [in] fp File pointer to write PEM encoding to.
  11466. * @param [in] ec EC private key to encode.
  11467. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11468. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11469. * @param [in] passwdSz Length of password string when PEM encrypted.
  11470. * @param [in] cb Password callback when PEM encrypted. Unused.
  11471. * @param [in] pass NUL terminated string for passphrase when PEM
  11472. * encrypted. Unused.
  11473. * @return 1 on success.
  11474. * @return 0 on error.
  11475. */
  11476. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  11477. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  11478. wc_pem_password_cb *cb, void *pass)
  11479. {
  11480. int ret = 1;
  11481. byte *pem = NULL;
  11482. int pLen = 0;
  11483. (void)cb;
  11484. (void)pass;
  11485. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  11486. /* Validate parameters. */
  11487. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  11488. WOLFSSL_MSG("Bad function arguments");
  11489. ret = 0;
  11490. }
  11491. /* Write EC private key to PEM. */
  11492. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11493. passwdSz, &pem, &pLen) != 1)) {
  11494. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11495. ret = 0;
  11496. }
  11497. /* Write out to file the PEM encoding of the EC private key. */
  11498. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  11499. WOLFSSL_MSG("ECC private key file write failed");
  11500. ret = 0;
  11501. }
  11502. /* Dispose of any dynamically allocated data. */
  11503. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11504. return ret;
  11505. }
  11506. #endif /* NO_FILESYSTEM */
  11507. #endif /* WOLFSSL_KEY_GEN && HAVE_ECC_KEY_EXPORT */
  11508. /*
  11509. * EC key print APIs
  11510. */
  11511. #ifndef NO_CERTS
  11512. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11513. !defined(NO_STDIO_FILESYSTEM)
  11514. /* Print the EC key to a file pointer as text.
  11515. *
  11516. * @param [in] fp File pointer.
  11517. * @param [in] key EC key to print.
  11518. * @param [in] indent Number of spaces to place before each line printed.
  11519. * @return 1 on success.
  11520. * @return 0 on failure.
  11521. */
  11522. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11523. {
  11524. int ret = 1;
  11525. int bits = 0;
  11526. int priv = 0;
  11527. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11528. /* Validate parameters. */
  11529. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11530. (indent < 0)) {
  11531. ret = 0;
  11532. }
  11533. if (ret == 1) {
  11534. /* Get EC groups order size in bits. */
  11535. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11536. if (bits <= 0) {
  11537. WOLFSSL_MSG("Failed to get group order bits.");
  11538. ret = 0;
  11539. }
  11540. }
  11541. if (ret == 1) {
  11542. const char* keyType;
  11543. /* Determine whether this is a private or public key. */
  11544. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11545. keyType = "Private-Key";
  11546. priv = 1;
  11547. }
  11548. else {
  11549. keyType = "Public-Key";
  11550. }
  11551. /* Print key header. */
  11552. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11553. ret = 0;
  11554. }
  11555. }
  11556. if ((ret == 1) && priv) {
  11557. /* Print the private key BN. */
  11558. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11559. }
  11560. /* Check for public key data in EC key. */
  11561. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11562. /* Get the public key point as one BN. */
  11563. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11564. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11565. if (pubBn == NULL) {
  11566. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11567. ret = 0;
  11568. }
  11569. else {
  11570. /* Print the public key in a BN. */
  11571. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11572. wolfSSL_BN_free(pubBn);
  11573. }
  11574. }
  11575. if (ret == 1) {
  11576. /* Get the NID of the group. */
  11577. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11578. if (nid > 0) {
  11579. /* Convert the NID into a long name and NIST name. */
  11580. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11581. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11582. /* Print OID name if known. */
  11583. if ((curve != NULL) &&
  11584. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11585. ret = 0;
  11586. }
  11587. /* Print NIST curve name if known. */
  11588. if ((nistName != NULL) &&
  11589. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11590. nistName) < 0)) {
  11591. ret = 0;
  11592. }
  11593. }
  11594. }
  11595. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11596. return ret;
  11597. }
  11598. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11599. #endif /* !NO_CERTS */
  11600. /*
  11601. * EC_KEY get/set/test APIs
  11602. */
  11603. /* Set data of internal, wolfCrypt EC key object into EC key.
  11604. *
  11605. * EC_KEY wolfSSL -> OpenSSL
  11606. *
  11607. * @param [in, out] p EC key to update.
  11608. * @return 1 on success.
  11609. * @return -1 on failure.
  11610. */
  11611. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11612. {
  11613. int ret = 1;
  11614. WOLFSSL_ENTER("SetECKeyExternal");
  11615. /* Validate parameter. */
  11616. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11617. WOLFSSL_MSG("ec key NULL error");
  11618. ret = WOLFSSL_FATAL_ERROR;
  11619. }
  11620. else {
  11621. ecc_key* key = (ecc_key*)eckey->internal;
  11622. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11623. eckey->group->curve_oid = (int)key->dp->oidSum;
  11624. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11625. eckey->group->curve_idx = key->idx;
  11626. if (eckey->pub_key->internal != NULL) {
  11627. /* Copy internal public point from internal key's public point. */
  11628. if (wc_ecc_copy_point(&key->pubkey,
  11629. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11630. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11631. ret = WOLFSSL_FATAL_ERROR;
  11632. }
  11633. /* Set external public key from internal wolfCrypt, public key. */
  11634. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11635. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11636. ret = WOLFSSL_FATAL_ERROR;
  11637. }
  11638. }
  11639. /* set the external privkey */
  11640. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11641. (wolfssl_bn_set_value(&eckey->priv_key,
  11642. wc_ecc_key_get_priv(key)) != 1)) {
  11643. WOLFSSL_MSG("ec priv key error");
  11644. ret = WOLFSSL_FATAL_ERROR;
  11645. }
  11646. /* External values set when operations succeeded. */
  11647. eckey->exSet = (ret == 1);
  11648. }
  11649. return ret;
  11650. }
  11651. /* Set data of EC key into internal, wolfCrypt EC key object.
  11652. *
  11653. * EC_KEY Openssl -> WolfSSL
  11654. *
  11655. * @param [in, out] p EC key to update.
  11656. * @return 1 on success.
  11657. * @return -1 on failure.
  11658. */
  11659. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11660. {
  11661. int ret = 1;
  11662. WOLFSSL_ENTER("SetECKeyInternal");
  11663. /* Validate parameter. */
  11664. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11665. (eckey->group == NULL)) {
  11666. WOLFSSL_MSG("ec key NULL error");
  11667. ret = WOLFSSL_FATAL_ERROR;
  11668. }
  11669. else {
  11670. ecc_key* key = (ecc_key*)eckey->internal;
  11671. int pubSet = 0;
  11672. /* Validate group. */
  11673. if ((eckey->group->curve_idx < 0) ||
  11674. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11675. WOLFSSL_MSG("invalid curve idx");
  11676. ret = WOLFSSL_FATAL_ERROR;
  11677. }
  11678. if (ret == 1) {
  11679. /* Set group (idx of curve and corresponding domain parameters). */
  11680. key->idx = eckey->group->curve_idx;
  11681. key->dp = &ecc_sets[key->idx];
  11682. pubSet = (eckey->pub_key != NULL);
  11683. }
  11684. /* Set public key (point). */
  11685. if ((ret == 1) && pubSet) {
  11686. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11687. WOLFSSL_MSG("ec key pub error");
  11688. ret = WOLFSSL_FATAL_ERROR;
  11689. }
  11690. /* Copy public point to key. */
  11691. if ((ret == 1) && (wc_ecc_copy_point(
  11692. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11693. MP_OKAY)) {
  11694. WOLFSSL_MSG("wc_ecc_copy_point error");
  11695. ret = WOLFSSL_FATAL_ERROR;
  11696. }
  11697. if (ret == 1) {
  11698. /* Set that the internal key is a public key */
  11699. key->type = ECC_PUBLICKEY;
  11700. }
  11701. }
  11702. /* set privkey */
  11703. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11704. if (wolfssl_bn_get_value(eckey->priv_key,
  11705. wc_ecc_key_get_priv(key)) != 1) {
  11706. WOLFSSL_MSG("ec key priv error");
  11707. ret = WOLFSSL_FATAL_ERROR;
  11708. }
  11709. /* private key */
  11710. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11711. if (pubSet) {
  11712. key->type = ECC_PRIVATEKEY;
  11713. }
  11714. else {
  11715. key->type = ECC_PRIVATEKEY_ONLY;
  11716. }
  11717. }
  11718. }
  11719. /* Internal values set when operations succeeded. */
  11720. eckey->inSet = (ret == 1);
  11721. }
  11722. return ret;
  11723. }
  11724. /* Get point conversion format of EC key.
  11725. *
  11726. * @param [in] key EC key.
  11727. * @return Point conversion format on success.
  11728. * @return -1 on error.
  11729. */
  11730. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11731. {
  11732. if (key == NULL)
  11733. return WOLFSSL_FATAL_ERROR;
  11734. return key->form;
  11735. }
  11736. /* Set point conversion format into EC key.
  11737. *
  11738. * @param [in, out] key EC key to set format into.
  11739. * @param [in] form Point conversion format. Valid values:
  11740. * POINT_CONVERSION_UNCOMPRESSED,
  11741. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11742. */
  11743. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11744. {
  11745. if (key == NULL) {
  11746. WOLFSSL_MSG("Key passed in NULL");
  11747. }
  11748. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11749. #ifdef HAVE_COMP_KEY
  11750. || form == POINT_CONVERSION_COMPRESSED
  11751. #endif
  11752. ) {
  11753. key->form = (unsigned char)form;
  11754. }
  11755. else {
  11756. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11757. }
  11758. }
  11759. /* Get the EC group object that is in EC key.
  11760. *
  11761. * @param [in] key EC key.
  11762. * @return EC group object on success.
  11763. * @return NULL when key is NULL.
  11764. */
  11765. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11766. {
  11767. WOLFSSL_EC_GROUP* group = NULL;
  11768. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11769. if (key != NULL) {
  11770. group = key->group;
  11771. }
  11772. return group;
  11773. }
  11774. /* Set the group in WOLFSSL_EC_KEY
  11775. *
  11776. * @param [in, out] key EC key to update.
  11777. * @param [in] group EC group to copy.
  11778. * @return 1 on success
  11779. * @return 0 on failure.
  11780. */
  11781. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11782. {
  11783. int ret = 1;
  11784. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11785. /* Validate parameters. */
  11786. if ((key == NULL) || (group == NULL)) {
  11787. ret = 0;
  11788. }
  11789. if (ret == 1) {
  11790. /* Dispose of the current group. */
  11791. if (key->group != NULL) {
  11792. wolfSSL_EC_GROUP_free(key->group);
  11793. }
  11794. /* Duplicate the passed in group into EC key. */
  11795. key->group = wolfSSL_EC_GROUP_dup(group);
  11796. if (key->group == NULL) {
  11797. ret = 0;
  11798. }
  11799. }
  11800. return ret;
  11801. }
  11802. /* Get the BN object that is the private key in the EC key.
  11803. *
  11804. * @param [in] key EC key.
  11805. * @return BN object on success.
  11806. * @return NULL when key is NULL or private key is not set.
  11807. */
  11808. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11809. {
  11810. WOLFSSL_BIGNUM* priv_key = NULL;
  11811. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11812. /* Validate parameter. */
  11813. if (key == NULL) {
  11814. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11815. }
  11816. /* Only return private key if it is not 0. */
  11817. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11818. priv_key = key->priv_key;
  11819. }
  11820. return priv_key;
  11821. }
  11822. /* Sets the private key value into EC key.
  11823. *
  11824. * Return code compliant with OpenSSL.
  11825. *
  11826. * @param [in, out] key EC key to set.
  11827. * @param [in] priv_key Private key value in a BN.
  11828. * @return 1 on success
  11829. * @return 0 on failure.
  11830. */
  11831. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11832. const WOLFSSL_BIGNUM *priv_key)
  11833. {
  11834. int ret = 1;
  11835. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11836. /* Validate parameters. */
  11837. if ((key == NULL) || (priv_key == NULL)) {
  11838. WOLFSSL_MSG("Bad arguments");
  11839. ret = 0;
  11840. }
  11841. /* Check for obvious invalid values. */
  11842. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11843. wolfSSL_BN_is_one(priv_key)) {
  11844. WOLFSSL_MSG("Invalid private key value");
  11845. ret = 0;
  11846. }
  11847. if (ret == 1) {
  11848. /* Free key if previously set. */
  11849. if (key->priv_key != NULL) {
  11850. wolfSSL_BN_free(key->priv_key);
  11851. }
  11852. /* Duplicate the BN passed in. */
  11853. key->priv_key = wolfSSL_BN_dup(priv_key);
  11854. if (key->priv_key == NULL) {
  11855. WOLFSSL_MSG("key ecc priv key NULL");
  11856. ret = 0;
  11857. }
  11858. }
  11859. /* Set the external values into internal EC key. */
  11860. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11861. WOLFSSL_MSG("SetECKeyInternal failed");
  11862. /* Dispose of new private key on error. */
  11863. wolfSSL_BN_free(key->priv_key);
  11864. key->priv_key = NULL;
  11865. ret = 0;
  11866. }
  11867. return ret;
  11868. }
  11869. /* Get the public key EC point object that is in EC key.
  11870. *
  11871. * @param [in] key EC key.
  11872. * @return EC point object that is the public key on success.
  11873. * @return NULL when key is NULL.
  11874. */
  11875. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11876. {
  11877. WOLFSSL_EC_POINT* pub_key = NULL;
  11878. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11879. if (key != NULL) {
  11880. pub_key = key->pub_key;
  11881. }
  11882. return pub_key;
  11883. }
  11884. /*
  11885. * Return code compliant with OpenSSL.
  11886. *
  11887. * @param [in, out] key EC key.
  11888. * @param [in] pub Public key as an EC point.
  11889. * @return 1 on success
  11890. * @return 0 on failure.
  11891. */
  11892. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11893. const WOLFSSL_EC_POINT *pub)
  11894. {
  11895. int ret = 1;
  11896. ecc_point *pub_p = NULL;
  11897. ecc_point *key_p = NULL;
  11898. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11899. /* Validate parameters. */
  11900. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11901. (pub->internal == NULL)) {
  11902. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11903. ret = 0;
  11904. }
  11905. /* Ensure the internal EC key is set. */
  11906. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11907. WOLFSSL_MSG("SetECKeyInternal failed");
  11908. ret = 0;
  11909. }
  11910. /* Ensure the internal EC point of pub is setup. */
  11911. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11912. ret = 0;
  11913. }
  11914. if (ret == 1) {
  11915. /* Get the internal point of pub and the public key in key. */
  11916. pub_p = (ecc_point*)pub->internal;
  11917. key_p = (ecc_point*)key->pub_key->internal;
  11918. /* Create new point if required. */
  11919. if (key_p == NULL) {
  11920. key_p = wc_ecc_new_point();
  11921. key->pub_key->internal = (void*)key_p;
  11922. }
  11923. /* Check point available. */
  11924. if (key_p == NULL) {
  11925. WOLFSSL_MSG("key ecc point NULL");
  11926. ret = 0;
  11927. }
  11928. }
  11929. /* Copy the internal pub point into internal key point. */
  11930. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11931. WOLFSSL_MSG("ecc_copy_point failure");
  11932. ret = 0;
  11933. }
  11934. /* Copy the internal point data into external. */
  11935. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11936. WOLFSSL_MSG("SetECKeyInternal failed");
  11937. ret = 0;
  11938. }
  11939. /* Copy the internal key into external. */
  11940. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11941. WOLFSSL_MSG("SetECKeyInternal failed");
  11942. ret = 0;
  11943. }
  11944. if (ret == 1) {
  11945. /* Dump out the point and the key's public key for debug. */
  11946. wolfSSL_EC_POINT_dump("pub", pub);
  11947. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11948. }
  11949. return ret;
  11950. }
  11951. #ifndef NO_WOLFSSL_STUB
  11952. /* Set the ASN.1 encoding flag against the EC key.
  11953. *
  11954. * No implementation as only named curves supported for encoding.
  11955. *
  11956. * @param [in, out] key EC key.
  11957. * @param [in] flag ASN.1 flag to set. Valid values:
  11958. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11959. */
  11960. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11961. {
  11962. (void)key;
  11963. (void)asn1_flag;
  11964. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11965. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11966. }
  11967. #endif
  11968. /*
  11969. * EC key generate key APIs
  11970. */
  11971. /* Generate an EC key.
  11972. *
  11973. * Uses the internal curve index set in the EC key or the default.
  11974. *
  11975. * @param [in, out] key EC key.
  11976. * @return 1 on success
  11977. * @return 0 on failure.
  11978. */
  11979. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11980. {
  11981. int res = 1;
  11982. int initTmpRng = 0;
  11983. WC_RNG* rng = NULL;
  11984. #ifdef WOLFSSL_SMALL_STACK
  11985. WC_RNG* tmpRng = NULL;
  11986. #else
  11987. WC_RNG tmpRng[1];
  11988. #endif
  11989. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11990. /* Validate parameters. */
  11991. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11992. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11993. res = 0;
  11994. }
  11995. if (res == 1) {
  11996. /* Check if we know which internal curve index to use. */
  11997. if (key->group->curve_idx < 0) {
  11998. /* Generate key using the default curve. */
  11999. #if FIPS_VERSION3_GE(6,0,0)
  12000. key->group->curve_idx = ECC_SECP256R1; /* FIPS default to 256 */
  12001. #else
  12002. key->group->curve_idx = ECC_CURVE_DEF;
  12003. #endif
  12004. }
  12005. /* Create a random number generator. */
  12006. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12007. if (rng == NULL) {
  12008. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12009. res = 0;
  12010. }
  12011. }
  12012. if (res == 1) {
  12013. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  12014. * is 0 then pass ECC_CURVE_DEF as arg */
  12015. int eccEnum = key->group->curve_nid ?
  12016. #if FIPS_VERSION3_GE(6,0,0)
  12017. NIDToEccEnum(key->group->curve_nid) : ECC_SECP256R1;
  12018. #else
  12019. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  12020. #endif
  12021. /* Get the internal EC key. */
  12022. ecc_key* ecKey = (ecc_key*)key->internal;
  12023. /* Make the key using internal API. */
  12024. int ret = 0;
  12025. #if FIPS_VERSION3_GE(6,0,0)
  12026. /* In the case of FIPS only allow key generation with approved curves */
  12027. if (eccEnum != ECC_SECP256R1 && eccEnum != ECC_SECP224R1 &&
  12028. eccEnum != ECC_SECP384R1 && eccEnum != ECC_SECP521R1) {
  12029. WOLFSSL_MSG("Unsupported curve selected in FIPS mode");
  12030. res = 0;
  12031. }
  12032. if (res == 1) {
  12033. #endif
  12034. ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  12035. #if FIPS_VERSION3_GE(6,0,0)
  12036. }
  12037. #endif
  12038. #if defined(WOLFSSL_ASYNC_CRYPT)
  12039. /* Wait on asynchronouse operation. */
  12040. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  12041. #endif
  12042. if (ret != 0) {
  12043. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  12044. res = 0;
  12045. }
  12046. }
  12047. /* Dispose of local random number generator if initialized. */
  12048. if (initTmpRng) {
  12049. wc_FreeRng(rng);
  12050. #ifdef WOLFSSL_SMALL_STACK
  12051. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12052. #endif
  12053. }
  12054. /* Set the external key from new internal key values. */
  12055. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  12056. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  12057. res = 0;
  12058. }
  12059. return res;
  12060. }
  12061. /*
  12062. * EC key check key APIs
  12063. */
  12064. /* Check that the EC key is valid.
  12065. *
  12066. * @param [in] key EC key.
  12067. * @return 1 on valid.
  12068. * @return 0 on invalid or error.
  12069. */
  12070. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  12071. {
  12072. int ret = 1;
  12073. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  12074. /* Validate parameter. */
  12075. if ((key == NULL) || (key->internal == NULL)) {
  12076. WOLFSSL_MSG("Bad parameter");
  12077. ret = 0;
  12078. }
  12079. /* Set the external EC key values into internal if not already. */
  12080. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  12081. (WOLFSSL_EC_KEY*)key) != 1)) {
  12082. WOLFSSL_MSG("SetECKeyInternal failed");
  12083. ret = 0;
  12084. }
  12085. if (ret == 1) {
  12086. /* Have internal EC implementation check key. */
  12087. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  12088. }
  12089. return ret;
  12090. }
  12091. /* End EC_KEY */
  12092. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  12093. /* Get the supported, built-in EC curves
  12094. *
  12095. * @param [in, out] curves Pre-allocated list to put supported curves into.
  12096. * @param [in] len Maximum number of items to place in list.
  12097. * @return Number of built-in EC curves when curves is NULL or len is 0.
  12098. * @return Number of items placed in list otherwise.
  12099. */
  12100. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  12101. size_t len)
  12102. {
  12103. size_t i;
  12104. size_t cnt;
  12105. #ifdef HAVE_SELFTEST
  12106. /* Defined in ecc.h when available. */
  12107. size_t ecc_sets_count;
  12108. /* Count the pre-defined curves since global not available. */
  12109. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  12110. /* Do nothing. */
  12111. }
  12112. ecc_sets_count = i;
  12113. #endif
  12114. /* Assume we are going to return total count. */
  12115. cnt = ecc_sets_count;
  12116. /* Check we have a list that can hold data. */
  12117. if ((curves != NULL) && (len != 0)) {
  12118. /* Limit count to length of list. */
  12119. if (cnt > len) {
  12120. cnt = len;
  12121. }
  12122. /* Put in built-in EC curve nid and short name. */
  12123. for (i = 0; i < cnt; i++) {
  12124. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  12125. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  12126. }
  12127. }
  12128. return cnt;
  12129. }
  12130. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  12131. /* Start ECDSA_SIG */
  12132. /* Allocate a new ECDSA signature object.
  12133. *
  12134. * @return New, allocated ECDSA signature object on success.
  12135. * @return NULL on error.
  12136. */
  12137. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  12138. {
  12139. int err = 0;
  12140. WOLFSSL_ECDSA_SIG *sig;
  12141. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  12142. /* Allocate memory for ECDSA signature object. */
  12143. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  12144. DYNAMIC_TYPE_ECC);
  12145. if (sig == NULL) {
  12146. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  12147. err = 1;
  12148. }
  12149. if (!err) {
  12150. /* Set s to NULL in case of error. */
  12151. sig->s = NULL;
  12152. /* Allocate BN into r. */
  12153. sig->r = wolfSSL_BN_new();
  12154. if (sig->r == NULL) {
  12155. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  12156. err = 1;
  12157. }
  12158. }
  12159. if (!err) {
  12160. /* Allocate BN into s. */
  12161. sig->s = wolfSSL_BN_new();
  12162. if (sig->s == NULL) {
  12163. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  12164. err = 1;
  12165. }
  12166. }
  12167. if (err && (sig != NULL)) {
  12168. /* Dispose of allocated memory. */
  12169. wolfSSL_ECDSA_SIG_free(sig);
  12170. sig = NULL;
  12171. }
  12172. return sig;
  12173. }
  12174. /* Dispose of ECDSA signature object.
  12175. *
  12176. * Cannot use object after this call.
  12177. *
  12178. * @param [in] sig ECDSA signature object to free.
  12179. */
  12180. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  12181. {
  12182. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  12183. if (sig != NULL) {
  12184. /* Dispose of BNs allocated for r and s. */
  12185. wolfSSL_BN_free(sig->r);
  12186. wolfSSL_BN_free(sig->s);
  12187. /* Dispose of memory associated with ECDSA signature object. */
  12188. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  12189. }
  12190. }
  12191. /* Create an ECDSA signature from the DER encoding.
  12192. *
  12193. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  12194. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  12195. * On out, reference to buffer after signature data.
  12196. * @param [in] len Length of the data in the buffer. May be more than
  12197. * the length of the signature.
  12198. * @return ECDSA signature object on success.
  12199. * @return NULL on error.
  12200. */
  12201. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  12202. const unsigned char** pp, long len)
  12203. {
  12204. int err = 0;
  12205. /* ECDSA signature object to return. */
  12206. WOLFSSL_ECDSA_SIG *s = NULL;
  12207. /* Validate parameter. */
  12208. if (pp == NULL) {
  12209. err = 1;
  12210. }
  12211. if (!err) {
  12212. if (sig != NULL) {
  12213. /* Use the ECDSA signature object passed in. */
  12214. s = *sig;
  12215. }
  12216. if (s == NULL) {
  12217. /* No ECDSA signature object passed in - create a new one. */
  12218. s = wolfSSL_ECDSA_SIG_new();
  12219. if (s == NULL) {
  12220. err = 1;
  12221. }
  12222. }
  12223. }
  12224. if (!err) {
  12225. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  12226. mp_free((mp_int*)s->r->internal);
  12227. mp_free((mp_int*)s->s->internal);
  12228. /* Decode the signature into internal r and s fields. */
  12229. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  12230. (mp_int*)s->s->internal) != MP_OKAY) {
  12231. err = 1;
  12232. }
  12233. }
  12234. if (!err) {
  12235. /* Move pointer passed signature data successfully decoded. */
  12236. *pp += wolfssl_der_length(*pp, (int)len);
  12237. if (sig != NULL) {
  12238. /* Update reference to ECDSA signature object. */
  12239. *sig = s;
  12240. }
  12241. }
  12242. /* Dispose of newly allocated object on error. */
  12243. if (err) {
  12244. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  12245. wolfSSL_ECDSA_SIG_free(s);
  12246. }
  12247. /* Return NULL for object on error. */
  12248. s = NULL;
  12249. }
  12250. return s;
  12251. }
  12252. /* Encode the ECDSA signature as DER.
  12253. *
  12254. * @param [in] sig ECDSA signature object.
  12255. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  12256. * On out, reference to buffer after encoding.
  12257. * May be NULL or point to NULL in which case no encoding
  12258. * is done.
  12259. * @return Length of encoding on success.
  12260. * @return 0 on error.
  12261. */
  12262. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  12263. {
  12264. word32 len = 0;
  12265. int update_p = 1;
  12266. /* Validate parameter. */
  12267. if (sig != NULL) {
  12268. /* ASN.1: SEQ + INT + INT
  12269. * ASN.1 Integer must be a positive value - prepend zero if number has
  12270. * top bit set.
  12271. */
  12272. /* Get total length of r including any prepended zero. */
  12273. word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) +
  12274. mp_unsigned_bin_size((mp_int*)sig->r->internal));
  12275. /* Get total length of s including any prepended zero. */
  12276. word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) +
  12277. mp_unsigned_bin_size((mp_int*)sig->s->internal));
  12278. /* Calculate length of data in sequence. */
  12279. len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen +
  12280. (word32)1 + ASN_LEN_SIZE(sLen) + sLen;
  12281. /* Add in the length of the SEQUENCE. */
  12282. len += (word32)1 + ASN_LEN_SIZE(len);
  12283. #ifdef WOLFSSL_I2D_ECDSA_SIG_ALLOC
  12284. if ((pp != NULL) && (*pp == NULL)) {
  12285. *pp = (unsigned char *)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  12286. if (*pp != NULL) {
  12287. WOLFSSL_MSG("malloc error");
  12288. return 0;
  12289. }
  12290. update_p = 0;
  12291. }
  12292. #endif
  12293. /* Encode only if there is a buffer to encode into. */
  12294. if ((pp != NULL) && (*pp != NULL)) {
  12295. /* Encode using the internal representations of r and s. */
  12296. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  12297. (mp_int*)sig->s->internal) != MP_OKAY) {
  12298. /* No bytes encoded. */
  12299. len = 0;
  12300. }
  12301. else if (update_p) {
  12302. /* Update pointer to after encoding. */
  12303. *pp += len;
  12304. }
  12305. }
  12306. }
  12307. return (int)len;
  12308. }
  12309. /* Get the pointer to the fields of the ECDSA signature.
  12310. *
  12311. * r and s untouched when sig is NULL.
  12312. *
  12313. * @param [in] sig ECDSA signature object.
  12314. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  12315. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  12316. */
  12317. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  12318. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  12319. {
  12320. /* Validate parameter. */
  12321. if (sig != NULL) {
  12322. /* Return the r BN when pointer to return through. */
  12323. if (r != NULL) {
  12324. *r = sig->r;
  12325. }
  12326. /* Return the s BN when pointer to return through. */
  12327. if (s != NULL) {
  12328. *s = sig->s;
  12329. }
  12330. }
  12331. }
  12332. /* Set the pointers to the fields of the ECDSA signature.
  12333. *
  12334. * @param [in, out] sig ECDSA signature object to update.
  12335. * @param [in] r R field of ECDSA signature as a BN.
  12336. * @param [in] s S field of ECDSA signature as a BN.
  12337. * @return 1 on success.
  12338. * @return 0 on error.
  12339. */
  12340. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  12341. WOLFSSL_BIGNUM* s)
  12342. {
  12343. int ret = 1;
  12344. /* Validate parameters. */
  12345. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  12346. ret = 0;
  12347. }
  12348. if (ret == 1) {
  12349. /* Dispose of old BN objects. */
  12350. wolfSSL_BN_free(sig->r);
  12351. wolfSSL_BN_free(sig->s);
  12352. /* Assign new BN objects. */
  12353. sig->r = r;
  12354. sig->s = s;
  12355. }
  12356. return ret;
  12357. }
  12358. /* End ECDSA_SIG */
  12359. /* Start ECDSA */
  12360. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  12361. *
  12362. * @param [in] key EC key.
  12363. * @return Size of DER encoded signature on success.
  12364. * @return 0 on error.
  12365. */
  12366. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  12367. {
  12368. int err = 0;
  12369. int len = 0;
  12370. const EC_GROUP *group = NULL;
  12371. int bits = 0;
  12372. /* Validate parameter. */
  12373. if (key == NULL) {
  12374. err = 1;
  12375. }
  12376. /* Get group from key to get order bits. */
  12377. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  12378. err = 1;
  12379. }
  12380. /* Get order bits of group. */
  12381. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  12382. /* Group is not set. */
  12383. err = 1;
  12384. }
  12385. if (!err) {
  12386. /* r and s are mod order. */
  12387. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  12388. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  12389. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  12390. bytes + bytes; /* max r and s in bytes */
  12391. }
  12392. return len;
  12393. }
  12394. /* Create ECDSA signature by signing digest with key.
  12395. *
  12396. * @param [in] dgst Digest to sign.
  12397. * @param [in] dLen Length of digest in bytes.
  12398. * @param [in] key EC key to sign with.
  12399. * @return ECDSA signature object on success.
  12400. * @return NULL on error.
  12401. */
  12402. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  12403. WOLFSSL_EC_KEY *key)
  12404. {
  12405. int err = 0;
  12406. WOLFSSL_ECDSA_SIG *sig = NULL;
  12407. #ifdef WOLFSSL_SMALL_STACK
  12408. byte* out = NULL;
  12409. #else
  12410. byte out[ECC_BUFSIZE];
  12411. #endif
  12412. unsigned int outLen = ECC_BUFSIZE;
  12413. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  12414. /* Validate parameters. */
  12415. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  12416. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  12417. err = 1;
  12418. }
  12419. /* Ensure internal EC key is set from external. */
  12420. if ((!err) && (key->inSet == 0)) {
  12421. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  12422. if (SetECKeyInternal(key) != 1) {
  12423. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  12424. err = 1;
  12425. }
  12426. }
  12427. #ifdef WOLFSSL_SMALL_STACK
  12428. if (!err) {
  12429. /* Allocate buffer to hold encoded signature. */
  12430. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12431. if (out == NULL) {
  12432. err = 1;
  12433. }
  12434. }
  12435. #endif
  12436. /* Sign the digest with the key to create encoded ECDSA signature. */
  12437. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  12438. err = 1;
  12439. }
  12440. if (!err) {
  12441. const byte* p = out;
  12442. /* Decode the ECDSA signature into a new object. */
  12443. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  12444. }
  12445. #ifdef WOLFSSL_SMALL_STACK
  12446. /* Dispose of any temporary dynamically allocated data. */
  12447. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12448. #endif
  12449. return sig;
  12450. }
  12451. /* Verify ECDSA signature in the object using digest and key.
  12452. *
  12453. * Return code compliant with OpenSSL.
  12454. *
  12455. * @param [in] dgst Digest to verify.
  12456. * @param [in] dLen Length of the digest in bytes.
  12457. * @param [in] sig ECDSA signature object.
  12458. * @param [in] key EC key containing public key.
  12459. * @return 1 when signature is valid.
  12460. * @return 0 when signature is invalid.
  12461. * @return -1 on error.
  12462. */
  12463. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  12464. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  12465. {
  12466. int ret = 1;
  12467. int verified = 0;
  12468. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  12469. byte signature[ECC_MAX_SIG_SIZE];
  12470. int signatureLen;
  12471. byte* p = signature;
  12472. #endif
  12473. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  12474. /* Validate parameters. */
  12475. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  12476. (key->internal == NULL)) {
  12477. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  12478. ret = WOLFSSL_FATAL_ERROR;
  12479. }
  12480. /* Ensure internal EC key is set from external. */
  12481. if ((ret == 1) && (key->inSet == 0)) {
  12482. WOLFSSL_MSG("No EC key internal set, do it");
  12483. if (SetECKeyInternal(key) != 1) {
  12484. WOLFSSL_MSG("SetECKeyInternal failed");
  12485. ret = WOLFSSL_FATAL_ERROR;
  12486. }
  12487. }
  12488. if (ret == 1) {
  12489. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12490. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  12491. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  12492. (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified,
  12493. (ecc_key *)key->internal) != MP_OKAY) {
  12494. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12495. ret = WOLFSSL_FATAL_ERROR;
  12496. }
  12497. else if (verified == 0) {
  12498. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12499. ret = 0;
  12500. }
  12501. #else
  12502. signatureLen = i2d_ECDSA_SIG(sig, &p);
  12503. if (signatureLen > 0) {
  12504. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  12505. ret = wc_ecc_verify_hash(signature, signatureLen, dgst,
  12506. (word32)dLen, &verified, (ecc_key*)key->internal);
  12507. if (ret != MP_OKAY) {
  12508. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12509. ret = WOLFSSL_FATAL_ERROR;
  12510. }
  12511. else if (verified == 0) {
  12512. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12513. ret = 0;
  12514. }
  12515. }
  12516. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12517. }
  12518. return ret;
  12519. }
  12520. /* Sign the digest with the key to produce a DER encode signature.
  12521. *
  12522. * @param [in] type Digest algorithm used to create digest. Unused.
  12523. * @param [in] digest Digest of the message to sign.
  12524. * @param [in] digestSz Size of the digest in bytes.
  12525. * @param [out] sig Buffer to hold signature.
  12526. * @param [in, out] sigSz On in, size of buffer in bytes.
  12527. * On out, size of signatre in bytes.
  12528. * @param [in] key EC key containing private key.
  12529. * @return 1 on success.
  12530. * @return 0 on error.
  12531. */
  12532. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12533. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12534. {
  12535. int ret = 1;
  12536. WC_RNG* rng = NULL;
  12537. #ifdef WOLFSSL_SMALL_STACK
  12538. WC_RNG* tmpRng = NULL;
  12539. #else
  12540. WC_RNG tmpRng[1];
  12541. #endif
  12542. int initTmpRng = 0;
  12543. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12544. /* Digest algorithm not used in DER encoding. */
  12545. (void)type;
  12546. /* Validate parameters. */
  12547. if (key == NULL) {
  12548. ret = 0;
  12549. }
  12550. if (ret == 1) {
  12551. /* Make an RNG - create local or get global. */
  12552. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12553. if (rng == NULL) {
  12554. ret = 0;
  12555. }
  12556. }
  12557. /* Sign the digest with the key using the RNG and put signature into buffer
  12558. * update sigSz to be actual length.
  12559. */
  12560. if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz,
  12561. rng, (ecc_key*)key->internal) != 0)) {
  12562. ret = 0;
  12563. }
  12564. if (initTmpRng) {
  12565. wc_FreeRng(rng);
  12566. #ifdef WOLFSSL_SMALL_STACK
  12567. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12568. #endif
  12569. }
  12570. return ret;
  12571. }
  12572. /* Verify the signature with the digest and key.
  12573. *
  12574. * @param [in] type Digest algorithm used to create digest. Unused.
  12575. * @param [in] digest Digest of the message to verify.
  12576. * @param [in] digestSz Size of the digest in bytes.
  12577. * @param [in] sig Buffer holding signature.
  12578. * @param [in] sigSz Size of signature data in bytes.
  12579. * @param [in] key EC key containing public key.
  12580. * @return 1 when signature is valid.
  12581. * @return 0 when signature is invalid or error.
  12582. */
  12583. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12584. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12585. {
  12586. int ret = 1;
  12587. int verify = 0;
  12588. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12589. /* Digest algorithm not used in DER encoding. */
  12590. (void)type;
  12591. /* Validate parameters. */
  12592. if (key == NULL) {
  12593. ret = 0;
  12594. }
  12595. /* Verify signature using digest and key. */
  12596. if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest,
  12597. (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) {
  12598. ret = 0;
  12599. }
  12600. /* When no error, verification may still have failed - check now. */
  12601. if ((ret == 1) && (verify != 1)) {
  12602. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12603. ret = 0;
  12604. }
  12605. return ret;
  12606. }
  12607. /* End ECDSA */
  12608. /* Start ECDH */
  12609. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12610. /* Compute the shared secret (key) using ECDH.
  12611. *
  12612. * KDF not supported.
  12613. *
  12614. * Return code compliant with OpenSSL.
  12615. *
  12616. * @param [out] out Buffer to hold key.
  12617. * @param [in] outLen Length of buffer in bytes.
  12618. * @param [in] pubKey Public key as an EC point.
  12619. * @param [in] privKey EC key holding a private key.
  12620. * @param [in] kdf Key derivation function to apply to secret.
  12621. * @return Length of computed key on success
  12622. * @return 0 on error.
  12623. */
  12624. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12625. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12626. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12627. {
  12628. int err = 0;
  12629. word32 len = 0;
  12630. ecc_key* key = NULL;
  12631. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12632. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12633. int setGlobalRNG = 0;
  12634. #endif
  12635. /* TODO: support using the KDF. */
  12636. (void)kdf;
  12637. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12638. /* Validate parameters. */
  12639. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12640. (privKey == NULL) || (privKey->internal == NULL)) {
  12641. WOLFSSL_MSG("Bad function arguments");
  12642. err = 1;
  12643. }
  12644. /* Ensure internal EC key is set from external. */
  12645. if ((!err) && (privKey->inSet == 0)) {
  12646. WOLFSSL_MSG("No EC key internal set, do it");
  12647. if (SetECKeyInternal(privKey) != 1) {
  12648. WOLFSSL_MSG("SetECKeyInternal failed");
  12649. err = 1;
  12650. }
  12651. }
  12652. if (!err) {
  12653. int ret;
  12654. /* Get the internal key. */
  12655. key = (ecc_key*)privKey->internal;
  12656. /* Set length into variable of type suitable for wolfSSL API. */
  12657. len = (word32)outLen;
  12658. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12659. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12660. /* An RNG is needed. */
  12661. if (key->rng == NULL) {
  12662. key->rng = wolfssl_make_global_rng();
  12663. /* RNG set and needs to be unset. */
  12664. setGlobalRNG = 1;
  12665. }
  12666. #endif
  12667. PRIVATE_KEY_UNLOCK();
  12668. /* Create secret using wolfSSL. */
  12669. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12670. (byte *)out, &len);
  12671. PRIVATE_KEY_LOCK();
  12672. if (ret != MP_OKAY) {
  12673. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12674. err = 1;
  12675. }
  12676. }
  12677. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12678. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12679. /* Remove global from key. */
  12680. if (setGlobalRNG) {
  12681. key->rng = NULL;
  12682. }
  12683. #endif
  12684. if (err) {
  12685. /* Make returned value zero. */
  12686. len = 0;
  12687. }
  12688. return (int)len;
  12689. }
  12690. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12691. /* End ECDH */
  12692. #ifndef NO_WOLFSSL_STUB
  12693. const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_OpenSSL(void)
  12694. {
  12695. WOLFSSL_STUB("wolfSSL_EC_KEY_OpenSSL");
  12696. return NULL;
  12697. }
  12698. WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_METHOD_new(
  12699. const WOLFSSL_EC_KEY_METHOD *meth)
  12700. {
  12701. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_new");
  12702. (void)meth;
  12703. return NULL;
  12704. }
  12705. void wolfSSL_EC_KEY_METHOD_free(WOLFSSL_EC_KEY_METHOD *meth)
  12706. {
  12707. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_free");
  12708. (void)meth;
  12709. }
  12710. void wolfSSL_EC_KEY_METHOD_set_init(WOLFSSL_EC_KEY_METHOD *meth,
  12711. void* a1, void* a2, void* a3, void* a4, void* a5, void* a6)
  12712. {
  12713. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_init");
  12714. (void)meth;
  12715. (void)a1;
  12716. (void)a2;
  12717. (void)a3;
  12718. (void)a4;
  12719. (void)a5;
  12720. (void)a6;
  12721. }
  12722. void wolfSSL_EC_KEY_METHOD_set_sign(WOLFSSL_EC_KEY_METHOD *meth,
  12723. void* a1, void* a2, void* a3)
  12724. {
  12725. WOLFSSL_STUB("wolfSSL_EC_KEY_METHOD_set_sign");
  12726. (void)meth;
  12727. (void)a1;
  12728. (void)a2;
  12729. (void)a3;
  12730. }
  12731. const WOLFSSL_EC_KEY_METHOD *wolfSSL_EC_KEY_get_method(
  12732. const WOLFSSL_EC_KEY *key)
  12733. {
  12734. WOLFSSL_STUB("wolfSSL_EC_KEY_get_method");
  12735. (void)key;
  12736. return NULL;
  12737. }
  12738. int wolfSSL_EC_KEY_set_method(WOLFSSL_EC_KEY *key,
  12739. const WOLFSSL_EC_KEY_METHOD *meth)
  12740. {
  12741. WOLFSSL_STUB("wolfSSL_EC_KEY_set_method");
  12742. (void)key;
  12743. (void)meth;
  12744. return 0;
  12745. }
  12746. #endif /* !NO_WOLFSSL_STUB */
  12747. #endif /* OPENSSL_EXTRA */
  12748. #endif /* HAVE_ECC */
  12749. /*******************************************************************************
  12750. * END OF EC API
  12751. ******************************************************************************/
  12752. /*******************************************************************************
  12753. * START OF EC25519 API
  12754. ******************************************************************************/
  12755. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519)
  12756. /* Generate an EC25519 key pair.
  12757. *
  12758. * Output keys are in little endian format.
  12759. *
  12760. * @param [out] priv EC25519 private key data.
  12761. * @param [in, out] privSz On in, the size of priv in bytes.
  12762. * On out, the length of the private key data in bytes.
  12763. * @param [out] pub EC25519 public key data.
  12764. * @param [in, out] pubSz On in, the size of pub in bytes.
  12765. * On out, the length of the public key data in bytes.
  12766. * @return 1 on success
  12767. * @return 0 on failure.
  12768. */
  12769. int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12770. unsigned char *pub, unsigned int *pubSz)
  12771. {
  12772. #ifdef WOLFSSL_KEY_GEN
  12773. int res = 1;
  12774. int initTmpRng = 0;
  12775. WC_RNG *rng = NULL;
  12776. #ifdef WOLFSSL_SMALL_STACK
  12777. WC_RNG *tmpRng = NULL;
  12778. #else
  12779. WC_RNG tmpRng[1];
  12780. #endif
  12781. curve25519_key key;
  12782. WOLFSSL_ENTER("wolfSSL_EC25519_generate_key");
  12783. /* Validate parameters. */
  12784. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE25519_KEYSIZE) ||
  12785. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE25519_KEYSIZE)) {
  12786. WOLFSSL_MSG("Bad arguments");
  12787. res = 0;
  12788. }
  12789. if (res) {
  12790. /* Create a random number generator. */
  12791. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12792. if (rng == NULL) {
  12793. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12794. res = 0;
  12795. }
  12796. }
  12797. /* Initialize a Curve25519 key. */
  12798. if (res && (wc_curve25519_init(&key) != 0)) {
  12799. WOLFSSL_MSG("wc_curve25519_init failed");
  12800. res = 0;
  12801. }
  12802. if (res) {
  12803. /* Make a Curve25519 key pair. */
  12804. int ret = wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key);
  12805. if (ret != MP_OKAY) {
  12806. WOLFSSL_MSG("wc_curve25519_make_key failed");
  12807. res = 0;
  12808. }
  12809. if (res) {
  12810. /* Export Curve25519 key pair to buffers. */
  12811. ret = wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub,
  12812. pubSz, EC25519_LITTLE_ENDIAN);
  12813. if (ret != MP_OKAY) {
  12814. WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed");
  12815. res = 0;
  12816. }
  12817. }
  12818. /* Dispose of key. */
  12819. wc_curve25519_free(&key);
  12820. }
  12821. if (initTmpRng) {
  12822. wc_FreeRng(rng);
  12823. #ifdef WOLFSSL_SMALL_STACK
  12824. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12825. #endif
  12826. }
  12827. return res;
  12828. #else
  12829. WOLFSSL_MSG("No Key Gen built in");
  12830. (void)priv;
  12831. (void)privSz;
  12832. (void)pub;
  12833. (void)pubSz;
  12834. return 0;
  12835. #endif /* WOLFSSL_KEY_GEN */
  12836. }
  12837. /* Compute a shared secret from private and public EC25519 keys.
  12838. *
  12839. * Input and output keys are in little endian format
  12840. *
  12841. * @param [out] shared Shared secret buffer.
  12842. * @param [in, out] sharedSz On in, the size of shared in bytes.
  12843. * On out, the length of the secret in bytes.
  12844. * @param [in] priv EC25519 private key data.
  12845. * @param [in] privSz Length of the private key data in bytes.
  12846. * @param [in] pub EC25519 public key data.
  12847. * @param [in] pubSz Length of the public key data in bytes.
  12848. * @return 1 on success
  12849. * @return 0 on failure.
  12850. */
  12851. int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz,
  12852. const unsigned char *priv, unsigned int privSz, const unsigned char *pub,
  12853. unsigned int pubSz)
  12854. {
  12855. #ifdef WOLFSSL_KEY_GEN
  12856. int res = 1;
  12857. curve25519_key privkey;
  12858. curve25519_key pubkey;
  12859. WOLFSSL_ENTER("wolfSSL_EC25519_shared_key");
  12860. /* Validate parameters. */
  12861. if ((shared == NULL) || (sharedSz == NULL) ||
  12862. (*sharedSz < CURVE25519_KEYSIZE) || (priv == NULL) ||
  12863. (privSz < CURVE25519_KEYSIZE) || (pub == NULL) ||
  12864. (pubSz < CURVE25519_KEYSIZE)) {
  12865. WOLFSSL_MSG("Bad arguments");
  12866. res = 0;
  12867. }
  12868. /* Initialize private key object. */
  12869. if (res && (wc_curve25519_init(&privkey) != 0)) {
  12870. WOLFSSL_MSG("wc_curve25519_init privkey failed");
  12871. res = 0;
  12872. }
  12873. if (res) {
  12874. /* Initialize public key object. */
  12875. if (wc_curve25519_init(&pubkey) != MP_OKAY) {
  12876. WOLFSSL_MSG("wc_curve25519_init pubkey failed");
  12877. res = 0;
  12878. }
  12879. if (res) {
  12880. /* Import our private key. */
  12881. int ret = wc_curve25519_import_private_ex(priv, privSz, &privkey,
  12882. EC25519_LITTLE_ENDIAN);
  12883. if (ret != 0) {
  12884. WOLFSSL_MSG("wc_curve25519_import_private_ex failed");
  12885. res = 0;
  12886. }
  12887. if (res) {
  12888. /* Import peer's public key. */
  12889. ret = wc_curve25519_import_public_ex(pub, pubSz, &pubkey,
  12890. EC25519_LITTLE_ENDIAN);
  12891. if (ret != 0) {
  12892. WOLFSSL_MSG("wc_curve25519_import_public_ex failed");
  12893. res = 0;
  12894. }
  12895. }
  12896. if (res) {
  12897. /* Compute shared secret. */
  12898. ret = wc_curve25519_shared_secret_ex(&privkey, &pubkey, shared,
  12899. sharedSz, EC25519_LITTLE_ENDIAN);
  12900. if (ret != 0) {
  12901. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  12902. res = 0;
  12903. }
  12904. }
  12905. wc_curve25519_free(&pubkey);
  12906. }
  12907. wc_curve25519_free(&privkey);
  12908. }
  12909. return res;
  12910. #else
  12911. WOLFSSL_MSG("No Key Gen built in");
  12912. (void)shared;
  12913. (void)sharedSz;
  12914. (void)priv;
  12915. (void)privSz;
  12916. (void)pub;
  12917. (void)pubSz;
  12918. return 0;
  12919. #endif /* WOLFSSL_KEY_GEN */
  12920. }
  12921. #endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */
  12922. /*******************************************************************************
  12923. * END OF EC25519 API
  12924. ******************************************************************************/
  12925. /*******************************************************************************
  12926. * START OF ED25519 API
  12927. ******************************************************************************/
  12928. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519)
  12929. /* Generate an ED25519 key pair.
  12930. *
  12931. * Output keys are in little endian format.
  12932. *
  12933. * @param [out] priv ED25519 private key data.
  12934. * @param [in, out] privSz On in, the size of priv in bytes.
  12935. * On out, the length of the private key data in bytes.
  12936. * @param [out] pub ED25519 public key data.
  12937. * @param [in, out] pubSz On in, the size of pub in bytes.
  12938. * On out, the length of the public key data in bytes.
  12939. * @return 1 on success
  12940. * @return 0 on failure.
  12941. */
  12942. int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12943. unsigned char *pub, unsigned int *pubSz)
  12944. {
  12945. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED25519_KEY_EXPORT)
  12946. int res = 1;
  12947. int initTmpRng = 0;
  12948. WC_RNG *rng = NULL;
  12949. #ifdef WOLFSSL_SMALL_STACK
  12950. WC_RNG *tmpRng = NULL;
  12951. #else
  12952. WC_RNG tmpRng[1];
  12953. #endif
  12954. ed25519_key key;
  12955. WOLFSSL_ENTER("wolfSSL_ED25519_generate_key");
  12956. /* Validate parameters. */
  12957. if ((priv == NULL) || (privSz == NULL) ||
  12958. (*privSz < ED25519_PRV_KEY_SIZE) || (pub == NULL) ||
  12959. (pubSz == NULL) || (*pubSz < ED25519_PUB_KEY_SIZE)) {
  12960. WOLFSSL_MSG("Bad arguments");
  12961. res = 0;
  12962. }
  12963. if (res) {
  12964. /* Create a random number generator. */
  12965. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12966. if (rng == NULL) {
  12967. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12968. res = 0;
  12969. }
  12970. }
  12971. /* Initialize an Ed25519 key. */
  12972. if (res && (wc_ed25519_init(&key) != 0)) {
  12973. WOLFSSL_MSG("wc_ed25519_init failed");
  12974. res = 0;
  12975. }
  12976. if (res) {
  12977. /* Make an Ed25519 key pair. */
  12978. int ret = wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key);
  12979. if (ret != 0) {
  12980. WOLFSSL_MSG("wc_ed25519_make_key failed");
  12981. res = 0;
  12982. }
  12983. if (res) {
  12984. /* Export Curve25519 key pair to buffers. */
  12985. ret = wc_ed25519_export_key(&key, priv, privSz, pub, pubSz);
  12986. if (ret != 0) {
  12987. WOLFSSL_MSG("wc_ed25519_export_key failed");
  12988. res = 0;
  12989. }
  12990. }
  12991. wc_ed25519_free(&key);
  12992. }
  12993. if (initTmpRng) {
  12994. wc_FreeRng(rng);
  12995. #ifdef WOLFSSL_SMALL_STACK
  12996. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12997. #endif
  12998. }
  12999. return res;
  13000. #else
  13001. #ifndef WOLFSSL_KEY_GEN
  13002. WOLFSSL_MSG("No Key Gen built in");
  13003. #else
  13004. WOLFSSL_MSG("No ED25519 key export built in");
  13005. #endif
  13006. (void)priv;
  13007. (void)privSz;
  13008. (void)pub;
  13009. (void)pubSz;
  13010. return 0;
  13011. #endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */
  13012. }
  13013. /* Sign a message with Ed25519 using the private key.
  13014. *
  13015. * Input and output keys are in little endian format.
  13016. * Priv is a buffer containing private and public part of key.
  13017. *
  13018. * @param [in] msg Message to be signed.
  13019. * @param [in] msgSz Length of message in bytes.
  13020. * @param [in] priv ED25519 private key data.
  13021. * @param [in] privSz Length in bytes of private key data.
  13022. * @param [out] sig Signature buffer.
  13023. * @param [in, out] sigSz On in, the length of the signature buffer in bytes.
  13024. * On out, the length of the signature in bytes.
  13025. * @return 1 on success
  13026. * @return 0 on failure.
  13027. */
  13028. int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz,
  13029. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  13030. unsigned int *sigSz)
  13031. {
  13032. #if defined(HAVE_ED25519_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  13033. defined(HAVE_ED25519_KEY_IMPORT)
  13034. ed25519_key key;
  13035. int res = 1;
  13036. WOLFSSL_ENTER("wolfSSL_ED25519_sign");
  13037. /* Validate parameters. */
  13038. if ((priv == NULL) || (privSz != ED25519_PRV_KEY_SIZE) ||
  13039. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  13040. (*sigSz < ED25519_SIG_SIZE)) {
  13041. WOLFSSL_MSG("Bad arguments");
  13042. res = 0;
  13043. }
  13044. /* Initialize Ed25519 key. */
  13045. if (res && (wc_ed25519_init(&key) != 0)) {
  13046. WOLFSSL_MSG("wc_curve25519_init failed");
  13047. res = 0;
  13048. }
  13049. if (res) {
  13050. /* Import private and public key. */
  13051. int ret = wc_ed25519_import_private_key(priv, privSz / 2,
  13052. priv + (privSz / 2), ED25519_PUB_KEY_SIZE, &key);
  13053. if (ret != 0) {
  13054. WOLFSSL_MSG("wc_ed25519_import_private failed");
  13055. res = 0;
  13056. }
  13057. if (res) {
  13058. /* Sign message with Ed25519. */
  13059. ret = wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key);
  13060. if (ret != 0) {
  13061. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  13062. res = 0;
  13063. }
  13064. }
  13065. wc_ed25519_free(&key);
  13066. }
  13067. return res;
  13068. #else
  13069. #if !defined(HAVE_ED25519_SIGN)
  13070. WOLFSSL_MSG("No ED25519 sign built in");
  13071. #elif !defined(WOLFSSL_KEY_GEN)
  13072. WOLFSSL_MSG("No Key Gen built in");
  13073. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  13074. WOLFSSL_MSG("No ED25519 Key import built in");
  13075. #endif
  13076. (void)msg;
  13077. (void)msgSz;
  13078. (void)priv;
  13079. (void)privSz;
  13080. (void)sig;
  13081. (void)sigSz;
  13082. return 0;
  13083. #endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  13084. }
  13085. /* Verify a message with Ed25519 using the public key.
  13086. *
  13087. * Input keys are in little endian format.
  13088. *
  13089. * @param [in] msg Message to be verified.
  13090. * @param [in] msgSz Length of message in bytes.
  13091. * @param [in] pub ED25519 public key data.
  13092. * @param [in] privSz Length in bytes of public key data.
  13093. * @param [in] sig Signature buffer.
  13094. * @param [in] sigSz Length of the signature in bytes.
  13095. * @return 1 on success
  13096. * @return 0 on failure.
  13097. */
  13098. int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz,
  13099. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  13100. unsigned int sigSz)
  13101. {
  13102. #if defined(HAVE_ED25519_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  13103. defined(HAVE_ED25519_KEY_IMPORT)
  13104. ed25519_key key;
  13105. int res = 1;
  13106. WOLFSSL_ENTER("wolfSSL_ED25519_verify");
  13107. /* Validate parameters. */
  13108. if ((pub == NULL) || (pubSz != ED25519_PUB_KEY_SIZE) || (msg == NULL) ||
  13109. (sig == NULL) || (sigSz != ED25519_SIG_SIZE)) {
  13110. WOLFSSL_MSG("Bad arguments");
  13111. res = 0;
  13112. }
  13113. /* Initialize Ed25519 key. */
  13114. if (res && (wc_ed25519_init(&key) != 0)) {
  13115. WOLFSSL_MSG("wc_curve25519_init failed");
  13116. res = 0;
  13117. }
  13118. if (res) {
  13119. /* Import public key. */
  13120. int ret = wc_ed25519_import_public(pub, pubSz, &key);
  13121. if (ret != 0) {
  13122. WOLFSSL_MSG("wc_ed25519_import_public failed");
  13123. res = 0;
  13124. }
  13125. if (res) {
  13126. int check = 0;
  13127. /* Verify signature with message and public key. */
  13128. ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  13129. &key);
  13130. /* Check for errors in verification process. */
  13131. if (ret != 0) {
  13132. WOLFSSL_MSG("wc_ed25519_verify_msg failed");
  13133. res = 0;
  13134. }
  13135. /* Check signature is valid. */
  13136. else if (!check) {
  13137. WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)");
  13138. res = 0;
  13139. }
  13140. }
  13141. wc_ed25519_free(&key);
  13142. }
  13143. return res;
  13144. #else
  13145. #if !defined(HAVE_ED25519_VERIFY)
  13146. WOLFSSL_MSG("No ED25519 verify built in");
  13147. #elif !defined(WOLFSSL_KEY_GEN)
  13148. WOLFSSL_MSG("No Key Gen built in");
  13149. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  13150. WOLFSSL_MSG("No ED25519 Key import built in");
  13151. #endif
  13152. (void)msg;
  13153. (void)msgSz;
  13154. (void)pub;
  13155. (void)pubSz;
  13156. (void)sig;
  13157. (void)sigSz;
  13158. return 0;
  13159. #endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  13160. }
  13161. #endif /* OPENSSL_EXTRA && HAVE_ED25519 */
  13162. /*******************************************************************************
  13163. * END OF ED25519 API
  13164. ******************************************************************************/
  13165. /*******************************************************************************
  13166. * START OF EC448 API
  13167. ******************************************************************************/
  13168. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448)
  13169. /* Generate an EC448 key pair.
  13170. *
  13171. * Output keys are in little endian format.
  13172. *
  13173. * @param [out] priv EC448 private key data.
  13174. * @param [in, out] privSz On in, the size of priv in bytes.
  13175. * On out, the length of the private key data in bytes.
  13176. * @param [out] pub EC448 public key data.
  13177. * @param [in, out] pubSz On in, the size of pub in bytes.
  13178. * On out, the length of the public key data in bytes.
  13179. * @return 1 on success
  13180. * @return 0 on failure.
  13181. */
  13182. int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz,
  13183. unsigned char *pub, unsigned int *pubSz)
  13184. {
  13185. #ifdef WOLFSSL_KEY_GEN
  13186. int res = 1;
  13187. int initTmpRng = 0;
  13188. WC_RNG *rng = NULL;
  13189. #ifdef WOLFSSL_SMALL_STACK
  13190. WC_RNG *tmpRng = NULL;
  13191. #else
  13192. WC_RNG tmpRng[1];
  13193. #endif
  13194. curve448_key key;
  13195. WOLFSSL_ENTER("wolfSSL_EC448_generate_key");
  13196. /* Validate parameters. */
  13197. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE448_KEY_SIZE) ||
  13198. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE448_KEY_SIZE)) {
  13199. WOLFSSL_MSG("Bad arguments");
  13200. res = 0;
  13201. }
  13202. if (res) {
  13203. /* Create a random number generator. */
  13204. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  13205. if (rng == NULL) {
  13206. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  13207. res = 0;
  13208. }
  13209. }
  13210. /* Initialize a Curve448 key. */
  13211. if (res && (wc_curve448_init(&key) != 0)) {
  13212. WOLFSSL_MSG("wc_curve448_init failed");
  13213. res = 0;
  13214. }
  13215. if (res) {
  13216. /* Make a Curve448 key pair. */
  13217. int ret = wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key);
  13218. if (ret != 0) {
  13219. WOLFSSL_MSG("wc_curve448_make_key failed");
  13220. res = 0;
  13221. }
  13222. if (res) {
  13223. /* Export Curve448 key pair to buffers. */
  13224. ret = wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz,
  13225. EC448_LITTLE_ENDIAN);
  13226. if (ret != 0) {
  13227. WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed");
  13228. res = 0;
  13229. }
  13230. }
  13231. /* Dispose of key. */
  13232. wc_curve448_free(&key);
  13233. }
  13234. if (initTmpRng) {
  13235. wc_FreeRng(rng);
  13236. #ifdef WOLFSSL_SMALL_STACK
  13237. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  13238. #endif
  13239. }
  13240. return res;
  13241. #else
  13242. WOLFSSL_MSG("No Key Gen built in");
  13243. (void)priv;
  13244. (void)privSz;
  13245. (void)pub;
  13246. (void)pubSz;
  13247. return 0;
  13248. #endif /* WOLFSSL_KEY_GEN */
  13249. }
  13250. /* Compute a shared secret from private and public EC448 keys.
  13251. *
  13252. * Input and output keys are in little endian format
  13253. *
  13254. * @param [out] shared Shared secret buffer.
  13255. * @param [in, out] sharedSz On in, the size of shared in bytes.
  13256. * On out, the length of the secret in bytes.
  13257. * @param [in] priv EC448 private key data.
  13258. * @param [in] privSz Length of the private key data in bytes.
  13259. * @param [in] pub EC448 public key data.
  13260. * @param [in] pubSz Length of the public key data in bytes.
  13261. * @return 1 on success
  13262. * @return 0 on failure.
  13263. */
  13264. int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz,
  13265. const unsigned char *priv, unsigned int privSz,
  13266. const unsigned char *pub, unsigned int pubSz)
  13267. {
  13268. #ifdef WOLFSSL_KEY_GEN
  13269. int res = 1;
  13270. curve448_key privkey;
  13271. curve448_key pubkey;
  13272. WOLFSSL_ENTER("wolfSSL_EC448_shared_key");
  13273. /* Validate parameters. */
  13274. if ((shared == NULL) || (sharedSz == NULL) ||
  13275. (*sharedSz < CURVE448_KEY_SIZE) || (priv == NULL) ||
  13276. (privSz < CURVE448_KEY_SIZE) || (pub == NULL) ||
  13277. (pubSz < CURVE448_KEY_SIZE)) {
  13278. WOLFSSL_MSG("Bad arguments");
  13279. res = 0;
  13280. }
  13281. /* Initialize private key object. */
  13282. if (res && (wc_curve448_init(&privkey) != 0)) {
  13283. WOLFSSL_MSG("wc_curve448_init privkey failed");
  13284. res = 0;
  13285. }
  13286. if (res) {
  13287. /* Initialize public key object. */
  13288. if (wc_curve448_init(&pubkey) != MP_OKAY) {
  13289. WOLFSSL_MSG("wc_curve448_init pubkey failed");
  13290. res = 0;
  13291. }
  13292. if (res) {
  13293. /* Import our private key. */
  13294. int ret = wc_curve448_import_private_ex(priv, privSz, &privkey,
  13295. EC448_LITTLE_ENDIAN);
  13296. if (ret != 0) {
  13297. WOLFSSL_MSG("wc_curve448_import_private_ex failed");
  13298. res = 0;
  13299. }
  13300. if (res) {
  13301. /* Import peer's public key. */
  13302. ret = wc_curve448_import_public_ex(pub, pubSz, &pubkey,
  13303. EC448_LITTLE_ENDIAN);
  13304. if (ret != 0) {
  13305. WOLFSSL_MSG("wc_curve448_import_public_ex failed");
  13306. res = 0;
  13307. }
  13308. }
  13309. if (res) {
  13310. /* Compute shared secret. */
  13311. ret = wc_curve448_shared_secret_ex(&privkey, &pubkey, shared,
  13312. sharedSz, EC448_LITTLE_ENDIAN);
  13313. if (ret != 0) {
  13314. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13315. res = 0;
  13316. }
  13317. }
  13318. wc_curve448_free(&pubkey);
  13319. }
  13320. wc_curve448_free(&privkey);
  13321. }
  13322. return res;
  13323. #else
  13324. WOLFSSL_MSG("No Key Gen built in");
  13325. (void)shared;
  13326. (void)sharedSz;
  13327. (void)priv;
  13328. (void)privSz;
  13329. (void)pub;
  13330. (void)pubSz;
  13331. return 0;
  13332. #endif /* WOLFSSL_KEY_GEN */
  13333. }
  13334. #endif /* OPENSSL_EXTRA && HAVE_CURVE448 */
  13335. /*******************************************************************************
  13336. * END OF EC448 API
  13337. ******************************************************************************/
  13338. /*******************************************************************************
  13339. * START OF ED448 API
  13340. ******************************************************************************/
  13341. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED448)
  13342. /* Generate an ED448 key pair.
  13343. *
  13344. * Output keys are in little endian format.
  13345. *
  13346. * @param [out] priv ED448 private key data.
  13347. * @param [in, out] privSz On in, the size of priv in bytes.
  13348. * On out, the length of the private key data in bytes.
  13349. * @param [out] pub ED448 public key data.
  13350. * @param [in, out] pubSz On in, the size of pub in bytes.
  13351. * On out, the length of the public key data in bytes.
  13352. * @return 1 on success
  13353. * @return 0 on failure.
  13354. */
  13355. int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz,
  13356. unsigned char *pub, unsigned int *pubSz)
  13357. {
  13358. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED448_KEY_EXPORT)
  13359. int res = 1;
  13360. int initTmpRng = 0;
  13361. WC_RNG *rng = NULL;
  13362. #ifdef WOLFSSL_SMALL_STACK
  13363. WC_RNG *tmpRng = NULL;
  13364. #else
  13365. WC_RNG tmpRng[1];
  13366. #endif
  13367. ed448_key key;
  13368. WOLFSSL_ENTER("wolfSSL_ED448_generate_key");
  13369. /* Validate parameters. */
  13370. if ((priv == NULL) || (privSz == NULL) ||
  13371. (*privSz < ED448_PRV_KEY_SIZE) || (pub == NULL) ||
  13372. (pubSz == NULL) || (*pubSz < ED448_PUB_KEY_SIZE)) {
  13373. WOLFSSL_MSG("Bad arguments");
  13374. res = 0;
  13375. }
  13376. if (res) {
  13377. /* Create a random number generator. */
  13378. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  13379. if (rng == NULL) {
  13380. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  13381. res = 0;
  13382. }
  13383. }
  13384. /* Initialize an Ed448 key. */
  13385. if (res && (wc_ed448_init(&key) != 0)) {
  13386. WOLFSSL_MSG("wc_ed448_init failed");
  13387. res = 0;
  13388. }
  13389. if (res) {
  13390. /* Make an Ed448 key pair. */
  13391. int ret = wc_ed448_make_key(rng, ED448_KEY_SIZE, &key);
  13392. if (ret != 0) {
  13393. WOLFSSL_MSG("wc_ed448_make_key failed");
  13394. res = 0;
  13395. }
  13396. if (res) {
  13397. /* Export Curve448 key pair to buffers. */
  13398. ret = wc_ed448_export_key(&key, priv, privSz, pub, pubSz);
  13399. if (ret != 0) {
  13400. WOLFSSL_MSG("wc_ed448_export_key failed");
  13401. res = 0;
  13402. }
  13403. }
  13404. wc_ed448_free(&key);
  13405. }
  13406. if (initTmpRng) {
  13407. wc_FreeRng(rng);
  13408. #ifdef WOLFSSL_SMALL_STACK
  13409. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  13410. #endif
  13411. }
  13412. return res;
  13413. #else
  13414. #ifndef WOLFSSL_KEY_GEN
  13415. WOLFSSL_MSG("No Key Gen built in");
  13416. #else
  13417. WOLFSSL_MSG("No ED448 key export built in");
  13418. #endif
  13419. (void)priv;
  13420. (void)privSz;
  13421. (void)pub;
  13422. (void)pubSz;
  13423. return 0;
  13424. #endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */
  13425. }
  13426. /* Sign a message with Ed448 using the private key.
  13427. *
  13428. * Input and output keys are in little endian format.
  13429. * Priv is a buffer containing private and public part of key.
  13430. *
  13431. * @param [in] msg Message to be signed.
  13432. * @param [in] msgSz Length of message in bytes.
  13433. * @param [in] priv ED448 private key data.
  13434. * @param [in] privSz Length in bytes of private key data.
  13435. * @param [out] sig Signature buffer.
  13436. * @param [in, out] sigSz On in, the length of the signature buffer in bytes.
  13437. * On out, the length of the signature in bytes.
  13438. * @return 1 on success
  13439. * @return 0 on failure.
  13440. */
  13441. int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz,
  13442. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  13443. unsigned int *sigSz)
  13444. {
  13445. #if defined(HAVE_ED448_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  13446. defined(HAVE_ED448_KEY_IMPORT)
  13447. ed448_key key;
  13448. int res = 1;
  13449. WOLFSSL_ENTER("wolfSSL_ED448_sign");
  13450. /* Validate parameters. */
  13451. if ((priv == NULL) || (privSz != ED448_PRV_KEY_SIZE) ||
  13452. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  13453. (*sigSz < ED448_SIG_SIZE)) {
  13454. WOLFSSL_MSG("Bad arguments");
  13455. res = 0;
  13456. }
  13457. /* Initialize Ed448 key. */
  13458. if (res && (wc_ed448_init(&key) != 0)) {
  13459. WOLFSSL_MSG("wc_curve448_init failed");
  13460. res = 0;
  13461. }
  13462. if (res) {
  13463. /* Import private and public key. */
  13464. int ret = wc_ed448_import_private_key(priv, privSz / 2,
  13465. priv + (privSz / 2), ED448_PUB_KEY_SIZE, &key);
  13466. if (ret != 0) {
  13467. WOLFSSL_MSG("wc_ed448_import_private failed");
  13468. res = 0;
  13469. }
  13470. if (res) {
  13471. /* Sign message with Ed448 - no context. */
  13472. ret = wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0);
  13473. if (ret != 0) {
  13474. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13475. res = 0;
  13476. }
  13477. }
  13478. wc_ed448_free(&key);
  13479. }
  13480. return res;
  13481. #else
  13482. #if !defined(HAVE_ED448_SIGN)
  13483. WOLFSSL_MSG("No ED448 sign built in");
  13484. #elif !defined(WOLFSSL_KEY_GEN)
  13485. WOLFSSL_MSG("No Key Gen built in");
  13486. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13487. WOLFSSL_MSG("No ED448 Key import built in");
  13488. #endif
  13489. (void)msg;
  13490. (void)msgSz;
  13491. (void)priv;
  13492. (void)privSz;
  13493. (void)sig;
  13494. (void)sigSz;
  13495. return 0;
  13496. #endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13497. }
  13498. /* Verify a message with Ed448 using the public key.
  13499. *
  13500. * Input keys are in little endian format.
  13501. *
  13502. * @param [in] msg Message to be verified.
  13503. * @param [in] msgSz Length of message in bytes.
  13504. * @param [in] pub ED448 public key data.
  13505. * @param [in] privSz Length in bytes of public key data.
  13506. * @param [in] sig Signature buffer.
  13507. * @param [in] sigSz Length of the signature in bytes.
  13508. * @return 1 on success
  13509. * @return 0 on failure.
  13510. */
  13511. int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz,
  13512. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  13513. unsigned int sigSz)
  13514. {
  13515. #if defined(HAVE_ED448_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  13516. defined(HAVE_ED448_KEY_IMPORT)
  13517. ed448_key key;
  13518. int res = 1;
  13519. WOLFSSL_ENTER("wolfSSL_ED448_verify");
  13520. /* Validate parameters. */
  13521. if ((pub == NULL) || (pubSz != ED448_PUB_KEY_SIZE) || (msg == NULL) ||
  13522. (sig == NULL) || (sigSz != ED448_SIG_SIZE)) {
  13523. WOLFSSL_MSG("Bad arguments");
  13524. res = 0;
  13525. }
  13526. /* Initialize Ed448 key. */
  13527. if (res && (wc_ed448_init(&key) != 0)) {
  13528. WOLFSSL_MSG("wc_curve448_init failed");
  13529. res = 0;
  13530. }
  13531. if (res) {
  13532. /* Import public key. */
  13533. int ret = wc_ed448_import_public(pub, pubSz, &key);
  13534. if (ret != 0) {
  13535. WOLFSSL_MSG("wc_ed448_import_public failed");
  13536. res = 0;
  13537. }
  13538. if (res) {
  13539. int check = 0;
  13540. /* Verify signature with message and public key - no context. */
  13541. ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  13542. &key, NULL, 0);
  13543. /* Check for errors in verification process. */
  13544. if (ret != 0) {
  13545. WOLFSSL_MSG("wc_ed448_verify_msg failed");
  13546. res = 0;
  13547. }
  13548. /* Check signature is valid. */
  13549. else if (!check) {
  13550. WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)");
  13551. res = 0;
  13552. }
  13553. }
  13554. wc_ed448_free(&key);
  13555. }
  13556. return res;
  13557. #else
  13558. #if !defined(HAVE_ED448_VERIFY)
  13559. WOLFSSL_MSG("No ED448 verify built in");
  13560. #elif !defined(WOLFSSL_KEY_GEN)
  13561. WOLFSSL_MSG("No Key Gen built in");
  13562. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13563. WOLFSSL_MSG("No ED448 Key import built in");
  13564. #endif
  13565. (void)msg;
  13566. (void)msgSz;
  13567. (void)pub;
  13568. (void)pubSz;
  13569. (void)sig;
  13570. (void)sigSz;
  13571. return 0;
  13572. #endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13573. }
  13574. #endif /* OPENSSL_EXTRA && HAVE_ED448 */
  13575. /*******************************************************************************
  13576. * END OF ED448 API
  13577. ******************************************************************************/
  13578. /*******************************************************************************
  13579. * START OF GENERIC PUBLIC KEY PEM APIs
  13580. ******************************************************************************/
  13581. #ifdef OPENSSL_EXTRA
  13582. /* Sets default callback password for PEM.
  13583. *
  13584. * @param [out] buf Buffer to hold password.
  13585. * @param [in] num Number of characters in buffer.
  13586. * @param [in] rwFlag Read/write flag. Ignored.
  13587. * @param [in] userData User data - assumed to be default password.
  13588. * @return Password size on success.
  13589. * @return 0 on failure.
  13590. */
  13591. int wolfSSL_PEM_def_callback(char* buf, int num, int rwFlag, void* userData)
  13592. {
  13593. int sz = 0;
  13594. WOLFSSL_ENTER("wolfSSL_PEM_def_callback");
  13595. (void)rwFlag;
  13596. /* We assume that the user passes a default password as userdata */
  13597. if ((buf != NULL) && (userData != NULL)) {
  13598. sz = (int)XSTRLEN((const char*)userData);
  13599. sz = (int)min((word32)sz, (word32)num);
  13600. XMEMCPY(buf, userData, sz);
  13601. }
  13602. else {
  13603. WOLFSSL_MSG("Error, default password cannot be created.");
  13604. }
  13605. return sz;
  13606. }
  13607. #ifndef NO_BIO
  13608. /* Writes a public key to a WOLFSSL_BIO encoded in PEM format.
  13609. *
  13610. * @param [in] bio BIO to write to.
  13611. * @param [in] key Public key to write in PEM format.
  13612. * @return 1 on success.
  13613. * @return 0 on failure.
  13614. */
  13615. int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
  13616. {
  13617. int ret = 0;
  13618. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY");
  13619. if ((bio != NULL) && (key != NULL)) {
  13620. switch (key->type) {
  13621. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)
  13622. case EVP_PKEY_RSA:
  13623. ret = wolfSSL_PEM_write_bio_RSA_PUBKEY(bio, key->rsa);
  13624. break;
  13625. #endif /* WOLFSSL_KEY_GEN && !NO_RSA */
  13626. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && \
  13627. (defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN))
  13628. case EVP_PKEY_DSA:
  13629. ret = wolfSSL_PEM_write_bio_DSA_PUBKEY(bio, key->dsa);
  13630. break;
  13631. #endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  13632. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && \
  13633. defined(WOLFSSL_KEY_GEN)
  13634. case EVP_PKEY_EC:
  13635. ret = wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key->ecc);
  13636. break;
  13637. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13638. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  13639. case EVP_PKEY_DH:
  13640. /* DH public key not supported. */
  13641. WOLFSSL_MSG("Writing DH PUBKEY not supported!");
  13642. break;
  13643. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  13644. default:
  13645. /* Key type not supported. */
  13646. WOLFSSL_MSG("Unknown Key type!");
  13647. break;
  13648. }
  13649. }
  13650. return ret;
  13651. }
  13652. /* Writes a private key to a WOLFSSL_BIO encoded in PEM format.
  13653. *
  13654. * @param [in] bio BIO to write to.
  13655. * @param [in] key Public key to write in PEM format.
  13656. * @param [in] cipher Encryption cipher to use.
  13657. * @param [in] passwd Password to use when encrypting.
  13658. * @param [in] len Length of password.
  13659. * @param [in] cb Password callback.
  13660. * @param [in] arg Password callback argument.
  13661. * @return 1 on success.
  13662. * @return 0 on failure.
  13663. */
  13664. int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key,
  13665. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  13666. wc_pem_password_cb* cb, void* arg)
  13667. {
  13668. int ret = 1;
  13669. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey");
  13670. (void)cipher;
  13671. (void)passwd;
  13672. (void)len;
  13673. (void)cb;
  13674. (void)arg;
  13675. /* Validate parameters. */
  13676. if ((bio == NULL) || (key == NULL)) {
  13677. WOLFSSL_MSG("Bad Function Arguments");
  13678. ret = 0;
  13679. }
  13680. if (ret == 1) {
  13681. #ifdef WOLFSSL_KEY_GEN
  13682. switch (key->type) {
  13683. #ifndef NO_RSA
  13684. case EVP_PKEY_RSA:
  13685. /* Write using RSA specific API. */
  13686. ret = wolfSSL_PEM_write_bio_RSAPrivateKey(bio, key->rsa,
  13687. cipher, passwd, len, cb, arg);
  13688. break;
  13689. #endif
  13690. #ifndef NO_DSA
  13691. case EVP_PKEY_DSA:
  13692. /* Write using DSA specific API. */
  13693. ret = wolfSSL_PEM_write_bio_DSAPrivateKey(bio, key->dsa,
  13694. cipher, passwd, len, cb, arg);
  13695. break;
  13696. #endif
  13697. #ifdef HAVE_ECC
  13698. case EVP_PKEY_EC:
  13699. #if defined(HAVE_ECC_KEY_EXPORT)
  13700. /* Write using EC specific API. */
  13701. ret = wolfSSL_PEM_write_bio_ECPrivateKey(bio, key->ecc,
  13702. cipher, passwd, len, cb, arg);
  13703. #else
  13704. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13705. key->pkey_sz, bio, EC_PRIVATEKEY_TYPE);
  13706. #endif
  13707. break;
  13708. #endif
  13709. #ifndef NO_DH
  13710. case EVP_PKEY_DH:
  13711. /* Write using generic API with DH type. */
  13712. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13713. key->pkey_sz, bio, DH_PRIVATEKEY_TYPE);
  13714. break;
  13715. #endif
  13716. default:
  13717. WOLFSSL_MSG("Unknown Key type!");
  13718. ret = 0;
  13719. break;
  13720. }
  13721. #else
  13722. int type = 0;
  13723. switch (key->type) {
  13724. #ifndef NO_DSA
  13725. case EVP_PKEY_DSA:
  13726. type = DSA_PRIVATEKEY_TYPE;
  13727. break;
  13728. #endif
  13729. #ifdef HAVE_ECC
  13730. case EVP_PKEY_EC:
  13731. type = ECC_PRIVATEKEY_TYPE;
  13732. break;
  13733. #endif
  13734. #ifndef NO_DH
  13735. case EVP_PKEY_DH:
  13736. type = DH_PRIVATEKEY_TYPE;
  13737. break;
  13738. #endif
  13739. #ifndef NO_RSA
  13740. case EVP_PKEY_RSA:
  13741. type = PRIVATEKEY_TYPE;
  13742. break;
  13743. #endif
  13744. default:
  13745. ret = 0;
  13746. break;
  13747. }
  13748. if (ret == 1) {
  13749. /* Write using generic API with generic type. */
  13750. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, key->pkey_sz,
  13751. bio, type);
  13752. }
  13753. #endif
  13754. }
  13755. return ret;
  13756. }
  13757. #endif /* !NO_BIO */
  13758. #ifndef NO_BIO
  13759. /* Create a private key object from the data in the BIO.
  13760. *
  13761. * @param [in] bio BIO to read from.
  13762. * @param [in, out] key Public key object. Object used if passed in.
  13763. * @param [in] cb Password callback.
  13764. * @param [in] arg Password callback argument.
  13765. * @return A WOLFSSL_EVP_PKEY object on success.
  13766. * @return NULL on failure.
  13767. */
  13768. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio,
  13769. WOLFSSL_EVP_PKEY **key, wc_pem_password_cb *cb, void *arg)
  13770. {
  13771. int err = 0;
  13772. WOLFSSL_EVP_PKEY* pkey = NULL;
  13773. DerBuffer* der = NULL;
  13774. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY");
  13775. if (bio == NULL) {
  13776. err = 1;
  13777. }
  13778. /* Read the PEM public key from the BIO and convert to DER. */
  13779. if ((!err) && (pem_read_bio_key(bio, cb, arg, PUBLICKEY_TYPE, NULL,
  13780. &der) < 0)) {
  13781. err = 1;
  13782. }
  13783. if (!err) {
  13784. const unsigned char* ptr = der->buffer;
  13785. /* Use key passed in if set. */
  13786. if ((key != NULL) && (*key != NULL)) {
  13787. pkey = *key;
  13788. }
  13789. /* Convert DER data to a public key object. */
  13790. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13791. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13792. pkey = NULL;
  13793. err = 1;
  13794. }
  13795. }
  13796. /* Return the key if possible. */
  13797. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13798. *key = pkey;
  13799. }
  13800. /* Dispose of the DER encoding. */
  13801. FreeDer(&der);
  13802. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0);
  13803. return pkey;
  13804. }
  13805. /* Create a private key object from the data in the BIO.
  13806. *
  13807. * @param [in] bio BIO to read from.
  13808. * @param [in, out] key Private key object. Object used if passed in.
  13809. * @param [in] cb Password callback.
  13810. * @param [in] arg Password callback argument.
  13811. * @return A WOLFSSL_EVP_PKEY object on success.
  13812. * @return NULL on failure.
  13813. */
  13814. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio,
  13815. WOLFSSL_EVP_PKEY** key, wc_pem_password_cb* cb, void* arg)
  13816. {
  13817. int err = 0;
  13818. WOLFSSL_EVP_PKEY* pkey = NULL;
  13819. DerBuffer* der = NULL;
  13820. int keyFormat = 0;
  13821. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey");
  13822. /* Validate parameters. */
  13823. if (bio == NULL) {
  13824. err = 1;
  13825. }
  13826. /* Read the PEM private key from the BIO and convert to DER. */
  13827. if ((!err) && (pem_read_bio_key(bio, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13828. &der) < 0)) {
  13829. err = 1;
  13830. }
  13831. if (!err) {
  13832. const unsigned char* ptr = der->buffer;
  13833. int type;
  13834. /* Set key type based on format returned. */
  13835. switch (keyFormat) {
  13836. /* No key format set - default to RSA. */
  13837. case 0:
  13838. case RSAk:
  13839. type = EVP_PKEY_RSA;
  13840. break;
  13841. case DSAk:
  13842. type = EVP_PKEY_DSA;
  13843. break;
  13844. case ECDSAk:
  13845. type = EVP_PKEY_EC;
  13846. break;
  13847. case DHk:
  13848. type = EVP_PKEY_DH;
  13849. break;
  13850. default:
  13851. type = WOLFSSL_FATAL_ERROR;
  13852. break;
  13853. }
  13854. /* Use key passed in if set. */
  13855. if ((key != NULL) && (*key != NULL)) {
  13856. pkey = *key;
  13857. }
  13858. /* Convert DER data to a private key object. */
  13859. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13860. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13861. pkey = NULL;
  13862. err = 1;
  13863. }
  13864. }
  13865. /* Return the key if possible. */
  13866. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13867. *key = pkey;
  13868. }
  13869. /* Dispose of the DER encoding. */
  13870. FreeDer(&der);
  13871. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", err);
  13872. return pkey;
  13873. }
  13874. #endif /* !NO_BIO */
  13875. #if !defined(NO_FILESYSTEM)
  13876. /* Create a private key object from the data in a file.
  13877. *
  13878. * @param [in] fp File pointer.
  13879. * @param [in, out] key Public key object. Object used if passed in.
  13880. * @param [in] cb Password callback.
  13881. * @param [in] arg Password callback argument.
  13882. * @return A WOLFSSL_EVP_PKEY object on success.
  13883. * @return NULL on failure.
  13884. */
  13885. WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13886. wc_pem_password_cb *cb, void *arg)
  13887. {
  13888. int err = 0;
  13889. WOLFSSL_EVP_PKEY* pkey = NULL;
  13890. DerBuffer* der = NULL;
  13891. WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY");
  13892. /* Validate parameters. */
  13893. if (fp == XBADFILE) {
  13894. err = 1;
  13895. }
  13896. /* Read the PEM public key from the file and convert to DER. */
  13897. if ((!err) && ((pem_read_file_key(fp, cb, arg, PUBLICKEY_TYPE, NULL,
  13898. &der) < 0) || (der == NULL))) {
  13899. err = 1;
  13900. }
  13901. if (!err) {
  13902. const unsigned char* ptr = der->buffer;
  13903. /* Use key passed in if set. */
  13904. if ((key != NULL) && (*key != NULL)) {
  13905. pkey = *key;
  13906. }
  13907. /* Convert DER data to a public key object. */
  13908. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13909. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13910. pkey = NULL;
  13911. err = 1;
  13912. }
  13913. }
  13914. /* Return the key if possible. */
  13915. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13916. *key = pkey;
  13917. }
  13918. /* Dispose of the DER encoding. */
  13919. FreeDer(&der);
  13920. WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0);
  13921. return pkey;
  13922. }
  13923. #ifndef NO_CERTS
  13924. /* Create a private key object from the data in a file.
  13925. *
  13926. * @param [in] fp File pointer.
  13927. * @param [in, out] key Private key object. Object used if passed in.
  13928. * @param [in] cb Password callback.
  13929. * @param [in] arg Password callback argument.
  13930. * @return A WOLFSSL_EVP_PKEY object on success.
  13931. * @return NULL on failure.
  13932. */
  13933. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13934. wc_pem_password_cb *cb, void *arg)
  13935. {
  13936. int err = 0;
  13937. WOLFSSL_EVP_PKEY* pkey = NULL;
  13938. DerBuffer* der = NULL;
  13939. int keyFormat = 0;
  13940. WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey");
  13941. /* Validate parameters. */
  13942. if (fp == XBADFILE) {
  13943. err = 1;
  13944. }
  13945. /* Read the PEM private key from the file and convert to DER. */
  13946. if ((!err) && (pem_read_file_key(fp, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13947. &der)) < 0) {
  13948. err = 1;
  13949. }
  13950. if (!err) {
  13951. const unsigned char* ptr = der->buffer;
  13952. int type;
  13953. /* Set key type based on format returned. */
  13954. switch (keyFormat) {
  13955. /* No key format set - default to RSA. */
  13956. case 0:
  13957. case RSAk:
  13958. type = EVP_PKEY_RSA;
  13959. break;
  13960. case DSAk:
  13961. type = EVP_PKEY_DSA;
  13962. break;
  13963. case ECDSAk:
  13964. type = EVP_PKEY_EC;
  13965. break;
  13966. case DHk:
  13967. type = EVP_PKEY_DH;
  13968. break;
  13969. default:
  13970. type = WOLFSSL_FATAL_ERROR;
  13971. break;
  13972. }
  13973. /* Use key passed in if set. */
  13974. if ((key != NULL) && (*key != NULL)) {
  13975. pkey = *key;
  13976. }
  13977. /* Convert DER data to a private key object. */
  13978. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13979. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13980. pkey = NULL;
  13981. err = 1;
  13982. }
  13983. }
  13984. /* Return the key if possible. */
  13985. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13986. *key = pkey;
  13987. }
  13988. /* Dispose of the DER encoding. */
  13989. FreeDer(&der);
  13990. WOLFSSL_LEAVE("wolfSSL_PEM_read_PrivateKey", 0);
  13991. return pkey;
  13992. }
  13993. #endif /* !NO_CERTS */
  13994. #endif /* !NO_FILESYSTEM */
  13995. #ifndef NO_CERTS
  13996. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  13997. #define PEM_BEGIN "-----BEGIN "
  13998. #define PEM_BEGIN_SZ 11
  13999. #define PEM_END "-----END "
  14000. #define PEM_END_SZ 9
  14001. #define PEM_HDR_FIN "-----"
  14002. #define PEM_HDR_FIN_SZ 5
  14003. #define PEM_HDR_FIN_EOL_NEWLINE "-----\n"
  14004. #define PEM_HDR_FIN_EOL_NULL_TERM "-----\0"
  14005. #define PEM_HDR_FIN_EOL_SZ 6
  14006. /* Find strings and return middle offsets.
  14007. *
  14008. * Find first string in pem as a prefix and then locate second string as a
  14009. * postfix.
  14010. * len returning with 0 indicates not found.
  14011. *
  14012. * @param [in] pem PEM data.
  14013. * @param [in] pemLen Length of PEM data.
  14014. * @param [in] idx Current index.
  14015. * @param [in] prefix First string to find.
  14016. * @param [in] postfix Second string to find after first.
  14017. * @param [out] start Start index of data between strings.
  14018. * @param [out] len Length of data between strings.
  14019. */
  14020. static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix,
  14021. const char* postfix, int* start, int* len)
  14022. {
  14023. int prefixLen = (int)XSTRLEN(prefix);
  14024. int postfixLen = (int)XSTRLEN(postfix);
  14025. *start = *len = 0;
  14026. /* Find prefix part. */
  14027. for (; idx < pemLen - prefixLen; idx++) {
  14028. if ((pem[idx] == prefix[0]) &&
  14029. (XMEMCMP(pem + idx, prefix, prefixLen) == 0)) {
  14030. idx += prefixLen;
  14031. *start = idx;
  14032. break;
  14033. }
  14034. }
  14035. /* Find postfix part. */
  14036. for (; idx < pemLen - postfixLen; idx++) {
  14037. if ((pem[idx] == postfix[0]) &&
  14038. (XMEMCMP(pem + idx, postfix, postfixLen) == 0)) {
  14039. *len = idx - *start;
  14040. break;
  14041. }
  14042. }
  14043. }
  14044. /* Parse out content type name, any encryption headers and DER encoding.
  14045. *
  14046. * @param [in] pem PEM data.
  14047. * @param [in] pemLen Length of PEM data.
  14048. * @param [out] name Name of content type.
  14049. * @param [out] header Encryption headers.
  14050. * @param [out] data DER encoding from PEM.
  14051. * @param [out] len Length of DER data.
  14052. * @return 0 on success.
  14053. * @return MEMORY_E when dynamic memory allocation fails.
  14054. * @return ASN_NO_PEM_HEADER when no header found or different names found.
  14055. */
  14056. static int pem_read_data(char* pem, int pemLen, char **name, char **header,
  14057. unsigned char **data, long *len)
  14058. {
  14059. int ret = 0;
  14060. int start;
  14061. int nameLen;
  14062. int startHdr = 0;
  14063. int hdrLen = 0;
  14064. int startEnd = 0;
  14065. int endLen;
  14066. *name = NULL;
  14067. *header = NULL;
  14068. /* Find header. */
  14069. pem_find_pattern(pem, pemLen, 0, PEM_BEGIN, PEM_HDR_FIN, &start, &nameLen);
  14070. /* Allocate memory for header name. */
  14071. *name = (char*)XMALLOC(nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14072. if (*name == NULL) {
  14073. ret = MEMORY_E;
  14074. }
  14075. if (ret == 0) {
  14076. /* Put in header name. */
  14077. (*name)[nameLen] = '\0';
  14078. if (nameLen == 0) {
  14079. ret = ASN_NO_PEM_HEADER;
  14080. }
  14081. else {
  14082. XMEMCPY(*name, pem + start, nameLen);
  14083. }
  14084. }
  14085. if (ret == 0) {
  14086. /* Find encryption headers after header. */
  14087. start += nameLen + PEM_HDR_FIN_SZ;
  14088. pem_find_pattern(pem, pemLen, start, "\n", "\n\n", &startHdr, &hdrLen);
  14089. if (hdrLen > 0) {
  14090. /* Include first of two '\n' characters. */
  14091. hdrLen++;
  14092. }
  14093. /* Allocate memory for encryption header string. */
  14094. *header = (char*)XMALLOC(hdrLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14095. if (*header == NULL) {
  14096. ret = MEMORY_E;
  14097. }
  14098. }
  14099. if (ret == 0) {
  14100. /* Put in encryption header string. */
  14101. (*header)[hdrLen] = '\0';
  14102. if (hdrLen > 0) {
  14103. XMEMCPY(*header, pem + startHdr, hdrLen);
  14104. start = startHdr + hdrLen + 1;
  14105. }
  14106. /* Find footer. */
  14107. pem_find_pattern(pem, pemLen, start, PEM_END, PEM_HDR_FIN, &startEnd,
  14108. &endLen);
  14109. /* Validate header name and footer name are the same. */
  14110. if ((endLen != nameLen) ||
  14111. (XMEMCMP(*name, pem + startEnd, nameLen) != 0)) {
  14112. ret = ASN_NO_PEM_HEADER;
  14113. }
  14114. }
  14115. if (ret == 0) {
  14116. unsigned char* der = (unsigned char*)pem;
  14117. word32 derLen;
  14118. /* Convert PEM body to DER. */
  14119. derLen = (word32)(startEnd - PEM_END_SZ - start);
  14120. ret = Base64_Decode(der + start, derLen, der, &derLen);
  14121. if (ret == 0) {
  14122. /* Return the DER data. */
  14123. *data = der;
  14124. *len = derLen;
  14125. }
  14126. }
  14127. return ret;
  14128. }
  14129. /* Encode the DER data in PEM format into a newly allocated buffer.
  14130. *
  14131. * @param [in] name Header/footer name.
  14132. * @param [in] header Encryption header.
  14133. * @param [in] data DER data.
  14134. * @param [in] len Length of DER data.
  14135. * @param [out] pemOut PEM encoded data.
  14136. * @param [out] pemOutLen Length of PEM encoded data.
  14137. * @return 0 on success.
  14138. * @return MEMORY_E when dynamic memory allocation fails.
  14139. */
  14140. static int pem_write_data(const char *name, const char *header,
  14141. const unsigned char *data, long len, char** pemOut, word32* pemOutLen)
  14142. {
  14143. int ret = 0;
  14144. int nameLen;
  14145. int headerLen;
  14146. char* pem = NULL;
  14147. word32 pemLen;
  14148. word32 derLen = (word32)len;
  14149. byte* p;
  14150. nameLen = (int)XSTRLEN(name);
  14151. headerLen = (int)XSTRLEN(header);
  14152. /* DER encode for PEM. */
  14153. pemLen = (derLen + 2) / 3 * 4;
  14154. pemLen += (pemLen + 63) / 64;
  14155. /* Header */
  14156. pemLen += PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  14157. if (headerLen > 0) {
  14158. /* Encryption lines plus extra carriage return. */
  14159. pemLen += headerLen + 1;
  14160. }
  14161. /* Trailer */
  14162. pemLen += PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  14163. pem = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14164. if (pem == NULL) {
  14165. ret = MEMORY_E;
  14166. }
  14167. p = (byte*)pem;
  14168. if (ret == 0) {
  14169. /* Add header. */
  14170. XMEMCPY(p, PEM_BEGIN, PEM_BEGIN_SZ);
  14171. p += PEM_BEGIN_SZ;
  14172. XMEMCPY(p, name, nameLen);
  14173. p += nameLen;
  14174. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  14175. p += PEM_HDR_FIN_EOL_SZ;
  14176. if (headerLen > 0) {
  14177. /* Add encryption header. */
  14178. XMEMCPY(p, header, headerLen);
  14179. p += headerLen;
  14180. /* Blank line after a header and before body. */
  14181. *(p++) = '\n';
  14182. }
  14183. /* Add DER data as PEM. */
  14184. pemLen -= (word32)((size_t)p - (size_t)pem);
  14185. ret = Base64_Encode(data, derLen, p, &pemLen);
  14186. }
  14187. if (ret == 0) {
  14188. p += pemLen;
  14189. /* Add trailer. */
  14190. XMEMCPY(p, PEM_END, PEM_END_SZ);
  14191. p += PEM_END_SZ;
  14192. XMEMCPY(p, name, nameLen);
  14193. p += nameLen;
  14194. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  14195. p += PEM_HDR_FIN_EOL_SZ;
  14196. /* Return buffer and length of data. */
  14197. *pemOut = pem;
  14198. *pemOutLen = (word32)((size_t)p - (size_t)pem);
  14199. }
  14200. return ret;
  14201. }
  14202. #endif /* !NO_BIO || !NO_FILESYSTEM */
  14203. #ifndef NO_BIO
  14204. /* Read PEM encoded data from a BIO.
  14205. *
  14206. * Reads the entire contents in.
  14207. *
  14208. * @param [in] bio BIO to read from.
  14209. * @param [out] name Name of content type.
  14210. * @param [out] header Encryption headers.
  14211. * @param [out] data DER encoding from PEM.
  14212. * @param [out] len Length of DER data.
  14213. * @return 1 on success.
  14214. * @return 0 on failure.
  14215. */
  14216. int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header,
  14217. unsigned char **data, long *len)
  14218. {
  14219. int res = 1;
  14220. char* pem = NULL;
  14221. int pemLen = 0;
  14222. int memAlloced = 1;
  14223. /* Validate parameters. */
  14224. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL) ||
  14225. (len == NULL)) {
  14226. res = 0;
  14227. }
  14228. /* Load all the data from the BIO. */
  14229. if ((res == 1) && (wolfssl_read_bio(bio, &pem, &pemLen, &memAlloced) !=
  14230. 0)) {
  14231. res = 0;
  14232. }
  14233. if ((res == 1) && (!memAlloced)) {
  14234. /* Need to return allocated memory - make sure it is allocated. */
  14235. char* p = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14236. if (p == NULL) {
  14237. res = 0;
  14238. }
  14239. else {
  14240. /* Copy the data into new buffer. */
  14241. XMEMCPY(p, pem, pemLen);
  14242. pem = p;
  14243. }
  14244. }
  14245. /* Read the PEM data. */
  14246. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  14247. 0)) {
  14248. /* Dispose of any allocated memory. */
  14249. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14250. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14251. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14252. *name = NULL;
  14253. *header = NULL;
  14254. res = 0;
  14255. }
  14256. return res;
  14257. }
  14258. /* Encode the DER data in PEM format into a BIO.
  14259. *
  14260. * @param [in] bio BIO to write to.
  14261. * @param [in] name Header/footer name.
  14262. * @param [in] header Encryption header.
  14263. * @param [in] data DER data.
  14264. * @param [in] len Length of DER data.
  14265. * @return 0 on failure.
  14266. */
  14267. int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name,
  14268. const char *header, const unsigned char *data, long len)
  14269. {
  14270. int err = 0;
  14271. char* pem = NULL;
  14272. word32 pemLen = 0;
  14273. /* Validate parameters. */
  14274. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL)) {
  14275. err = BAD_FUNC_ARG;
  14276. }
  14277. /* Encode into a buffer. */
  14278. if (!err) {
  14279. err = pem_write_data(name, header, data, len, &pem, &pemLen);
  14280. }
  14281. /* Write PEM into BIO. */
  14282. if ((!err) && (wolfSSL_BIO_write(bio, pem, (int)pemLen) != (int)pemLen)) {
  14283. err = IO_FAILED_E;
  14284. }
  14285. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14286. return (!err) ? pemLen : 0;
  14287. }
  14288. #endif /* !NO_BIO */
  14289. #if !defined(NO_FILESYSTEM)
  14290. /* Read PEM encoded data from a file.
  14291. *
  14292. * Reads the entire contents in.
  14293. *
  14294. * @param [in] bio BIO to read from.
  14295. * @param [out] name Name of content type.
  14296. * @param [out] header Encryption headers.
  14297. * @param [out] data DER encoding from PEM.
  14298. * @param [out] len Length of DER data.
  14299. * @return 1 on success.
  14300. * @return 0 on failure.
  14301. */
  14302. int wolfSSL_PEM_read(XFILE fp, char **name, char **header, unsigned char **data,
  14303. long *len)
  14304. {
  14305. int res = 1;
  14306. char* pem = NULL;
  14307. int pemLen = 0;
  14308. /* Validate parameters. */
  14309. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14310. (data == NULL) || (len == NULL)) {
  14311. res = 0;
  14312. }
  14313. /* Load all the data from the file. */
  14314. if ((res == 1) && (wolfssl_read_file(fp, &pem, &pemLen) != 0)) {
  14315. res = 0;
  14316. }
  14317. /* Read the PEM data. */
  14318. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  14319. 0)) {
  14320. /* Dispose of any allocated memory. */
  14321. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14322. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14323. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14324. *name = NULL;
  14325. *header = NULL;
  14326. res = 0;
  14327. }
  14328. return res;
  14329. }
  14330. /* Encode the DER data in PEM format into a file.
  14331. *
  14332. * @param [in] fp File pointer to write to.
  14333. * @param [in] name Header/footer name.
  14334. * @param [in] header Encryption header.
  14335. * @param [in] data DER data.
  14336. * @param [in] len Length of DER data.
  14337. * @return 0 on success.
  14338. * @return MEMORY_E when dynamic memory allocation fails.
  14339. */
  14340. int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header,
  14341. const unsigned char *data, long len)
  14342. {
  14343. int err = 0;
  14344. char* pem = NULL;
  14345. word32 pemLen = 0;
  14346. /* Validate parameters. */
  14347. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14348. (data == NULL)) {
  14349. err = 1;
  14350. }
  14351. /* Encode into a buffer. */
  14352. if ((!err) && (pem_write_data(name, header, data, len, &pem, &pemLen) !=
  14353. 0)) {
  14354. pemLen = 0;
  14355. err = 1;
  14356. }
  14357. /* Write PEM to a file. */
  14358. if ((!err) && (XFWRITE(pem, 1, pemLen, fp) != pemLen)) {
  14359. pemLen = 0;
  14360. }
  14361. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14362. return (int)pemLen;
  14363. }
  14364. #endif
  14365. /* Get EVP cipher info from encryption header string.
  14366. *
  14367. * @param [in] header Encryption header.
  14368. * @param [out] cipher EVP Cipher info.
  14369. * @return 1 on success.
  14370. * @return 0 on failure.
  14371. */
  14372. int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header, EncryptedInfo* cipher)
  14373. {
  14374. int res = 1;
  14375. /* Validate parameters. */
  14376. if ((header == NULL) || (cipher == NULL)) {
  14377. res = 0;
  14378. }
  14379. if (res == 1) {
  14380. XMEMSET(cipher, 0, sizeof(*cipher));
  14381. if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0) {
  14382. res = 0;
  14383. }
  14384. }
  14385. return res;
  14386. }
  14387. /* Apply cipher to DER data.
  14388. *
  14389. * @param [in] cipher EVP cipher info.
  14390. * @param [in, out] data On in, encrypted DER data.
  14391. * On out, unencrypted DER data.
  14392. * @param [in, out] len On in, length of encrypted DER data.
  14393. * On out, length of unencrypted DER data.
  14394. * @param [in] cb Password callback.
  14395. * @param [in] ctx Context for password callback.
  14396. * @return 1 on success.
  14397. * @return 0 on failure.
  14398. */
  14399. int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len,
  14400. wc_pem_password_cb* cb, void* ctx)
  14401. {
  14402. int ret = 1;
  14403. char password[NAME_SZ];
  14404. int passwordSz = 0;
  14405. /* Validate parameters. */
  14406. if ((cipher == NULL) || (data == NULL) || (len == NULL) || (cb == NULL)) {
  14407. ret = 0;
  14408. }
  14409. if (ret == 1) {
  14410. /* Get password and length. */
  14411. passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx);
  14412. if (passwordSz < 0) {
  14413. ret = 0;
  14414. }
  14415. }
  14416. if (ret == 1) {
  14417. /* Decrypt the data using password and MD5. */
  14418. if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password,
  14419. passwordSz, WC_MD5) != 0) {
  14420. ret = WOLFSSL_FAILURE;
  14421. }
  14422. }
  14423. if (passwordSz > 0) {
  14424. /* Ensure password is erased from memory. */
  14425. ForceZero(password, (word32)passwordSz);
  14426. }
  14427. return ret;
  14428. }
  14429. #endif /* !NO_CERTS */
  14430. #endif /* OPENSSL_EXTRA */
  14431. #ifdef OPENSSL_ALL
  14432. #if !defined(NO_PWDBASED) && defined(HAVE_PKCS8)
  14433. #if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \
  14434. !defined(NO_STDIO_FILESYSTEM))
  14435. /* Encrypt the key into a buffer using PKCS$8 and a password.
  14436. *
  14437. * @param [in] pkey Private key to encrypt.
  14438. * @param [in] enc EVP cipher.
  14439. * @param [in] passwd Password to encrypt with.
  14440. * @param [in] passwdSz Number of bytes in password.
  14441. * @param [in] key Buffer to hold encrypted key.
  14442. * @param [in, out] keySz On in, size of buffer in bytes.
  14443. * On out, size of encrypted key in bytes.
  14444. * @return 0 on success.
  14445. * @return BAD_FUNC_ARG when EVP cipher not supported.
  14446. */
  14447. static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey,
  14448. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key,
  14449. word32* keySz)
  14450. {
  14451. int ret;
  14452. WC_RNG rng;
  14453. /* Initialize a new random number generator. */
  14454. ret = wc_InitRng(&rng);
  14455. if (ret == 0) {
  14456. int encAlgId = 0;
  14457. /* Convert EVP cipher to a support encryption id. */
  14458. #ifndef NO_DES3
  14459. if (enc == EVP_DES_CBC) {
  14460. encAlgId = DESb;
  14461. }
  14462. else if (enc == EVP_DES_EDE3_CBC) {
  14463. encAlgId = DES3b;
  14464. }
  14465. else
  14466. #endif
  14467. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  14468. #ifdef WOLFSSL_AES_128
  14469. if (enc == EVP_AES_128_CBC) {
  14470. encAlgId = AES128CBCb;
  14471. }
  14472. else
  14473. #endif
  14474. #ifdef WOLFSSL_AES_256
  14475. if (enc == EVP_AES_256_CBC) {
  14476. encAlgId = AES256CBCb;
  14477. }
  14478. else
  14479. #endif
  14480. #endif
  14481. {
  14482. ret = BAD_FUNC_ARG;
  14483. }
  14484. if (ret == 0) {
  14485. /* Encrypt private into buffer. */
  14486. ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz,
  14487. key, keySz, passwd, passwdSz, PKCS5, PBES2, encAlgId,
  14488. NULL, 0, WC_PKCS12_ITT_DEFAULT, &rng, NULL);
  14489. if (ret > 0) {
  14490. *keySz = (word32)ret;
  14491. }
  14492. }
  14493. /* Dispose of random number generator. */
  14494. wc_FreeRng(&rng);
  14495. }
  14496. return ret;
  14497. }
  14498. /* Encode private key in PKCS#8 format.
  14499. *
  14500. * @param [in] pkey Private key.
  14501. * @param [out] key Buffer to hold encoding.
  14502. * @param [in, out] keySz On in, size of buffer in bytes.
  14503. * @param On out, size of encoded key in bytes.
  14504. * @return 0 on success.
  14505. */
  14506. static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz)
  14507. {
  14508. int ret = 0;
  14509. int algId;
  14510. const byte* curveOid;
  14511. word32 oidSz;
  14512. /* Get the details of the private key. */
  14513. #ifdef HAVE_ECC
  14514. if (pkey->type == EVP_PKEY_EC) {
  14515. /* ECC private and get curve OID information. */
  14516. algId = ECDSAk;
  14517. ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid,
  14518. &oidSz);
  14519. }
  14520. else
  14521. #endif
  14522. if (pkey->type == EVP_PKEY_RSA) {
  14523. /* RSA private has no curve information. */
  14524. algId = RSAk;
  14525. curveOid = NULL;
  14526. oidSz = 0;
  14527. }
  14528. else {
  14529. ret = NOT_COMPILED_IN;
  14530. }
  14531. if (ret >= 0) {
  14532. /* Encode private key in PKCS#8 format. */
  14533. ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr,
  14534. pkey->pkey_sz, algId, curveOid, oidSz);
  14535. }
  14536. return ret;
  14537. }
  14538. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14539. *
  14540. * @param [out] pem Buffer holding PEM encoding.
  14541. * @param [out] pemSz Size of data in buffer in bytes.
  14542. * @param [in] pkey Private key to write.
  14543. * @param [in] enc Encryption information to use. May be NULL.
  14544. * @param [in] passwd Password to use when encrypting. May be NULL.
  14545. * @param [in] passwdSz Size of password in bytes.
  14546. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14547. * NULL.
  14548. * @param [in] ctx Context for password callback.
  14549. * @return Length of PEM encoding on success.
  14550. * @return 0 on failure.
  14551. */
  14552. static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz,
  14553. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14554. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14555. {
  14556. int res = 1;
  14557. int ret = 0;
  14558. char password[NAME_SZ];
  14559. byte* key = NULL;
  14560. word32 keySz;
  14561. int type = PKCS8_PRIVATEKEY_TYPE;
  14562. /* Validate parameters. */
  14563. if (pkey == NULL) {
  14564. res = 0;
  14565. }
  14566. if (res == 1) {
  14567. /* Guestimate key size and PEM size. */
  14568. if (pem_pkcs8_encode(pkey, NULL, &keySz) != WC_NO_ERR_TRACE(LENGTH_ONLY_E)) {
  14569. res = 0;
  14570. }
  14571. }
  14572. if (res == 1) {
  14573. if (enc != NULL) {
  14574. /* Add on enough for extra DER data when encrypting. */
  14575. keySz += 128;
  14576. }
  14577. /* PEM encoding size from DER size. */
  14578. *pemSz = (int)(keySz + 2) / 3 * 4;
  14579. *pemSz += (*pemSz + 63) / 64;
  14580. /* Header and footer. */
  14581. if (enc != NULL) {
  14582. /* Name is: 'ENCRYPTED PRIVATE KEY'. */
  14583. *pemSz += 74;
  14584. }
  14585. else {
  14586. /* Name is: 'PRIVATE KEY'. */
  14587. *pemSz += 54;
  14588. }
  14589. /* Allocate enough memory to hold PEM encoded encrypted key. */
  14590. *pem = (byte*)XMALLOC((size_t)*pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14591. if (*pem == NULL) {
  14592. res = 0;
  14593. }
  14594. else {
  14595. /* Use end of PEM buffer for key data. */
  14596. key = *pem + *pemSz - keySz;
  14597. }
  14598. }
  14599. if ((res == 1) && (enc != NULL)) {
  14600. /* Set type for PEM. */
  14601. type = PKCS8_ENC_PRIVATEKEY_TYPE;
  14602. if (passwd == NULL) {
  14603. /* Get the password by using callback. */
  14604. passwdSz = cb(password, sizeof(password), 1, ctx);
  14605. if (passwdSz < 0) {
  14606. res = 0;
  14607. }
  14608. passwd = password;
  14609. }
  14610. if (res == 1) {
  14611. /* Encrypt the private key. */
  14612. ret = pem_pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz);
  14613. if (ret <= 0) {
  14614. res = 0;
  14615. }
  14616. }
  14617. /* Zeroize the password from memory. */
  14618. if ((password == passwd) && (passwdSz > 0)) {
  14619. ForceZero(password, (word32)passwdSz);
  14620. }
  14621. }
  14622. else if ((res == 1) && (enc == NULL)) {
  14623. /* Set type for PEM. */
  14624. type = PKCS8_PRIVATEKEY_TYPE;
  14625. /* Encode private key in PKCS#8 format. */
  14626. ret = pem_pkcs8_encode(pkey, key, &keySz);
  14627. if (ret < 0) {
  14628. res = 0;
  14629. }
  14630. }
  14631. if (res == 1) {
  14632. /* Encode PKCS#8 formatted key to PEM. */
  14633. ret = wc_DerToPemEx(key, keySz, *pem, (word32)*pemSz, NULL, type);
  14634. if (ret < 0) {
  14635. res = 0;
  14636. }
  14637. else {
  14638. *pemSz = ret;
  14639. }
  14640. }
  14641. /* Return appropriate return code. */
  14642. return (res == 0) ? 0 : ret;
  14643. }
  14644. #endif /* !NO_BIO || (!NO_FILESYSTEM && !NO_STDIO_FILESYSTEM) */
  14645. #ifndef NO_BIO
  14646. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14647. *
  14648. * TODO: OpenSSL returns 1 and 0 only.
  14649. *
  14650. * @param [in] bio BIO to write to.
  14651. * @param [in] pkey Private key to write.
  14652. * @param [in] enc Encryption information to use. May be NULL.
  14653. * @param [in] passwd Password to use when encrypting. May be NULL.
  14654. * @param [in] passwdSz Size of password in bytes.
  14655. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14656. * NULL.
  14657. * @param [in] ctx Context for password callback.
  14658. * @return Length of PEM encoding on success.
  14659. * @return 0 on failure.
  14660. */
  14661. int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio,
  14662. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14663. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14664. {
  14665. byte* pem = NULL;
  14666. int pemSz = 0;
  14667. int res = 1;
  14668. /* Validate parameters. */
  14669. if (bio == NULL) {
  14670. res = 0;
  14671. }
  14672. if (res == 1) {
  14673. /* Write private key to memory. */
  14674. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14675. passwdSz, cb, ctx);
  14676. }
  14677. /* Write encoded key to BIO. */
  14678. if ((res >= 1) && (wolfSSL_BIO_write(bio, pem, pemSz) != pemSz)) {
  14679. res = 0;
  14680. }
  14681. /* Dispose of dynamically allocated memory (pem and key). */
  14682. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14683. return res;
  14684. }
  14685. #endif /* !NO_BIO */
  14686. #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
  14687. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14688. *
  14689. * TODO: OpenSSL returns 1 and 0 only.
  14690. *
  14691. * @param [in] f File pointer.
  14692. * @param [in] pkey Private key to write.
  14693. * @param [in] enc Encryption information to use. May be NULL.
  14694. * @param [in] passwd Password to use when encrypting. May be NULL.
  14695. * @param [in] passwdSz Size of password in bytes.
  14696. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14697. * NULL.
  14698. * @param [in] ctx Context for password callback.
  14699. * @return Length of PEM encoding on success.
  14700. * @return 0 on failure.
  14701. */
  14702. int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey,
  14703. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz,
  14704. wc_pem_password_cb* cb, void* ctx)
  14705. {
  14706. byte* pem = NULL;
  14707. int pemSz = 0;
  14708. int res = 1;
  14709. /* Validate parameters. */
  14710. if (f == XBADFILE) {
  14711. res = 0;
  14712. }
  14713. if (res == 1) {
  14714. /* Write private key to memory. */
  14715. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14716. passwdSz, cb, ctx);
  14717. }
  14718. /* Write encoded key to file. */
  14719. if ((res >= 1) && (XFWRITE(pem, 1, (size_t)pemSz, f) != (size_t)pemSz)) {
  14720. res = 0;
  14721. }
  14722. /* Dispose of dynamically allocated memory (pem and key). */
  14723. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14724. return res;
  14725. }
  14726. #endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  14727. #endif /* !NO_PWDBASED && HAVE_PKCS8 */
  14728. #endif /* OPENSSL_ALL */
  14729. /*******************************************************************************
  14730. * END OF GENERIC PUBLIC KEY PEM APIs
  14731. ******************************************************************************/
  14732. #endif /* !WOLFSSL_PK_INCLUDED */