pk.c 464 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278
  1. /* pk.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/internal.h>
  26. #ifndef WC_NO_RNG
  27. #include <wolfssl/wolfcrypt/random.h>
  28. #endif
  29. #ifdef HAVE_ECC
  30. #include <wolfssl/wolfcrypt/ecc.h>
  31. #endif
  32. #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  33. /* FIPS build has replaced ecc.h. */
  34. #define wc_ecc_key_get_priv(key) (&((key)->k))
  35. #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  36. #endif
  37. #if !defined(WOLFSSL_PK_INCLUDED)
  38. #ifndef WOLFSSL_IGNORE_FILE_WARN
  39. #warning pk.c does not need to be compiled separately from ssl.c
  40. #endif
  41. #else
  42. #ifndef NO_RSA
  43. #include <wolfssl/wolfcrypt/rsa.h>
  44. #endif
  45. /*******************************************************************************
  46. * COMMON FUNCTIONS
  47. ******************************************************************************/
  48. /* Calculate the number of bytes require to represent a length value in ASN.
  49. *
  50. * @param [in] l Length value to use.
  51. * @return Number of bytes required to represent length value.
  52. */
  53. #define ASN_LEN_SIZE(l) \
  54. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  55. #if defined(OPENSSL_EXTRA)
  56. #ifndef NO_ASN
  57. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  58. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  59. /* Convert the PEM encoding in the buffer to DER.
  60. *
  61. * @param [in] pem Buffer containing PEM encoded data.
  62. * @param [in] pemSz Size of data in buffer in bytes.
  63. * @param [in] cb Password callback when PEM encrypted.
  64. * @param [in] pass NUL terminated string for passphrase when PEM
  65. * encrypted.
  66. * @param [in] keyType Type of key to match against PEM header/footer.
  67. * @param [out] keyFormat Format of key.
  68. * @param [out] der Buffer holding DER encoding.
  69. * @return Negative on failure.
  70. * @return Number of bytes consumed on success.
  71. */
  72. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  73. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  74. {
  75. #ifdef WOLFSSL_SMALL_STACK
  76. EncryptedInfo* info = NULL;
  77. #else
  78. EncryptedInfo info[1];
  79. #endif /* WOLFSSL_SMALL_STACK */
  80. wc_pem_password_cb* localCb = NULL;
  81. int ret = 0;
  82. if (cb != NULL) {
  83. localCb = cb;
  84. }
  85. else if (pass != NULL) {
  86. localCb = wolfSSL_PEM_def_callback;
  87. }
  88. #ifdef WOLFSSL_SMALL_STACK
  89. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  90. DYNAMIC_TYPE_ENCRYPTEDINFO);
  91. if (info == NULL) {
  92. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  93. ret = MEMORY_E;
  94. }
  95. #endif /* WOLFSSL_SMALL_STACK */
  96. if (ret == 0) {
  97. XMEMSET(info, 0, sizeof(EncryptedInfo));
  98. info->passwd_cb = localCb;
  99. info->passwd_userdata = pass;
  100. /* Do not strip PKCS8 header */
  101. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  102. info, keyFormat);
  103. if (ret < 0) {
  104. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  105. }
  106. }
  107. if (ret >= 0) {
  108. ret = (int)info->consumed;
  109. }
  110. #ifdef WOLFSSL_SMALL_STACK
  111. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  112. #endif
  113. return ret;
  114. }
  115. #endif
  116. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  117. #ifndef NO_BIO
  118. /* Read PEM data from a BIO and decode to DER in a new buffer.
  119. *
  120. * @param [in, out] bio BIO object to read with.
  121. * @param [in] cb Password callback when PEM encrypted.
  122. * @param [in] pass NUL terminated string for passphrase when PEM
  123. * encrypted.
  124. * @param [in] keyType Type of key to match against PEM header/footer.
  125. * @param [out] keyFormat Format of key.
  126. * @param [out] der Buffer holding DER encoding.
  127. * @return Negative on failure.
  128. * @return Number of bytes consumed on success.
  129. */
  130. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  131. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  132. {
  133. int ret;
  134. char* mem = NULL;
  135. int memSz;
  136. int alloced = 0;
  137. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  138. if (ret == 0) {
  139. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  140. /* Write left over data back to BIO if not a file BIO */
  141. if ((ret > 0) && ((memSz - ret) > 0) &&
  142. (bio->type != WOLFSSL_BIO_FILE)) {
  143. int res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  144. if (res != memSz - ret) {
  145. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  146. if (res < 0) {
  147. ret = res;
  148. }
  149. else {
  150. ret = MEMORY_E;
  151. }
  152. }
  153. }
  154. if (alloced) {
  155. XFREE(mem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  156. }
  157. }
  158. return ret;
  159. }
  160. #endif /* !NO_BIO */
  161. #if !defined(NO_FILESYSTEM)
  162. /* Read PEM data from a file and decode to DER in a new buffer.
  163. *
  164. * @param [in] fp File pointer to read with.
  165. * @param [in] cb Password callback when PEM encrypted.
  166. * @param [in] pass NUL terminated string for passphrase when PEM
  167. * encrypted.
  168. * @param [in] keyType Type of key to match against PEM header/footer.
  169. * @param [out] keyFormat Format of key.
  170. * @param [out] der Buffer holding DER encoding.
  171. * @return Negative on failure.
  172. * @return Number of bytes consumed on success.
  173. */
  174. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  175. int keyType, int* keyFormat, DerBuffer** der)
  176. {
  177. int ret;
  178. char* mem = NULL;
  179. int memSz;
  180. ret = wolfssl_read_file(fp, &mem, &memSz);
  181. if (ret == 0) {
  182. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  183. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  184. }
  185. return ret;
  186. }
  187. #endif /* !NO_FILESYSTEM */
  188. #endif
  189. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) \
  190. || !defined(WOLFCRYPT_ONLY))
  191. /* Convert DER data to PEM in an allocated buffer.
  192. *
  193. * @param [in] der Buffer containing DER data.
  194. * @param [in] derSz Size of DER data in bytes.
  195. * @param [in] type Type of key being encoded.
  196. * @param [in] heap Heap hint for dynamic memory allocation.
  197. * @param [out] out Allocated buffer containing PEM.
  198. * @param [out] outSz Size of PEM encoding.
  199. * @return 1 on success.
  200. * @return 0 on error.
  201. */
  202. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  203. void* heap, byte** out, int* outSz)
  204. {
  205. int ret = 1;
  206. int pemSz;
  207. byte* pem = NULL;
  208. (void)heap;
  209. /* Convert DER to PEM - to get size. */
  210. pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
  211. if (pemSz < 0) {
  212. ret = 0;
  213. }
  214. if (ret == 1) {
  215. /* Allocate memory for PEM to be encoded into. */
  216. pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  217. if (pem == NULL) {
  218. ret = 0;
  219. }
  220. }
  221. /* Convert DER to PEM. */
  222. if ((ret == 1) && (wc_DerToPem(der, (word32)derSz, pem, (word32)pemSz,
  223. type) < 0)) {
  224. ret = 0;
  225. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  226. pem = NULL;
  227. }
  228. *out = pem;
  229. *outSz = pemSz;
  230. return ret;
  231. }
  232. #ifndef NO_BIO
  233. /* Write the DER data as PEM into BIO.
  234. *
  235. * @param [in] der Buffer containing DER data.
  236. * @param [in] derSz Size of DER data in bytes.
  237. * @param [in, out] bio BIO object to write with.
  238. * @param [in] type Type of key being encoded.
  239. * @return 1 on success.
  240. * @return 0 on error.
  241. */
  242. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  243. WOLFSSL_BIO* bio, int type)
  244. {
  245. int ret;
  246. int pemSz;
  247. byte* pem = NULL;
  248. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  249. if (ret == 1) {
  250. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  251. if (len != pemSz) {
  252. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  253. ret = 0;
  254. }
  255. }
  256. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  257. return ret;
  258. }
  259. #endif
  260. #endif
  261. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || \
  262. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  263. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  264. #if !defined(NO_FILESYSTEM)
  265. /* Write the DER data as PEM into file pointer.
  266. *
  267. * @param [in] der Buffer containing DER data.
  268. * @param [in] derSz Size of DER data in bytes.
  269. * @param [in] fp File pointer to write with.
  270. * @param [in] type Type of key being encoded.
  271. * @param [in] heap Heap hint for dynamic memory allocation.
  272. * @return 1 on success.
  273. * @return 0 on error.
  274. */
  275. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  276. XFILE fp, int type, void* heap)
  277. {
  278. int ret;
  279. int pemSz;
  280. byte* pem = NULL;
  281. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  282. if (ret == 1) {
  283. int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
  284. if (len != pemSz) {
  285. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  286. ret = 0;
  287. }
  288. }
  289. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  290. return ret;
  291. }
  292. #endif
  293. #endif
  294. #if defined(WOLFSSL_KEY_GEN) && defined(WOLFSSL_PEM_TO_DER)
  295. /* Encrypt private key into PEM format.
  296. *
  297. * DER is encrypted in place.
  298. *
  299. * @param [in] der DER encoding of private key.
  300. * @param [in] derSz Size of DER in bytes.
  301. * @param [in] cipher EVP cipher.
  302. * @param [in] passwd Password to use with encryption.
  303. * @param [in] passedSz Size of password in bytes.
  304. * @param [out] cipherInfo PEM cipher information lines.
  305. * @param [in] maxDerSz Maximum size of DER buffer.
  306. * @return 1 on success.
  307. * @return 0 on error.
  308. */
  309. int EncryptDerKey(byte *der, int *derSz, const EVP_CIPHER* cipher,
  310. unsigned char* passwd, int passwdSz, byte **cipherInfo, int maxDerSz)
  311. {
  312. int ret = 0;
  313. int paddingSz = 0;
  314. word32 idx;
  315. word32 cipherInfoSz;
  316. #ifdef WOLFSSL_SMALL_STACK
  317. EncryptedInfo* info = NULL;
  318. #else
  319. EncryptedInfo info[1];
  320. #endif
  321. WOLFSSL_ENTER("EncryptDerKey");
  322. /* Validate parameters. */
  323. if ((der == NULL) || (derSz == NULL) || (cipher == NULL) ||
  324. (passwd == NULL) || (cipherInfo == NULL)) {
  325. ret = BAD_FUNC_ARG;
  326. }
  327. #ifdef WOLFSSL_SMALL_STACK
  328. if (ret == 0) {
  329. /* Allocate encrypted info. */
  330. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  331. DYNAMIC_TYPE_ENCRYPTEDINFO);
  332. if (info == NULL) {
  333. WOLFSSL_MSG("malloc failed");
  334. ret = 0;
  335. }
  336. }
  337. #endif
  338. if (ret == 0) {
  339. /* Clear the encrypted info and set name. */
  340. XMEMSET(info, 0, sizeof(EncryptedInfo));
  341. XSTRNCPY(info->name, cipher, NAME_SZ - 1);
  342. info->name[NAME_SZ - 1] = '\0'; /* null term */
  343. /* Get encrypted info from name. */
  344. ret = wc_EncryptedInfoGet(info, info->name);
  345. if (ret != 0) {
  346. WOLFSSL_MSG("unsupported cipher");
  347. }
  348. }
  349. if (ret == 0) {
  350. /* Generate a random salt. */
  351. if (wolfSSL_RAND_bytes(info->iv, info->ivSz) != 1) {
  352. WOLFSSL_MSG("generate iv failed");
  353. ret = -1;
  354. }
  355. }
  356. if (ret == 0) {
  357. /* Calculate padding size - always a padding block. */
  358. paddingSz = info->ivSz - ((*derSz) % info->ivSz);
  359. /* Check der is big enough. */
  360. if (maxDerSz < (*derSz) + paddingSz) {
  361. WOLFSSL_MSG("not enough DER buffer allocated");
  362. ret = BAD_FUNC_ARG;
  363. }
  364. }
  365. if (ret == 0) {
  366. /* Set padding bytes to padding length. */
  367. XMEMSET(der + (*derSz), (byte)paddingSz, paddingSz);
  368. /* Add padding to DER size. */
  369. (*derSz) += (int)paddingSz;
  370. /* Encrypt DER buffer. */
  371. ret = wc_BufferKeyEncrypt(info, der, *derSz, passwd, passwdSz, WC_MD5);
  372. if (ret != 0) {
  373. WOLFSSL_MSG("encrypt key failed");
  374. }
  375. }
  376. if (ret == 0) {
  377. /* Create cipher info : 'cipher_name,Salt(hex)' */
  378. cipherInfoSz = (word32)(2 * info->ivSz + XSTRLEN(info->name) + 2);
  379. /* Allocate memory for PEM encryption lines. */
  380. *cipherInfo = (byte*)XMALLOC(cipherInfoSz, NULL, DYNAMIC_TYPE_STRING);
  381. if (*cipherInfo == NULL) {
  382. WOLFSSL_MSG("malloc failed");
  383. ret = MEMORY_E;
  384. }
  385. }
  386. if (ret == 0) {
  387. /* Copy in name and add on comma. */
  388. XSTRLCPY((char*)*cipherInfo, info->name, cipherInfoSz);
  389. XSTRLCAT((char*)*cipherInfo, ",", cipherInfoSz);
  390. /* Find end of string. */
  391. idx = (word32)XSTRLEN((char*)*cipherInfo);
  392. /* Calculate remaining bytes. */
  393. cipherInfoSz -= idx;
  394. /* Encode IV into PEM encryption lines. */
  395. ret = Base16_Encode(info->iv, info->ivSz, *cipherInfo + idx,
  396. &cipherInfoSz);
  397. if (ret != 0) {
  398. WOLFSSL_MSG("Base16_Encode failed");
  399. XFREE(*cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  400. *cipherInfo = NULL;
  401. }
  402. }
  403. #ifdef WOLFSSL_SMALL_STACK
  404. /* Free dynamically allocated info. */
  405. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  406. #endif
  407. return ret == 0;
  408. }
  409. #endif /* WOLFSSL_KEY_GEN || WOLFSSL_PEM_TO_DER */
  410. #if defined(WOLFSSL_KEY_GEN) && \
  411. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  412. (!defined(NO_RSA) || defined(HAVE_ECC))
  413. /* Encrypt the DER in PEM format.
  414. *
  415. * @param [in] der DER encoded private key.
  416. * @param [in] derSz Size of DER in bytes.
  417. * @param [in] cipher EVP cipher.
  418. * @param [in] passwd Password to use in encryption.
  419. * @param [in] passwdSz Size of password in bytes.
  420. * @param [in] type PEM type of write out.
  421. * @param [in] heap Dynamic memory hint.
  422. * @param [out] out Allocated buffer containing PEM encoding.
  423. * heap was NULL and dynamic type is DYNAMIC_TYPE_KEY.
  424. * @param [out] outSz Size of PEM encoding in bytes.
  425. * @return 1 on success.
  426. * @return 0 on failure.
  427. */
  428. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  429. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  430. void* heap, byte** out, int* outSz)
  431. {
  432. int ret = 1;
  433. byte* tmp = NULL;
  434. byte* cipherInfo = NULL;
  435. int pemSz = 0;
  436. /* Macro doesn't always use it. */
  437. (void)heap;
  438. /* Encrypt DER buffer if required. */
  439. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  440. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  441. byte *tmpBuf;
  442. /* Add space for padding. */
  443. tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
  444. DYNAMIC_TYPE_TMP_BUFFER);
  445. if (tmpBuf == NULL) {
  446. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  447. ret = 0; /* der buffer is free'd at the end of the function */
  448. }
  449. else {
  450. der = tmpBuf;
  451. /* Encrypt DER inline. */
  452. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  453. &cipherInfo, derSz + blockSz);
  454. if (ret != 1) {
  455. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  456. }
  457. }
  458. }
  459. if (ret == 1) {
  460. /* Calculate PEM encoding size. */
  461. pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
  462. if (pemSz <= 0) {
  463. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  464. ret = 0;
  465. }
  466. }
  467. if (ret == 1) {
  468. /* Allocate space for PEM encoding plus a NUL terminator. */
  469. tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
  470. if (tmp == NULL) {
  471. WOLFSSL_ERROR_MSG("malloc failed");
  472. ret = 0;
  473. }
  474. }
  475. if (ret == 1) {
  476. /* DER to PEM */
  477. pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
  478. cipherInfo, type);
  479. if (pemSz <= 0) {
  480. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  481. ret = 0;
  482. }
  483. }
  484. if (ret == 1) {
  485. /* NUL terminate string - PEM. */
  486. tmp[pemSz] = 0x00;
  487. /* Return allocated buffer and size. */
  488. *out = tmp;
  489. *outSz = pemSz;
  490. /* Don't free returning buffer. */
  491. tmp = NULL;
  492. }
  493. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  494. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  495. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  496. return ret;
  497. }
  498. #endif
  499. #endif /* !NO_ASN */
  500. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  501. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  502. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  503. /* Print the number bn in hex with name field and indentation indent to file fp.
  504. *
  505. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  506. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  507. *
  508. * @param [in] fp File pointer to write to.
  509. * @param [in] indent Number of spaces to prepend to each line.
  510. * @param [in] field Name of field.
  511. * @param [in] bn Big number to print.
  512. * @return 1 on success.
  513. * @return 0 on failure.
  514. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  515. * bn or NULL.
  516. */
  517. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  518. const WOLFSSL_BIGNUM* bn)
  519. {
  520. static const int HEX_INDENT = 4;
  521. static const int MAX_DIGITS_PER_LINE = 30;
  522. int ret = 1;
  523. int i = 0;
  524. char* buf = NULL;
  525. /* Internal function - assume parameters are valid. */
  526. /* Convert BN to hexadecimal character array (allocates buffer). */
  527. buf = wolfSSL_BN_bn2hex(bn);
  528. if (buf == NULL) {
  529. ret = 0;
  530. }
  531. if (ret == 1) {
  532. /* Print leading spaces, name and spaces before data. */
  533. if (indent > 0) {
  534. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  535. ret = 0;
  536. }
  537. }
  538. if (ret == 1) {
  539. if (XFPRINTF(fp, "%s:\n", field) < 0)
  540. ret = 0;
  541. }
  542. if (ret == 1) {
  543. if (indent > 0) {
  544. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  545. ret = 0;
  546. }
  547. }
  548. if (ret == 1) {
  549. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  550. ret = 0;
  551. }
  552. if (ret == 1) {
  553. /* Print first byte - should always exist. */
  554. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  555. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  556. ret = 0;
  557. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  558. ret = 0;
  559. }
  560. }
  561. if (ret == 1) {
  562. /* Print each hexadecimal character with byte separator. */
  563. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  564. /* Byte separator every two nibbles - one byte. */
  565. if (XFPRINTF(fp, ":") < 0) {
  566. ret = 0;
  567. break;
  568. }
  569. /* New line after every 15 bytes - 30 nibbles. */
  570. if (i % MAX_DIGITS_PER_LINE == 0) {
  571. if (XFPRINTF(fp, "\n") < 0) {
  572. ret = 0;
  573. break;
  574. }
  575. if (indent > 0) {
  576. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  577. ret = 0;
  578. break;
  579. }
  580. }
  581. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  582. ret = 0;
  583. break;
  584. }
  585. }
  586. /* Print two nibbles - one byte. */
  587. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  588. ret = 0;
  589. break;
  590. }
  591. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  592. ret = 0;
  593. break;
  594. }
  595. }
  596. /* Ensure on new line after data. */
  597. if (XFPRINTF(fp, "\n") < 0) {
  598. ret = 0;
  599. }
  600. }
  601. /* Dispose of any allocated character array. */
  602. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  603. return ret;
  604. }
  605. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  606. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  607. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA)
  608. /* snprintf() must be available */
  609. /* Maximum number of extra indent spaces on each line. */
  610. #define PRINT_NUM_MAX_INDENT 48
  611. /* Maximum size of a line containing a value. */
  612. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  613. /* Number of leading spaces on each line. */
  614. #define PRINT_NUM_INDENT_CNT 4
  615. /* Indent spaces for number lines. */
  616. #define PRINT_NUM_INDENT " "
  617. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  618. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  619. /* Print indent to BIO.
  620. *
  621. * @param [in] bio BIO object to write to.
  622. * @param [in] line Buffer to put characters to before writing to BIO.
  623. * @param [in] lineLen Length of buffer.
  624. * @return 1 on success.
  625. * @return 0 on failure.
  626. */
  627. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  628. int indent)
  629. {
  630. int ret = 1;
  631. if (indent > 0) {
  632. /* Print indent spaces. */
  633. int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
  634. if (len_wanted >= lineLen) {
  635. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  636. ret = 0;
  637. }
  638. else {
  639. /* Write indents string to BIO */
  640. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  641. ret = 0;
  642. }
  643. }
  644. }
  645. return ret;
  646. }
  647. /* Print out name, and value in decimal and hex to BIO.
  648. *
  649. * @param [in] bio BIO object to write to.
  650. * @param [in] value MP integer to write.
  651. * @param [in] name Name of value.
  652. * @param [in] indent Number of leading spaces before line.
  653. * @return 1 on success.
  654. * @return 0 on failure.
  655. */
  656. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  657. const char* name, int indent)
  658. {
  659. int ret = 1;
  660. int len;
  661. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  662. /* Get the length of hex encoded value. */
  663. len = mp_unsigned_bin_size(value);
  664. /* Value must no more than 32-bits - 4 bytes. */
  665. if ((len < 0) || (len > 4)) {
  666. WOLFSSL_ERROR_MSG("Error getting exponent size");
  667. ret = 0;
  668. }
  669. if (ret == 1) {
  670. /* Print any indent spaces. */
  671. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  672. }
  673. if (ret == 1) {
  674. /* Get 32-bits of value. */
  675. word32 v = (word32)value->dp[0];
  676. /* Print the line to the string. */
  677. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  678. v);
  679. if (len >= (int)sizeof(line)) {
  680. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  681. ret = 0;
  682. } else {
  683. /* Write string to BIO */
  684. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  685. ret = 0;
  686. }
  687. }
  688. }
  689. return ret;
  690. }
  691. /* Print out name and multi-precision number to BIO.
  692. *
  693. * @param [in] bio BIO object to write to.
  694. * @param [in] num MP integer to write.
  695. * @param [in] name Name of value.
  696. * @param [in] indent Number of leading spaces before each line.
  697. * @return 1 on success.
  698. * @return 0 on failure.
  699. */
  700. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  701. int indent)
  702. {
  703. int ret = 1;
  704. int rawLen = 0;
  705. byte* rawKey = NULL;
  706. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  707. int li = 0; /* Line index. */
  708. int i;
  709. /* Allocate a buffer to hold binary encoded data. */
  710. rawLen = mp_unsigned_bin_size(num);
  711. if (rawLen == 0) {
  712. WOLFSSL_ERROR_MSG("Invalid number");
  713. ret = 0;
  714. }
  715. if (ret == 1) {
  716. rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  717. if (rawKey == NULL) {
  718. WOLFSSL_ERROR_MSG("Memory allocation error");
  719. ret = 0;
  720. }
  721. }
  722. /* Encode number as big-endian byte array. */
  723. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  724. ret = 0;
  725. }
  726. if (ret == 1) {
  727. /* Print any indent spaces. */
  728. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  729. }
  730. if (ret == 1) {
  731. /* Print header string line to string. */
  732. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  733. if (li >= (int)sizeof(line)) {
  734. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  735. ret = 0;
  736. }
  737. else {
  738. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  739. ret = 0;
  740. }
  741. }
  742. }
  743. if (ret == 1) {
  744. /* Print any indent spaces. */
  745. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  746. }
  747. if (ret == 1) {
  748. /* Start first digit line with spaces.
  749. * Writing out zeros ensures number is a positive value. */
  750. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  751. mp_leading_bit(num) ? "00:" : "");
  752. if (li >= (int)sizeof(line)) {
  753. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  754. ret = 0;
  755. }
  756. }
  757. /* Put out each line of numbers. */
  758. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  759. /* Encode another byte as 2 hex digits and append colon. */
  760. int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
  761. "%02x:", rawKey[i]);
  762. /* Check if there was room -- if not, print the current line, not
  763. * including the newest octet.
  764. */
  765. if (len_wanted >= (int)sizeof(line) - li) {
  766. /* bump current octet to the next line. */
  767. --i;
  768. /* More bytes coming so add a line break. */
  769. line[li++] = '\n';
  770. /* Write out the line. */
  771. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  772. ret = 0;
  773. }
  774. if (ret == 1) {
  775. /* Print any indent spaces. */
  776. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  777. }
  778. /* Put the leading spaces on new line. */
  779. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  780. li = PRINT_NUM_INDENT_CNT;
  781. }
  782. else {
  783. li += len_wanted;
  784. }
  785. }
  786. if (ret == 1) {
  787. /* Put out last line - replace last colon with carriage return. */
  788. line[li-1] = '\n';
  789. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  790. ret = 0;
  791. }
  792. }
  793. /* Dispose of any allocated data. */
  794. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  795. return ret;
  796. }
  797. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA */
  798. #endif /* OPENSSL_EXTRA */
  799. #if !defined(NO_CERTS) || (defined(OPENSSL_EXTRA) && (!defined(NO_RSA) || \
  800. (!defined(NO_DH) && defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || \
  801. defined(HAVE_ECC)))
  802. /* Uses the DER SEQUENCE to determine size of DER data.
  803. *
  804. * Outer SEQUENCE encapsulates all the DER encoding.
  805. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  806. *
  807. * @param [in] seq Buffer holding DER encoded sequence.
  808. * @param [in] len Length of data in buffer (may be larger than SEQ).
  809. * @return Size of complete DER encoding on success.
  810. * @return 0 on failure.
  811. */
  812. static int wolfssl_der_length(const unsigned char* seq, int len)
  813. {
  814. int ret = 0;
  815. word32 i = 0;
  816. /* Check it is a SEQUENCE and get the length of the underlying data.
  817. * i is updated to be after SEQUENCE header bytes.
  818. */
  819. if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
  820. /* Add SEQUENCE header length to underlying data length. */
  821. ret += (int)i;
  822. }
  823. return ret;
  824. }
  825. #endif
  826. /*******************************************************************************
  827. * START OF RSA API
  828. ******************************************************************************/
  829. #ifndef NO_RSA
  830. /*
  831. * RSA METHOD
  832. * Could be used to hold function pointers to implementations of RSA operations.
  833. */
  834. #if defined(OPENSSL_EXTRA)
  835. /* Return a blank RSA method and set the name and flags.
  836. *
  837. * Only one implementation of RSA operations.
  838. * name is duplicated.
  839. *
  840. * @param [in] name Name to use in method.
  841. * @param [in] flags Flags to set into method.
  842. * @return Newly allocated RSA method on success.
  843. * @return NULL on failure.
  844. */
  845. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  846. {
  847. WOLFSSL_RSA_METHOD* meth = NULL;
  848. int name_len = 0;
  849. int err;
  850. /* Validate name is not NULL. */
  851. err = (name == NULL);
  852. if (!err) {
  853. /* Allocate an RSA METHOD to return. */
  854. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  855. DYNAMIC_TYPE_OPENSSL);
  856. err = (meth == NULL);
  857. }
  858. if (!err) {
  859. XMEMSET(meth, 0, sizeof(*meth));
  860. meth->flags = flags;
  861. meth->dynamic = 1;
  862. name_len = (int)XSTRLEN(name);
  863. meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL,
  864. DYNAMIC_TYPE_OPENSSL);
  865. err = (meth->name == NULL);
  866. }
  867. if (!err) {
  868. XMEMCPY(meth->name, name, (size_t)(name_len + 1));
  869. }
  870. if (err) {
  871. /* meth->name won't be allocated on error. */
  872. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  873. meth = NULL;
  874. }
  875. return meth;
  876. }
  877. /* Default RSA method is one with wolfSSL name and no flags.
  878. *
  879. * @return Newly allocated wolfSSL RSA method on success.
  880. * @return NULL on failure.
  881. */
  882. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  883. {
  884. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  885. 0, /* No flags. */
  886. (char*)"wolfSSL RSA",
  887. 0 /* Static definition. */
  888. };
  889. return &wolfssl_rsa_meth;
  890. }
  891. /* Dispose of RSA method and allocated data.
  892. *
  893. * @param [in] meth RSA method to free.
  894. */
  895. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  896. {
  897. /* Free method if available and dynamically allocated. */
  898. if ((meth != NULL) && meth->dynamic) {
  899. /* Name was duplicated and must be freed. */
  900. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  901. /* Dispose of RSA method. */
  902. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  903. }
  904. }
  905. #ifndef NO_WOLFSSL_STUB
  906. /* Stub function for any RSA method setting function.
  907. *
  908. * Nothing is stored - not even flags or name.
  909. *
  910. * @param [in] meth RSA method.
  911. * @param [in] p A pointer.
  912. * @return 1 to indicate success.
  913. */
  914. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  915. {
  916. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  917. (void)meth;
  918. (void)p;
  919. return 1;
  920. }
  921. #endif /* !NO_WOLFSSL_STUB */
  922. #endif /* OPENSSL_EXTRA */
  923. /*
  924. * RSA constructor/deconstructor APIs
  925. */
  926. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  927. /* Dispose of RSA key and allocated data.
  928. *
  929. * Cannot use rsa after this call.
  930. *
  931. * @param [in] rsa RSA key to free.
  932. */
  933. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  934. {
  935. int doFree = 1;
  936. WOLFSSL_ENTER("wolfSSL_RSA_free");
  937. /* Validate parameter. */
  938. if (rsa == NULL) {
  939. doFree = 0;
  940. }
  941. if (doFree) {
  942. int err;
  943. /* Decrement reference count. */
  944. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  945. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  946. (void)err;
  947. #endif
  948. }
  949. if (doFree) {
  950. void* heap = rsa->heap;
  951. /* Dispose of allocated reference counting data. */
  952. wolfSSL_RefFree(&rsa->ref);
  953. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  954. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  955. #endif
  956. if (rsa->internal != NULL) {
  957. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  958. /* Check if RNG is owned before freeing it. */
  959. if (rsa->ownRng) {
  960. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  961. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  962. wc_FreeRng(rng);
  963. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  964. }
  965. /* RNG isn't freed by wolfCrypt RSA free. */
  966. }
  967. #endif
  968. /* Dispose of allocated data in wolfCrypt RSA key. */
  969. wc_FreeRsaKey((RsaKey*)rsa->internal);
  970. /* Dispose of memory for wolfCrypt RSA key. */
  971. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  972. }
  973. /* Dispose of external representation of RSA values. */
  974. wolfSSL_BN_clear_free(rsa->iqmp);
  975. wolfSSL_BN_clear_free(rsa->dmq1);
  976. wolfSSL_BN_clear_free(rsa->dmp1);
  977. wolfSSL_BN_clear_free(rsa->q);
  978. wolfSSL_BN_clear_free(rsa->p);
  979. wolfSSL_BN_clear_free(rsa->d);
  980. wolfSSL_BN_free(rsa->e);
  981. wolfSSL_BN_free(rsa->n);
  982. #if defined(OPENSSL_EXTRA)
  983. if (rsa->meth) {
  984. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  985. }
  986. #endif
  987. /* Set back to NULLs for safety. */
  988. ForceZero(rsa, sizeof(*rsa));
  989. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  990. (void)heap;
  991. }
  992. }
  993. /* Allocate and initialize a new RSA key.
  994. *
  995. * Not OpenSSL API.
  996. *
  997. * @param [in] heap Heap hint for dynamic memory allocation.
  998. * @param [in] devId Device identifier value.
  999. * @return RSA key on success.
  1000. * @return NULL on failure.
  1001. */
  1002. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  1003. {
  1004. WOLFSSL_RSA* rsa = NULL;
  1005. RsaKey* key = NULL;
  1006. int err = 0;
  1007. int rsaKeyInited = 0;
  1008. WOLFSSL_ENTER("wolfSSL_RSA_new");
  1009. /* Allocate memory for new wolfCrypt RSA key. */
  1010. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  1011. if (key == NULL) {
  1012. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  1013. err = 1;
  1014. }
  1015. if (!err) {
  1016. /* Allocate memory for new RSA key. */
  1017. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  1018. DYNAMIC_TYPE_RSA);
  1019. if (rsa == NULL) {
  1020. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  1021. err = 1;
  1022. }
  1023. }
  1024. if (!err) {
  1025. /* Clear all fields of RSA key. */
  1026. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  1027. /* Cache heap to use for all allocations. */
  1028. rsa->heap = heap;
  1029. #ifdef OPENSSL_EXTRA
  1030. /* Always have a method set. */
  1031. rsa->meth = wolfSSL_RSA_get_default_method();
  1032. #endif
  1033. /* Initialize reference counting. */
  1034. wolfSSL_RefInit(&rsa->ref, &err);
  1035. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  1036. }
  1037. if (!err) {
  1038. #endif
  1039. /* Initialize wolfCrypt RSA key. */
  1040. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  1041. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  1042. err = 1;
  1043. }
  1044. else {
  1045. rsaKeyInited = 1;
  1046. }
  1047. }
  1048. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  1049. if (!err) {
  1050. WC_RNG* rng;
  1051. /* Create a local RNG. */
  1052. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  1053. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  1054. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  1055. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  1056. rng = NULL;
  1057. }
  1058. rsa->ownRng = 1;
  1059. if (rng == NULL) {
  1060. /* Get the wolfSSL global RNG - not thread safe. */
  1061. rng = wolfssl_get_global_rng();
  1062. rsa->ownRng = 0;
  1063. }
  1064. if (rng == NULL) {
  1065. /* Couldn't create global either. */
  1066. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  1067. err = 1;
  1068. }
  1069. else {
  1070. /* Set the local or global RNG into the wolfCrypt RSA key. */
  1071. (void)wc_RsaSetRNG(key, rng);
  1072. /* Won't fail as key and rng are not NULL. */
  1073. }
  1074. }
  1075. #endif /* !HAVE_FIPS && WC_RSA_BLINDING */
  1076. if (!err) {
  1077. /* Set wolfCrypt RSA key into RSA key. */
  1078. rsa->internal = key;
  1079. /* Data from external RSA key has not been set into internal one. */
  1080. rsa->inSet = 0;
  1081. }
  1082. if (err) {
  1083. /* Dispose of any allocated data on error. */
  1084. /* No failure after RNG allocation - no need to free RNG. */
  1085. if (rsaKeyInited) {
  1086. wc_FreeRsaKey(key);
  1087. }
  1088. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  1089. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  1090. /* Return NULL. */
  1091. rsa = NULL;
  1092. }
  1093. return rsa;
  1094. }
  1095. /* Allocate and initialize a new RSA key.
  1096. *
  1097. * @return RSA key on success.
  1098. * @return NULL on failure.
  1099. */
  1100. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  1101. {
  1102. /* Call wolfSSL API to do work. */
  1103. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  1104. }
  1105. /* Increments ref count of RSA key.
  1106. *
  1107. * @param [in, out] rsa RSA key.
  1108. * @return 1 on success
  1109. * @return 0 on error
  1110. */
  1111. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  1112. {
  1113. int err = 0;
  1114. if (rsa != NULL) {
  1115. wolfSSL_RefInc(&rsa->ref, &err);
  1116. }
  1117. return !err;
  1118. }
  1119. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1120. #ifdef OPENSSL_EXTRA
  1121. #if defined(WOLFSSL_KEY_GEN)
  1122. /* Allocate a new RSA key and make it a copy.
  1123. *
  1124. * Encodes to and from DER to copy.
  1125. *
  1126. * @param [in] rsa RSA key to duplicate.
  1127. * @return RSA key on success.
  1128. * @return NULL on error.
  1129. */
  1130. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1131. {
  1132. WOLFSSL_RSA* ret = NULL;
  1133. int derSz = 0;
  1134. byte* derBuf = NULL;
  1135. int err;
  1136. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1137. err = (rsa == NULL);
  1138. if (!err) {
  1139. /* Create a new RSA key to return. */
  1140. ret = wolfSSL_RSA_new();
  1141. if (ret == NULL) {
  1142. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1143. err = 1;
  1144. }
  1145. }
  1146. if (!err) {
  1147. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1148. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1149. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1150. err = 1;
  1151. }
  1152. }
  1153. if (!err) {
  1154. /* Decode DER of the RSA public key into new key. */
  1155. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1156. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1157. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1158. err = 1;
  1159. }
  1160. }
  1161. /* Dispose of any allocated DER buffer. */
  1162. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1163. if (err) {
  1164. /* Disposes of any created RSA key - on error. */
  1165. wolfSSL_RSA_free(ret);
  1166. ret = NULL;
  1167. }
  1168. return ret;
  1169. }
  1170. /* wolfSSL_RSAPrivateKey_dup not supported */
  1171. #endif /* WOLFSSL_KEY_GEN */
  1172. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1173. void* heap);
  1174. /*
  1175. * RSA to/from bin APIs
  1176. */
  1177. /* Convert RSA public key data to internal.
  1178. *
  1179. * Creates new RSA key from the DER encoded RSA public key.
  1180. *
  1181. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1182. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1183. * @param [in] derSz Length of the data in the DER buffer.
  1184. * @return RSA key on success.
  1185. * @return NULL on failure.
  1186. */
  1187. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1188. const unsigned char **derBuf, long derSz)
  1189. {
  1190. WOLFSSL_RSA *rsa = NULL;
  1191. int err = 0;
  1192. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1193. /* Validate parameters. */
  1194. if (derBuf == NULL) {
  1195. WOLFSSL_ERROR_MSG("Bad argument");
  1196. err = 1;
  1197. }
  1198. /* Create a new RSA key to return. */
  1199. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1200. WOLFSSL_ERROR_MSG("RSA_new failed");
  1201. err = 1;
  1202. }
  1203. /* Decode RSA key from DER. */
  1204. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1205. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1206. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1207. err = 1;
  1208. }
  1209. if ((!err) && (out != NULL)) {
  1210. /* Return through parameter too. */
  1211. *out = rsa;
  1212. /* Move buffer on by the used amount. */
  1213. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1214. }
  1215. if (err) {
  1216. /* Dispose of any created RSA key. */
  1217. wolfSSL_RSA_free(rsa);
  1218. rsa = NULL;
  1219. }
  1220. return rsa;
  1221. }
  1222. /* Convert RSA private key data to internal.
  1223. *
  1224. * Create a new RSA key from the DER encoded RSA private key.
  1225. *
  1226. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1227. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1228. * @param [in] derSz Length of the data in the DER buffer.
  1229. * @return RSA key on success.
  1230. * @return NULL on failure.
  1231. */
  1232. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1233. const unsigned char **derBuf, long derSz)
  1234. {
  1235. WOLFSSL_RSA *rsa = NULL;
  1236. int err = 0;
  1237. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1238. /* Validate parameters. */
  1239. if (derBuf == NULL) {
  1240. WOLFSSL_ERROR_MSG("Bad argument");
  1241. err = 1;
  1242. }
  1243. /* Create a new RSA key to return. */
  1244. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1245. WOLFSSL_ERROR_MSG("RSA_new failed");
  1246. err = 1;
  1247. }
  1248. /* Decode RSA key from DER. */
  1249. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1250. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1251. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1252. err = 1;
  1253. }
  1254. if ((!err) && (out != NULL)) {
  1255. /* Return through parameter too. */
  1256. *out = rsa;
  1257. /* Move buffer on by the used amount. */
  1258. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1259. }
  1260. if (err) {
  1261. /* Dispose of any created RSA key. */
  1262. wolfSSL_RSA_free(rsa);
  1263. rsa = NULL;
  1264. }
  1265. return rsa;
  1266. }
  1267. /* Converts an internal RSA structure to DER format for the private key.
  1268. *
  1269. * If "pp" is null then buffer size only is returned.
  1270. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1271. * responsible for free'ing it.
  1272. *
  1273. * @param [in] rsa RSA key.
  1274. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1275. * May be NULL.
  1276. * On out, newly allocated buffer or pointer to byte after
  1277. * encoding in passed in buffer.
  1278. *
  1279. * @return Size of DER encoding on success
  1280. * @return BAD_FUNC_ARG when rsa is NULL.
  1281. * @return 0 on failure.
  1282. */
  1283. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1284. {
  1285. int ret;
  1286. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1287. /* Validate parameters. */
  1288. if (rsa == NULL) {
  1289. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1290. ret = BAD_FUNC_ARG;
  1291. }
  1292. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1293. * No heap hint as this gets returned to the user */
  1294. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1295. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1296. ret = 0;
  1297. }
  1298. /* Size of DER encoding. */
  1299. return ret;
  1300. }
  1301. /* Converts an internal RSA structure to DER format for the public key.
  1302. *
  1303. * If "pp" is null then buffer size only is returned.
  1304. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1305. * responsible for free'ing it.
  1306. *
  1307. * @param [in] rsa RSA key.
  1308. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1309. * May be NULL.
  1310. * On out, newly allocated buffer or pointer to byte after
  1311. * encoding in passed in buffer.
  1312. * @return Size of DER encoding on success
  1313. * @return BAD_FUNC_ARG when rsa is NULL.
  1314. * @return 0 on failure.
  1315. */
  1316. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1317. {
  1318. int ret;
  1319. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1320. /* check for bad functions arguments */
  1321. if (rsa == NULL) {
  1322. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1323. ret = BAD_FUNC_ARG;
  1324. }
  1325. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1326. * No heap hint as this gets returned to the user */
  1327. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1328. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1329. ret = 0;
  1330. }
  1331. return ret;
  1332. }
  1333. #endif /* OPENSSL_EXTRA */
  1334. /*
  1335. * RSA to/from BIO APIs
  1336. */
  1337. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1338. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1339. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1340. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_BIO)
  1341. /* Read DER data from a BIO.
  1342. *
  1343. * DER structures start with a constructed sequence. Use this to calculate the
  1344. * total length of the DER data.
  1345. *
  1346. * @param [in] bio BIO object to read from.
  1347. * @param [out] out Buffer holding DER encoding.
  1348. * @return Number of bytes to DER encoding on success.
  1349. * @return 0 on failure.
  1350. */
  1351. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1352. {
  1353. int err = 0;
  1354. unsigned char seq[MAX_SEQ_SZ];
  1355. unsigned char* der = NULL;
  1356. int derLen = 0;
  1357. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1358. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1359. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1360. err = 1;
  1361. }
  1362. /* Calculate complete DER encoding length. */
  1363. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1364. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1365. err = 1;
  1366. }
  1367. /* Allocate a buffer to read DER data into. */
  1368. if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap,
  1369. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1370. WOLFSSL_ERROR_MSG("Malloc failure");
  1371. err = 1;
  1372. }
  1373. if (!err) {
  1374. /* Calculate the unread amount. */
  1375. int len = derLen - (int)sizeof(seq);
  1376. /* Copy the previously read data into the buffer. */
  1377. XMEMCPY(der, seq, sizeof(seq));
  1378. /* Read rest of DER data from BIO. */
  1379. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1380. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1381. err = 1;
  1382. }
  1383. }
  1384. if (!err) {
  1385. /* Return buffer through parameter. */
  1386. *out = der;
  1387. }
  1388. if (err) {
  1389. /* Dispose of any allocated buffer on error. */
  1390. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1391. derLen = 0;
  1392. }
  1393. return derLen;
  1394. }
  1395. /* Reads the RSA private key data from a BIO to the internal form.
  1396. *
  1397. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1398. *
  1399. * @param [in] bio BIO object to read from.
  1400. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1401. * @return RSA key on success.
  1402. * @return NULL on failure.
  1403. */
  1404. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1405. {
  1406. WOLFSSL_RSA* key = NULL;
  1407. unsigned char* der = NULL;
  1408. int derLen = 0;
  1409. int err;
  1410. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1411. /* Validate parameters. */
  1412. err = (bio == NULL);
  1413. /* Read just DER encoding from BIO - buffer allocated in call. */
  1414. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1415. err = 1;
  1416. }
  1417. if (!err) {
  1418. /* Keep der for call to deallocate. */
  1419. const unsigned char* cder = der;
  1420. /* Create an RSA key from the data from the BIO. */
  1421. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1422. err = (key == NULL);
  1423. }
  1424. if ((!err) && (out != NULL)) {
  1425. /* Return the created RSA key through the parameter. */
  1426. *out = key;
  1427. }
  1428. if (err) {
  1429. /* Dispose of created key on error. */
  1430. wolfSSL_RSA_free(key);
  1431. key = NULL;
  1432. }
  1433. /* Dispose of allocated data. */
  1434. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1435. return key;
  1436. }
  1437. #endif /* defined(WOLFSSL_KEY_GEN) && !NO_BIO */
  1438. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1439. /*
  1440. * RSA DER APIs
  1441. */
  1442. #ifdef OPENSSL_EXTRA
  1443. /* Create a DER encoding of key.
  1444. *
  1445. * Not OpenSSL API.
  1446. *
  1447. * @param [in] rsa RSA key.
  1448. * @param [out] outBuf Allocated buffer containing DER encoding.
  1449. * May be NULL.
  1450. * @param [in] publicKey Whether to encode as public key.
  1451. * @param [in] heap Heap hint.
  1452. * @return Encoding size on success.
  1453. * @return Negative on failure.
  1454. */
  1455. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1456. void* heap)
  1457. {
  1458. byte* p = NULL;
  1459. int ret;
  1460. if (outBuf != NULL) {
  1461. p = *outBuf;
  1462. }
  1463. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1464. if ((ret > 0) && (p != NULL)) {
  1465. *outBuf = p;
  1466. }
  1467. return ret;
  1468. }
  1469. /* Create a DER encoding of key.
  1470. *
  1471. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1472. *
  1473. * @param [in] rsa RSA key.
  1474. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1475. * May be NULL.
  1476. * On out, newly allocated buffer or pointer to byte
  1477. * after encoding in passed in buffer.
  1478. * @param [in] publicKey Whether to encode as public key.
  1479. * @param [in] heap Heap hint.
  1480. * @return Encoding size on success.
  1481. * @return Negative on failure.
  1482. */
  1483. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1484. void* heap)
  1485. {
  1486. int ret = 1;
  1487. int derSz = 0;
  1488. byte* derBuf = NULL;
  1489. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1490. /* Unused if memory is disabled. */
  1491. (void)heap;
  1492. /* Validate parameters. */
  1493. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1494. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1495. ret = BAD_FUNC_ARG;
  1496. }
  1497. /* Push external RSA data into internal RSA key if not set. */
  1498. if ((ret == 1) && (!rsa->inSet)) {
  1499. ret = SetRsaInternal(rsa);
  1500. }
  1501. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1502. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1503. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1504. ret = BAD_FUNC_ARG;
  1505. }
  1506. if (ret == 1) {
  1507. if (publicKey) {
  1508. /* Calculate length of DER encoded RSA public key. */
  1509. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1510. if (derSz < 0) {
  1511. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1512. ret = derSz;
  1513. }
  1514. }
  1515. else {
  1516. /* Calculate length of DER encoded RSA private key. */
  1517. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1518. if (derSz < 0) {
  1519. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1520. ret = derSz;
  1521. }
  1522. }
  1523. }
  1524. if ((ret == 1) && (outBuf != NULL)) {
  1525. derBuf = *outBuf;
  1526. if (derBuf == NULL) {
  1527. /* Allocate buffer to hold DER encoded RSA key. */
  1528. derBuf = (byte*)XMALLOC((size_t)derSz, heap,
  1529. DYNAMIC_TYPE_TMP_BUFFER);
  1530. if (derBuf == NULL) {
  1531. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1532. ret = MEMORY_ERROR;
  1533. }
  1534. }
  1535. }
  1536. if ((ret == 1) && (outBuf != NULL)) {
  1537. if (publicKey > 0) {
  1538. /* RSA public key to DER. */
  1539. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf,
  1540. (word32)derSz);
  1541. }
  1542. else {
  1543. /* RSA private key to DER. */
  1544. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf,
  1545. (word32)derSz);
  1546. }
  1547. if (derSz < 0) {
  1548. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1549. ret = derSz;
  1550. }
  1551. else if ((*outBuf) != NULL) {
  1552. derBuf = NULL;
  1553. *outBuf += derSz;
  1554. }
  1555. else {
  1556. /* Return allocated buffer. */
  1557. *outBuf = derBuf;
  1558. }
  1559. }
  1560. if (ret == 1) {
  1561. /* Success - return DER encoding size. */
  1562. ret = derSz;
  1563. }
  1564. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1565. /* Not returning buffer, needs to be disposed of. */
  1566. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1567. }
  1568. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1569. return ret;
  1570. }
  1571. #endif /* OPENSSL_EXTRA */
  1572. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1573. /* Load the DER encoded private RSA key.
  1574. *
  1575. * Not OpenSSL API.
  1576. *
  1577. * @param [in] rsa RSA key.
  1578. * @param [in] derBuf Buffer holding DER encoding.
  1579. * @param [in] derSz Length of DER encoding.
  1580. * @return 1 on success.
  1581. * @return -1 on failure.
  1582. */
  1583. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1584. int derSz)
  1585. {
  1586. /* Call implementation that handles both private and public keys. */
  1587. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1588. }
  1589. /* Load the DER encoded public or private RSA key.
  1590. *
  1591. * Not OpenSSL API.
  1592. *
  1593. * @param [in] rsa RSA key.
  1594. * @param [in] derBuf Buffer holding DER encoding.
  1595. * @param [in] derSz Length of DER encoding.
  1596. * @param [in] opt Indicates public or private key.
  1597. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1598. * @return 1 on success.
  1599. * @return -1 on failure.
  1600. */
  1601. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1602. int derSz, int opt)
  1603. {
  1604. int ret = 1;
  1605. int res;
  1606. word32 idx = 0;
  1607. word32 algId;
  1608. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1609. /* Validate parameters. */
  1610. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1611. (derSz <= 0)) {
  1612. WOLFSSL_ERROR_MSG("Bad function arguments");
  1613. ret = -1;
  1614. }
  1615. if (ret == 1) {
  1616. rsa->pkcs8HeaderSz = 0;
  1617. /* Check if input buffer has PKCS8 header. In the case that it does not
  1618. * have a PKCS8 header then do not error out. */
  1619. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1620. &algId);
  1621. if (res > 0) {
  1622. /* Store size of PKCS#8 header for encoding. */
  1623. WOLFSSL_MSG("Found PKCS8 header");
  1624. rsa->pkcs8HeaderSz = (word16)idx;
  1625. }
  1626. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1627. else if (res != ASN_PARSE_E) {
  1628. /* Something went wrong while decoding. */
  1629. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1630. "header");
  1631. ret = -1;
  1632. }
  1633. }
  1634. if (ret == 1) {
  1635. /* Decode private or public key data. */
  1636. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1637. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1638. (word32)derSz);
  1639. }
  1640. else {
  1641. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1642. (word32)derSz);
  1643. }
  1644. /* Check for error. */
  1645. if (res < 0) {
  1646. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1647. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1648. }
  1649. else {
  1650. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1651. }
  1652. WOLFSSL_ERROR_VERBOSE(res);
  1653. ret = -1;
  1654. }
  1655. }
  1656. if (ret == 1) {
  1657. /* Set external RSA key data from wolfCrypt key. */
  1658. if (SetRsaExternal(rsa) != 1) {
  1659. ret = -1;
  1660. }
  1661. else {
  1662. rsa->inSet = 1;
  1663. }
  1664. }
  1665. return ret;
  1666. }
  1667. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1668. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1669. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1670. /* Load DER encoded data into WOLFSSL_RSA object.
  1671. *
  1672. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1673. *
  1674. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1675. * When rsa or *rsa is NULL a new object is created.
  1676. * When not NULL and *rsa is NULL then new object
  1677. * returned through pointer.
  1678. * @param [in] in DER encoded RSA key data.
  1679. * @param [in] inSz Size of DER encoded data in bytes.
  1680. * @param [in] opt Public or private key encoded in data. Valid values:
  1681. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1682. * @return NULL on failure.
  1683. * @return WOLFSSL_RSA object on success.
  1684. */
  1685. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1686. long inSz, int opt)
  1687. {
  1688. WOLFSSL_RSA* ret = NULL;
  1689. if ((rsa != NULL) && (*rsa != NULL)) {
  1690. ret = *rsa;
  1691. }
  1692. else {
  1693. ret = wolfSSL_RSA_new();
  1694. }
  1695. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1696. != 1)) {
  1697. if ((rsa == NULL) || (ret != *rsa)) {
  1698. wolfSSL_RSA_free(ret);
  1699. }
  1700. ret = NULL;
  1701. }
  1702. if ((rsa != NULL) && (*rsa == NULL)) {
  1703. *rsa = ret;
  1704. }
  1705. return ret;
  1706. }
  1707. #endif
  1708. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1709. /*
  1710. * RSA PEM APIs
  1711. */
  1712. #ifdef OPENSSL_EXTRA
  1713. #ifndef NO_BIO
  1714. #if defined(WOLFSSL_KEY_GEN)
  1715. /* Writes PEM encoding of an RSA public key to a BIO.
  1716. *
  1717. * @param [in] bio BIO object to write to.
  1718. * @param [in] rsa RSA key to write.
  1719. * @return 1 on success.
  1720. * @return 0 on failure.
  1721. */
  1722. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1723. {
  1724. int ret = 1;
  1725. int derSz = 0;
  1726. byte* derBuf = NULL;
  1727. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1728. /* Validate parameters. */
  1729. if ((bio == NULL) || (rsa == NULL)) {
  1730. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1731. return 0;
  1732. }
  1733. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1734. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1735. ret = 0;
  1736. }
  1737. if (derBuf == NULL) {
  1738. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1739. ret = 0;
  1740. }
  1741. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1742. PUBLICKEY_TYPE) != 1)) {
  1743. ret = 0;
  1744. }
  1745. /* Dispose of DER buffer. */
  1746. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1747. return ret;
  1748. }
  1749. #endif /* WOLFSSL_KEY_GEN */
  1750. #endif /* !NO_BIO */
  1751. #if defined(WOLFSSL_KEY_GEN)
  1752. #ifndef NO_FILESYSTEM
  1753. /* Writes PEM encoding of an RSA public key to a file pointer.
  1754. *
  1755. * @param [in] fp File pointer to write to.
  1756. * @param [in] rsa RSA key to write.
  1757. * @param [in] type PEM type to write out.
  1758. * @return 1 on success.
  1759. * @return 0 on failure.
  1760. */
  1761. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1762. int type)
  1763. {
  1764. int ret = 1;
  1765. int derSz;
  1766. byte* derBuf = NULL;
  1767. /* Validate parameters. */
  1768. if ((fp == XBADFILE) || (rsa == NULL)) {
  1769. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1770. return 0;
  1771. }
  1772. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1773. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1774. ret = 0;
  1775. }
  1776. if (derBuf == NULL) {
  1777. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1778. ret = 0;
  1779. }
  1780. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1781. rsa->heap) != 1)) {
  1782. ret = 0;
  1783. }
  1784. /* Dispose of DER buffer. */
  1785. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1786. return ret;
  1787. }
  1788. /* Writes PEM encoding of an RSA public key to a file pointer.
  1789. *
  1790. * Header/footer will contain: PUBLIC KEY
  1791. *
  1792. * @param [in] fp File pointer to write to.
  1793. * @param [in] rsa RSA key to write.
  1794. * @return 1 on success.
  1795. * @return 0 on failure.
  1796. */
  1797. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1798. {
  1799. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1800. }
  1801. /* Writes PEM encoding of an RSA public key to a file pointer.
  1802. *
  1803. * Header/footer will contain: RSA PUBLIC KEY
  1804. *
  1805. * @param [in] fp File pointer to write to.
  1806. * @param [in] rsa RSA key to write.
  1807. * @return 1 on success.
  1808. * @return 0 on failure.
  1809. */
  1810. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1811. {
  1812. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1813. }
  1814. #endif /* !NO_FILESYSTEM */
  1815. #endif /* WOLFSSL_KEY_GEN */
  1816. #ifndef NO_BIO
  1817. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1818. *
  1819. * @param [in] bio BIO object to read from.
  1820. * @param [out] out RSA key created.
  1821. * @param [in] cb Password callback when PEM encrypted.
  1822. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1823. * @return RSA key on success.
  1824. * @return NULL on failure.
  1825. */
  1826. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1827. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1828. {
  1829. WOLFSSL_RSA* rsa = NULL;
  1830. DerBuffer* der = NULL;
  1831. int keyFormat = 0;
  1832. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1833. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1834. &keyFormat, &der) >= 0)) {
  1835. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1836. WOLFSSL_RSA_LOAD_PUBLIC);
  1837. if (rsa == NULL) {
  1838. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1839. }
  1840. }
  1841. FreeDer(&der);
  1842. if ((out != NULL) && (rsa != NULL)) {
  1843. *out = rsa;
  1844. }
  1845. return rsa;
  1846. }
  1847. #endif /* !NO_BIO */
  1848. #ifndef NO_FILESYSTEM
  1849. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1850. *
  1851. * Header/footer should contain: PUBLIC KEY
  1852. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1853. *
  1854. * @param [in] fp File pointer to read from.
  1855. * @param [out] out RSA key created.
  1856. * @param [in] cb Password callback when PEM encrypted.
  1857. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1858. * @return RSA key on success.
  1859. * @return NULL on failure.
  1860. */
  1861. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1862. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1863. {
  1864. WOLFSSL_RSA* rsa = NULL;
  1865. DerBuffer* der = NULL;
  1866. int keyFormat = 0;
  1867. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1868. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1869. &keyFormat, &der) >= 0)) {
  1870. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1871. WOLFSSL_RSA_LOAD_PUBLIC);
  1872. if (rsa == NULL) {
  1873. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1874. }
  1875. }
  1876. FreeDer(&der);
  1877. if ((out != NULL) && (rsa != NULL)) {
  1878. *out = rsa;
  1879. }
  1880. return rsa;
  1881. }
  1882. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1883. *
  1884. * Header/footer should contain: RSA PUBLIC KEY
  1885. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1886. *
  1887. * @param [in] fp File pointer to read from.
  1888. * @param [out] rsa RSA key created.
  1889. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1890. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1891. * May be NULL.
  1892. * @return RSA key on success.
  1893. * @return NULL on failure.
  1894. */
  1895. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1896. wc_pem_password_cb* cb, void* pass)
  1897. {
  1898. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1899. }
  1900. #endif /* NO_FILESYSTEM */
  1901. #if defined(WOLFSSL_KEY_GEN) && \
  1902. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1903. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1904. *
  1905. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1906. *
  1907. * @param [in] rsa RSA key to write.
  1908. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1909. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1910. * @param [in] passwdSz Length of password string when PEM encrypted.
  1911. * @param [out] pem Allocated buffer with PEM encoding.
  1912. * @param [out] pLen Length of PEM encoding.
  1913. * @return 1 on success.
  1914. * @return 0 on failure.
  1915. */
  1916. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1917. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1918. {
  1919. int ret = 1;
  1920. byte* derBuf = NULL;
  1921. int derSz = 0;
  1922. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1923. /* Validate parameters. */
  1924. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1925. (rsa->internal == NULL)) {
  1926. WOLFSSL_ERROR_MSG("Bad function arguments");
  1927. ret = 0;
  1928. }
  1929. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1930. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1931. ret = 0;
  1932. }
  1933. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1934. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1935. rsa->heap)) < 0)) {
  1936. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1937. ret = 0;
  1938. }
  1939. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1940. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1941. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1942. ret = 0;
  1943. }
  1944. return ret;
  1945. }
  1946. #ifndef NO_BIO
  1947. /* Writes PEM encoding of an RSA private key to a BIO.
  1948. *
  1949. * @param [in] bio BIO object to write to.
  1950. * @param [in] rsa RSA key to write.
  1951. * @param [in] cipher Cipher to use when PEM encrypted.
  1952. * @param [in] passwd Password string when PEM encrypted.
  1953. * @param [in] len Length of password string when PEM encrypted.
  1954. * @param [in] cb Password callback to use when PEM encrypted.
  1955. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1956. * @return 1 on success.
  1957. * @return 0 on failure.
  1958. */
  1959. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1960. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1961. wc_pem_password_cb* cb, void* arg)
  1962. {
  1963. int ret = 1;
  1964. byte* pem = NULL;
  1965. int pLen = 0;
  1966. (void)cb;
  1967. (void)arg;
  1968. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1969. /* Validate parameters. */
  1970. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1971. WOLFSSL_ERROR_MSG("Bad function arguments");
  1972. ret = 0;
  1973. }
  1974. if (ret == 1) {
  1975. /* Write PEM to buffer that is allocated in the call. */
  1976. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1977. &pem, &pLen);
  1978. if (ret != 1) {
  1979. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1980. }
  1981. }
  1982. /* Write PEM to BIO. */
  1983. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  1984. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1985. ret = 0;
  1986. }
  1987. /* Dispose of any allocated PEM buffer. */
  1988. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1989. return ret;
  1990. }
  1991. #endif /* !NO_BIO */
  1992. #ifndef NO_FILESYSTEM
  1993. /* Writes PEM encoding of an RSA private key to a file pointer.
  1994. *
  1995. * TODO: Support use of the password callback and callback context.
  1996. *
  1997. * @param [in] fp File pointer to write to.
  1998. * @param [in] rsa RSA key to write.
  1999. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  2000. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  2001. * @param [in] passwdSz Length of password string when PEM encrypted.
  2002. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  2003. * @param [in] arg NUL terminated string for passphrase when PEM
  2004. * encrypted. Unused.
  2005. * @return 1 on success.
  2006. * @return 0 on failure.
  2007. */
  2008. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  2009. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  2010. wc_pem_password_cb *cb, void *arg)
  2011. {
  2012. int ret = 1;
  2013. byte* pem = NULL;
  2014. int pLen = 0;
  2015. (void)cb;
  2016. (void)arg;
  2017. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  2018. /* Validate parameters. */
  2019. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  2020. WOLFSSL_ERROR_MSG("Bad function arguments");
  2021. ret = 0;
  2022. }
  2023. if (ret == 1) {
  2024. /* Write PEM to buffer that is allocated in the call. */
  2025. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  2026. &pem, &pLen);
  2027. if (ret != 1) {
  2028. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  2029. }
  2030. }
  2031. /* Write PEM to file pointer. */
  2032. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  2033. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  2034. ret = 0;
  2035. }
  2036. /* Dispose of any allocated PEM buffer. */
  2037. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  2038. return ret;
  2039. }
  2040. #endif /* NO_FILESYSTEM */
  2041. #endif /* WOLFSSL_KEY_GEN && WOLFSSL_PEM_TO_DER */
  2042. #ifndef NO_BIO
  2043. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  2044. *
  2045. * @param [in] bio BIO object to read from.
  2046. * @param [out] out RSA key created.
  2047. * @param [in] cb Password callback when PEM encrypted.
  2048. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2049. * @return RSA key on success.
  2050. * @return NULL on failure.
  2051. */
  2052. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  2053. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  2054. {
  2055. WOLFSSL_RSA* rsa = NULL;
  2056. DerBuffer* der = NULL;
  2057. int keyFormat = 0;
  2058. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  2059. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  2060. &keyFormat, &der) >= 0)) {
  2061. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2062. WOLFSSL_RSA_LOAD_PRIVATE);
  2063. if (rsa == NULL) {
  2064. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2065. }
  2066. }
  2067. FreeDer(&der);
  2068. if ((out != NULL) && (rsa != NULL)) {
  2069. *out = rsa;
  2070. }
  2071. return rsa;
  2072. }
  2073. #endif /* !NO_BIO */
  2074. /* Create an RSA private key by reading the PEM encoded data from the file
  2075. * pointer.
  2076. *
  2077. * @param [in] fp File pointer to read from.
  2078. * @param [out] out RSA key created.
  2079. * @param [in] cb Password callback when PEM encrypted.
  2080. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  2081. * @return RSA key on success.
  2082. * @return NULL on failure.
  2083. */
  2084. #ifndef NO_FILESYSTEM
  2085. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  2086. wc_pem_password_cb* cb, void* pass)
  2087. {
  2088. WOLFSSL_RSA* rsa = NULL;
  2089. DerBuffer* der = NULL;
  2090. int keyFormat = 0;
  2091. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  2092. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  2093. &keyFormat, &der) >= 0)) {
  2094. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  2095. WOLFSSL_RSA_LOAD_PRIVATE);
  2096. if (rsa == NULL) {
  2097. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  2098. }
  2099. }
  2100. FreeDer(&der);
  2101. if ((out != NULL) && (rsa != NULL)) {
  2102. *out = rsa;
  2103. }
  2104. return rsa;
  2105. }
  2106. #endif /* !NO_FILESYSTEM */
  2107. /*
  2108. * RSA print APIs
  2109. */
  2110. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  2111. !defined(NO_STDIO_FILESYSTEM)
  2112. /* Print an RSA key to a file pointer.
  2113. *
  2114. * @param [in] fp File pointer to write to.
  2115. * @param [in] rsa RSA key to write.
  2116. * @param [in] indent Number of spaces to prepend to each line.
  2117. * @return 1 on success.
  2118. * @return 0 on failure.
  2119. */
  2120. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2121. {
  2122. int ret = 1;
  2123. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2124. /* Validate parameters. */
  2125. if ((fp == XBADFILE) || (rsa == NULL)) {
  2126. ret = 0;
  2127. }
  2128. /* Set the external data from the wolfCrypt RSA key if not done. */
  2129. if ((ret == 1) && (!rsa->exSet)) {
  2130. ret = SetRsaExternal(rsa);
  2131. }
  2132. /* Get the key size from modulus if available. */
  2133. if ((ret == 1) && (rsa->n != NULL)) {
  2134. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2135. if (keySize == 0) {
  2136. ret = 0;
  2137. }
  2138. else {
  2139. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2140. ret = 0;
  2141. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2142. keySize) < 0)
  2143. ret = 0;
  2144. }
  2145. }
  2146. /* Print out any components available. */
  2147. if ((ret == 1) && (rsa->n != NULL)) {
  2148. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2149. }
  2150. if ((ret == 1) && (rsa->d != NULL)) {
  2151. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2152. }
  2153. if ((ret == 1) && (rsa->p != NULL)) {
  2154. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2155. }
  2156. if ((ret == 1) && (rsa->q != NULL)) {
  2157. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2158. }
  2159. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2160. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2161. }
  2162. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2163. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2164. }
  2165. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2166. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2167. }
  2168. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2169. return ret;
  2170. }
  2171. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2172. #if defined(XSNPRINTF) && !defined(NO_BIO)
  2173. /* snprintf() must be available */
  2174. /* Maximum size of a header line. */
  2175. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2176. /* Writes the human readable form of RSA to a BIO.
  2177. *
  2178. * @param [in] bio BIO object to write to.
  2179. * @param [in] rsa RSA key to write.
  2180. * @param [in] indent Number of spaces before each line.
  2181. * @return 1 on success.
  2182. * @return 0 on failure.
  2183. */
  2184. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2185. {
  2186. int ret = 1;
  2187. int sz = 0;
  2188. RsaKey* key = NULL;
  2189. char line[RSA_PRINT_MAX_HEADER_LINE];
  2190. int i = 0;
  2191. mp_int *num = NULL;
  2192. /* Header strings. */
  2193. const char *name[] = {
  2194. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2195. "Exponent1:", "Exponent2:", "Coefficient:"
  2196. };
  2197. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2198. /* Validate parameters. */
  2199. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2200. ret = -1;
  2201. }
  2202. if (ret == 1) {
  2203. key = (RsaKey*)rsa->internal;
  2204. /* Get size in bits of key for printing out. */
  2205. sz = wolfSSL_RSA_bits(rsa);
  2206. if (sz <= 0) {
  2207. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2208. ret = 0;
  2209. }
  2210. }
  2211. if (ret == 1) {
  2212. /* Print any indent spaces. */
  2213. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2214. }
  2215. if (ret == 1) {
  2216. /* Print header line. */
  2217. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2218. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2219. if (len >= (int)sizeof(line)) {
  2220. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2221. ret = 0;
  2222. }
  2223. else {
  2224. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2225. ret = 0;
  2226. }
  2227. }
  2228. }
  2229. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2230. /* Get mp_int for index. */
  2231. switch (i) {
  2232. case 0:
  2233. /* Print out modulus */
  2234. num = &key->n;
  2235. break;
  2236. case 1:
  2237. num = &key->e;
  2238. break;
  2239. case 2:
  2240. num = &key->d;
  2241. break;
  2242. case 3:
  2243. num = &key->p;
  2244. break;
  2245. case 4:
  2246. num = &key->q;
  2247. break;
  2248. case 5:
  2249. num = &key->dP;
  2250. break;
  2251. case 6:
  2252. num = &key->dQ;
  2253. break;
  2254. case 7:
  2255. num = &key->u;
  2256. break;
  2257. default:
  2258. WOLFSSL_ERROR_MSG("Bad index value");
  2259. }
  2260. if (i == 1) {
  2261. /* Print exponent as a 32-bit value. */
  2262. ret = wolfssl_print_value(bio, num, name[i], indent);
  2263. }
  2264. else if (!mp_iszero(num)) {
  2265. /* Print name and MP integer. */
  2266. ret = wolfssl_print_number(bio, num, name[i], indent);
  2267. }
  2268. }
  2269. return ret;
  2270. }
  2271. #endif /* XSNPRINTF && !NO_BIO */
  2272. #endif /* OPENSSL_EXTRA */
  2273. /*
  2274. * RSA get/set/test APIs
  2275. */
  2276. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2277. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2278. *
  2279. * @param [in, out] rsa RSA key.
  2280. * @return 1 on success.
  2281. * @return 0 on failure.
  2282. */
  2283. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2284. {
  2285. int ret = 1;
  2286. WOLFSSL_ENTER("SetRsaExternal");
  2287. /* Validate parameters. */
  2288. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2289. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2290. ret = -1;
  2291. }
  2292. if (ret == 1) {
  2293. RsaKey* key = (RsaKey*)rsa->internal;
  2294. /* Copy modulus. */
  2295. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2296. if (ret != 1) {
  2297. WOLFSSL_ERROR_MSG("rsa n error");
  2298. }
  2299. if (ret == 1) {
  2300. /* Copy public exponent. */
  2301. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2302. if (ret != 1) {
  2303. WOLFSSL_ERROR_MSG("rsa e error");
  2304. }
  2305. }
  2306. if (key->type == RSA_PRIVATE) {
  2307. if (ret == 1) {
  2308. /* Copy private exponent. */
  2309. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2310. if (ret != 1) {
  2311. WOLFSSL_ERROR_MSG("rsa d error");
  2312. }
  2313. }
  2314. if (ret == 1) {
  2315. /* Copy first prime. */
  2316. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2317. if (ret != 1) {
  2318. WOLFSSL_ERROR_MSG("rsa p error");
  2319. }
  2320. }
  2321. if (ret == 1) {
  2322. /* Copy second prime. */
  2323. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2324. if (ret != 1) {
  2325. WOLFSSL_ERROR_MSG("rsa q error");
  2326. }
  2327. }
  2328. #ifndef RSA_LOW_MEM
  2329. if (ret == 1) {
  2330. /* Copy d mod p-1. */
  2331. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2332. if (ret != 1) {
  2333. WOLFSSL_ERROR_MSG("rsa dP error");
  2334. }
  2335. }
  2336. if (ret == 1) {
  2337. /* Copy d mod q-1. */
  2338. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2339. if (ret != 1) {
  2340. WOLFSSL_ERROR_MSG("rsa dq error");
  2341. }
  2342. }
  2343. if (ret == 1) {
  2344. /* Copy 1/q mod p. */
  2345. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2346. if (ret != 1) {
  2347. WOLFSSL_ERROR_MSG("rsa u error");
  2348. }
  2349. }
  2350. #endif /* !RSA_LOW_MEM */
  2351. }
  2352. }
  2353. if (ret == 1) {
  2354. /* External values set. */
  2355. rsa->exSet = 1;
  2356. }
  2357. else {
  2358. /* Return 0 on failure. */
  2359. ret = 0;
  2360. }
  2361. return ret;
  2362. }
  2363. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2364. #ifdef OPENSSL_EXTRA
  2365. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2366. *
  2367. * @param [in, out] rsa RSA key.
  2368. * @return 1 on success.
  2369. * @return 0 on failure.
  2370. */
  2371. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2372. {
  2373. int ret = 1;
  2374. WOLFSSL_ENTER("SetRsaInternal");
  2375. /* Validate parameters. */
  2376. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2377. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2378. ret = -1;
  2379. }
  2380. if (ret == 1) {
  2381. RsaKey* key = (RsaKey*)rsa->internal;
  2382. /* Copy down modulus if available. */
  2383. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2384. WOLFSSL_ERROR_MSG("rsa n key error");
  2385. ret = -1;
  2386. }
  2387. /* Copy down public exponent if available. */
  2388. if ((ret == 1) && (rsa->e != NULL) &&
  2389. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2390. WOLFSSL_ERROR_MSG("rsa e key error");
  2391. ret = -1;
  2392. }
  2393. /* Enough numbers for public key */
  2394. key->type = RSA_PUBLIC;
  2395. /* Copy down private exponent if available. */
  2396. if ((ret == 1) && (rsa->d != NULL)) {
  2397. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2398. WOLFSSL_ERROR_MSG("rsa d key error");
  2399. ret = -1;
  2400. }
  2401. else {
  2402. /* Enough numbers for private key */
  2403. key->type = RSA_PRIVATE;
  2404. }
  2405. }
  2406. /* Copy down first prime if available. */
  2407. if ((ret == 1) && (rsa->p != NULL) &&
  2408. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2409. WOLFSSL_ERROR_MSG("rsa p key error");
  2410. ret = -1;
  2411. }
  2412. /* Copy down second prime if available. */
  2413. if ((ret == 1) && (rsa->q != NULL) &&
  2414. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2415. WOLFSSL_ERROR_MSG("rsa q key error");
  2416. ret = -1;
  2417. }
  2418. #ifndef RSA_LOW_MEM
  2419. /* Copy down d mod p-1 if available. */
  2420. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2421. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2422. WOLFSSL_ERROR_MSG("rsa dP key error");
  2423. ret = -1;
  2424. }
  2425. /* Copy down d mod q-1 if available. */
  2426. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2427. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2428. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2429. ret = -1;
  2430. }
  2431. /* Copy down 1/q mod p if available. */
  2432. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2433. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2434. WOLFSSL_ERROR_MSG("rsa u key error");
  2435. ret = -1;
  2436. }
  2437. #endif /* !RSA_LOW_MEM */
  2438. if (ret == 1) {
  2439. /* All available numbers have been set down. */
  2440. rsa->inSet = 1;
  2441. }
  2442. }
  2443. return ret;
  2444. }
  2445. /* Set the RSA method into object.
  2446. *
  2447. * @param [in, out] rsa RSA key.
  2448. * @param [in] meth RSA method.
  2449. * @return 1 always.
  2450. */
  2451. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2452. {
  2453. if (rsa != NULL) {
  2454. /* Store the method into object. */
  2455. rsa->meth = meth;
  2456. /* Copy over flags. */
  2457. rsa->flags = meth->flags;
  2458. }
  2459. /* OpenSSL always assumes it will work. */
  2460. return 1;
  2461. }
  2462. /* Get the RSA method from the RSA object.
  2463. *
  2464. * @param [in] rsa RSA key.
  2465. * @return RSA method on success.
  2466. * @return NULL when RSA is NULL or no method set.
  2467. */
  2468. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2469. {
  2470. return (rsa != NULL) ? rsa->meth : NULL;
  2471. }
  2472. /* Get the size in bytes of the RSA key.
  2473. *
  2474. * Return compliant with OpenSSL
  2475. *
  2476. * @param [in] rsa RSA key.
  2477. * @return RSA modulus size in bytes.
  2478. * @return 0 on error.
  2479. */
  2480. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2481. {
  2482. int ret = 0;
  2483. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2484. if (rsa != NULL) {
  2485. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2486. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2487. /* Get key size in bytes using wolfCrypt RSA key. */
  2488. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2489. }
  2490. }
  2491. return ret;
  2492. }
  2493. /* Get the size in bits of the RSA key.
  2494. *
  2495. * Uses external modulus field.
  2496. *
  2497. * @param [in] rsa RSA key.
  2498. * @return RSA modulus size in bits.
  2499. * @return 0 on error.
  2500. */
  2501. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2502. {
  2503. int ret = 0;
  2504. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2505. if (rsa != NULL) {
  2506. /* Get number of bits in external modulus. */
  2507. ret = wolfSSL_BN_num_bits(rsa->n);
  2508. }
  2509. return ret;
  2510. }
  2511. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2512. *
  2513. * Only for those that are not NULL parameters.
  2514. *
  2515. * @param [in] rsa RSA key.
  2516. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2517. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2518. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2519. */
  2520. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2521. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2522. const WOLFSSL_BIGNUM **iqmp)
  2523. {
  2524. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2525. /* For any parameters not NULL, return the BN from the key or NULL. */
  2526. if (dmp1 != NULL) {
  2527. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2528. }
  2529. if (dmq1 != NULL) {
  2530. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2531. }
  2532. if (iqmp != NULL) {
  2533. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2534. }
  2535. }
  2536. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2537. * into RSA key.
  2538. *
  2539. * If CRT parameter is NULL then there must be one in the RSA key already.
  2540. *
  2541. * @param [in, out] rsa RSA key.
  2542. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2543. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2544. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2545. * @return 1 on success.
  2546. * @return 0 on failure.
  2547. */
  2548. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2549. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2550. {
  2551. int ret = 1;
  2552. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2553. /* If a param is NULL in rsa then it must be non-NULL in the
  2554. * corresponding user input. */
  2555. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2556. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2557. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2558. WOLFSSL_ERROR_MSG("Bad parameters");
  2559. ret = 0;
  2560. }
  2561. if (ret == 1) {
  2562. /* Replace the BNs. */
  2563. if (dmp1 != NULL) {
  2564. wolfSSL_BN_clear_free(rsa->dmp1);
  2565. rsa->dmp1 = dmp1;
  2566. }
  2567. if (dmq1 != NULL) {
  2568. wolfSSL_BN_clear_free(rsa->dmq1);
  2569. rsa->dmq1 = dmq1;
  2570. }
  2571. if (iqmp != NULL) {
  2572. wolfSSL_BN_clear_free(rsa->iqmp);
  2573. rsa->iqmp = iqmp;
  2574. }
  2575. /* Set the values into the wolfCrypt RSA key. */
  2576. if (SetRsaInternal(rsa) != 1) {
  2577. if (dmp1 != NULL) {
  2578. rsa->dmp1 = NULL;
  2579. }
  2580. if (dmq1 != NULL) {
  2581. rsa->dmq1 = NULL;
  2582. }
  2583. if (iqmp != NULL) {
  2584. rsa->iqmp = NULL;
  2585. }
  2586. ret = 0;
  2587. }
  2588. }
  2589. return ret;
  2590. }
  2591. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2592. *
  2593. * @param [in] rsa RSA key.
  2594. * @param [out] p BN that is first prime. May be NULL.
  2595. * @param [out] q BN that is second prime. May be NULL.
  2596. */
  2597. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2598. const WOLFSSL_BIGNUM **q)
  2599. {
  2600. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2601. /* For any primes not NULL, return the BN from the key or NULL. */
  2602. if (p != NULL) {
  2603. *p = (rsa != NULL) ? rsa->p : NULL;
  2604. }
  2605. if (q != NULL) {
  2606. *q = (rsa != NULL) ? rsa->q : NULL;
  2607. }
  2608. }
  2609. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2610. *
  2611. * If factor parameter is NULL then there must be one in the RSA key already.
  2612. *
  2613. * @param [in, out] rsa RSA key.
  2614. * @param [in] p BN that is first prime. May be NULL.
  2615. * @param [in] q BN that is second prime. May be NULL.
  2616. * @return 1 on success.
  2617. * @return 0 on failure.
  2618. */
  2619. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2620. WOLFSSL_BIGNUM *q)
  2621. {
  2622. int ret = 1;
  2623. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2624. /* If a param is null in r then it must be non-null in the
  2625. * corresponding user input. */
  2626. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2627. ((rsa->q == NULL) && (q == NULL))) {
  2628. WOLFSSL_ERROR_MSG("Bad parameters");
  2629. ret = 0;
  2630. }
  2631. if (ret == 1) {
  2632. /* Replace the BNs. */
  2633. if (p != NULL) {
  2634. wolfSSL_BN_clear_free(rsa->p);
  2635. rsa->p = p;
  2636. }
  2637. if (q != NULL) {
  2638. wolfSSL_BN_clear_free(rsa->q);
  2639. rsa->q = q;
  2640. }
  2641. /* Set the values into the wolfCrypt RSA key. */
  2642. if (SetRsaInternal(rsa) != 1) {
  2643. if (p != NULL) {
  2644. rsa->p = NULL;
  2645. }
  2646. if (q != NULL) {
  2647. rsa->q = NULL;
  2648. }
  2649. ret = 0;
  2650. }
  2651. }
  2652. return ret;
  2653. }
  2654. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2655. * exponent, private exponent).
  2656. *
  2657. * @param [in] rsa RSA key.
  2658. * @param [out] n BN that is the modulus. May be NULL.
  2659. * @param [out] e BN that is the public exponent. May be NULL.
  2660. * @param [out] d BN that is the private exponent. May be NULL.
  2661. */
  2662. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2663. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2664. {
  2665. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2666. /* For any parameters not NULL, return the BN from the key or NULL. */
  2667. if (n != NULL) {
  2668. *n = (rsa != NULL) ? rsa->n : NULL;
  2669. }
  2670. if (e != NULL) {
  2671. *e = (rsa != NULL) ? rsa->e : NULL;
  2672. }
  2673. if (d != NULL) {
  2674. *d = (rsa != NULL) ? rsa->d : NULL;
  2675. }
  2676. }
  2677. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2678. * public exponent, private exponent).
  2679. *
  2680. * If BN parameter is NULL then there must be one in the RSA key already.
  2681. *
  2682. * @param [in,out] rsa RSA key.
  2683. * @param [in] n BN that is the modulus. May be NULL.
  2684. * @param [in] e BN that is the public exponent. May be NULL.
  2685. * @param [in] d BN that is the private exponent. May be NULL.
  2686. * @return 1 on success.
  2687. * @return 0 on failure.
  2688. */
  2689. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2690. WOLFSSL_BIGNUM *d)
  2691. {
  2692. int ret = 1;
  2693. /* If the fields n and e in r are NULL, the corresponding input
  2694. * parameters MUST be non-NULL for n and e. d may be
  2695. * left NULL (in case only the public key is used).
  2696. */
  2697. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2698. ((rsa->e == NULL) && (e == NULL))) {
  2699. ret = 0;
  2700. }
  2701. if (ret == 1) {
  2702. /* Replace the BNs. */
  2703. if (n != NULL) {
  2704. wolfSSL_BN_free(rsa->n);
  2705. rsa->n = n;
  2706. }
  2707. if (e != NULL) {
  2708. wolfSSL_BN_free(rsa->e);
  2709. rsa->e = e;
  2710. }
  2711. if (d != NULL) {
  2712. /* Private key is sensitive data. */
  2713. wolfSSL_BN_clear_free(rsa->d);
  2714. rsa->d = d;
  2715. }
  2716. /* Set the values into the wolfCrypt RSA key. */
  2717. if (SetRsaInternal(rsa) != 1) {
  2718. if (n != NULL) {
  2719. rsa->n = NULL;
  2720. }
  2721. if (e != NULL) {
  2722. rsa->e = NULL;
  2723. }
  2724. if (d != NULL) {
  2725. rsa->d = NULL;
  2726. }
  2727. ret = 0;
  2728. }
  2729. }
  2730. return ret;
  2731. }
  2732. /* Get the flags of the RSA key.
  2733. *
  2734. * @param [in] rsa RSA key.
  2735. * @return Flags set in RSA key on success.
  2736. * @return 0 when RSA key is NULL.
  2737. */
  2738. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2739. {
  2740. int ret = 0;
  2741. /* Get flags from the RSA key if available. */
  2742. if (rsa != NULL) {
  2743. ret = rsa->flags;
  2744. }
  2745. return ret;
  2746. }
  2747. /* Set the flags into the RSA key.
  2748. *
  2749. * @param [in, out] rsa RSA key.
  2750. * @param [in] flags Flags to set.
  2751. */
  2752. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2753. {
  2754. /* Add the flags into RSA key if available. */
  2755. if (rsa != NULL) {
  2756. rsa->flags |= flags;
  2757. }
  2758. }
  2759. /* Clear the flags in the RSA key.
  2760. *
  2761. * @param [in, out] rsa RSA key.
  2762. * @param [in] flags Flags to clear.
  2763. */
  2764. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2765. {
  2766. /* Clear the flags passed in that are on the RSA key if available. */
  2767. if (rsa != NULL) {
  2768. rsa->flags &= ~flags;
  2769. }
  2770. }
  2771. /* Test the flags in the RSA key.
  2772. *
  2773. * @param [in] rsa RSA key.
  2774. * @return Matching flags of RSA key on success.
  2775. * @return 0 when RSA key is NULL.
  2776. */
  2777. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2778. {
  2779. /* Return the flags passed in that are set on the RSA key if available. */
  2780. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2781. }
  2782. /* Get the extra data, by index, associated with the RSA key.
  2783. *
  2784. * @param [in] rsa RSA key.
  2785. * @param [in] idx Index of extra data.
  2786. * @return Extra data (anonymous type) on success.
  2787. * @return NULL on failure.
  2788. */
  2789. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2790. {
  2791. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2792. #ifdef HAVE_EX_DATA
  2793. return (rsa == NULL) ? NULL :
  2794. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2795. #else
  2796. (void)rsa;
  2797. (void)idx;
  2798. return NULL;
  2799. #endif
  2800. }
  2801. /* Set extra data against the RSA key at an index.
  2802. *
  2803. * @param [in, out] rsa RSA key.
  2804. * @param [in] idx Index set set extra data at.
  2805. * @param [in] data Extra data of anonymous type.
  2806. * @return 1 on success.
  2807. * @return 0 on failure.
  2808. */
  2809. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2810. {
  2811. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2812. #ifdef HAVE_EX_DATA
  2813. return (rsa == NULL) ? 0 :
  2814. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2815. #else
  2816. (void)rsa;
  2817. (void)idx;
  2818. (void)data;
  2819. return 0;
  2820. #endif
  2821. }
  2822. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2823. /* Set the extra data and cleanup callback against the RSA key at an index.
  2824. *
  2825. * Not OpenSSL API.
  2826. *
  2827. * @param [in, out] rsa RSA key.
  2828. * @param [in] idx Index set set extra data at.
  2829. * @param [in] data Extra data of anonymous type.
  2830. * @param [in] freeCb Callback function to free extra data.
  2831. * @return 1 on success.
  2832. * @return 0 on failure.
  2833. */
  2834. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2835. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2836. {
  2837. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2838. return (rsa == NULL) ? 0 :
  2839. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2840. freeCb);
  2841. }
  2842. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2843. /*
  2844. * RSA check key APIs
  2845. */
  2846. #ifdef WOLFSSL_RSA_KEY_CHECK
  2847. /* Check that the RSA key is valid using wolfCrypt.
  2848. *
  2849. * @param [in] rsa RSA key.
  2850. * @return 1 on success.
  2851. * @return 0 on failure.
  2852. */
  2853. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2854. {
  2855. int ret = 1;
  2856. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2857. /* Validate parameters. */
  2858. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2859. ret = 0;
  2860. }
  2861. /* Constant RSA - assume internal data has been set. */
  2862. /* Check wolfCrypt RSA key. */
  2863. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2864. ret = 0;
  2865. }
  2866. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2867. return ret;
  2868. }
  2869. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2870. /*
  2871. * RSA generate APIs
  2872. */
  2873. /* Get a random number generator associated with the RSA key.
  2874. *
  2875. * If not able, then get the global if possible.
  2876. * *tmpRng must not be an initialized RNG.
  2877. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2878. * associated with the wolfCrypt RSA key.
  2879. *
  2880. * @param [in] rsa RSA key.
  2881. * @param [out] tmpRng Temporary random number generator.
  2882. * @param [out] initTmpRng Temporary random number generator was initialized.
  2883. *
  2884. * @return A wolfCrypt RNG to use on success.
  2885. * @return NULL on error.
  2886. */
  2887. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2888. {
  2889. WC_RNG* rng = NULL;
  2890. int err = 0;
  2891. /* Check validity of parameters. */
  2892. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2893. err = 1;
  2894. }
  2895. if (!err) {
  2896. /* Haven't initialized any RNG passed through tmpRng. */
  2897. *initTmpRng = 0;
  2898. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2899. /* Use wolfCrypt RSA key's RNG if available/set. */
  2900. rng = ((RsaKey*)rsa->internal)->rng;
  2901. #endif
  2902. }
  2903. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2904. /* Make an RNG with tmpRng or get global. */
  2905. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2906. if ((rng != NULL) && *initTmpRng) {
  2907. *tmpRng = rng;
  2908. }
  2909. }
  2910. return rng;
  2911. }
  2912. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2913. *
  2914. * @param [in, out] rsa RSA key.
  2915. * @param [in] bits Number of bits that the modulus must have.
  2916. * @param [in] e A BN object holding the public exponent to use.
  2917. * @param [in] cb Status callback. Unused.
  2918. * @return 0 on success.
  2919. * @return wolfSSL native error code on error.
  2920. */
  2921. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2922. WOLFSSL_BIGNUM* e, void* cb)
  2923. {
  2924. #ifdef WOLFSSL_KEY_GEN
  2925. int ret = 0;
  2926. #ifdef WOLFSSL_SMALL_STACK
  2927. WC_RNG* tmpRng = NULL;
  2928. #else
  2929. WC_RNG _tmpRng[1];
  2930. WC_RNG* tmpRng = _tmpRng;
  2931. #endif
  2932. int initTmpRng = 0;
  2933. WC_RNG* rng = NULL;
  2934. #endif
  2935. (void)cb;
  2936. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2937. #ifdef WOLFSSL_KEY_GEN
  2938. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2939. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2940. if (rng == NULL) {
  2941. /* Something went wrong so return memory error. */
  2942. ret = MEMORY_E;
  2943. }
  2944. if (ret == 0) {
  2945. /* Generate an RSA key. */
  2946. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2947. (long)wolfSSL_BN_get_word(e), rng);
  2948. if (ret != MP_OKAY) {
  2949. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2950. }
  2951. }
  2952. if (ret == 0) {
  2953. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2954. ret = SetRsaExternal(rsa);
  2955. if (ret == 1) {
  2956. /* Internal matches external. */
  2957. rsa->inSet = 1;
  2958. /* Return success. */
  2959. ret = 0;
  2960. }
  2961. else {
  2962. /* Something went wrong so return memory error. */
  2963. ret = MEMORY_E;
  2964. }
  2965. }
  2966. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2967. if (initTmpRng) {
  2968. wc_FreeRng(tmpRng);
  2969. }
  2970. #ifdef WOLFSSL_SMALL_STACK
  2971. /* Dispose of any allocated RNG. */
  2972. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2973. #endif
  2974. return ret;
  2975. #else
  2976. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2977. (void)rsa;
  2978. (void)e;
  2979. (void)bits;
  2980. return NOT_COMPILED_IN;
  2981. #endif
  2982. }
  2983. /* Generate an RSA key that has the specified modulus size and public exponent.
  2984. *
  2985. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2986. * down to nearest multiple of 8. For example generating a key of size
  2987. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2988. *
  2989. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2990. * @param [in] e Public exponent to use i.e. 65537.
  2991. * @param [in] cb Status callback. Unused.
  2992. * @param [in] data Data to pass to status callback. Unused.
  2993. * @return A new RSA key on success.
  2994. * @return NULL on failure.
  2995. */
  2996. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2997. void(*cb)(int, int, void*), void* data)
  2998. {
  2999. WOLFSSL_RSA* rsa = NULL;
  3000. WOLFSSL_BIGNUM* bn = NULL;
  3001. int err = 0;
  3002. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  3003. (void)cb;
  3004. (void)data;
  3005. /* Validate bits. */
  3006. if (bits < 0) {
  3007. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  3008. err = 1;
  3009. }
  3010. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  3011. * longer values. */
  3012. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  3013. WOLFSSL_ERROR_MSG("Error creating big number");
  3014. err = 1;
  3015. }
  3016. /* Set public exponent. */
  3017. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  3018. WOLFSSL_ERROR_MSG("Error using e value");
  3019. err = 1;
  3020. }
  3021. /* Create an RSA key object to hold generated key. */
  3022. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  3023. WOLFSSL_ERROR_MSG("memory error");
  3024. err = 1;
  3025. }
  3026. while (!err) {
  3027. int ret;
  3028. /* Use wolfCrypt to generate RSA key. */
  3029. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  3030. #ifdef HAVE_FIPS
  3031. /* Keep trying if failed to find a prime. */
  3032. if (ret == PRIME_GEN_E) {
  3033. continue;
  3034. }
  3035. #endif
  3036. if (ret != WOLFSSL_ERROR_NONE) {
  3037. /* Unrecoverable error in generation. */
  3038. err = 1;
  3039. }
  3040. /* Done generating - unrecoverable error or success. */
  3041. break;
  3042. }
  3043. if (err) {
  3044. /* Dispose of RSA key object if generation didn't work. */
  3045. wolfSSL_RSA_free(rsa);
  3046. /* Returning NULL on error. */
  3047. rsa = NULL;
  3048. }
  3049. /* Dispose of the temporary BN used for the public exponent. */
  3050. wolfSSL_BN_free(bn);
  3051. return rsa;
  3052. }
  3053. /* Generate an RSA key that has the specified modulus size and public exponent.
  3054. *
  3055. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  3056. * down to nearest multiple of 8. For example generating a key of size
  3057. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  3058. *
  3059. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  3060. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  3061. * @param [in] cb Status callback. Unused.
  3062. * @return 1 on success.
  3063. * @return 0 on failure.
  3064. */
  3065. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  3066. void* cb)
  3067. {
  3068. int ret = 1;
  3069. /* Validate parameters. */
  3070. if ((rsa == NULL) || (rsa->internal == NULL)) {
  3071. WOLFSSL_ERROR_MSG("bad arguments");
  3072. ret = 0;
  3073. }
  3074. else {
  3075. for (;;) {
  3076. /* Use wolfCrypt to generate RSA key. */
  3077. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  3078. #ifdef HAVE_FIPS
  3079. /* Keep trying again if public key value didn't work. */
  3080. if (gen_ret == PRIME_GEN_E) {
  3081. continue;
  3082. }
  3083. #endif
  3084. if (gen_ret != WOLFSSL_ERROR_NONE) {
  3085. /* Unrecoverable error in generation. */
  3086. ret = 0;
  3087. }
  3088. /* Done generating - unrecoverable error or success. */
  3089. break;
  3090. }
  3091. }
  3092. return ret;
  3093. }
  3094. #endif /* OPENSSL_EXTRA */
  3095. /*
  3096. * RSA padding APIs
  3097. */
  3098. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  3099. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  3100. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  3101. /* Add PKCS#1 PSS padding to hash.
  3102. *
  3103. *
  3104. * +-----------+
  3105. * | M |
  3106. * +-----------+
  3107. * |
  3108. * V
  3109. * Hash
  3110. * |
  3111. * V
  3112. * +--------+----------+----------+
  3113. * M' = |Padding1| mHash | salt |
  3114. * +--------+----------+----------+
  3115. * |
  3116. * +--------+----------+ V
  3117. * DB = |Padding2|maskedseed| Hash
  3118. * +--------+----------+ |
  3119. * | |
  3120. * V | +--+
  3121. * xor <--- MGF <---| |bc|
  3122. * | | +--+
  3123. * | | |
  3124. * V V V
  3125. * +-------------------+----------+--+
  3126. * EM = | maskedDB |maskedseed|bc|
  3127. * +-------------------+----------+--+
  3128. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3129. *
  3130. * @param [in] rsa RSA key.
  3131. * @param [out] em Encoded message.
  3132. * @param [in[ mHash Message hash.
  3133. * @param [in] hashAlg Hash algorithm.
  3134. * @param [in] saltLen Length of salt to generate.
  3135. * @return 1 on success.
  3136. * @return 0 on failure.
  3137. */
  3138. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3139. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3140. {
  3141. int ret = 1;
  3142. enum wc_HashType hashType;
  3143. int hashLen = 0;
  3144. int emLen = 0;
  3145. int mgf = 0;
  3146. int initTmpRng = 0;
  3147. WC_RNG *rng = NULL;
  3148. #ifdef WOLFSSL_SMALL_STACK
  3149. WC_RNG* tmpRng = NULL;
  3150. #else
  3151. WC_RNG _tmpRng[1];
  3152. WC_RNG* tmpRng = _tmpRng;
  3153. #endif
  3154. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3155. /* Validate parameters. */
  3156. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3157. ret = 0;
  3158. }
  3159. if (ret == 1) {
  3160. /* Get/create an RNG. */
  3161. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3162. if (rng == NULL) {
  3163. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3164. ret = 0;
  3165. }
  3166. }
  3167. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3168. /* Set the external data from the wolfCrypt RSA key if not done. */
  3169. if ((ret == 1) && (!rsa->exSet)) {
  3170. ret = SetRsaExternal(rsa);
  3171. }
  3172. if (ret == 1) {
  3173. /* Get the wolfCrypt hash algorithm type. */
  3174. hashType = EvpMd2MacType(hashAlg);
  3175. if (hashType > WC_HASH_TYPE_MAX) {
  3176. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3177. ret = 0;
  3178. }
  3179. }
  3180. if (ret == 1) {
  3181. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3182. mgf = wc_hash2mgf(hashType);
  3183. if (mgf == WC_MGF1NONE) {
  3184. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3185. ret = 0;
  3186. }
  3187. }
  3188. if (ret == 1) {
  3189. /* Get the length of the hash output. */
  3190. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3191. if (hashLen < 0) {
  3192. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3193. ret = 0;
  3194. }
  3195. }
  3196. if (ret == 1) {
  3197. /* Get length of RSA key - encrypted message length. */
  3198. emLen = wolfSSL_RSA_size(rsa);
  3199. if (ret <= 0) {
  3200. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3201. ret = 0;
  3202. }
  3203. }
  3204. if (ret == 1) {
  3205. /* Calculate the salt length to use for special cases. */
  3206. /* TODO: use special case wolfCrypt values? */
  3207. switch (saltLen) {
  3208. /* Negative saltLen values are treated differently. */
  3209. case RSA_PSS_SALTLEN_DIGEST:
  3210. saltLen = hashLen;
  3211. break;
  3212. case RSA_PSS_SALTLEN_MAX_SIGN:
  3213. case RSA_PSS_SALTLEN_MAX:
  3214. #ifdef WOLFSSL_PSS_LONG_SALT
  3215. saltLen = emLen - hashLen - 2;
  3216. #else
  3217. saltLen = hashLen;
  3218. #endif
  3219. break;
  3220. default:
  3221. if (saltLen < 0) {
  3222. /* No other negative values implemented. */
  3223. WOLFSSL_ERROR_MSG("invalid saltLen");
  3224. ret = 0;
  3225. }
  3226. }
  3227. }
  3228. if (ret == 1) {
  3229. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3230. if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen,
  3231. RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0,
  3232. saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3233. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3234. ret = 0;
  3235. }
  3236. }
  3237. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3238. if (initTmpRng) {
  3239. wc_FreeRng(tmpRng);
  3240. }
  3241. #ifdef WOLFSSL_SMALL_STACK
  3242. /* Dispose of any allocated RNG. */
  3243. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3244. #endif
  3245. return ret;
  3246. }
  3247. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3248. *
  3249. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3250. *
  3251. * @param [in] rsa RSA key.
  3252. * @param [in[ mHash Message hash.
  3253. * @param [in] hashAlg Hash algorithm.
  3254. * @param [in] em Encoded message.
  3255. * @param [in] saltLen Length of salt to generate.
  3256. * @return 1 on success.
  3257. * @return 0 on failure.
  3258. */
  3259. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3260. const WOLFSSL_EVP_MD *hashAlg,
  3261. const unsigned char *em, int saltLen)
  3262. {
  3263. int ret = 1;
  3264. int hashLen = 0;
  3265. int mgf = 0;
  3266. int emLen = 0;
  3267. int mPrimeLen = 0;
  3268. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3269. byte *mPrime = NULL;
  3270. byte *buf = NULL;
  3271. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3272. /* Validate parameters. */
  3273. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3274. ret = 0;
  3275. }
  3276. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3277. /* Set the external data from the wolfCrypt RSA key if not done. */
  3278. if ((ret == 1) && (!rsa->exSet)) {
  3279. ret = SetRsaExternal(rsa);
  3280. }
  3281. if (ret == 1) {
  3282. /* Get hash length for hash algorithm. */
  3283. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3284. if (hashLen < 0) {
  3285. ret = 0;
  3286. }
  3287. }
  3288. if (ret == 1) {
  3289. /* Get length of RSA key - encrypted message length. */
  3290. emLen = wolfSSL_RSA_size(rsa);
  3291. if (emLen <= 0) {
  3292. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3293. ret = 0;
  3294. }
  3295. }
  3296. if (ret == 1) {
  3297. /* Calculate the salt length to use for special cases. */
  3298. switch (saltLen) {
  3299. /* Negative saltLen values are treated differently */
  3300. case RSA_PSS_SALTLEN_DIGEST:
  3301. saltLen = hashLen;
  3302. break;
  3303. case RSA_PSS_SALTLEN_AUTO:
  3304. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3305. saltLen = RSA_PSS_SALT_LEN_DISCOVER;
  3306. break;
  3307. #endif
  3308. case RSA_PSS_SALTLEN_MAX:
  3309. #ifdef WOLFSSL_PSS_LONG_SALT
  3310. saltLen = emLen - hashLen - 2;
  3311. #else
  3312. saltLen = hashLen;
  3313. #endif
  3314. break;
  3315. default:
  3316. if (saltLen < 0) {
  3317. /* No other negative values implemented. */
  3318. WOLFSSL_ERROR_MSG("invalid saltLen");
  3319. ret = 0;
  3320. }
  3321. }
  3322. }
  3323. if (ret == 1) {
  3324. /* Get the wolfCrypt hash algorithm type. */
  3325. hashType = EvpMd2MacType(hashAlg);
  3326. if (hashType > WC_HASH_TYPE_MAX) {
  3327. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3328. ret = 0;
  3329. }
  3330. }
  3331. if (ret == 1) {
  3332. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3333. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3334. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3335. ret = 0;
  3336. }
  3337. }
  3338. if (ret == 1) {
  3339. /* Allocate buffer to unpad inline with. */
  3340. buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3341. if (buf == NULL) {
  3342. WOLFSSL_ERROR_MSG("malloc error");
  3343. ret = 0;
  3344. }
  3345. }
  3346. if (ret == 1) {
  3347. /* Copy encrypted message to temp for inline unpadding. */
  3348. XMEMCPY(buf, em, (size_t)emLen);
  3349. /* Remove and verify the PSS padding. */
  3350. mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime,
  3351. RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3352. wolfSSL_BN_num_bits(rsa->n), NULL);
  3353. if (mPrimeLen < 0) {
  3354. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3355. ret = 0;
  3356. }
  3357. }
  3358. if (ret == 1) {
  3359. /* Verify the hash is correct. */
  3360. if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime,
  3361. (word32)mPrimeLen, hashType, saltLen,
  3362. wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3363. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3364. ret = 0;
  3365. }
  3366. }
  3367. /* Dispose of any allocated buffer. */
  3368. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3369. return ret;
  3370. }
  3371. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3372. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3373. * WOLFSSL_NGINX) */
  3374. /*
  3375. * RSA sign/verify APIs
  3376. */
  3377. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3378. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3379. #else
  3380. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3381. #endif
  3382. #if defined(OPENSSL_EXTRA)
  3383. /* Encode the message hash.
  3384. *
  3385. * Used by signing and verification.
  3386. *
  3387. * @param [in] hashAlg Hash algorithm OID.
  3388. * @param [in] hash Hash of message to encode for signing.
  3389. * @param [in] hLen Length of hash of message.
  3390. * @param [out] enc Encoded message hash.
  3391. * @param [out] encLen Length of encoded message hash.
  3392. * @param [in] padding Which padding scheme is being used.
  3393. * @return 1 on success.
  3394. * @return 0 on failure.
  3395. */
  3396. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3397. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3398. {
  3399. int ret = 1;
  3400. int hType = WC_HASH_TYPE_NONE;
  3401. /* Validate parameters. */
  3402. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3403. ret = 0;
  3404. }
  3405. if ((ret == 1) && (hashAlg != NID_undef) &&
  3406. (padding == RSA_PKCS1_PADDING)) {
  3407. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3408. hType = (int)nid2oid(hashAlg, oidHashType);
  3409. if (hType == -1) {
  3410. ret = 0;
  3411. }
  3412. }
  3413. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3414. /* PKCS#1.5 encoding. */
  3415. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3416. if (encSz == 0) {
  3417. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3418. ret = 0;
  3419. }
  3420. else {
  3421. *encLen = (unsigned int)encSz;
  3422. }
  3423. }
  3424. /* Other padding schemes require the hash as is. */
  3425. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3426. XMEMCPY(enc, hash, hLen);
  3427. *encLen = hLen;
  3428. }
  3429. return ret;
  3430. }
  3431. /* Sign the message hash using hash algorithm and RSA key.
  3432. *
  3433. * @param [in] hashAlg Hash algorithm OID.
  3434. * @param [in] hash Hash of message to encode for signing.
  3435. * @param [in] hLen Length of hash of message.
  3436. * @param [out] enc Encoded message hash.
  3437. * @param [out] encLen Length of encoded message hash.
  3438. * @param [in] rsa RSA key.
  3439. * @return 1 on success.
  3440. * @return 0 on failure.
  3441. */
  3442. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3443. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3444. {
  3445. if (sigLen != NULL) {
  3446. /* No size checking in this API */
  3447. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3448. }
  3449. /* flag is 1: output complete signature. */
  3450. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3451. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3452. }
  3453. /* Sign the message hash using hash algorithm and RSA key.
  3454. *
  3455. * Not OpenSSL API.
  3456. *
  3457. * @param [in] hashAlg Hash algorithm NID.
  3458. * @param [in] hash Hash of message to encode for signing.
  3459. * @param [in] hLen Length of hash of message.
  3460. * @param [out] enc Encoded message hash.
  3461. * @param [out] encLen Length of encoded message hash.
  3462. * @param [in] rsa RSA key.
  3463. * @param [in] flag When 1: Output encrypted signature.
  3464. * When 0: Output encoded hash.
  3465. * @return 1 on success.
  3466. * @return 0 on failure.
  3467. */
  3468. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3469. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3470. WOLFSSL_RSA* rsa, int flag)
  3471. {
  3472. int ret = 0;
  3473. if ((flag == 0) || (flag == 1)) {
  3474. if (sigLen != NULL) {
  3475. /* No size checking in this API */
  3476. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3477. }
  3478. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3479. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3480. }
  3481. return ret;
  3482. }
  3483. /**
  3484. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3485. *
  3486. * Not OpenSSL API.
  3487. *
  3488. * @param [in] hashAlg Hash NID
  3489. * @param [in] hash Message hash to sign.
  3490. * @param [in] mLen Length of message hash to sign.
  3491. * @param [out] sigRet Output buffer.
  3492. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3493. * On Output: length of data written to sigRet.
  3494. * @param [in] rsa RSA key used to sign the input.
  3495. * @param [in] flag 1: Output the signature.
  3496. * 0: Output the value that the unpadded signature
  3497. * should be compared to.
  3498. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3499. * RSA_PKCS1_PADDING are currently supported for
  3500. * signing.
  3501. * @return 1 on success.
  3502. * @return 0 on failure.
  3503. */
  3504. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3505. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3506. WOLFSSL_RSA* rsa, int flag, int padding)
  3507. {
  3508. int ret = 1;
  3509. word32 outLen = 0;
  3510. int signSz = 0;
  3511. WC_RNG* rng = NULL;
  3512. int initTmpRng = 0;
  3513. #ifdef WOLFSSL_SMALL_STACK
  3514. WC_RNG* tmpRng = NULL;
  3515. byte* encodedSig = NULL;
  3516. #else
  3517. WC_RNG _tmpRng[1];
  3518. WC_RNG* tmpRng = _tmpRng;
  3519. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3520. #endif
  3521. unsigned int encSz = 0;
  3522. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3523. if (flag == 0) {
  3524. /* Only encode message. */
  3525. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3526. padding);
  3527. }
  3528. /* Validate parameters. */
  3529. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3530. WOLFSSL_ERROR_MSG("Bad function arguments");
  3531. ret = 0;
  3532. }
  3533. /* Set wolfCrypt RSA key data from external if not already done. */
  3534. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3535. ret = 0;
  3536. }
  3537. if (ret == 1) {
  3538. /* Get the maximum signature length. */
  3539. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3540. /* Check not an error return. */
  3541. if (outLen == 0) {
  3542. WOLFSSL_ERROR_MSG("Bad RSA size");
  3543. ret = 0;
  3544. }
  3545. /* Check signature buffer is big enough. */
  3546. else if (outLen > *sigLen) {
  3547. WOLFSSL_ERROR_MSG("Output buffer too small");
  3548. ret = 0;
  3549. }
  3550. }
  3551. #ifdef WOLFSSL_SMALL_STACK
  3552. if (ret == 1) {
  3553. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3554. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3555. DYNAMIC_TYPE_SIGNATURE);
  3556. if (encodedSig == NULL) {
  3557. ret = 0;
  3558. }
  3559. }
  3560. #endif
  3561. if (ret == 1) {
  3562. /* Get/create an RNG. */
  3563. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3564. if (rng == NULL) {
  3565. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3566. ret = 0;
  3567. }
  3568. }
  3569. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3570. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3571. &encSz, padding) == 0)) {
  3572. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3573. ret = 0;
  3574. }
  3575. if (ret == 1) {
  3576. switch (padding) {
  3577. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3578. case RSA_NO_PADDING:
  3579. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3580. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3581. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3582. ret = 0;
  3583. }
  3584. break;
  3585. #endif
  3586. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3587. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3588. case RSA_PKCS1_PSS_PADDING:
  3589. {
  3590. enum wc_HashType hType =
  3591. wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3592. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3593. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3594. "OpenSSL uses max length by default.");
  3595. #endif
  3596. /* Create RSA PSS signature. */
  3597. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3598. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3599. (RsaKey*)rsa->internal, rng)) <= 0) {
  3600. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3601. ret = 0;
  3602. }
  3603. break;
  3604. }
  3605. #endif
  3606. #ifndef WC_NO_RSA_OAEP
  3607. case RSA_PKCS1_OAEP_PADDING:
  3608. /* Not a signature padding scheme. */
  3609. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3610. "signing");
  3611. ret = 0;
  3612. break;
  3613. #endif
  3614. case RSA_PKCS1_PADDING:
  3615. {
  3616. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3617. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3618. (RsaKey*)rsa->internal, rng)) <= 0) {
  3619. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3620. ret = 0;
  3621. }
  3622. break;
  3623. }
  3624. default:
  3625. WOLFSSL_ERROR_MSG("Unsupported padding");
  3626. ret = 0;
  3627. break;
  3628. }
  3629. }
  3630. if (ret == 1) {
  3631. /* Return the size of signature generated. */
  3632. *sigLen = (unsigned int)signSz;
  3633. }
  3634. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3635. if (initTmpRng) {
  3636. wc_FreeRng(tmpRng);
  3637. }
  3638. #ifdef WOLFSSL_SMALL_STACK
  3639. /* Dispose of any allocated RNG and encoded signature. */
  3640. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3641. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3642. #endif
  3643. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3644. return ret;
  3645. }
  3646. /**
  3647. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3648. *
  3649. * @param [in] hashAlg Hash NID
  3650. * @param [in] hash Message hash.
  3651. * @param [in] mLen Length of message hash.
  3652. * @param [in] sigRet Signature data.
  3653. * @param [in] sigLen Length of signature data.
  3654. * @param [in] rsa RSA key used to sign the input
  3655. * @return 1 on success.
  3656. * @return 0 on failure.
  3657. */
  3658. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3659. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3660. WOLFSSL_RSA* rsa)
  3661. {
  3662. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3663. RSA_PKCS1_PADDING);
  3664. }
  3665. /**
  3666. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3667. *
  3668. * Not OpenSSL API.
  3669. *
  3670. * @param [in] hashAlg Hash NID
  3671. * @param [in] hash Message hash.
  3672. * @param [in] mLen Length of message hash.
  3673. * @param [in] sigRet Signature data.
  3674. * @param [in] sigLen Length of signature data.
  3675. * @param [in] rsa RSA key used to sign the input
  3676. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3677. * RSA_PKCS1_PADDING are currently supported for
  3678. * signing.
  3679. * @return 1 on success.
  3680. * @return 0 on failure.
  3681. */
  3682. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3683. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3684. WOLFSSL_RSA* rsa, int padding)
  3685. {
  3686. int ret = 1;
  3687. #ifdef WOLFSSL_SMALL_STACK
  3688. unsigned char* encodedSig = NULL;
  3689. #else
  3690. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3691. #endif
  3692. unsigned char* sigDec = NULL;
  3693. unsigned int len = MAX_ENCODED_SIG_SZ;
  3694. int verLen = 0;
  3695. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3696. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3697. #endif
  3698. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3699. /* Validate parameters. */
  3700. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3701. WOLFSSL_ERROR_MSG("Bad function arguments");
  3702. ret = 0;
  3703. }
  3704. if (ret == 1) {
  3705. /* Allocate memory for decrypted signature. */
  3706. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3707. DYNAMIC_TYPE_TMP_BUFFER);
  3708. if (sigDec == NULL) {
  3709. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3710. ret = 0;
  3711. }
  3712. }
  3713. #ifdef WOLFSSL_SMALL_STACK
  3714. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3715. /* Allocate memory for encoded signature. */
  3716. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3717. DYNAMIC_TYPE_TMP_BUFFER);
  3718. if (encodedSig == NULL) {
  3719. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3720. ret = 0;
  3721. }
  3722. }
  3723. #endif
  3724. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3725. /* Make encoded signature to compare with decrypted signature. */
  3726. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3727. padding) <= 0) {
  3728. WOLFSSL_ERROR_MSG("Message Digest Error");
  3729. ret = 0;
  3730. }
  3731. }
  3732. if (ret == 1) {
  3733. /* Decrypt signature */
  3734. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3735. !defined(HAVE_SELFTEST)
  3736. hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3737. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3738. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3739. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3740. ret = 0;
  3741. }
  3742. #else
  3743. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3744. (RsaKey*)rsa->internal);
  3745. if (verLen < 0) {
  3746. ret = 0;
  3747. }
  3748. #endif
  3749. }
  3750. if (ret == 1) {
  3751. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3752. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3753. if (padding == RSA_PKCS1_PSS_PADDING) {
  3754. /* Check PSS padding is valid. */
  3755. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen,
  3756. hType, DEF_PSS_SALT_LEN,
  3757. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3758. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3759. ret = 0;
  3760. }
  3761. }
  3762. else
  3763. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3764. * FIPS_VERSION >= 5.1) */
  3765. /* Compare decrypted signature to encoded signature. */
  3766. if (((int)len != verLen) ||
  3767. (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) {
  3768. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3769. ret = 0;
  3770. }
  3771. }
  3772. /* Dispose of any allocated data. */
  3773. #ifdef WOLFSSL_SMALL_STACK
  3774. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3775. #endif
  3776. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3777. return ret;
  3778. }
  3779. /*
  3780. * RSA public/private encrypt/decrypt APIs
  3781. */
  3782. /* Encrypt with the RSA public key.
  3783. *
  3784. * Return compliant with OpenSSL.
  3785. *
  3786. * @param [in] len Length of data to encrypt.
  3787. * @param [in] from Data to encrypt.
  3788. * @param [out] to Encrypted data.
  3789. * @param [in] rsa RSA key.
  3790. * @param [in] padding Type of padding to place around plaintext.
  3791. * @return Size of encrypted data on success.
  3792. * @return -1 on failure.
  3793. */
  3794. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3795. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3796. {
  3797. int ret = 0;
  3798. int initTmpRng = 0;
  3799. WC_RNG *rng = NULL;
  3800. #ifdef WOLFSSL_SMALL_STACK
  3801. WC_RNG* tmpRng = NULL;
  3802. #else
  3803. WC_RNG _tmpRng[1];
  3804. WC_RNG* tmpRng = _tmpRng;
  3805. #endif
  3806. #if !defined(HAVE_FIPS)
  3807. int mgf = WC_MGF1NONE;
  3808. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3809. int pad_type = WC_RSA_NO_PAD;
  3810. #endif
  3811. int outLen = 0;
  3812. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3813. /* Validate parameters. */
  3814. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3815. (from == NULL)) {
  3816. WOLFSSL_ERROR_MSG("Bad function arguments");
  3817. ret = -1;
  3818. }
  3819. if (ret == 0) {
  3820. #if !defined(HAVE_FIPS)
  3821. /* Convert to wolfCrypt padding, hash and MGF. */
  3822. switch (padding) {
  3823. case RSA_PKCS1_PADDING:
  3824. pad_type = WC_RSA_PKCSV15_PAD;
  3825. break;
  3826. case RSA_PKCS1_OAEP_PADDING:
  3827. pad_type = WC_RSA_OAEP_PAD;
  3828. hash = WC_HASH_TYPE_SHA;
  3829. mgf = WC_MGF1SHA1;
  3830. break;
  3831. case RSA_NO_PADDING:
  3832. pad_type = WC_RSA_NO_PAD;
  3833. break;
  3834. default:
  3835. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3836. "scheme");
  3837. ret = -1;
  3838. }
  3839. #else
  3840. /* Check for supported padding schemes in FIPS. */
  3841. /* TODO: Do we support more schemes in later versions of FIPS? */
  3842. if (padding != RSA_PKCS1_PADDING) {
  3843. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3844. "FIPS");
  3845. ret = -1;
  3846. }
  3847. #endif
  3848. }
  3849. /* Set wolfCrypt RSA key data from external if not already done. */
  3850. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3851. ret = -1;
  3852. }
  3853. if (ret == 0) {
  3854. /* Calculate maximum length of encrypted data. */
  3855. outLen = wolfSSL_RSA_size(rsa);
  3856. if (outLen == 0) {
  3857. WOLFSSL_ERROR_MSG("Bad RSA size");
  3858. ret = -1;
  3859. }
  3860. }
  3861. if (ret == 0) {
  3862. /* Get an RNG. */
  3863. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3864. if (rng == NULL) {
  3865. ret = -1;
  3866. }
  3867. }
  3868. if (ret == 0) {
  3869. /* Use wolfCrypt to public-encrypt with RSA key. */
  3870. #if !defined(HAVE_FIPS)
  3871. ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen,
  3872. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3873. #else
  3874. ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen,
  3875. (RsaKey*)rsa->internal, rng);
  3876. #endif
  3877. }
  3878. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3879. if (initTmpRng) {
  3880. wc_FreeRng(tmpRng);
  3881. }
  3882. #ifdef WOLFSSL_SMALL_STACK
  3883. /* Dispose of any allocated RNG. */
  3884. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3885. #endif
  3886. /* wolfCrypt error means return -1. */
  3887. if (ret <= 0) {
  3888. ret = -1;
  3889. }
  3890. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3891. return ret;
  3892. }
  3893. /* Decrypt with the RSA public key.
  3894. *
  3895. * Return compliant with OpenSSL.
  3896. *
  3897. * @param [in] len Length of encrypted data.
  3898. * @param [in] from Encrypted data.
  3899. * @param [out] to Decrypted data.
  3900. * @param [in] rsa RSA key.
  3901. * @param [in] padding Type of padding to around plaintext to remove.
  3902. * @return Size of decrypted data on success.
  3903. * @return -1 on failure.
  3904. */
  3905. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3906. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3907. {
  3908. int ret = 0;
  3909. #if !defined(HAVE_FIPS)
  3910. int mgf = WC_MGF1NONE;
  3911. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3912. int pad_type = WC_RSA_NO_PAD;
  3913. #endif
  3914. int outLen = 0;
  3915. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3916. /* Validate parameters. */
  3917. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3918. (from == NULL)) {
  3919. WOLFSSL_ERROR_MSG("Bad function arguments");
  3920. ret = -1;
  3921. }
  3922. if (ret == 0) {
  3923. #if !defined(HAVE_FIPS)
  3924. switch (padding) {
  3925. case RSA_PKCS1_PADDING:
  3926. pad_type = WC_RSA_PKCSV15_PAD;
  3927. break;
  3928. case RSA_PKCS1_OAEP_PADDING:
  3929. pad_type = WC_RSA_OAEP_PAD;
  3930. hash = WC_HASH_TYPE_SHA;
  3931. mgf = WC_MGF1SHA1;
  3932. break;
  3933. case RSA_NO_PADDING:
  3934. pad_type = WC_RSA_NO_PAD;
  3935. break;
  3936. default:
  3937. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3938. ret = -1;
  3939. }
  3940. #else
  3941. /* Check for supported padding schemes in FIPS. */
  3942. /* TODO: Do we support more schemes in later versions of FIPS? */
  3943. if (padding != RSA_PKCS1_PADDING) {
  3944. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3945. "FIPS");
  3946. ret = -1;
  3947. }
  3948. #endif
  3949. }
  3950. /* Set wolfCrypt RSA key data from external if not already done. */
  3951. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3952. ret = -1;
  3953. }
  3954. if (ret == 0) {
  3955. /* Calculate maximum length of decrypted data. */
  3956. outLen = wolfSSL_RSA_size(rsa);
  3957. if (outLen == 0) {
  3958. WOLFSSL_ERROR_MSG("Bad RSA size");
  3959. ret = -1;
  3960. }
  3961. }
  3962. if (ret == 0) {
  3963. /* Use wolfCrypt to private-decrypt with RSA key.
  3964. * Size of 'to' buffer must be size of RSA key */
  3965. #if !defined(HAVE_FIPS)
  3966. ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen,
  3967. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3968. #else
  3969. ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen,
  3970. (RsaKey*)rsa->internal);
  3971. #endif
  3972. }
  3973. /* wolfCrypt error means return -1. */
  3974. if (ret <= 0) {
  3975. ret = -1;
  3976. }
  3977. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  3978. return ret;
  3979. }
  3980. /* Decrypt with the RSA public key.
  3981. *
  3982. * @param [in] len Length of encrypted data.
  3983. * @param [in] from Encrypted data.
  3984. * @param [out] to Decrypted data.
  3985. * @param [in] rsa RSA key.
  3986. * @param [in] padding Type of padding to around plaintext to remove.
  3987. * @return Size of decrypted data on success.
  3988. * @return -1 on failure.
  3989. */
  3990. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3991. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3992. {
  3993. int ret = 0;
  3994. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3995. int pad_type = WC_RSA_NO_PAD;
  3996. #endif
  3997. int outLen = 0;
  3998. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  3999. /* Validate parameters. */
  4000. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4001. (from == NULL)) {
  4002. WOLFSSL_ERROR_MSG("Bad function arguments");
  4003. ret = -1;
  4004. }
  4005. if (ret == 0) {
  4006. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4007. switch (padding) {
  4008. case RSA_PKCS1_PADDING:
  4009. pad_type = WC_RSA_PKCSV15_PAD;
  4010. break;
  4011. case RSA_NO_PADDING:
  4012. pad_type = WC_RSA_NO_PAD;
  4013. break;
  4014. /* TODO: RSA_X931_PADDING not supported */
  4015. default:
  4016. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  4017. ret = -1;
  4018. }
  4019. #else
  4020. if (padding != RSA_PKCS1_PADDING) {
  4021. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  4022. "FIPS");
  4023. ret = -1;
  4024. }
  4025. #endif
  4026. }
  4027. /* Set wolfCrypt RSA key data from external if not already done. */
  4028. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4029. ret = -1;
  4030. }
  4031. if (ret == 0) {
  4032. /* Calculate maximum length of encrypted data. */
  4033. outLen = wolfSSL_RSA_size(rsa);
  4034. if (outLen == 0) {
  4035. WOLFSSL_ERROR_MSG("Bad RSA size");
  4036. ret = -1;
  4037. }
  4038. }
  4039. if (ret == 0) {
  4040. /* Use wolfCrypt to public-decrypt with RSA key. */
  4041. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  4042. /* Size of 'to' buffer must be size of RSA key. */
  4043. ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen,
  4044. (RsaKey*)rsa->internal, pad_type);
  4045. #else
  4046. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  4047. ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen,
  4048. (RsaKey*)rsa->internal);
  4049. #endif
  4050. }
  4051. /* wolfCrypt error means return -1. */
  4052. if (ret <= 0) {
  4053. ret = -1;
  4054. }
  4055. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  4056. return ret;
  4057. }
  4058. /* Encrypt with the RSA private key.
  4059. *
  4060. * Calls wc_RsaSSL_Sign.
  4061. *
  4062. * @param [in] len Length of data to encrypt.
  4063. * @param [in] from Data to encrypt.
  4064. * @param [out] to Encrypted data.
  4065. * @param [in] rsa RSA key.
  4066. * @param [in] padding Type of padding to place around plaintext.
  4067. * @return Size of encrypted data on success.
  4068. * @return -1 on failure.
  4069. */
  4070. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  4071. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  4072. {
  4073. int ret = 0;
  4074. int initTmpRng = 0;
  4075. WC_RNG *rng = NULL;
  4076. #ifdef WOLFSSL_SMALL_STACK
  4077. WC_RNG* tmpRng = NULL;
  4078. #else
  4079. WC_RNG _tmpRng[1];
  4080. WC_RNG* tmpRng = _tmpRng;
  4081. #endif
  4082. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  4083. /* Validate parameters. */
  4084. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  4085. (from == NULL)) {
  4086. WOLFSSL_ERROR_MSG("Bad function arguments");
  4087. ret = -1;
  4088. }
  4089. if (ret == 0) {
  4090. switch (padding) {
  4091. case RSA_PKCS1_PADDING:
  4092. #ifdef WC_RSA_NO_PADDING
  4093. case RSA_NO_PADDING:
  4094. #endif
  4095. break;
  4096. /* TODO: RSA_X931_PADDING not supported */
  4097. default:
  4098. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  4099. ret = -1;
  4100. }
  4101. }
  4102. /* Set wolfCrypt RSA key data from external if not already done. */
  4103. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  4104. ret = -1;
  4105. }
  4106. if (ret == 0) {
  4107. /* Get an RNG. */
  4108. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  4109. if (rng == NULL) {
  4110. ret = -1;
  4111. }
  4112. }
  4113. if (ret == 0) {
  4114. /* Use wolfCrypt to private-encrypt with RSA key.
  4115. * Size of output buffer must be size of RSA key. */
  4116. if (padding == RSA_PKCS1_PADDING) {
  4117. ret = wc_RsaSSL_Sign(from, (word32)len, to,
  4118. (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng);
  4119. }
  4120. #ifdef WC_RSA_NO_PADDING
  4121. else if (padding == RSA_NO_PADDING) {
  4122. word32 outLen = (word32)wolfSSL_RSA_size(rsa);
  4123. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  4124. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  4125. if (ret == 0)
  4126. ret = (int)outLen;
  4127. }
  4128. #endif
  4129. }
  4130. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4131. if (initTmpRng) {
  4132. wc_FreeRng(tmpRng);
  4133. }
  4134. #ifdef WOLFSSL_SMALL_STACK
  4135. /* Dispose of any allocated RNG. */
  4136. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4137. #endif
  4138. /* wolfCrypt error means return -1. */
  4139. if (ret <= 0) {
  4140. ret = -1;
  4141. }
  4142. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4143. return ret;
  4144. }
  4145. /*
  4146. * RSA misc operation APIs
  4147. */
  4148. /* Calculate d mod p-1 and q-1 into BNs.
  4149. *
  4150. * Not OpenSSL API.
  4151. *
  4152. * @param [in, out] rsa RSA key.
  4153. * @return 1 on success.
  4154. * @return -1 on failure.
  4155. */
  4156. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4157. {
  4158. int ret = 1;
  4159. int err;
  4160. mp_int* t = NULL;
  4161. #ifdef WOLFSSL_SMALL_STACK
  4162. mp_int *tmp = NULL;
  4163. #else
  4164. mp_int tmp[1];
  4165. #endif
  4166. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4167. /* Validate parameters. */
  4168. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4169. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4170. WOLFSSL_ERROR_MSG("rsa no init error");
  4171. ret = -1;
  4172. }
  4173. #ifdef WOLFSSL_SMALL_STACK
  4174. if (ret == 1) {
  4175. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4176. DYNAMIC_TYPE_TMP_BUFFER);
  4177. if (tmp == NULL) {
  4178. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4179. ret = -1;
  4180. }
  4181. }
  4182. #endif
  4183. if (ret == 1) {
  4184. /* Initialize temp MP integer. */
  4185. if (mp_init(tmp) != MP_OKAY) {
  4186. WOLFSSL_ERROR_MSG("mp_init error");
  4187. ret = -1;
  4188. }
  4189. }
  4190. if (ret == 1) {
  4191. t = tmp;
  4192. /* Sub 1 from p into temp. */
  4193. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4194. if (err != MP_OKAY) {
  4195. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4196. ret = -1;
  4197. }
  4198. }
  4199. if (ret == 1) {
  4200. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4201. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4202. (mp_int*)rsa->dmp1->internal);
  4203. if (err != MP_OKAY) {
  4204. WOLFSSL_ERROR_MSG("mp_mod error");
  4205. ret = -1;
  4206. }
  4207. }
  4208. if (ret == 1) {
  4209. /* Sub 1 from q into temp. */
  4210. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4211. if (err != MP_OKAY) {
  4212. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4213. ret = -1;
  4214. }
  4215. }
  4216. if (ret == 1) {
  4217. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4218. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4219. (mp_int*)rsa->dmq1->internal);
  4220. if (err != MP_OKAY) {
  4221. WOLFSSL_ERROR_MSG("mp_mod error");
  4222. ret = -1;
  4223. }
  4224. }
  4225. mp_clear(t);
  4226. #ifdef WOLFSSL_SMALL_STACK
  4227. if (tmp != NULL)
  4228. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4229. #endif
  4230. return ret;
  4231. }
  4232. #ifndef NO_WOLFSSL_STUB
  4233. /* Enable blinding for RSA key operations.
  4234. *
  4235. * Blinding is a compile time option in wolfCrypt.
  4236. *
  4237. * @param [in] rsa RSA key. Unused.
  4238. * @param [in] bnCtx BN context to use for blinding. Unused.
  4239. * @return 1 always.
  4240. */
  4241. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4242. {
  4243. WOLFSSL_STUB("RSA_blinding_on");
  4244. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4245. (void)rsa;
  4246. (void)bnCtx;
  4247. return 1; /* on by default */
  4248. }
  4249. #endif
  4250. #endif /* OPENSSL_EXTRA */
  4251. #endif /* !NO_RSA */
  4252. /*******************************************************************************
  4253. * END OF RSA API
  4254. ******************************************************************************/
  4255. /*******************************************************************************
  4256. * START OF DSA API
  4257. ******************************************************************************/
  4258. #ifndef NO_DSA
  4259. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4260. !defined(NO_STDIO_FILESYSTEM)
  4261. /* return code compliant with OpenSSL :
  4262. * 1 if success, 0 if error
  4263. */
  4264. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4265. {
  4266. int ret = 1;
  4267. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4268. if (fp == XBADFILE || dsa == NULL) {
  4269. ret = 0;
  4270. }
  4271. if (ret == 1 && dsa->p != NULL) {
  4272. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4273. if (pBits == 0) {
  4274. ret = 0;
  4275. }
  4276. else {
  4277. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4278. ret = 0;
  4279. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4280. ret = 0;
  4281. }
  4282. }
  4283. if (ret == 1 && dsa->priv_key != NULL) {
  4284. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4285. }
  4286. if (ret == 1 && dsa->pub_key != NULL) {
  4287. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4288. }
  4289. if (ret == 1 && dsa->p != NULL) {
  4290. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4291. }
  4292. if (ret == 1 && dsa->q != NULL) {
  4293. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4294. }
  4295. if (ret == 1 && dsa->g != NULL) {
  4296. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4297. }
  4298. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4299. return ret;
  4300. }
  4301. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4302. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4303. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4304. {
  4305. if (dsa) {
  4306. dsa->p = NULL;
  4307. dsa->q = NULL;
  4308. dsa->g = NULL;
  4309. dsa->pub_key = NULL;
  4310. dsa->priv_key = NULL;
  4311. dsa->internal = NULL;
  4312. dsa->inSet = 0;
  4313. dsa->exSet = 0;
  4314. }
  4315. }
  4316. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4317. {
  4318. WOLFSSL_DSA* external;
  4319. DsaKey* key;
  4320. WOLFSSL_MSG("wolfSSL_DSA_new");
  4321. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4322. if (key == NULL) {
  4323. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4324. return NULL;
  4325. }
  4326. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4327. DYNAMIC_TYPE_DSA);
  4328. if (external == NULL) {
  4329. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4330. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4331. return NULL;
  4332. }
  4333. InitwolfSSL_DSA(external);
  4334. if (wc_InitDsaKey(key) != 0) {
  4335. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4336. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4337. wolfSSL_DSA_free(external);
  4338. return NULL;
  4339. }
  4340. external->internal = key;
  4341. return external;
  4342. }
  4343. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4344. {
  4345. WOLFSSL_MSG("wolfSSL_DSA_free");
  4346. if (dsa) {
  4347. if (dsa->internal) {
  4348. FreeDsaKey((DsaKey*)dsa->internal);
  4349. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4350. dsa->internal = NULL;
  4351. }
  4352. wolfSSL_BN_free(dsa->priv_key);
  4353. wolfSSL_BN_free(dsa->pub_key);
  4354. wolfSSL_BN_free(dsa->g);
  4355. wolfSSL_BN_free(dsa->q);
  4356. wolfSSL_BN_free(dsa->p);
  4357. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4358. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4359. /* dsa = NULL, don't try to access or double free it */
  4360. }
  4361. }
  4362. /* wolfSSL -> OpenSSL */
  4363. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4364. {
  4365. DsaKey* key;
  4366. WOLFSSL_MSG("Entering SetDsaExternal");
  4367. if (dsa == NULL || dsa->internal == NULL) {
  4368. WOLFSSL_MSG("dsa key NULL error");
  4369. return -1;
  4370. }
  4371. key = (DsaKey*)dsa->internal;
  4372. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4373. WOLFSSL_MSG("dsa p key error");
  4374. return -1;
  4375. }
  4376. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4377. WOLFSSL_MSG("dsa q key error");
  4378. return -1;
  4379. }
  4380. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4381. WOLFSSL_MSG("dsa g key error");
  4382. return -1;
  4383. }
  4384. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4385. WOLFSSL_MSG("dsa y key error");
  4386. return -1;
  4387. }
  4388. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4389. WOLFSSL_MSG("dsa x key error");
  4390. return -1;
  4391. }
  4392. dsa->exSet = 1;
  4393. return 1;
  4394. }
  4395. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4396. #ifdef OPENSSL_EXTRA
  4397. /* Openssl -> WolfSSL */
  4398. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4399. {
  4400. DsaKey* key;
  4401. WOLFSSL_MSG("Entering SetDsaInternal");
  4402. if (dsa == NULL || dsa->internal == NULL) {
  4403. WOLFSSL_MSG("dsa key NULL error");
  4404. return -1;
  4405. }
  4406. key = (DsaKey*)dsa->internal;
  4407. if (dsa->p != NULL &&
  4408. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4409. WOLFSSL_MSG("rsa p key error");
  4410. return -1;
  4411. }
  4412. if (dsa->q != NULL &&
  4413. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4414. WOLFSSL_MSG("rsa q key error");
  4415. return -1;
  4416. }
  4417. if (dsa->g != NULL &&
  4418. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4419. WOLFSSL_MSG("rsa g key error");
  4420. return -1;
  4421. }
  4422. if (dsa->pub_key != NULL) {
  4423. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4424. WOLFSSL_MSG("rsa pub_key error");
  4425. return -1;
  4426. }
  4427. /* public key */
  4428. key->type = DSA_PUBLIC;
  4429. }
  4430. if (dsa->priv_key != NULL) {
  4431. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4432. WOLFSSL_MSG("rsa priv_key error");
  4433. return -1;
  4434. }
  4435. /* private key */
  4436. key->type = DSA_PRIVATE;
  4437. }
  4438. dsa->inSet = 1;
  4439. return 1;
  4440. }
  4441. /* return code compliant with OpenSSL :
  4442. * 1 if success, 0 if error
  4443. */
  4444. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4445. {
  4446. int ret = 0;
  4447. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4448. if (dsa == NULL || dsa->internal == NULL) {
  4449. WOLFSSL_MSG("Bad arguments");
  4450. return 0;
  4451. }
  4452. if (dsa->inSet == 0) {
  4453. WOLFSSL_MSG("No DSA internal set, do it");
  4454. if (SetDsaInternal(dsa) != 1) {
  4455. WOLFSSL_MSG("SetDsaInternal failed");
  4456. return ret;
  4457. }
  4458. }
  4459. #ifdef WOLFSSL_KEY_GEN
  4460. {
  4461. int initTmpRng = 0;
  4462. WC_RNG *rng = NULL;
  4463. #ifdef WOLFSSL_SMALL_STACK
  4464. WC_RNG *tmpRng;
  4465. #else
  4466. WC_RNG tmpRng[1];
  4467. #endif
  4468. #ifdef WOLFSSL_SMALL_STACK
  4469. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4470. if (tmpRng == NULL)
  4471. return -1;
  4472. #endif
  4473. if (wc_InitRng(tmpRng) == 0) {
  4474. rng = tmpRng;
  4475. initTmpRng = 1;
  4476. }
  4477. else {
  4478. WOLFSSL_MSG("Bad RNG Init, trying global");
  4479. rng = wolfssl_get_global_rng();
  4480. }
  4481. if (rng) {
  4482. /* These were allocated above by SetDsaInternal(). They should
  4483. * be cleared before wc_MakeDsaKey() which reinitializes
  4484. * x and y. */
  4485. mp_clear(&((DsaKey*)dsa->internal)->x);
  4486. mp_clear(&((DsaKey*)dsa->internal)->y);
  4487. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4488. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4489. else if (SetDsaExternal(dsa) != 1)
  4490. WOLFSSL_MSG("SetDsaExternal failed");
  4491. else
  4492. ret = 1;
  4493. }
  4494. if (initTmpRng)
  4495. wc_FreeRng(tmpRng);
  4496. #ifdef WOLFSSL_SMALL_STACK
  4497. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4498. #endif
  4499. }
  4500. #else /* WOLFSSL_KEY_GEN */
  4501. WOLFSSL_MSG("No Key Gen built in");
  4502. #endif
  4503. return ret;
  4504. }
  4505. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4506. */
  4507. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4508. int seedLen, int* counterRet, unsigned long* hRet,
  4509. WOLFSSL_BN_CB cb, void* CBArg)
  4510. {
  4511. WOLFSSL_DSA* dsa;
  4512. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4513. (void)cb;
  4514. (void)CBArg;
  4515. dsa = wolfSSL_DSA_new();
  4516. if (dsa == NULL) {
  4517. return NULL;
  4518. }
  4519. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4520. counterRet, hRet, NULL) != 1) {
  4521. wolfSSL_DSA_free(dsa);
  4522. return NULL;
  4523. }
  4524. return dsa;
  4525. }
  4526. /* return code compliant with OpenSSL :
  4527. * 1 if success, 0 if error
  4528. */
  4529. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4530. unsigned char* seed, int seedLen,
  4531. int* counterRet,
  4532. unsigned long* hRet, void* cb)
  4533. {
  4534. int ret = 0;
  4535. (void)bits;
  4536. (void)seed;
  4537. (void)seedLen;
  4538. (void)counterRet;
  4539. (void)hRet;
  4540. (void)cb;
  4541. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4542. if (dsa == NULL || dsa->internal == NULL) {
  4543. WOLFSSL_MSG("Bad arguments");
  4544. return 0;
  4545. }
  4546. #ifdef WOLFSSL_KEY_GEN
  4547. {
  4548. int initTmpRng = 0;
  4549. WC_RNG *rng = NULL;
  4550. #ifdef WOLFSSL_SMALL_STACK
  4551. WC_RNG *tmpRng;
  4552. #else
  4553. WC_RNG tmpRng[1];
  4554. #endif
  4555. #ifdef WOLFSSL_SMALL_STACK
  4556. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4557. if (tmpRng == NULL)
  4558. return -1;
  4559. #endif
  4560. if (wc_InitRng(tmpRng) == 0) {
  4561. rng = tmpRng;
  4562. initTmpRng = 1;
  4563. }
  4564. else {
  4565. WOLFSSL_MSG("Bad RNG Init, trying global");
  4566. rng = wolfssl_get_global_rng();
  4567. }
  4568. if (rng) {
  4569. if (wc_MakeDsaParameters(rng, bits,
  4570. (DsaKey*)dsa->internal) != MP_OKAY)
  4571. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4572. else if (SetDsaExternal(dsa) != 1)
  4573. WOLFSSL_MSG("SetDsaExternal failed");
  4574. else
  4575. ret = 1;
  4576. }
  4577. if (initTmpRng)
  4578. wc_FreeRng(tmpRng);
  4579. #ifdef WOLFSSL_SMALL_STACK
  4580. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4581. #endif
  4582. }
  4583. #else /* WOLFSSL_KEY_GEN */
  4584. WOLFSSL_MSG("No Key Gen built in");
  4585. #endif
  4586. return ret;
  4587. }
  4588. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4589. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4590. {
  4591. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4592. if (d != NULL) {
  4593. if (p != NULL)
  4594. *p = d->p;
  4595. if (q != NULL)
  4596. *q = d->q;
  4597. if (g != NULL)
  4598. *g = d->g;
  4599. }
  4600. }
  4601. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4602. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4603. {
  4604. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4605. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4606. WOLFSSL_MSG("Bad parameter");
  4607. return 0;
  4608. }
  4609. wolfSSL_BN_free(d->p);
  4610. wolfSSL_BN_free(d->q);
  4611. wolfSSL_BN_free(d->g);
  4612. d->p = p;
  4613. d->q = q;
  4614. d->g = g;
  4615. return 1;
  4616. }
  4617. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4618. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4619. {
  4620. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4621. if (d != NULL) {
  4622. if (pub_key != NULL)
  4623. *pub_key = d->pub_key;
  4624. if (priv_key != NULL)
  4625. *priv_key = d->priv_key;
  4626. }
  4627. }
  4628. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4629. WOLFSSL_BIGNUM *priv_key)
  4630. {
  4631. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4632. /* The private key may be NULL */
  4633. if (d->pub_key == NULL && pub_key == NULL) {
  4634. WOLFSSL_MSG("Bad parameter");
  4635. return 0;
  4636. }
  4637. if (pub_key != NULL) {
  4638. wolfSSL_BN_free(d->pub_key);
  4639. d->pub_key = pub_key;
  4640. }
  4641. if (priv_key != NULL) {
  4642. wolfSSL_BN_free(d->priv_key);
  4643. d->priv_key = priv_key;
  4644. }
  4645. return 1;
  4646. }
  4647. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4648. {
  4649. WOLFSSL_DSA_SIG* sig;
  4650. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4651. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4652. DYNAMIC_TYPE_OPENSSL);
  4653. if (sig)
  4654. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4655. return sig;
  4656. }
  4657. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4658. {
  4659. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4660. if (sig) {
  4661. if (sig->r) {
  4662. wolfSSL_BN_free(sig->r);
  4663. }
  4664. if (sig->s) {
  4665. wolfSSL_BN_free(sig->s);
  4666. }
  4667. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4668. }
  4669. }
  4670. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4671. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4672. {
  4673. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4674. if (sig != NULL) {
  4675. *r = sig->r;
  4676. *s = sig->s;
  4677. }
  4678. }
  4679. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4680. WOLFSSL_BIGNUM *s)
  4681. {
  4682. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4683. if (r == NULL || s == NULL) {
  4684. WOLFSSL_MSG("Bad parameter");
  4685. return 0;
  4686. }
  4687. wolfSSL_BN_clear_free(sig->r);
  4688. wolfSSL_BN_clear_free(sig->s);
  4689. sig->r = r;
  4690. sig->s = s;
  4691. return 1;
  4692. }
  4693. #ifndef HAVE_SELFTEST
  4694. /**
  4695. *
  4696. * @param sig The input signature to encode
  4697. * @param out The output buffer. If *out is NULL then a new buffer is
  4698. * allocated. Otherwise the output is written to the buffer.
  4699. * @return length on success and -1 on error
  4700. */
  4701. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4702. {
  4703. /* Space for sequence + two asn ints */
  4704. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4705. word32 bufLen = sizeof(buf);
  4706. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4707. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4708. out == NULL) {
  4709. WOLFSSL_MSG("Bad function arguments");
  4710. return -1;
  4711. }
  4712. if (StoreECC_DSA_Sig(buf, &bufLen,
  4713. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4714. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4715. return -1;
  4716. }
  4717. if (*out == NULL) {
  4718. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4719. if (tmp == NULL) {
  4720. WOLFSSL_MSG("malloc error");
  4721. return -1;
  4722. }
  4723. *out = tmp;
  4724. }
  4725. XMEMCPY(*out, buf, bufLen);
  4726. return (int)bufLen;
  4727. }
  4728. /**
  4729. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4730. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4731. */
  4732. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4733. {
  4734. WOLFSSL_DSA_SIG* ret;
  4735. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4736. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4737. return NULL;
  4738. }
  4739. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4740. WOLFSSL_MSG("wolfSSL_BN_new error");
  4741. wolfSSL_DSA_SIG_free(ret);
  4742. return NULL;
  4743. }
  4744. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4745. WOLFSSL_MSG("wolfSSL_BN_new error");
  4746. wolfSSL_DSA_SIG_free(ret);
  4747. return NULL;
  4748. }
  4749. return ret;
  4750. }
  4751. /**
  4752. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4753. * ASN1_SEQUENCE
  4754. * ASN1_INTEGER (DSA r)
  4755. * ASN1_INTEGER (DSA s)
  4756. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4757. * length then this API interprets this as two unsigned binary numbers.
  4758. * @param sig If non-null then free'd first and then newly created
  4759. * WOLFSSL_DSA_SIG is assigned
  4760. * @param pp Input buffer that is moved forward on success
  4761. * @param length Length of input buffer
  4762. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4763. */
  4764. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4765. const unsigned char **pp, long length)
  4766. {
  4767. WOLFSSL_DSA_SIG* ret;
  4768. mp_int* r;
  4769. mp_int* s;
  4770. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4771. if (pp == NULL || *pp == NULL || length < 0) {
  4772. WOLFSSL_MSG("Bad function arguments");
  4773. return NULL;
  4774. }
  4775. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4776. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4777. return NULL;
  4778. }
  4779. r = (mp_int*)ret->r->internal;
  4780. s = (mp_int*)ret->s->internal;
  4781. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4782. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4783. /* Two raw numbers of length/2 size each */
  4784. if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) {
  4785. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4786. wolfSSL_DSA_SIG_free(ret);
  4787. return NULL;
  4788. }
  4789. if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) !=
  4790. 0) {
  4791. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4792. wolfSSL_DSA_SIG_free(ret);
  4793. return NULL;
  4794. }
  4795. *pp += length;
  4796. }
  4797. else {
  4798. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4799. wolfSSL_DSA_SIG_free(ret);
  4800. return NULL;
  4801. }
  4802. }
  4803. else {
  4804. /* DecodeECC_DSA_Sig success move pointer forward */
  4805. #ifndef NO_STRICT_ECDSA_LEN
  4806. *pp += length;
  4807. #else
  4808. {
  4809. /* We need to figure out how much to move by ourselves */
  4810. word32 idx = 0;
  4811. int len = 0;
  4812. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4813. WOLFSSL_MSG("GetSequence error");
  4814. wolfSSL_DSA_SIG_free(ret);
  4815. return NULL;
  4816. }
  4817. *pp += len;
  4818. }
  4819. #endif
  4820. }
  4821. if (sig != NULL) {
  4822. if (*sig != NULL)
  4823. wolfSSL_DSA_SIG_free(*sig);
  4824. *sig = ret;
  4825. }
  4826. return ret;
  4827. }
  4828. #endif /* HAVE_SELFTEST */
  4829. /* return 1 on success, < 0 otherwise */
  4830. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4831. WOLFSSL_DSA* dsa)
  4832. {
  4833. int ret = -1;
  4834. int initTmpRng = 0;
  4835. WC_RNG* rng = NULL;
  4836. #ifdef WOLFSSL_SMALL_STACK
  4837. WC_RNG* tmpRng = NULL;
  4838. #else
  4839. WC_RNG tmpRng[1];
  4840. #endif
  4841. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4842. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4843. WOLFSSL_MSG("Bad function arguments");
  4844. return ret;
  4845. }
  4846. if (dsa->inSet == 0) {
  4847. WOLFSSL_MSG("No DSA internal set, do it");
  4848. if (SetDsaInternal(dsa) != 1) {
  4849. WOLFSSL_MSG("SetDsaInternal failed");
  4850. return ret;
  4851. }
  4852. }
  4853. #ifdef WOLFSSL_SMALL_STACK
  4854. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4855. if (tmpRng == NULL)
  4856. return -1;
  4857. #endif
  4858. if (wc_InitRng(tmpRng) == 0) {
  4859. rng = tmpRng;
  4860. initTmpRng = 1;
  4861. }
  4862. else {
  4863. WOLFSSL_MSG("Bad RNG Init, trying global");
  4864. rng = wolfssl_get_global_rng();
  4865. }
  4866. if (rng) {
  4867. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4868. WOLFSSL_MSG("DsaSign failed");
  4869. else
  4870. ret = 1;
  4871. }
  4872. if (initTmpRng)
  4873. wc_FreeRng(tmpRng);
  4874. #ifdef WOLFSSL_SMALL_STACK
  4875. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4876. #endif
  4877. return ret;
  4878. }
  4879. #ifndef HAVE_SELFTEST
  4880. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4881. int inLen, WOLFSSL_DSA* dsa)
  4882. {
  4883. byte sigBin[DSA_MAX_SIG_SIZE];
  4884. const byte *tmp = sigBin;
  4885. int sigLen;
  4886. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4887. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4888. WOLFSSL_MSG("Bad function arguments");
  4889. return NULL;
  4890. }
  4891. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4892. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4893. return NULL;
  4894. }
  4895. if (dsa->internal == NULL) {
  4896. WOLFSSL_MSG("dsa->internal is null");
  4897. return NULL;
  4898. }
  4899. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4900. if (sigLen <= 0) {
  4901. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4902. return NULL;
  4903. }
  4904. /* 2 * sigLen for the two points r and s */
  4905. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4906. }
  4907. #endif /* !HAVE_SELFTEST */
  4908. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4909. WOLFSSL_DSA* dsa, int *dsacheck)
  4910. {
  4911. int ret = -1;
  4912. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4913. if (d == NULL || sig == NULL || dsa == NULL) {
  4914. WOLFSSL_MSG("Bad function arguments");
  4915. return -1;
  4916. }
  4917. if (dsa->inSet == 0)
  4918. {
  4919. WOLFSSL_MSG("No DSA internal set, do it");
  4920. if (SetDsaInternal(dsa) != 1) {
  4921. WOLFSSL_MSG("SetDsaInternal failed");
  4922. return -1;
  4923. }
  4924. }
  4925. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4926. if (ret != 0 || *dsacheck != 1) {
  4927. WOLFSSL_MSG("DsaVerify failed");
  4928. return ret;
  4929. }
  4930. return 1;
  4931. }
  4932. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4933. {
  4934. if (!d)
  4935. return 0;
  4936. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4937. return 0;
  4938. return wolfSSL_BN_num_bits(d->p);
  4939. }
  4940. #ifndef HAVE_SELFTEST
  4941. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4942. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4943. {
  4944. int dsacheck, sz;
  4945. byte sigBin[DSA_MAX_SIG_SIZE];
  4946. byte* sigBinPtr = sigBin;
  4947. DsaKey* key;
  4948. int qSz;
  4949. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4950. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4951. WOLFSSL_MSG("Bad function arguments");
  4952. return 0;
  4953. }
  4954. if (!sig->r || !sig->s) {
  4955. WOLFSSL_MSG("No signature found in DSA_SIG");
  4956. return 0;
  4957. }
  4958. if (dsa->inSet == 0) {
  4959. WOLFSSL_MSG("No DSA internal set, do it");
  4960. if (SetDsaInternal(dsa) != 1) {
  4961. WOLFSSL_MSG("SetDsaInternal failed");
  4962. return 0;
  4963. }
  4964. }
  4965. key = (DsaKey*)dsa->internal;
  4966. if (key == NULL) {
  4967. WOLFSSL_MSG("dsa->internal is null");
  4968. return 0;
  4969. }
  4970. qSz = mp_unsigned_bin_size(&key->q);
  4971. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4972. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4973. return 0;
  4974. }
  4975. /* read r */
  4976. /* front pad with zeros */
  4977. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4978. return 0;
  4979. while (sz++ < qSz)
  4980. *sigBinPtr++ = 0;
  4981. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4982. return 0;
  4983. /* Move to s */
  4984. sigBinPtr = sigBin + qSz;
  4985. /* read s */
  4986. /* front pad with zeros */
  4987. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4988. return 0;
  4989. while (sz++ < qSz)
  4990. *sigBinPtr++ = 0;
  4991. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4992. return 0;
  4993. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4994. != 1) || dsacheck != 1) {
  4995. return 0;
  4996. }
  4997. return 1;
  4998. }
  4999. #endif /* !HAVE_SELFTEST */
  5000. WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  5001. unsigned char** out)
  5002. {
  5003. int ret = 0;
  5004. word32 derLen = 0;
  5005. int preAllocated = 1;
  5006. DsaKey* key = NULL;
  5007. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  5008. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  5009. ret = BAD_FUNC_ARG;
  5010. }
  5011. if (ret == 0) {
  5012. key = (DsaKey*)dsa->internal;
  5013. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  5014. if (ret == LENGTH_ONLY_E) {
  5015. ret = 0;
  5016. }
  5017. }
  5018. if (ret == 0 && *out == NULL) {
  5019. /* If we're allocating out for the caller, we don't increment out just
  5020. past the end of the DER buffer. If out is already allocated, we do.
  5021. (OpenSSL convention) */
  5022. preAllocated = 0;
  5023. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  5024. if (*out == NULL) {
  5025. ret = MEMORY_E;
  5026. }
  5027. }
  5028. if (ret == 0) {
  5029. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  5030. }
  5031. if (ret >= 0 && preAllocated == 1) {
  5032. *out += derLen;
  5033. }
  5034. if (ret < 0 && preAllocated == 0) {
  5035. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  5036. }
  5037. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  5038. return ret;
  5039. }
  5040. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  5041. long derLen)
  5042. {
  5043. WOLFSSL_DSA* ret = NULL;
  5044. int err = 0;
  5045. word32 idx = 0;
  5046. int asnLen;
  5047. DsaKey* internalKey = NULL;
  5048. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  5049. if (der == NULL || *der == NULL || derLen <= 0) {
  5050. err = 1;
  5051. }
  5052. if (err == 0) {
  5053. ret = wolfSSL_DSA_new();
  5054. err = ret == NULL;
  5055. }
  5056. if (err == 0) {
  5057. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  5058. }
  5059. if (err == 0) {
  5060. internalKey = (DsaKey*)ret->internal;
  5061. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  5062. }
  5063. if (err == 0) {
  5064. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  5065. }
  5066. if (err == 0) {
  5067. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  5068. }
  5069. if (err == 0) {
  5070. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  5071. != 1;
  5072. }
  5073. if (err == 0) {
  5074. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  5075. != 1;
  5076. }
  5077. if (err == 0) {
  5078. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  5079. != 1;
  5080. }
  5081. if (err == 0 && dsa != NULL) {
  5082. *dsa = ret;
  5083. }
  5084. if (err != 0 && ret != NULL) {
  5085. wolfSSL_DSA_free(ret);
  5086. ret = NULL;
  5087. }
  5088. return ret;
  5089. }
  5090. #if defined(WOLFSSL_KEY_GEN)
  5091. #ifndef NO_BIO
  5092. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  5093. * Returns 1 or 0
  5094. */
  5095. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  5096. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  5097. wc_pem_password_cb* cb, void* arg)
  5098. {
  5099. int ret = 1;
  5100. byte *pem = NULL;
  5101. int pLen = 0;
  5102. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  5103. (void)cb;
  5104. (void)arg;
  5105. /* Validate parameters. */
  5106. if ((bio == NULL) || (dsa == NULL)) {
  5107. WOLFSSL_MSG("Bad Function Arguments");
  5108. ret = 0;
  5109. }
  5110. if (ret == 1) {
  5111. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, cipher, passwd, passwdSz,
  5112. &pem, &pLen);
  5113. }
  5114. /* Write PEM to BIO. */
  5115. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  5116. WOLFSSL_ERROR_MSG("DSA private key BIO write failed");
  5117. ret = 0;
  5118. }
  5119. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5120. return ret;
  5121. }
  5122. #ifndef HAVE_SELFTEST
  5123. /* Encode the DSA public key as DER.
  5124. *
  5125. * @param [in] key DSA key to encode.
  5126. * @param [out] der Pointer through which buffer is returned.
  5127. * @param [in] heap Heap hint.
  5128. * @return Size of encoding on success.
  5129. * @return 0 on error.
  5130. */
  5131. static int wolfssl_dsa_key_to_pubkey_der(WOLFSSL_DSA* key, unsigned char** der,
  5132. void* heap)
  5133. {
  5134. int sz;
  5135. unsigned char* buf = NULL;
  5136. /* Use maximum encoded size to allocate. */
  5137. sz = MAX_DSA_PUBKEY_SZ;
  5138. /* Allocate memory to hold encoding. */
  5139. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5140. if (buf == NULL) {
  5141. WOLFSSL_MSG("malloc failed");
  5142. sz = 0;
  5143. }
  5144. if (sz > 0) {
  5145. /* Encode public key to DER using wolfSSL. */
  5146. sz = wc_DsaKeyToPublicDer((DsaKey*)key->internal, buf, sz);
  5147. if (sz < 0) {
  5148. WOLFSSL_MSG("wc_DsaKeyToPublicDer failed");
  5149. sz = 0;
  5150. }
  5151. }
  5152. /* Return buffer on success. */
  5153. if (sz > 0) {
  5154. *der = buf;
  5155. }
  5156. else {
  5157. /* Dispose of any dynamically allocated data not returned. */
  5158. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  5159. }
  5160. return sz;
  5161. }
  5162. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5163. * Returns 1 or 0
  5164. */
  5165. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5166. {
  5167. int ret = 1;
  5168. unsigned char* derBuf = NULL;
  5169. int derSz = 0;
  5170. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5171. /* Validate parameters. */
  5172. if ((bio == NULL) || (dsa == NULL)) {
  5173. WOLFSSL_MSG("Bad Function Arguments");
  5174. return 0;
  5175. }
  5176. /* Encode public key in EC key as DER. */
  5177. derSz = wolfssl_dsa_key_to_pubkey_der(dsa, &derBuf, bio->heap);
  5178. if (derSz == 0) {
  5179. ret = 0;
  5180. }
  5181. /* Write out to BIO the PEM encoding of the DSA public key. */
  5182. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  5183. PUBLICKEY_TYPE) != 1)) {
  5184. ret = 0;
  5185. }
  5186. /* Dispose of any dynamically allocated data. */
  5187. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5188. return ret;
  5189. }
  5190. #endif /* HAVE_SELFTEST */
  5191. #endif /* !NO_BIO */
  5192. /* return code compliant with OpenSSL :
  5193. * 1 if success, 0 if error
  5194. */
  5195. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5196. const EVP_CIPHER* cipher,
  5197. unsigned char* passwd, int passwdSz,
  5198. unsigned char **pem, int *pLen)
  5199. {
  5200. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5201. byte *derBuf, *tmp, *cipherInfo = NULL;
  5202. int der_max_len = 0, derSz = 0;
  5203. const int type = DSA_PRIVATEKEY_TYPE;
  5204. const char* header = NULL;
  5205. const char* footer = NULL;
  5206. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5207. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5208. WOLFSSL_MSG("Bad function arguments");
  5209. return 0;
  5210. }
  5211. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5212. return 0;
  5213. if (dsa->inSet == 0) {
  5214. WOLFSSL_MSG("No DSA internal set, do it");
  5215. if (SetDsaInternal(dsa) != 1) {
  5216. WOLFSSL_MSG("SetDsaInternal failed");
  5217. return 0;
  5218. }
  5219. }
  5220. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5221. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER);
  5222. if (derBuf == NULL) {
  5223. WOLFSSL_MSG("malloc failed");
  5224. return 0;
  5225. }
  5226. /* Key to DER */
  5227. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5228. if (derSz < 0) {
  5229. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5230. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5231. return 0;
  5232. }
  5233. /* encrypt DER buffer if required */
  5234. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5235. int ret;
  5236. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5237. passwd, passwdSz, &cipherInfo, der_max_len);
  5238. if (ret != 1) {
  5239. WOLFSSL_MSG("EncryptDerKey failed");
  5240. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5241. return ret;
  5242. }
  5243. /* tmp buffer with a max size */
  5244. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5245. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5246. }
  5247. else { /* tmp buffer with a max size */
  5248. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5249. (int)XSTRLEN(footer) + 1;
  5250. }
  5251. tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM);
  5252. if (tmp == NULL) {
  5253. WOLFSSL_MSG("malloc failed");
  5254. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5255. if (cipherInfo != NULL)
  5256. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5257. return 0;
  5258. }
  5259. /* DER to PEM */
  5260. *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo,
  5261. type);
  5262. if (*pLen <= 0) {
  5263. WOLFSSL_MSG("wc_DerToPemEx failed");
  5264. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5265. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5266. if (cipherInfo != NULL)
  5267. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5268. return 0;
  5269. }
  5270. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5271. if (cipherInfo != NULL)
  5272. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5273. *pem = (byte*)XMALLOC((size_t)((*pLen)+1), NULL, DYNAMIC_TYPE_KEY);
  5274. if (*pem == NULL) {
  5275. WOLFSSL_MSG("malloc failed");
  5276. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5277. return 0;
  5278. }
  5279. XMEMSET(*pem, 0, (size_t)((*pLen)+1));
  5280. if (XMEMCPY(*pem, tmp, (size_t)*pLen) == NULL) {
  5281. WOLFSSL_MSG("XMEMCPY failed");
  5282. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5283. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5284. return 0;
  5285. }
  5286. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5287. return 1;
  5288. #else
  5289. (void)dsa;
  5290. (void)cipher;
  5291. (void)passwd;
  5292. (void)passwdSz;
  5293. (void)pem;
  5294. (void)pLen;
  5295. return 0;
  5296. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5297. }
  5298. #ifndef NO_FILESYSTEM
  5299. /* return code compliant with OpenSSL :
  5300. * 1 if success, 0 if error
  5301. */
  5302. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5303. const EVP_CIPHER *enc,
  5304. unsigned char *kstr, int klen,
  5305. wc_pem_password_cb *cb, void *u)
  5306. {
  5307. byte *pem;
  5308. int pLen, ret;
  5309. (void)cb;
  5310. (void)u;
  5311. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5312. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5313. WOLFSSL_MSG("Bad function arguments");
  5314. return 0;
  5315. }
  5316. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5317. &pLen);
  5318. if (ret != 1) {
  5319. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5320. return 0;
  5321. }
  5322. ret = (int)XFWRITE(pem, (size_t)pLen, 1, fp);
  5323. if (ret != 1) {
  5324. WOLFSSL_MSG("DSA private key file write failed");
  5325. return 0;
  5326. }
  5327. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5328. return 1;
  5329. }
  5330. #endif /* NO_FILESYSTEM */
  5331. #endif /* defined(WOLFSSL_KEY_GEN) */
  5332. #ifndef NO_FILESYSTEM
  5333. /* return code compliant with OpenSSL :
  5334. * 1 if success, 0 if error
  5335. */
  5336. #ifndef NO_WOLFSSL_STUB
  5337. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5338. {
  5339. (void)fp;
  5340. (void)x;
  5341. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5342. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5343. return 0;
  5344. }
  5345. #endif
  5346. #endif /* NO_FILESYSTEM */
  5347. #ifndef NO_BIO
  5348. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5349. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5350. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5351. * the results to be an DSA key.
  5352. *
  5353. * bio structure to read DSA private key from
  5354. * dsa if not null is then set to the result
  5355. * cb password callback for reading PEM
  5356. * pass password string
  5357. *
  5358. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5359. */
  5360. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5361. WOLFSSL_DSA** dsa,
  5362. wc_pem_password_cb* cb,
  5363. void* pass)
  5364. {
  5365. WOLFSSL_EVP_PKEY* pkey = NULL;
  5366. WOLFSSL_DSA* local;
  5367. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5368. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5369. if (pkey == NULL) {
  5370. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5371. return NULL;
  5372. }
  5373. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5374. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5375. * to avoid having it free'd */
  5376. pkey->ownDsa = 0;
  5377. local = pkey->dsa;
  5378. if (dsa != NULL) {
  5379. *dsa = local;
  5380. }
  5381. wolfSSL_EVP_PKEY_free(pkey);
  5382. return local;
  5383. }
  5384. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5385. * Returns 1 or 0
  5386. */
  5387. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5388. wc_pem_password_cb* cb, void* pass)
  5389. {
  5390. WOLFSSL_EVP_PKEY* pkey;
  5391. WOLFSSL_DSA* local;
  5392. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5393. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5394. if (pkey == NULL) {
  5395. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5396. return NULL;
  5397. }
  5398. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5399. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5400. * to avoid having it free'd */
  5401. pkey->ownDsa = 0;
  5402. local = pkey->dsa;
  5403. if (dsa != NULL) {
  5404. *dsa = local;
  5405. }
  5406. wolfSSL_EVP_PKEY_free(pkey);
  5407. return local;
  5408. }
  5409. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5410. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5411. #endif /* NO_BIO */
  5412. #endif /* OPENSSL_EXTRA */
  5413. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5414. /* return 1 if success, -1 if error */
  5415. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5416. {
  5417. word32 idx = 0;
  5418. int ret;
  5419. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5420. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5421. WOLFSSL_MSG("Bad function arguments");
  5422. return -1;
  5423. }
  5424. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5425. (word32)derSz);
  5426. if (ret < 0) {
  5427. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5428. return -1;
  5429. }
  5430. if (SetDsaExternal(dsa) != 1) {
  5431. WOLFSSL_MSG("SetDsaExternal failed");
  5432. return -1;
  5433. }
  5434. dsa->inSet = 1;
  5435. return 1;
  5436. }
  5437. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5438. returns 1 on success, or 0 on failure. */
  5439. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5440. int derSz, int opt)
  5441. {
  5442. word32 idx = 0;
  5443. int ret;
  5444. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5445. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5446. WOLFSSL_MSG("Bad function arguments");
  5447. return -1;
  5448. }
  5449. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5450. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5451. (word32)derSz);
  5452. }
  5453. else {
  5454. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5455. (word32)derSz);
  5456. }
  5457. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5458. WOLFSSL_ERROR_VERBOSE(ret);
  5459. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5460. return -1;
  5461. }
  5462. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5463. WOLFSSL_ERROR_VERBOSE(ret);
  5464. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5465. return -1;
  5466. }
  5467. if (SetDsaExternal(dsa) != 1) {
  5468. WOLFSSL_MSG("SetDsaExternal failed");
  5469. return -1;
  5470. }
  5471. dsa->inSet = 1;
  5472. return 1;
  5473. }
  5474. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5475. #ifdef OPENSSL_EXTRA
  5476. #ifndef NO_BIO
  5477. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5478. wc_pem_password_cb *cb, void *u)
  5479. {
  5480. WOLFSSL_DSA* dsa;
  5481. DsaKey* key;
  5482. int length;
  5483. unsigned char* buf;
  5484. word32 bufSz;
  5485. int ret;
  5486. word32 idx = 0;
  5487. DerBuffer* pDer;
  5488. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5489. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5490. if (ret <= 0) {
  5491. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5492. return NULL;
  5493. }
  5494. bufSz = (word32)ret;
  5495. if (cb != NULL || u != NULL) {
  5496. /*
  5497. * cb is for a call back when encountering encrypted PEM files
  5498. * if cb == NULL and u != NULL then u = null terminated password string
  5499. */
  5500. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5501. }
  5502. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5503. NULL) < 0 ) {
  5504. WOLFSSL_MSG("Issue converting from PEM to DER");
  5505. return NULL;
  5506. }
  5507. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5508. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5509. FreeDer(&pDer);
  5510. return NULL;
  5511. }
  5512. dsa = wolfSSL_DSA_new();
  5513. if (dsa == NULL) {
  5514. FreeDer(&pDer);
  5515. WOLFSSL_MSG("Error creating DSA struct");
  5516. return NULL;
  5517. }
  5518. key = (DsaKey*)dsa->internal;
  5519. if (key == NULL) {
  5520. FreeDer(&pDer);
  5521. wolfSSL_DSA_free(dsa);
  5522. WOLFSSL_MSG("Error finding DSA key struct");
  5523. return NULL;
  5524. }
  5525. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5526. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5527. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5528. WOLFSSL_MSG("dsa key error");
  5529. FreeDer(&pDer);
  5530. wolfSSL_DSA_free(dsa);
  5531. return NULL;
  5532. }
  5533. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5534. WOLFSSL_MSG("dsa p key error");
  5535. FreeDer(&pDer);
  5536. wolfSSL_DSA_free(dsa);
  5537. return NULL;
  5538. }
  5539. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5540. WOLFSSL_MSG("dsa q key error");
  5541. FreeDer(&pDer);
  5542. wolfSSL_DSA_free(dsa);
  5543. return NULL;
  5544. }
  5545. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5546. WOLFSSL_MSG("dsa g key error");
  5547. FreeDer(&pDer);
  5548. wolfSSL_DSA_free(dsa);
  5549. return NULL;
  5550. }
  5551. if (x != NULL) {
  5552. *x = dsa;
  5553. }
  5554. FreeDer(&pDer);
  5555. return dsa;
  5556. }
  5557. #endif /* !NO_BIO */
  5558. #if !defined(NO_DH)
  5559. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5560. {
  5561. WOLFSSL_DH* dh;
  5562. DhKey* key;
  5563. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5564. if (dsa == NULL) {
  5565. return NULL;
  5566. }
  5567. dh = wolfSSL_DH_new();
  5568. if (dh == NULL) {
  5569. return NULL;
  5570. }
  5571. key = (DhKey*)dh->internal;
  5572. if (dsa->p != NULL &&
  5573. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5574. != 1) {
  5575. WOLFSSL_MSG("rsa p key error");
  5576. wolfSSL_DH_free(dh);
  5577. return NULL;
  5578. }
  5579. if (dsa->g != NULL &&
  5580. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5581. != 1) {
  5582. WOLFSSL_MSG("rsa g key error");
  5583. wolfSSL_DH_free(dh);
  5584. return NULL;
  5585. }
  5586. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5587. WOLFSSL_MSG("dsa p key error");
  5588. wolfSSL_DH_free(dh);
  5589. return NULL;
  5590. }
  5591. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5592. WOLFSSL_MSG("dsa g key error");
  5593. wolfSSL_DH_free(dh);
  5594. return NULL;
  5595. }
  5596. return dh;
  5597. }
  5598. #endif /* !NO_DH */
  5599. #endif /* OPENSSL_EXTRA */
  5600. #endif /* !NO_DSA */
  5601. /*******************************************************************************
  5602. * END OF DSA API
  5603. ******************************************************************************/
  5604. /*******************************************************************************
  5605. * START OF DH API
  5606. ******************************************************************************/
  5607. #ifndef NO_DH
  5608. #ifdef OPENSSL_EXTRA
  5609. /*
  5610. * DH constructor/deconstructor APIs
  5611. */
  5612. /* Allocate and initialize a new DH key.
  5613. *
  5614. * @return DH key on success.
  5615. * @return NULL on failure.
  5616. */
  5617. WOLFSSL_DH* wolfSSL_DH_new(void)
  5618. {
  5619. int err = 0;
  5620. WOLFSSL_DH* dh = NULL;
  5621. DhKey* key = NULL;
  5622. WOLFSSL_ENTER("wolfSSL_DH_new");
  5623. /* Allocate OpenSSL DH key. */
  5624. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5625. if (dh == NULL) {
  5626. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5627. err = 1;
  5628. }
  5629. if (!err) {
  5630. /* Clear key data. */
  5631. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5632. /* Initialize reference counting. */
  5633. wolfSSL_RefInit(&dh->ref, &err);
  5634. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5635. }
  5636. if (!err) {
  5637. #endif
  5638. /* Allocate wolfSSL DH key. */
  5639. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5640. if (key == NULL) {
  5641. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5642. err = 1;
  5643. }
  5644. }
  5645. if (!err) {
  5646. /* Set and initialize wolfSSL DH key. */
  5647. dh->internal = key;
  5648. if (wc_InitDhKey(key) != 0) {
  5649. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5650. err = 1;
  5651. }
  5652. }
  5653. if (err && (dh != NULL)) {
  5654. /* Dispose of the allocated memory. */
  5655. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5656. wolfSSL_RefFree(&dh->ref);
  5657. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5658. dh = NULL;
  5659. }
  5660. return dh;
  5661. }
  5662. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5663. /* Set the DH parameters based on the NID.
  5664. *
  5665. * @param [in, out] dh DH key to set.
  5666. * @param [in] nid Numeric ID of predefined DH parameters.
  5667. * @return 0 on success.
  5668. * @return 1 on failure.
  5669. */
  5670. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5671. {
  5672. int err = 0;
  5673. const DhParams* params = NULL;
  5674. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5675. * FIPS v2 module */
  5676. switch (nid) {
  5677. #ifdef HAVE_FFDHE_2048
  5678. case NID_ffdhe2048:
  5679. params = wc_Dh_ffdhe2048_Get();
  5680. break;
  5681. #endif /* HAVE_FFDHE_2048 */
  5682. #ifdef HAVE_FFDHE_3072
  5683. case NID_ffdhe3072:
  5684. params = wc_Dh_ffdhe3072_Get();
  5685. break;
  5686. #endif /* HAVE_FFDHE_3072 */
  5687. #ifdef HAVE_FFDHE_4096
  5688. case NID_ffdhe4096:
  5689. params = wc_Dh_ffdhe4096_Get();
  5690. break;
  5691. #endif /* HAVE_FFDHE_4096 */
  5692. default:
  5693. break;
  5694. }
  5695. if (params == NULL) {
  5696. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5697. err = 1;
  5698. }
  5699. if (!err) {
  5700. /* Set prime from data retrieved. */
  5701. dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL);
  5702. if (dh->p == NULL) {
  5703. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5704. err = 1;
  5705. }
  5706. }
  5707. if (!err) {
  5708. /* Set generator from data retrieved. */
  5709. dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL);
  5710. if (dh->g == NULL) {
  5711. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5712. err = 1;
  5713. }
  5714. }
  5715. #ifdef HAVE_FFDHE_Q
  5716. if (!err) {
  5717. /* Set order from data retrieved. */
  5718. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5719. if (dh->q == NULL) {
  5720. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5721. err = 1;
  5722. }
  5723. }
  5724. #endif
  5725. /* Synchronize the external into internal DH key's parameters. */
  5726. if ((!err) && (SetDhInternal(dh) != 1)) {
  5727. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5728. err = 1;
  5729. }
  5730. if (!err) {
  5731. /* External DH key parameters were set. */
  5732. dh->exSet = 1;
  5733. }
  5734. if (err == 1) {
  5735. /* Dispose of any external parameters. */
  5736. #ifdef HAVE_FFDHE_Q
  5737. wolfSSL_BN_free(dh->q);
  5738. dh->q = NULL;
  5739. #endif
  5740. wolfSSL_BN_free(dh->p);
  5741. dh->p = NULL;
  5742. wolfSSL_BN_free(dh->g);
  5743. dh->g = NULL;
  5744. }
  5745. return err;
  5746. }
  5747. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5748. FIPS_VERSION_GT(2,0))
  5749. /* Set the DH parameters based on the NID.
  5750. *
  5751. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5752. *
  5753. * @param [in, out] dh DH key to set.
  5754. * @param [in] nid Numeric ID of predefined DH parameters.
  5755. * @return 0 on success.
  5756. * @return 1 on failure.
  5757. */
  5758. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5759. {
  5760. int err = 0;
  5761. int name = 0;
  5762. #ifdef HAVE_FFDHE_Q
  5763. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5764. #else
  5765. int elements = ELEMENT_P | ELEMENT_G;
  5766. #endif /* HAVE_FFDHE_Q */
  5767. switch (nid) {
  5768. #ifdef HAVE_FFDHE_2048
  5769. case NID_ffdhe2048:
  5770. name = WC_FFDHE_2048;
  5771. break;
  5772. #endif /* HAVE_FFDHE_2048 */
  5773. #ifdef HAVE_FFDHE_3072
  5774. case NID_ffdhe3072:
  5775. name = WC_FFDHE_3072;
  5776. break;
  5777. #endif /* HAVE_FFDHE_3072 */
  5778. #ifdef HAVE_FFDHE_4096
  5779. case NID_ffdhe4096:
  5780. name = WC_FFDHE_4096;
  5781. break;
  5782. #endif /* HAVE_FFDHE_4096 */
  5783. default:
  5784. err = 1;
  5785. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5786. break;
  5787. }
  5788. /* Set the internal DH key's parameters based on name. */
  5789. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5790. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5791. err = 1;
  5792. }
  5793. /* Synchronize the internal into external DH key's parameters. */
  5794. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5795. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5796. err = 1;
  5797. }
  5798. return err;
  5799. }
  5800. #else
  5801. /* Set the DH parameters based on the NID.
  5802. *
  5803. * Pre-defined DH parameters not available.
  5804. *
  5805. * @param [in, out] dh DH key to set.
  5806. * @param [in] nid Numeric ID of predefined DH parameters.
  5807. * @return 1 for failure.
  5808. */
  5809. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5810. {
  5811. return 1;
  5812. }
  5813. #endif
  5814. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5815. *
  5816. * @param [in] nid Numeric ID of DH parameters.
  5817. *
  5818. * @return DH key on success.
  5819. * @return NULL on failure.
  5820. */
  5821. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5822. {
  5823. WOLFSSL_DH* dh = NULL;
  5824. int err = 0;
  5825. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5826. /* Allocate a new DH key. */
  5827. dh = wolfSSL_DH_new();
  5828. if (dh == NULL) {
  5829. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5830. err = 1;
  5831. }
  5832. if (!err) {
  5833. /* Set the parameters based on NID. */
  5834. err = wolfssl_dh_set_nid(dh, nid);
  5835. }
  5836. if (err && (dh != NULL)) {
  5837. /* Dispose of the key on failure to set. */
  5838. wolfSSL_DH_free(dh);
  5839. dh = NULL;
  5840. }
  5841. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5842. return dh;
  5843. }
  5844. /* Dispose of DH key and allocated data.
  5845. *
  5846. * Cannot use dh after this call.
  5847. *
  5848. * @param [in] dh DH key to free.
  5849. */
  5850. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5851. {
  5852. int doFree = 0;
  5853. WOLFSSL_ENTER("wolfSSL_DH_free");
  5854. if (dh != NULL) {
  5855. int err;
  5856. /* Only free if all references to it are done */
  5857. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5858. /* Ignore errors - doFree will be 0 on error. */
  5859. (void)err;
  5860. }
  5861. if (doFree) {
  5862. /* Dispose of allocated reference counting data. */
  5863. wolfSSL_RefFree(&dh->ref);
  5864. /* Dispose of wolfSSL DH key. */
  5865. if (dh->internal) {
  5866. wc_FreeDhKey((DhKey*)dh->internal);
  5867. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5868. dh->internal = NULL;
  5869. }
  5870. /* Dispose of any allocated BNs. */
  5871. wolfSSL_BN_free(dh->priv_key);
  5872. wolfSSL_BN_free(dh->pub_key);
  5873. wolfSSL_BN_free(dh->g);
  5874. wolfSSL_BN_free(dh->p);
  5875. wolfSSL_BN_free(dh->q);
  5876. /* Set back to NULLs for safety. */
  5877. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5878. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5879. }
  5880. }
  5881. /* Increments ref count of DH key.
  5882. *
  5883. * @param [in, out] dh DH key.
  5884. * @return 1 on success
  5885. * @return 0 on error
  5886. */
  5887. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5888. {
  5889. int err = 1;
  5890. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5891. if (dh != NULL) {
  5892. wolfSSL_RefInc(&dh->ref, &err);
  5893. }
  5894. return !err;
  5895. }
  5896. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5897. defined(OPENSSL_EXTRA)
  5898. #ifdef WOLFSSL_DH_EXTRA
  5899. /* Duplicate the DH key.
  5900. *
  5901. * Internal DH key in 'dh' is updated if necessary.
  5902. *
  5903. * @param [in, out] dh DH key to duplicate.
  5904. * @return NULL on failure.
  5905. * @return DH key on success.
  5906. */
  5907. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5908. {
  5909. WOLFSSL_DH* ret = NULL;
  5910. int err = 0;
  5911. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5912. /* Validate parameters. */
  5913. if (dh == NULL) {
  5914. WOLFSSL_ERROR_MSG("Bad parameter");
  5915. err = 1;
  5916. }
  5917. /* Ensure internal DH key is set. */
  5918. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5919. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5920. err = 1;
  5921. }
  5922. /* Create a new DH key object. */
  5923. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5924. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5925. err = 1;
  5926. }
  5927. /* Copy internal DH key from original to new. */
  5928. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5929. MP_OKAY)) {
  5930. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5931. err = 1;
  5932. }
  5933. if (!err) {
  5934. ret->inSet = 1;
  5935. /* Synchronize the internal into external DH key's parameters. */
  5936. if (SetDhExternal(ret) != 1) {
  5937. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5938. err = 1;
  5939. }
  5940. }
  5941. /* Dispose of any allocated DH key on error. */
  5942. if (err && (ret != NULL)) {
  5943. wolfSSL_DH_free(ret);
  5944. ret = NULL;
  5945. }
  5946. return ret;
  5947. }
  5948. #endif /* WOLFSSL_DH_EXTRA */
  5949. #endif
  5950. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5951. *
  5952. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5953. * Subgroup."
  5954. *
  5955. * @return NULL on failure.
  5956. * @return DH Key on success.
  5957. */
  5958. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5959. {
  5960. WOLFSSL_DH* dh;
  5961. int err = 0;
  5962. static const byte pHex[] = {
  5963. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5964. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5965. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5966. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5967. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5968. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5969. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5970. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5971. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5972. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5973. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5974. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5975. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5976. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5977. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5978. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5979. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5980. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5981. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5982. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5983. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5984. 0x1E, 0x1A, 0x15, 0x97
  5985. };
  5986. static const byte gHex[] = {
  5987. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5988. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5989. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5990. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5991. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5992. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5993. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5994. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5995. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5996. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5997. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5998. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5999. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  6000. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  6001. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  6002. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  6003. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  6004. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  6005. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  6006. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  6007. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  6008. 0x6C, 0xC4, 0x16, 0x59
  6009. };
  6010. static const byte qHex[] = {
  6011. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  6012. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  6013. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  6014. };
  6015. /* Create a new DH key to return. */
  6016. dh = wolfSSL_DH_new();
  6017. if (dh == NULL) {
  6018. err = 1;
  6019. }
  6020. if (!err) {
  6021. /* Set prime. */
  6022. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  6023. if (dh->p == NULL) {
  6024. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  6025. err = 1;
  6026. }
  6027. }
  6028. if (!err) {
  6029. /* Set generator. */
  6030. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  6031. if (dh->g == NULL) {
  6032. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  6033. err = 1;
  6034. }
  6035. }
  6036. if (!err) {
  6037. /* Set order. */
  6038. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  6039. if (dh->q == NULL) {
  6040. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  6041. err = 1;
  6042. }
  6043. }
  6044. /* Set values into wolfSSL DH key. */
  6045. if ((!err) && (SetDhInternal(dh) != 1)) {
  6046. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  6047. err = 1;
  6048. }
  6049. if (!err) {
  6050. /* External DH key parameters were set. */
  6051. dh->exSet = 1;
  6052. }
  6053. /* Dispose of any allocated DH key on error. */
  6054. if (err && (dh != NULL)) {
  6055. wolfSSL_DH_free(dh);
  6056. dh = NULL;
  6057. }
  6058. return dh;
  6059. }
  6060. /* TODO: consider changing strings to byte arrays. */
  6061. /* Returns a big number with the 768-bit prime from RFC 2409.
  6062. *
  6063. * @param [in, out] bn If not NULL then this BN is set and returned.
  6064. * If NULL then a new BN is created, set and returned.
  6065. *
  6066. * @return NULL on failure.
  6067. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  6068. */
  6069. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  6070. {
  6071. #if WOLFSSL_MAX_BN_BITS >= 768
  6072. static const char prm[] = {
  6073. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6074. "C4C6628B80DC1CD129024E088A67CC74"
  6075. "020BBEA63B139B22514A08798E3404DD"
  6076. "EF9519B3CD3A431B302B0A6DF25F1437"
  6077. "4FE1356D6D51C245E485B576625E7EC6"
  6078. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  6079. };
  6080. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  6081. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6082. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6083. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  6084. bn = NULL;
  6085. }
  6086. return bn;
  6087. #else
  6088. (void)bn;
  6089. return NULL;
  6090. #endif
  6091. }
  6092. /* Returns a big number with the 1024-bit prime from RFC 2409.
  6093. *
  6094. * @param [in, out] bn If not NULL then this BN is set and returned.
  6095. * If NULL then a new BN is created, set and returned.
  6096. *
  6097. * @return NULL on failure.
  6098. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  6099. */
  6100. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  6101. {
  6102. #if WOLFSSL_MAX_BN_BITS >= 1024
  6103. static const char prm[] = {
  6104. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6105. "C4C6628B80DC1CD129024E088A67CC74"
  6106. "020BBEA63B139B22514A08798E3404DD"
  6107. "EF9519B3CD3A431B302B0A6DF25F1437"
  6108. "4FE1356D6D51C245E485B576625E7EC6"
  6109. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6110. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6111. "49286651ECE65381FFFFFFFFFFFFFFFF"
  6112. };
  6113. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  6114. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6115. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6116. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  6117. bn = NULL;
  6118. }
  6119. return bn;
  6120. #else
  6121. (void)bn;
  6122. return NULL;
  6123. #endif
  6124. }
  6125. /* Returns a big number with the 1536-bit prime from RFC 3526.
  6126. *
  6127. * @param [in, out] bn If not NULL then this BN is set and returned.
  6128. * If NULL then a new BN is created, set and returned.
  6129. *
  6130. * @return NULL on failure.
  6131. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  6132. */
  6133. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  6134. {
  6135. #if WOLFSSL_MAX_BN_BITS >= 1536
  6136. static const char prm[] = {
  6137. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6138. "C4C6628B80DC1CD129024E088A67CC74"
  6139. "020BBEA63B139B22514A08798E3404DD"
  6140. "EF9519B3CD3A431B302B0A6DF25F1437"
  6141. "4FE1356D6D51C245E485B576625E7EC6"
  6142. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6143. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6144. "49286651ECE45B3DC2007CB8A163BF05"
  6145. "98DA48361C55D39A69163FA8FD24CF5F"
  6146. "83655D23DCA3AD961C62F356208552BB"
  6147. "9ED529077096966D670C354E4ABC9804"
  6148. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6149. };
  6150. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6151. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6152. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6153. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6154. bn = NULL;
  6155. }
  6156. return bn;
  6157. #else
  6158. (void)bn;
  6159. return NULL;
  6160. #endif
  6161. }
  6162. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6163. *
  6164. * @param [in, out] bn If not NULL then this BN is set and returned.
  6165. * If NULL then a new BN is created, set and returned.
  6166. *
  6167. * @return NULL on failure.
  6168. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6169. */
  6170. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6171. {
  6172. #if WOLFSSL_MAX_BN_BITS >= 2048
  6173. static const char prm[] = {
  6174. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6175. "C4C6628B80DC1CD129024E088A67CC74"
  6176. "020BBEA63B139B22514A08798E3404DD"
  6177. "EF9519B3CD3A431B302B0A6DF25F1437"
  6178. "4FE1356D6D51C245E485B576625E7EC6"
  6179. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6180. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6181. "49286651ECE45B3DC2007CB8A163BF05"
  6182. "98DA48361C55D39A69163FA8FD24CF5F"
  6183. "83655D23DCA3AD961C62F356208552BB"
  6184. "9ED529077096966D670C354E4ABC9804"
  6185. "F1746C08CA18217C32905E462E36CE3B"
  6186. "E39E772C180E86039B2783A2EC07A28F"
  6187. "B5C55DF06F4C52C9DE2BCBF695581718"
  6188. "3995497CEA956AE515D2261898FA0510"
  6189. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6190. };
  6191. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6192. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6193. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6194. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6195. bn = NULL;
  6196. }
  6197. return bn;
  6198. #else
  6199. (void)bn;
  6200. return NULL;
  6201. #endif
  6202. }
  6203. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6204. *
  6205. * @param [in, out] bn If not NULL then this BN is set and returned.
  6206. * If NULL then a new BN is created, set and returned.
  6207. *
  6208. * @return NULL on failure.
  6209. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6210. */
  6211. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6212. {
  6213. #if WOLFSSL_MAX_BN_BITS >= 3072
  6214. static const char prm[] = {
  6215. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6216. "C4C6628B80DC1CD129024E088A67CC74"
  6217. "020BBEA63B139B22514A08798E3404DD"
  6218. "EF9519B3CD3A431B302B0A6DF25F1437"
  6219. "4FE1356D6D51C245E485B576625E7EC6"
  6220. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6221. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6222. "49286651ECE45B3DC2007CB8A163BF05"
  6223. "98DA48361C55D39A69163FA8FD24CF5F"
  6224. "83655D23DCA3AD961C62F356208552BB"
  6225. "9ED529077096966D670C354E4ABC9804"
  6226. "F1746C08CA18217C32905E462E36CE3B"
  6227. "E39E772C180E86039B2783A2EC07A28F"
  6228. "B5C55DF06F4C52C9DE2BCBF695581718"
  6229. "3995497CEA956AE515D2261898FA0510"
  6230. "15728E5A8AAAC42DAD33170D04507A33"
  6231. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6232. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6233. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6234. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6235. "D87602733EC86A64521F2B18177B200C"
  6236. "BBE117577A615D6C770988C0BAD946E2"
  6237. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6238. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6239. };
  6240. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6241. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6242. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6243. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6244. bn = NULL;
  6245. }
  6246. return bn;
  6247. #else
  6248. (void)bn;
  6249. return NULL;
  6250. #endif
  6251. }
  6252. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6253. *
  6254. * @param [in, out] bn If not NULL then this BN is set and returned.
  6255. * If NULL then a new BN is created, set and returned.
  6256. *
  6257. * @return NULL on failure.
  6258. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6259. */
  6260. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6261. {
  6262. #if WOLFSSL_MAX_BN_BITS >= 4096
  6263. static const char prm[] = {
  6264. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6265. "C4C6628B80DC1CD129024E088A67CC74"
  6266. "020BBEA63B139B22514A08798E3404DD"
  6267. "EF9519B3CD3A431B302B0A6DF25F1437"
  6268. "4FE1356D6D51C245E485B576625E7EC6"
  6269. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6270. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6271. "49286651ECE45B3DC2007CB8A163BF05"
  6272. "98DA48361C55D39A69163FA8FD24CF5F"
  6273. "83655D23DCA3AD961C62F356208552BB"
  6274. "9ED529077096966D670C354E4ABC9804"
  6275. "F1746C08CA18217C32905E462E36CE3B"
  6276. "E39E772C180E86039B2783A2EC07A28F"
  6277. "B5C55DF06F4C52C9DE2BCBF695581718"
  6278. "3995497CEA956AE515D2261898FA0510"
  6279. "15728E5A8AAAC42DAD33170D04507A33"
  6280. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6281. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6282. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6283. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6284. "D87602733EC86A64521F2B18177B200C"
  6285. "BBE117577A615D6C770988C0BAD946E2"
  6286. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6287. "4B82D120A92108011A723C12A787E6D7"
  6288. "88719A10BDBA5B2699C327186AF4E23C"
  6289. "1A946834B6150BDA2583E9CA2AD44CE8"
  6290. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6291. "287C59474E6BC05D99B2964FA090C3A2"
  6292. "233BA186515BE7ED1F612970CEE2D7AF"
  6293. "B81BDD762170481CD0069127D5B05AA9"
  6294. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6295. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6296. };
  6297. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6298. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6299. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6300. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6301. bn = NULL;
  6302. }
  6303. return bn;
  6304. #else
  6305. (void)bn;
  6306. return NULL;
  6307. #endif
  6308. }
  6309. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6310. *
  6311. * @param [in, out] bn If not NULL then this BN is set and returned.
  6312. * If NULL then a new BN is created, set and returned.
  6313. *
  6314. * @return NULL on failure.
  6315. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6316. */
  6317. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6318. {
  6319. #if WOLFSSL_MAX_BN_BITS >= 6144
  6320. static const char prm[] = {
  6321. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6322. "C4C6628B80DC1CD129024E088A67CC74"
  6323. "020BBEA63B139B22514A08798E3404DD"
  6324. "EF9519B3CD3A431B302B0A6DF25F1437"
  6325. "4FE1356D6D51C245E485B576625E7EC6"
  6326. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6327. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6328. "49286651ECE45B3DC2007CB8A163BF05"
  6329. "98DA48361C55D39A69163FA8FD24CF5F"
  6330. "83655D23DCA3AD961C62F356208552BB"
  6331. "9ED529077096966D670C354E4ABC9804"
  6332. "F1746C08CA18217C32905E462E36CE3B"
  6333. "E39E772C180E86039B2783A2EC07A28F"
  6334. "B5C55DF06F4C52C9DE2BCBF695581718"
  6335. "3995497CEA956AE515D2261898FA0510"
  6336. "15728E5A8AAAC42DAD33170D04507A33"
  6337. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6338. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6339. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6340. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6341. "D87602733EC86A64521F2B18177B200C"
  6342. "BBE117577A615D6C770988C0BAD946E2"
  6343. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6344. "4B82D120A92108011A723C12A787E6D7"
  6345. "88719A10BDBA5B2699C327186AF4E23C"
  6346. "1A946834B6150BDA2583E9CA2AD44CE8"
  6347. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6348. "287C59474E6BC05D99B2964FA090C3A2"
  6349. "233BA186515BE7ED1F612970CEE2D7AF"
  6350. "B81BDD762170481CD0069127D5B05AA9"
  6351. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6352. "4DF435C93402849236C3FAB4D27C7026"
  6353. "C1D4DCB2602646DEC9751E763DBA37BD"
  6354. "F8FF9406AD9E530EE5DB382F413001AE"
  6355. "B06A53ED9027D831179727B0865A8918"
  6356. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6357. "DB7F1447E6CC254B332051512BD7AF42"
  6358. "6FB8F401378CD2BF5983CA01C64B92EC"
  6359. "F032EA15D1721D03F482D7CE6E74FEF6"
  6360. "D55E702F46980C82B5A84031900B1C9E"
  6361. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6362. "0F1D45B7FF585AC54BD407B22B4154AA"
  6363. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6364. "A79715EEF29BE32806A1D58BB7C5DA76"
  6365. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6366. "DA56C9EC2EF29632387FE8D76E3C0468"
  6367. "043E8F663F4860EE12BF2D5B0B7474D6"
  6368. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6369. };
  6370. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6371. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6372. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6373. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6374. bn = NULL;
  6375. }
  6376. return bn;
  6377. #else
  6378. (void)bn;
  6379. return NULL;
  6380. #endif
  6381. }
  6382. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6383. *
  6384. * @param [in, out] bn If not NULL then this BN is set and returned.
  6385. * If NULL then a new BN is created, set and returned.
  6386. *
  6387. * @return NULL on failure.
  6388. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6389. */
  6390. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6391. {
  6392. #if WOLFSSL_MAX_BN_BITS >= 8192
  6393. static const char prm[] = {
  6394. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6395. "C4C6628B80DC1CD129024E088A67CC74"
  6396. "020BBEA63B139B22514A08798E3404DD"
  6397. "EF9519B3CD3A431B302B0A6DF25F1437"
  6398. "4FE1356D6D51C245E485B576625E7EC6"
  6399. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6400. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6401. "49286651ECE45B3DC2007CB8A163BF05"
  6402. "98DA48361C55D39A69163FA8FD24CF5F"
  6403. "83655D23DCA3AD961C62F356208552BB"
  6404. "9ED529077096966D670C354E4ABC9804"
  6405. "F1746C08CA18217C32905E462E36CE3B"
  6406. "E39E772C180E86039B2783A2EC07A28F"
  6407. "B5C55DF06F4C52C9DE2BCBF695581718"
  6408. "3995497CEA956AE515D2261898FA0510"
  6409. "15728E5A8AAAC42DAD33170D04507A33"
  6410. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6411. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6412. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6413. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6414. "D87602733EC86A64521F2B18177B200C"
  6415. "BBE117577A615D6C770988C0BAD946E2"
  6416. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6417. "4B82D120A92108011A723C12A787E6D7"
  6418. "88719A10BDBA5B2699C327186AF4E23C"
  6419. "1A946834B6150BDA2583E9CA2AD44CE8"
  6420. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6421. "287C59474E6BC05D99B2964FA090C3A2"
  6422. "233BA186515BE7ED1F612970CEE2D7AF"
  6423. "B81BDD762170481CD0069127D5B05AA9"
  6424. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6425. "4DF435C93402849236C3FAB4D27C7026"
  6426. "C1D4DCB2602646DEC9751E763DBA37BD"
  6427. "F8FF9406AD9E530EE5DB382F413001AE"
  6428. "B06A53ED9027D831179727B0865A8918"
  6429. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6430. "DB7F1447E6CC254B332051512BD7AF42"
  6431. "6FB8F401378CD2BF5983CA01C64B92EC"
  6432. "F032EA15D1721D03F482D7CE6E74FEF6"
  6433. "D55E702F46980C82B5A84031900B1C9E"
  6434. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6435. "0F1D45B7FF585AC54BD407B22B4154AA"
  6436. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6437. "A79715EEF29BE32806A1D58BB7C5DA76"
  6438. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6439. "DA56C9EC2EF29632387FE8D76E3C0468"
  6440. "043E8F663F4860EE12BF2D5B0B7474D6"
  6441. "E694F91E6DBE115974A3926F12FEE5E4"
  6442. "38777CB6A932DF8CD8BEC4D073B931BA"
  6443. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6444. "2576F6936BA424663AAB639C5AE4F568"
  6445. "3423B4742BF1C978238F16CBE39D652D"
  6446. "E3FDB8BEFC848AD922222E04A4037C07"
  6447. "13EB57A81A23F0C73473FC646CEA306B"
  6448. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6449. "79683303ED5BDD3A062B3CF5B3A278A6"
  6450. "6D2A13F83F44F82DDF310EE074AB6A36"
  6451. "4597E899A0255DC164F31CC50846851D"
  6452. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6453. "FAF36BC31ECFA268359046F4EB879F92"
  6454. "4009438B481C6CD7889A002ED5EE382B"
  6455. "C9190DA6FC026E479558E4475677E9AA"
  6456. "9E3050E2765694DFC81F56E880B96E71"
  6457. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6458. };
  6459. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6460. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6461. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6462. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6463. bn = NULL;
  6464. }
  6465. return bn;
  6466. #else
  6467. (void)bn;
  6468. return NULL;
  6469. #endif
  6470. }
  6471. /*
  6472. * DH to/from bin APIs
  6473. */
  6474. #ifndef NO_CERTS
  6475. /* Load the DER encoded DH parameters/key into DH key.
  6476. *
  6477. * @param [in, out] dh DH key to load parameters into.
  6478. * @param [in] der Buffer holding DER encoded parameters data.
  6479. * @param [in, out] idx On in, index at which DH key DER data starts.
  6480. * On out, index after DH key DER data.
  6481. * @param [in] derSz Size of DER buffer in bytes.
  6482. *
  6483. * @return 0 on success.
  6484. * @return 1 when decoding DER or setting the external key fails.
  6485. */
  6486. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6487. word32* idx, word32 derSz)
  6488. {
  6489. int err = 0;
  6490. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6491. int ret;
  6492. /* Decode DH parameters/key from DER. */
  6493. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6494. if (ret != 0) {
  6495. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6496. err = 1;
  6497. }
  6498. if (!err) {
  6499. /* wolfSSL DH key set. */
  6500. dh->inSet = 1;
  6501. /* Set the external DH key based on wolfSSL DH key. */
  6502. if (SetDhExternal(dh) != 1) {
  6503. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6504. err = 1;
  6505. }
  6506. }
  6507. #else
  6508. byte* p;
  6509. byte* g;
  6510. word32 pSz = MAX_DH_SIZE;
  6511. word32 gSz = MAX_DH_SIZE;
  6512. /* Only DH parameters supported. */
  6513. /* Load external and set internal. */
  6514. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6515. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6516. if ((p == NULL) || (g == NULL)) {
  6517. err = 1;
  6518. }
  6519. /* Extract the p and g as data from the DER encoded DH parameters. */
  6520. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6521. &gSz) < 0)) {
  6522. err = 1;
  6523. }
  6524. if (!err) {
  6525. /* Put p and g in as big numbers - free existing BNs. */
  6526. if (dh->p != NULL) {
  6527. wolfSSL_BN_free(dh->p);
  6528. dh->p = NULL;
  6529. }
  6530. if (dh->g != NULL) {
  6531. wolfSSL_BN_free(dh->g);
  6532. dh->g = NULL;
  6533. }
  6534. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6535. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6536. if (dh->p == NULL || dh->g == NULL) {
  6537. err = 1;
  6538. }
  6539. else {
  6540. /* External DH key parameters were set. */
  6541. dh->exSet = 1;
  6542. }
  6543. }
  6544. /* Set internal as the outside has been updated. */
  6545. if ((!err) && (SetDhInternal(dh) != 1)) {
  6546. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6547. err = 1;
  6548. }
  6549. if (!err) {
  6550. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6551. }
  6552. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6553. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6554. #endif
  6555. return err;
  6556. }
  6557. #ifdef OPENSSL_ALL
  6558. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6559. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6560. *
  6561. * @param [out] dh DH key to put parameters into. May be NULL.
  6562. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6563. * Value updated to end of data when dh is not NULL.
  6564. * @param [in] length Length of data available in bytes.
  6565. *
  6566. * @return DH key on success.
  6567. * @return NULL on failure.
  6568. */
  6569. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6570. long length)
  6571. {
  6572. WOLFSSL_DH *newDh = NULL;
  6573. word32 idx = 0;
  6574. int err = 0;
  6575. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6576. /* Validate parameters. */
  6577. if ((pp == NULL) || (length <= 0)) {
  6578. WOLFSSL_ERROR_MSG("bad argument");
  6579. err = 1;
  6580. }
  6581. /* Create new DH key to return. */
  6582. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6583. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6584. err = 1;
  6585. }
  6586. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6587. (word32)length) != 0)) {
  6588. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6589. err = 1;
  6590. }
  6591. if ((!err) && (dh != NULL)) {
  6592. /* Return through parameter too. */
  6593. *dh = newDh;
  6594. /* Move buffer on by the used amount. */
  6595. *pp += idx;
  6596. }
  6597. if (err && (newDh != NULL)) {
  6598. /* Dispose of any created DH key. */
  6599. wolfSSL_DH_free(newDh);
  6600. newDh = NULL;
  6601. }
  6602. return newDh;
  6603. }
  6604. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6605. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6606. *
  6607. * @params [in] dh DH key with parameters to encode.
  6608. * @params [in, out] out Pointer to buffer to encode into.
  6609. * When NULL or pointer to NULL, only length returned.
  6610. * @return 0 on error.
  6611. * @return Size of DER encoding in bytes on success.
  6612. */
  6613. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6614. {
  6615. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6616. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6617. word32 len = (word32)-1;
  6618. int err = 0;
  6619. /* Validate parameters. */
  6620. if (dh == NULL) {
  6621. WOLFSSL_ERROR_MSG("Bad parameters");
  6622. err = 1;
  6623. }
  6624. /* Push external DH data into internal DH key if not set. */
  6625. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6626. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6627. err = 1;
  6628. }
  6629. if (!err) {
  6630. int ret;
  6631. unsigned char* der = NULL;
  6632. /* Use *out when available otherwise NULL. */
  6633. if (out != NULL) {
  6634. der = *out;
  6635. }
  6636. /* Get length and/or encode. */
  6637. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6638. /* Length of encoded data is returned on success. */
  6639. if (ret > 0) {
  6640. *out += len;
  6641. }
  6642. /* An error occurred unless only length returned. */
  6643. else if (ret != LENGTH_ONLY_E) {
  6644. err = 1;
  6645. }
  6646. }
  6647. /* Set return to 0 on error. */
  6648. if (err) {
  6649. len = 0;
  6650. }
  6651. return (int)len;
  6652. #else
  6653. word32 len;
  6654. int ret = 0;
  6655. int pSz;
  6656. int gSz;
  6657. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6658. /* Validate parameters. */
  6659. if (dh == NULL) {
  6660. WOLFSSL_ERROR_MSG("Bad parameters");
  6661. len = 0;
  6662. }
  6663. else {
  6664. /* SEQ <len>
  6665. * INT <len> [0x00] <prime>
  6666. * INT <len> [0x00] <generator>
  6667. * Integers have 0x00 prepended if the top bit of positive number is
  6668. * set.
  6669. */
  6670. /* Get total length of prime including any prepended zeros. */
  6671. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6672. mp_leading_bit((mp_int*)dh->p->internal);
  6673. /* Get total length of generator including any prepended zeros. */
  6674. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6675. mp_leading_bit((mp_int*)dh->g->internal);
  6676. /* Calculate length of data in sequence. */
  6677. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6678. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6679. /* Add in the length of the SEQUENCE. */
  6680. len += 1 + ASN_LEN_SIZE(len);
  6681. if ((out != NULL) && (*out != NULL)) {
  6682. /* Encode parameters. */
  6683. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6684. (mp_int*)dh->g->internal);
  6685. if (ret != MP_OKAY) {
  6686. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6687. len = 0;
  6688. }
  6689. else {
  6690. /* Move pointer on if encoded. */
  6691. *out += len;
  6692. }
  6693. }
  6694. }
  6695. return (int)len;
  6696. #endif
  6697. }
  6698. #endif /* OPENSSL_ALL */
  6699. #endif /* !NO_CERTS */
  6700. #endif /* OPENSSL_EXTRA */
  6701. #if defined(OPENSSL_EXTRA) || \
  6702. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6703. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6704. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6705. /* Load the DER encoded DH parameters into DH key.
  6706. *
  6707. * @param [in, out] dh DH key to load parameters into.
  6708. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6709. * @param [in] derSz Size of DER data in buffer in bytes.
  6710. *
  6711. * @return 1 on success.
  6712. * @return -1 when DH or derBuf is NULL,
  6713. * internal DH key in DH is NULL,
  6714. * derSz is 0 or less,
  6715. * error decoding DER data or
  6716. * setting external parameter values fails.
  6717. */
  6718. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6719. {
  6720. int ret = 1;
  6721. word32 idx = 0;
  6722. /* Validate parameters. */
  6723. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6724. (derSz <= 0)) {
  6725. WOLFSSL_ERROR_MSG("Bad function arguments");
  6726. ret = -1;
  6727. }
  6728. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6729. (word32)derSz) != 0)) {
  6730. WOLFSSL_ERROR_MSG("DH key decode failed");
  6731. ret = -1;
  6732. }
  6733. return ret;
  6734. }
  6735. #endif
  6736. /*
  6737. * DH PEM APIs
  6738. */
  6739. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6740. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6741. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6742. /* Create a DH key by reading the PEM encoded data from the BIO.
  6743. *
  6744. * @param [in] bio BIO object to read from.
  6745. * @param [in, out] dh DH key to use. May be NULL.
  6746. * @param [in] pem PEM data to decode.
  6747. * @param [in] pemSz Size of PEM data in bytes.
  6748. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6749. * freed after use.
  6750. * @return DH key on success.
  6751. * @return NULL on failure.
  6752. */
  6753. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6754. unsigned char* pem, int pemSz, int memAlloced)
  6755. {
  6756. WOLFSSL_DH* localDh = NULL;
  6757. DerBuffer *der = NULL;
  6758. int err = 0;
  6759. /* Convert PEM to DER assuming DH Parameter format. */
  6760. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6761. NULL) < 0)) {
  6762. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6763. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6764. != 0) {
  6765. err = 1;
  6766. }
  6767. /* If Success on X9.42 DH format, clear error from failed DH format */
  6768. else {
  6769. unsigned long error;
  6770. CLEAR_ASN_NO_PEM_HEADER_ERROR(error);
  6771. }
  6772. }
  6773. if (memAlloced) {
  6774. /* PEM data no longer needed. */
  6775. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  6776. }
  6777. if (!err) {
  6778. /* Use the DH key passed in or allocate a new one. */
  6779. if (dh != NULL) {
  6780. localDh = *dh;
  6781. }
  6782. if (localDh == NULL) {
  6783. localDh = wolfSSL_DH_new();
  6784. if (localDh == NULL) {
  6785. err = 1;
  6786. }
  6787. }
  6788. }
  6789. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6790. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length)
  6791. != 1)) {
  6792. /* Free an allocated DH key. */
  6793. if ((dh == NULL) || (localDh != *dh)) {
  6794. wolfSSL_DH_free(localDh);
  6795. }
  6796. localDh = NULL;
  6797. err = 1;
  6798. }
  6799. /* Return the DH key on success. */
  6800. if ((!err) && (dh != NULL)) {
  6801. *dh = localDh;
  6802. }
  6803. /* Dispose of DER data. */
  6804. if (der != NULL) {
  6805. FreeDer(&der);
  6806. }
  6807. return localDh;
  6808. }
  6809. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6810. #ifndef NO_BIO
  6811. /* Create a DH key by reading the PEM encoded data from the BIO.
  6812. *
  6813. * DH parameters are public data and are not expected to be encrypted.
  6814. *
  6815. * @param [in] bio BIO object to read from.
  6816. * @param [in, out] dh DH key to When pointer to
  6817. * NULL, a new DH key is created.
  6818. * @param [in] cb Password callback when PEM encrypted. Not used.
  6819. * @param [in] pass NUL terminated string for passphrase when PEM
  6820. * encrypted. Not used.
  6821. * @return DH key on success.
  6822. * @return NULL on failure.
  6823. */
  6824. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6825. wc_pem_password_cb *cb, void *pass)
  6826. {
  6827. WOLFSSL_DH* localDh = NULL;
  6828. int err = 0;
  6829. unsigned char* mem = NULL;
  6830. int size = 0;
  6831. int memAlloced = 0;
  6832. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6833. (void)cb;
  6834. (void)pass;
  6835. /* Validate parameters. */
  6836. if (bio == NULL) {
  6837. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6838. err = 1;
  6839. }
  6840. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6841. */
  6842. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6843. != 0)) {
  6844. err = 1;
  6845. }
  6846. if (!err) {
  6847. /* Create a DH key from the PEM - try two different headers. */
  6848. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6849. }
  6850. return localDh;
  6851. }
  6852. #endif /* !NO_BIO */
  6853. #ifndef NO_FILESYSTEM
  6854. /* Read DH parameters from a file pointer into DH key.
  6855. *
  6856. * DH parameters are public data and are not expected to be encrypted.
  6857. *
  6858. * @param [in] fp File pointer to read DH parameter file from.
  6859. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6860. * NULL, a new DH key is created.
  6861. * @param [in] cb Password callback when PEM encrypted. Not used.
  6862. * @param [in] pass NUL terminated string for passphrase when PEM
  6863. * encrypted. Not used.
  6864. *
  6865. * @return NULL on failure.
  6866. * @return DH key with parameters set on success.
  6867. */
  6868. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6869. wc_pem_password_cb* cb, void* pass)
  6870. {
  6871. WOLFSSL_DH* localDh = NULL;
  6872. int err = 0;
  6873. unsigned char* mem = NULL;
  6874. int size = 0;
  6875. (void)cb;
  6876. (void)pass;
  6877. /* Read data from file pointer. */
  6878. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6879. err = 1;
  6880. }
  6881. if (!err) {
  6882. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6883. }
  6884. return localDh;
  6885. }
  6886. #endif /* !NO_FILESYSTEM */
  6887. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6888. /* Encoded parameter data in DH key as DER.
  6889. *
  6890. * @param [in, out] dh DH key object to encode.
  6891. * @param [out] out Buffer containing DER encoding.
  6892. * @param [in] heap Heap hint.
  6893. * @return <0 on error.
  6894. * @return Length of DER encoded DH parameters in bytes.
  6895. */
  6896. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6897. void* heap)
  6898. {
  6899. int ret = -1;
  6900. int err = 0;
  6901. byte* der = NULL;
  6902. word32 derSz;
  6903. DhKey* key = NULL;
  6904. (void)heap;
  6905. /* Set internal parameters based on external parameters. */
  6906. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6907. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6908. err = 1;
  6909. }
  6910. if (!err) {
  6911. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6912. key = (DhKey*)dh->internal;
  6913. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6914. if (ret != LENGTH_ONLY_E) {
  6915. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6916. err = 1;
  6917. }
  6918. }
  6919. if (!err) {
  6920. /* Allocate memory for DER encoding. */
  6921. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6922. if (der == NULL) {
  6923. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6924. err = 1;
  6925. }
  6926. }
  6927. if (!err) {
  6928. /* Encode DH parameters into DER buffer. */
  6929. ret = wc_DhParamsToDer(key, der, &derSz);
  6930. if (ret < 0) {
  6931. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6932. err = 1;
  6933. }
  6934. }
  6935. if (!err) {
  6936. *out = der;
  6937. der = NULL;
  6938. }
  6939. if (der != NULL) {
  6940. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6941. }
  6942. return ret;
  6943. }
  6944. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6945. * passed in.
  6946. *
  6947. * @param [in] fp File pointer to write to.
  6948. * @param [in] dh DH key to write.
  6949. * @return 1 on success.
  6950. * @return 0 on failure.
  6951. */
  6952. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6953. {
  6954. int ret = 1;
  6955. int derSz;
  6956. byte* derBuf = NULL;
  6957. void* heap = NULL;
  6958. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6959. /* Validate parameters. */
  6960. if ((fp == XBADFILE) || (dh == NULL)) {
  6961. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6962. ret = 0;
  6963. }
  6964. if (ret == 1) {
  6965. DhKey* key = (DhKey*)dh->internal;
  6966. if (key)
  6967. heap = key->heap;
  6968. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6969. WOLFSSL_ERROR_MSG("DER encoding failed");
  6970. ret = 0;
  6971. }
  6972. if (derBuf == NULL) {
  6973. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6974. ret = 0;
  6975. }
  6976. }
  6977. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6978. DH_PARAM_TYPE, NULL) != 1)) {
  6979. ret = 0;
  6980. }
  6981. /* Dispose of DER buffer. */
  6982. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6983. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6984. return ret;
  6985. }
  6986. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6987. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6988. * OPENSSL_EXTRA */
  6989. /*
  6990. * DH get/set APIs
  6991. */
  6992. #ifdef OPENSSL_EXTRA
  6993. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6994. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6995. /* Set the members of DhKey into WOLFSSL_DH
  6996. * Specify elements to set via the 2nd parameter
  6997. *
  6998. * @param [in, out] dh DH key to synchronize.
  6999. * @param [in] elm Elements to synchronize.
  7000. * @return 1 on success.
  7001. * @return -1 on failure.
  7002. */
  7003. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  7004. {
  7005. int ret = 1;
  7006. DhKey *key = NULL;
  7007. WOLFSSL_ENTER("SetDhExternal_ex");
  7008. /* Validate parameters. */
  7009. if ((dh == NULL) || (dh->internal == NULL)) {
  7010. WOLFSSL_ERROR_MSG("dh key NULL error");
  7011. ret = -1;
  7012. }
  7013. if (ret == 1) {
  7014. /* Get the wolfSSL DH key. */
  7015. key = (DhKey*)dh->internal;
  7016. }
  7017. if ((ret == 1) && (elm & ELEMENT_P)) {
  7018. /* Set the prime. */
  7019. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  7020. WOLFSSL_ERROR_MSG("dh param p error");
  7021. ret = -1;
  7022. }
  7023. }
  7024. if ((ret == 1) && (elm & ELEMENT_G)) {
  7025. /* Set the generator. */
  7026. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  7027. WOLFSSL_ERROR_MSG("dh param g error");
  7028. ret = -1;
  7029. }
  7030. }
  7031. if ((ret == 1) && (elm & ELEMENT_Q)) {
  7032. /* Set the order. */
  7033. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  7034. WOLFSSL_ERROR_MSG("dh param q error");
  7035. ret = -1;
  7036. }
  7037. }
  7038. #ifdef WOLFSSL_DH_EXTRA
  7039. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  7040. /* Set the private key. */
  7041. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  7042. WOLFSSL_ERROR_MSG("No DH Private Key");
  7043. ret = -1;
  7044. }
  7045. }
  7046. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  7047. /* Set the public key. */
  7048. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  7049. WOLFSSL_ERROR_MSG("No DH Public Key");
  7050. ret = -1;
  7051. }
  7052. }
  7053. #endif /* WOLFSSL_DH_EXTRA */
  7054. if (ret == 1) {
  7055. /* On success record that the external values have been set. */
  7056. dh->exSet = 1;
  7057. }
  7058. return ret;
  7059. }
  7060. /* Set the members of DhKey into WOLFSSL_DH
  7061. * DhKey was populated from wc_DhKeyDecode
  7062. * p, g, pub_key and priv_key are set.
  7063. *
  7064. * @param [in, out] dh DH key to synchronize.
  7065. * @return 1 on success.
  7066. * @return -1 on failure.
  7067. */
  7068. int SetDhExternal(WOLFSSL_DH *dh)
  7069. {
  7070. /* Assuming Q not required when using this API. */
  7071. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  7072. WOLFSSL_ENTER("SetDhExternal");
  7073. return SetDhExternal_ex(dh, elements);
  7074. }
  7075. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  7076. /* Set the internal/wolfSSL DH key with data from the external parts.
  7077. *
  7078. * @param [in, out] dh DH key to synchronize.
  7079. * @return 1 on success.
  7080. * @return -1 on failure.
  7081. */
  7082. int SetDhInternal(WOLFSSL_DH* dh)
  7083. {
  7084. int ret = 1;
  7085. DhKey *key = NULL;
  7086. WOLFSSL_ENTER("SetDhInternal");
  7087. /* Validate parameters. */
  7088. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7089. WOLFSSL_ERROR_MSG("Bad function arguments");
  7090. ret = -1;
  7091. }
  7092. if (ret == 1) {
  7093. /* Get the wolfSSL DH key. */
  7094. key = (DhKey*)dh->internal;
  7095. /* Clear out key and initialize. */
  7096. wc_FreeDhKey(key);
  7097. if (wc_InitDhKey(key) != 0) {
  7098. ret = -1;
  7099. }
  7100. }
  7101. if (ret == 1) {
  7102. /* Transfer prime. */
  7103. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  7104. ret = -1;
  7105. }
  7106. }
  7107. if (ret == 1) {
  7108. /* Transfer generator. */
  7109. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  7110. ret = -1;
  7111. }
  7112. }
  7113. #ifdef HAVE_FFDHE_Q
  7114. /* Transfer order if available. */
  7115. if ((ret == 1) && (dh->q != NULL)) {
  7116. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  7117. ret = -1;
  7118. }
  7119. }
  7120. #endif
  7121. #ifdef WOLFSSL_DH_EXTRA
  7122. /* Transfer private key if available. */
  7123. if ((ret == 1) && (dh->priv_key != NULL) &&
  7124. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  7125. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7126. ret = -1;
  7127. }
  7128. }
  7129. /* Transfer public key if available. */
  7130. if ((ret == 1) && (dh->pub_key != NULL) &&
  7131. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  7132. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7133. ret = -1;
  7134. }
  7135. }
  7136. #endif /* WOLFSSL_DH_EXTRA */
  7137. if (ret == 1) {
  7138. /* On success record that the internal values have been set. */
  7139. dh->inSet = 1;
  7140. }
  7141. return ret;
  7142. }
  7143. /* Get the size, in bytes, of the DH key.
  7144. *
  7145. * Return code compliant with OpenSSL.
  7146. *
  7147. * @param [in] dh DH key.
  7148. * @return -1 on error.
  7149. * @return Size of DH key in bytes on success.
  7150. */
  7151. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7152. {
  7153. int ret = -1;
  7154. WOLFSSL_ENTER("wolfSSL_DH_size");
  7155. /* Validate parameter. */
  7156. if (dh != NULL) {
  7157. /* Size of key is size of prime in bytes. */
  7158. ret = wolfSSL_BN_num_bytes(dh->p);
  7159. }
  7160. return ret;
  7161. }
  7162. /**
  7163. * Return parameters p, q and/or g of the DH key.
  7164. *
  7165. * @param [in] dh DH key to retrieve parameters from.
  7166. * @param [out] p Pointer to return prime in. May be NULL.
  7167. * @param [out] q Pointer to return order in. May be NULL.
  7168. * @param [out] g Pointer to return generator in. May be NULL.
  7169. */
  7170. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7171. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7172. {
  7173. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7174. if (dh != NULL) {
  7175. /* Return prime if required. */
  7176. if (p != NULL) {
  7177. *p = dh->p;
  7178. }
  7179. /* Return order if required. */
  7180. if (q != NULL) {
  7181. *q = dh->q;
  7182. }
  7183. /* Return generator if required. */
  7184. if (g != NULL) {
  7185. *g = dh->g;
  7186. }
  7187. }
  7188. }
  7189. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7190. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7191. #if defined(OPENSSL_ALL) || \
  7192. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7193. /* Sets the parameters p, g and optionally q into the DH key.
  7194. *
  7195. * Ownership of p, q and g get taken over by "dh" on success and should be
  7196. * free'd with a call to wolfSSL_DH_free -- not individually.
  7197. *
  7198. * @param [in, out] dh DH key to set.
  7199. * @param [in] p Prime value to set. May be NULL when value already
  7200. * present.
  7201. * @param [in] q Order value to set. May be NULL.
  7202. * @param [in] g Generator value to set. May be NULL when value already
  7203. * present.
  7204. * @return 1 on success.
  7205. * @return 0 on failure.
  7206. */
  7207. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7208. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7209. {
  7210. int ret = 1;
  7211. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7212. /* Validate parameters - q is optional. */
  7213. if (dh == NULL) {
  7214. WOLFSSL_ERROR_MSG("Bad function arguments");
  7215. ret = 0;
  7216. }
  7217. /* p can be NULL if we already have one set. */
  7218. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7219. WOLFSSL_ERROR_MSG("Bad function arguments");
  7220. ret = 0;
  7221. }
  7222. /* g can be NULL if we already have one set. */
  7223. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7224. WOLFSSL_ERROR_MSG("Bad function arguments");
  7225. ret = 0;
  7226. }
  7227. if (ret == 1) {
  7228. /* Invalidate internal key. */
  7229. dh->inSet = 0;
  7230. /* Free external representation of parameters and set with those passed
  7231. * in. */
  7232. if (p != NULL) {
  7233. wolfSSL_BN_free(dh->p);
  7234. dh->p = p;
  7235. }
  7236. if (q != NULL) {
  7237. wolfSSL_BN_free(dh->q);
  7238. dh->q = q;
  7239. }
  7240. if (g != NULL) {
  7241. wolfSSL_BN_free(dh->g);
  7242. dh->g = g;
  7243. }
  7244. /* External DH key parameters were set. */
  7245. dh->exSet = 1;
  7246. /* Set internal/wolfSSL DH key as well. */
  7247. if (SetDhInternal(dh) != 1) {
  7248. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7249. /* Don't keep parameters on failure. */
  7250. dh->p = NULL;
  7251. dh->q = NULL;
  7252. dh->g = NULL;
  7253. /* Internal and external DH key not set. */
  7254. dh->inSet = 0;
  7255. dh->exSet = 0;
  7256. ret = 0;
  7257. }
  7258. }
  7259. return ret;
  7260. }
  7261. /* Set the length of the DH private key in bits.
  7262. *
  7263. * Length field is checked at generation.
  7264. *
  7265. * @param [in, out] dh DH key to set.
  7266. * @param [in] len Length of DH private key in bytes.
  7267. * @return 0 on failure.
  7268. * @return 1 on success.
  7269. */
  7270. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7271. {
  7272. int ret = 1;
  7273. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7274. /* Validate parameter. */
  7275. if (dh == NULL) {
  7276. WOLFSSL_ERROR_MSG("Bad function arguments");
  7277. ret = 0;
  7278. }
  7279. else {
  7280. /* Store length. */
  7281. dh->length = (int)len;
  7282. }
  7283. return ret;
  7284. }
  7285. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7286. #endif
  7287. /* Get the public and private keys requested.
  7288. *
  7289. * @param [in] dh DH key to get keys from.
  7290. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7291. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7292. */
  7293. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7294. const WOLFSSL_BIGNUM **priv_key)
  7295. {
  7296. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7297. /* Get only when valid DH passed in. */
  7298. if (dh != NULL) {
  7299. /* Return public key if required and available. */
  7300. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7301. *pub_key = dh->pub_key;
  7302. }
  7303. /* Return private key if required and available. */
  7304. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7305. *priv_key = dh->priv_key;
  7306. }
  7307. }
  7308. }
  7309. /* Set the public and/or private key.
  7310. *
  7311. * @param [in, out] dh DH key to have keys set into.
  7312. * @param [in] pub_key Public key to set. May be NULL.
  7313. * @param [in] priv_key Private key to set. May be NULL.
  7314. * @return 0 on failure.
  7315. * @return 1 on success.
  7316. */
  7317. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7318. WOLFSSL_BIGNUM *priv_key)
  7319. {
  7320. int ret = 1;
  7321. #ifdef WOLFSSL_DH_EXTRA
  7322. DhKey *key = NULL;
  7323. #endif
  7324. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7325. /* Validate parameters. */
  7326. if (dh == NULL) {
  7327. ret = 0;
  7328. }
  7329. #ifdef WOLFSSL_DH_EXTRA
  7330. else {
  7331. key = (DhKey*)dh->internal;
  7332. }
  7333. #endif
  7334. /* Replace public key when one passed in. */
  7335. if ((ret == 1) && (pub_key != NULL)) {
  7336. wolfSSL_BN_free(dh->pub_key);
  7337. dh->pub_key = pub_key;
  7338. #ifdef WOLFSSL_DH_EXTRA
  7339. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7340. ret = 0;
  7341. }
  7342. #endif
  7343. }
  7344. /* Replace private key when one passed in. */
  7345. if ((ret == 1) && (priv_key != NULL)) {
  7346. wolfSSL_BN_clear_free(dh->priv_key);
  7347. dh->priv_key = priv_key;
  7348. #ifdef WOLFSSL_DH_EXTRA
  7349. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7350. ret = 0;
  7351. }
  7352. #endif
  7353. }
  7354. return ret;
  7355. }
  7356. #endif /* OPENSSL_EXTRA */
  7357. /*
  7358. * DH check APIs
  7359. */
  7360. #ifdef OPENSSL_EXTRA
  7361. #ifndef NO_CERTS
  7362. #ifdef OPENSSL_ALL
  7363. /* Check whether BN number is a prime.
  7364. *
  7365. * @param [in] n Number to check.
  7366. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7367. * @return 1 on success.
  7368. * @return 0 on error.
  7369. */
  7370. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7371. {
  7372. int ret = 1;
  7373. #ifdef WOLFSSL_SMALL_STACK
  7374. WC_RNG* tmpRng = NULL;
  7375. #else
  7376. WC_RNG tmpRng[1];
  7377. #endif
  7378. WC_RNG* rng;
  7379. int localRng;
  7380. /* Make an RNG with tmpRng or get global. */
  7381. rng = wolfssl_make_rng(tmpRng, &localRng);
  7382. if (rng == NULL) {
  7383. ret = 0;
  7384. }
  7385. if (ret == 1) {
  7386. mp_int* prime = (mp_int*)n->internal;
  7387. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7388. ret = 0;
  7389. }
  7390. /* Free local random number generator if created. */
  7391. if (localRng) {
  7392. wc_FreeRng(rng);
  7393. #ifdef WOLFSSL_SMALL_STACK
  7394. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7395. #endif
  7396. }
  7397. }
  7398. return ret;
  7399. }
  7400. /* Checks the Diffie-Hellman parameters.
  7401. *
  7402. * Checks that the generator and prime are available.
  7403. * Checks that the prime is prime.
  7404. * OpenSSL expects codes to be non-NULL.
  7405. *
  7406. * @param [in] dh DH key to check.
  7407. * @param [out] codes Codes of checks that failed.
  7408. * @return 1 on success.
  7409. * @return 0 when DH is NULL, there were errors or failed to create a random
  7410. * number generator.
  7411. */
  7412. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7413. {
  7414. int ret = 1;
  7415. int errors = 0;
  7416. WOLFSSL_ENTER("wolfSSL_DH_check");
  7417. /* Validate parameters. */
  7418. if (dh == NULL) {
  7419. ret = 0;
  7420. }
  7421. /* Check generator available. */
  7422. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7423. errors |= DH_NOT_SUITABLE_GENERATOR;
  7424. }
  7425. if (ret == 1) {
  7426. /* Check prime available. */
  7427. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7428. errors |= DH_CHECK_P_NOT_PRIME;
  7429. }
  7430. else {
  7431. /* Test if dh->p is prime. */
  7432. int isPrime = MP_NO;
  7433. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7434. /* Set error code if parameter p is not prime. */
  7435. if ((ret == 1) && (isPrime != MP_YES)) {
  7436. errors |= DH_CHECK_P_NOT_PRIME;
  7437. }
  7438. }
  7439. }
  7440. /* Return errors when user wants exact issues. */
  7441. if (codes != NULL) {
  7442. *codes = errors;
  7443. }
  7444. else if (errors) {
  7445. ret = 0;
  7446. }
  7447. return ret;
  7448. }
  7449. #endif /* OPENSSL_ALL */
  7450. #endif /* !NO_CERTS */
  7451. #endif /* OPENSSL_EXTRA */
  7452. /*
  7453. * DH generate APIs
  7454. */
  7455. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7456. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7457. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7458. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7459. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7460. /* Generate DH parameters.
  7461. *
  7462. * @param [in] prime_len Length of prime in bits.
  7463. * @param [in] generator Generator value to use.
  7464. * @param [in] callback Called with progress information. Unused.
  7465. * @param [in] cb_arg User callback argument. Unused.
  7466. * @return NULL on failure.
  7467. * @return DH key on success.
  7468. */
  7469. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7470. void (*callback) (int, int, void *), void *cb_arg)
  7471. {
  7472. WOLFSSL_DH* dh = NULL;
  7473. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7474. /* Not supported by wolfSSl APIs. */
  7475. (void)callback;
  7476. (void)cb_arg;
  7477. /* Create an empty DH key. */
  7478. if ((dh = wolfSSL_DH_new()) == NULL) {
  7479. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7480. }
  7481. /* Generate parameters into DH key. */
  7482. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7483. != 1) {
  7484. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7485. wolfSSL_DH_free(dh);
  7486. dh = NULL;
  7487. }
  7488. return dh;
  7489. }
  7490. /* Generate DH parameters.
  7491. *
  7492. * @param [in] dh DH key to generate parameters into.
  7493. * @param [in] prime_len Length of prime in bits.
  7494. * @param [in] generator Generator value to use.
  7495. * @param [in] callback Called with progress information. Unused.
  7496. * @param [in] cb_arg User callback argument. Unused.
  7497. * @return 0 on failure.
  7498. * @return 1 on success.
  7499. */
  7500. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7501. int generator, void (*callback) (int, int, void *))
  7502. {
  7503. int ret = 1;
  7504. DhKey* key = NULL;
  7505. #ifdef WOLFSSL_SMALL_STACK
  7506. WC_RNG* tmpRng = NULL;
  7507. #else
  7508. WC_RNG tmpRng[1];
  7509. #endif
  7510. WC_RNG* rng = NULL;
  7511. int localRng = 0;
  7512. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7513. /* Not supported by wolfSSL APIs. */
  7514. (void)callback;
  7515. (void)generator;
  7516. /* Validate parameters. */
  7517. if (dh == NULL) {
  7518. WOLFSSL_ERROR_MSG("Bad parameter");
  7519. ret = 0;
  7520. }
  7521. if (ret == 1) {
  7522. /* Make an RNG with tmpRng or get global. */
  7523. rng = wolfssl_make_rng(tmpRng, &localRng);
  7524. if (rng == NULL) {
  7525. WOLFSSL_ERROR_MSG("No RNG to use");
  7526. ret = 0;
  7527. }
  7528. }
  7529. if (ret == 1) {
  7530. /* Get internal/wolfSSL DH key. */
  7531. key = (DhKey*)dh->internal;
  7532. /* Clear out data from internal DH key. */
  7533. wc_FreeDhKey(key);
  7534. /* Re-initialize internal DH key. */
  7535. if (wc_InitDhKey(key) != 0) {
  7536. ret = 0;
  7537. }
  7538. }
  7539. if (ret == 1) {
  7540. /* Generate parameters into internal DH key. */
  7541. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7542. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7543. ret = 0;
  7544. }
  7545. }
  7546. /* Free local random number generator if created. */
  7547. if (localRng) {
  7548. wc_FreeRng(rng);
  7549. #ifdef WOLFSSL_SMALL_STACK
  7550. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7551. #endif
  7552. }
  7553. if (ret == 1) {
  7554. /* Internal parameters set by generation. */
  7555. dh->inSet = 1;
  7556. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7557. /* Synchronize the external to the internal parameters. */
  7558. if (SetDhExternal(dh) != 1) {
  7559. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7560. ret = 0;
  7561. }
  7562. }
  7563. return ret;
  7564. }
  7565. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7566. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7567. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7568. * HAVE_SBLIM_SFCB)) */
  7569. #ifdef OPENSSL_EXTRA
  7570. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7571. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7572. /* Generate a public/private key pair base on parameters.
  7573. *
  7574. * @param [in, out] dh DH key to generate keys into.
  7575. * @return 1 on success.
  7576. * @return 0 on error.
  7577. */
  7578. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7579. {
  7580. int ret = 1;
  7581. word32 pubSz = 0;
  7582. word32 privSz = 0;
  7583. int localRng = 0;
  7584. WC_RNG* rng = NULL;
  7585. #ifdef WOLFSSL_SMALL_STACK
  7586. WC_RNG* tmpRng = NULL;
  7587. #else
  7588. WC_RNG tmpRng[1];
  7589. #endif
  7590. unsigned char* pub = NULL;
  7591. unsigned char* priv = NULL;
  7592. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7593. /* Validate parameters. */
  7594. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7595. WOLFSSL_ERROR_MSG("Bad function arguments");
  7596. ret = 0;
  7597. }
  7598. /* Synchronize the external and internal parameters. */
  7599. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7600. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7601. ret = 0;
  7602. }
  7603. if (ret == 1) {
  7604. /* Make a new RNG or use global. */
  7605. rng = wolfssl_make_rng(tmpRng, &localRng);
  7606. /* Check we have a random number generator. */
  7607. if (rng == NULL) {
  7608. ret = 0;
  7609. }
  7610. }
  7611. if (ret == 1) {
  7612. /* Get the size of the prime in bytes. */
  7613. pubSz = (word32)wolfSSL_BN_num_bytes(dh->p);
  7614. if (pubSz == 0) {
  7615. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7616. ret = 0;
  7617. }
  7618. }
  7619. if (ret == 1) {
  7620. /* Private key size can be as much as the size of the prime. */
  7621. if (dh->length) {
  7622. privSz = (word32)(dh->length / 8); /* to bytes */
  7623. }
  7624. else {
  7625. privSz = pubSz;
  7626. }
  7627. /* Allocate public and private key arrays. */
  7628. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7629. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7630. if (pub == NULL || priv == NULL) {
  7631. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7632. ret = 0;
  7633. }
  7634. }
  7635. if (ret == 1) {
  7636. /* Dispose of old public and private keys. */
  7637. wolfSSL_BN_free(dh->pub_key);
  7638. wolfSSL_BN_free(dh->priv_key);
  7639. /* Allocate new public and private keys. */
  7640. dh->pub_key = wolfSSL_BN_new();
  7641. dh->priv_key = wolfSSL_BN_new();
  7642. if (dh->pub_key == NULL) {
  7643. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7644. ret = 0;
  7645. }
  7646. if (dh->priv_key == NULL) {
  7647. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7648. ret = 0;
  7649. }
  7650. }
  7651. PRIVATE_KEY_UNLOCK();
  7652. /* Generate public and private keys into arrays. */
  7653. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7654. &privSz, pub, &pubSz) < 0)) {
  7655. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7656. ret = 0;
  7657. }
  7658. /* Set public key from array. */
  7659. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) ==
  7660. NULL)) {
  7661. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7662. ret = 0;
  7663. }
  7664. /* Set private key from array. */
  7665. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) ==
  7666. NULL)) {
  7667. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7668. ret = 0;
  7669. }
  7670. PRIVATE_KEY_LOCK();
  7671. if (localRng) {
  7672. /* Free an initialized local random number generator. */
  7673. wc_FreeRng(rng);
  7674. #ifdef WOLFSSL_SMALL_STACK
  7675. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7676. #endif
  7677. }
  7678. /* Dispose of allocated data. */
  7679. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7680. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7681. return ret;
  7682. }
  7683. /* Compute the shared key from the private key and peer's public key.
  7684. *
  7685. * Return code compliant with OpenSSL.
  7686. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7687. * supported.
  7688. *
  7689. * @param [out] key Buffer to place shared key.
  7690. * @param [in] otherPub Peer's public key.
  7691. * @param [in] dh DH key containing private key.
  7692. * @return -1 on error.
  7693. * @return Size of shared secret in bytes on success.
  7694. */
  7695. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7696. WOLFSSL_DH* dh)
  7697. {
  7698. int ret = 0;
  7699. word32 keySz = 0;
  7700. int pubSz = MAX_DHKEY_SZ;
  7701. int privSz = MAX_DHKEY_SZ;
  7702. int sz = 0;
  7703. #ifdef WOLFSSL_SMALL_STACK
  7704. unsigned char* pub = NULL;
  7705. unsigned char* priv = NULL;
  7706. #else
  7707. unsigned char pub [MAX_DHKEY_SZ];
  7708. unsigned char priv[MAX_DHKEY_SZ];
  7709. #endif
  7710. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7711. /* Validate parameters. */
  7712. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7713. WOLFSSL_ERROR_MSG("Bad function arguments");
  7714. ret = -1;
  7715. }
  7716. /* Get the maximum size of computed DH key. */
  7717. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7718. WOLFSSL_ERROR_MSG("Bad DH_size");
  7719. ret = -1;
  7720. }
  7721. if (ret == 0) {
  7722. /* Validate the size of the private key. */
  7723. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7724. if (sz > (int)privSz) {
  7725. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7726. ret = -1;
  7727. }
  7728. }
  7729. if (ret == 0) {
  7730. #ifdef WOLFSSL_SMALL_STACK
  7731. /* Keep real private key size to minimize amount allocated. */
  7732. privSz = sz;
  7733. #endif
  7734. /* Validate the size of the public key. */
  7735. sz = wolfSSL_BN_num_bytes(otherPub);
  7736. if (sz > pubSz) {
  7737. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7738. ret = -1;
  7739. }
  7740. }
  7741. if (ret == 0) {
  7742. #ifdef WOLFSSL_SMALL_STACK
  7743. /* Allocate memory for the public key array. */
  7744. pub = (unsigned char*)XMALLOC((size_t)sz, NULL,
  7745. DYNAMIC_TYPE_PUBLIC_KEY);
  7746. if (pub == NULL)
  7747. ret = -1;
  7748. }
  7749. if (ret == 0) {
  7750. /* Allocate memory for the private key array. */
  7751. priv = (unsigned char*)XMALLOC((size_t)privSz, NULL,
  7752. DYNAMIC_TYPE_PRIVATE_KEY);
  7753. if (priv == NULL) {
  7754. ret = -1;
  7755. }
  7756. }
  7757. if (ret == 0) {
  7758. #endif
  7759. /* Get the private key into the array. */
  7760. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7761. if (privSz <= 0) {
  7762. ret = -1;
  7763. }
  7764. }
  7765. if (ret == 0) {
  7766. /* Get the public key into the array. */
  7767. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7768. if (privSz <= 0) {
  7769. ret = -1;
  7770. }
  7771. }
  7772. /* Synchronize the external into the internal parameters. */
  7773. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7774. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7775. ret = -1;
  7776. }
  7777. PRIVATE_KEY_UNLOCK();
  7778. /* Calculate shared secret from private and public keys. */
  7779. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7780. (word32)privSz, pub, (word32)pubSz) < 0)) {
  7781. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7782. ret = -1;
  7783. }
  7784. if (ret == 0) {
  7785. /* Return actual length. */
  7786. ret = (int)keySz;
  7787. }
  7788. PRIVATE_KEY_LOCK();
  7789. #ifdef WOLFSSL_SMALL_STACK
  7790. if (priv != NULL)
  7791. #endif
  7792. {
  7793. /* Zeroize sensitive data. */
  7794. ForceZero(priv, (word32)privSz);
  7795. }
  7796. #ifdef WOLFSSL_SMALL_STACK
  7797. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7798. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7799. #endif
  7800. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7801. return ret;
  7802. }
  7803. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7804. * HAVE_FIPS_VERSION > 2 */
  7805. #endif /* OPENSSL_EXTRA */
  7806. #endif /* NO_DH */
  7807. /*******************************************************************************
  7808. * END OF DH API
  7809. ******************************************************************************/
  7810. /*******************************************************************************
  7811. * START OF EC API
  7812. ******************************************************************************/
  7813. #ifdef HAVE_ECC
  7814. #if defined(OPENSSL_EXTRA)
  7815. /* Start EC_curve */
  7816. /* Get the NIST name for the numeric ID.
  7817. *
  7818. * @param [in] nid Numeric ID of an EC curve.
  7819. * @return String representing NIST name of EC curve on success.
  7820. * @return NULL on error.
  7821. */
  7822. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7823. {
  7824. const char* name = NULL;
  7825. const WOLF_EC_NIST_NAME* nist_name;
  7826. /* Attempt to find the curve info matching the NID passed in. */
  7827. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7828. if (nist_name->nid == nid) {
  7829. /* NID found - return name. */
  7830. name = nist_name->name;
  7831. break;
  7832. }
  7833. }
  7834. return name;
  7835. }
  7836. /* Get the numeric ID for the NIST name.
  7837. *
  7838. * @param [in] name NIST name of EC curve.
  7839. * @return NID matching NIST name on success.
  7840. * @return 0 on error.
  7841. */
  7842. int wolfSSL_EC_curve_nist2nid(const char* name)
  7843. {
  7844. int nid = 0;
  7845. const WOLF_EC_NIST_NAME* nist_name;
  7846. /* Attempt to find the curve info matching the NIST name passed in. */
  7847. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7848. if (XSTRCMP(nist_name->name, name) == 0) {
  7849. /* Name found - return NID. */
  7850. nid = nist_name->nid;
  7851. break;
  7852. }
  7853. }
  7854. return nid;
  7855. }
  7856. #endif /* OPENSSL_EXTRA */
  7857. /* End EC_curve */
  7858. /* Start EC_METHOD */
  7859. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7860. /* Get the EC method of the EC group object.
  7861. *
  7862. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7863. * the NID.
  7864. *
  7865. * @param [in] group EC group object.
  7866. * @return EC method.
  7867. */
  7868. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7869. const WOLFSSL_EC_GROUP *group)
  7870. {
  7871. /* No method table used so just return the same object. */
  7872. return group;
  7873. }
  7874. /* Get field type for method.
  7875. *
  7876. * Only prime fields are supported.
  7877. *
  7878. * @param [in] meth EC method.
  7879. * @return X9.63 prime field NID on success.
  7880. * @return 0 on error.
  7881. */
  7882. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7883. {
  7884. int nid = 0;
  7885. if (meth != NULL) {
  7886. /* Only field type supported by code base. */
  7887. nid = NID_X9_62_prime_field;
  7888. }
  7889. return nid;
  7890. }
  7891. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7892. /* End EC_METHOD */
  7893. /* Start EC_GROUP */
  7894. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7895. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7896. * value.
  7897. *
  7898. * @param [in] n ECC curve id.
  7899. * @return ECC curve NID (OpenSSL compatible value).
  7900. */
  7901. int EccEnumToNID(int n)
  7902. {
  7903. WOLFSSL_ENTER("EccEnumToNID");
  7904. switch(n) {
  7905. case ECC_SECP192R1:
  7906. return NID_X9_62_prime192v1;
  7907. case ECC_PRIME192V2:
  7908. return NID_X9_62_prime192v2;
  7909. case ECC_PRIME192V3:
  7910. return NID_X9_62_prime192v3;
  7911. case ECC_PRIME239V1:
  7912. return NID_X9_62_prime239v1;
  7913. case ECC_PRIME239V2:
  7914. return NID_X9_62_prime239v2;
  7915. case ECC_PRIME239V3:
  7916. return NID_X9_62_prime239v3;
  7917. case ECC_SECP256R1:
  7918. return NID_X9_62_prime256v1;
  7919. case ECC_SECP112R1:
  7920. return NID_secp112r1;
  7921. case ECC_SECP112R2:
  7922. return NID_secp112r2;
  7923. case ECC_SECP128R1:
  7924. return NID_secp128r1;
  7925. case ECC_SECP128R2:
  7926. return NID_secp128r2;
  7927. case ECC_SECP160R1:
  7928. return NID_secp160r1;
  7929. case ECC_SECP160R2:
  7930. return NID_secp160r2;
  7931. case ECC_SECP224R1:
  7932. return NID_secp224r1;
  7933. case ECC_SECP384R1:
  7934. return NID_secp384r1;
  7935. case ECC_SECP521R1:
  7936. return NID_secp521r1;
  7937. case ECC_SECP160K1:
  7938. return NID_secp160k1;
  7939. case ECC_SECP192K1:
  7940. return NID_secp192k1;
  7941. case ECC_SECP224K1:
  7942. return NID_secp224k1;
  7943. case ECC_SECP256K1:
  7944. return NID_secp256k1;
  7945. case ECC_BRAINPOOLP160R1:
  7946. return NID_brainpoolP160r1;
  7947. case ECC_BRAINPOOLP192R1:
  7948. return NID_brainpoolP192r1;
  7949. case ECC_BRAINPOOLP224R1:
  7950. return NID_brainpoolP224r1;
  7951. case ECC_BRAINPOOLP256R1:
  7952. return NID_brainpoolP256r1;
  7953. case ECC_BRAINPOOLP320R1:
  7954. return NID_brainpoolP320r1;
  7955. case ECC_BRAINPOOLP384R1:
  7956. return NID_brainpoolP384r1;
  7957. case ECC_BRAINPOOLP512R1:
  7958. return NID_brainpoolP512r1;
  7959. #ifdef WOLFSSL_SM2
  7960. case ECC_SM2P256V1:
  7961. return NID_sm2;
  7962. #endif
  7963. default:
  7964. WOLFSSL_MSG("NID not found");
  7965. return -1;
  7966. }
  7967. }
  7968. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7969. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7970. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  7971. *
  7972. * Used by ecc_sets[].
  7973. *
  7974. * @param [in] n OpenSSL NID of EC curve.
  7975. * @return wolfCrypt EC curve id.
  7976. * @return -1 on error.
  7977. */
  7978. int NIDToEccEnum(int nid)
  7979. {
  7980. /* -1 on error. */
  7981. int id = -1;
  7982. WOLFSSL_ENTER("NIDToEccEnum");
  7983. switch (nid) {
  7984. case NID_X9_62_prime192v1:
  7985. id = ECC_SECP192R1;
  7986. break;
  7987. case NID_X9_62_prime192v2:
  7988. id = ECC_PRIME192V2;
  7989. break;
  7990. case NID_X9_62_prime192v3:
  7991. id = ECC_PRIME192V3;
  7992. break;
  7993. case NID_X9_62_prime239v1:
  7994. id = ECC_PRIME239V1;
  7995. break;
  7996. case NID_X9_62_prime239v2:
  7997. id = ECC_PRIME239V2;
  7998. break;
  7999. case NID_X9_62_prime239v3:
  8000. id = ECC_PRIME239V3;
  8001. break;
  8002. case NID_X9_62_prime256v1:
  8003. id = ECC_SECP256R1;
  8004. break;
  8005. case NID_secp112r1:
  8006. id = ECC_SECP112R1;
  8007. break;
  8008. case NID_secp112r2:
  8009. id = ECC_SECP112R2;
  8010. break;
  8011. case NID_secp128r1:
  8012. id = ECC_SECP128R1;
  8013. break;
  8014. case NID_secp128r2:
  8015. id = ECC_SECP128R2;
  8016. break;
  8017. case NID_secp160r1:
  8018. id = ECC_SECP160R1;
  8019. break;
  8020. case NID_secp160r2:
  8021. id = ECC_SECP160R2;
  8022. break;
  8023. case NID_secp224r1:
  8024. id = ECC_SECP224R1;
  8025. break;
  8026. case NID_secp384r1:
  8027. id = ECC_SECP384R1;
  8028. break;
  8029. case NID_secp521r1:
  8030. id = ECC_SECP521R1;
  8031. break;
  8032. case NID_secp160k1:
  8033. id = ECC_SECP160K1;
  8034. break;
  8035. case NID_secp192k1:
  8036. id = ECC_SECP192K1;
  8037. break;
  8038. case NID_secp224k1:
  8039. id = ECC_SECP224K1;
  8040. break;
  8041. case NID_secp256k1:
  8042. id = ECC_SECP256K1;
  8043. break;
  8044. case NID_brainpoolP160r1:
  8045. id = ECC_BRAINPOOLP160R1;
  8046. break;
  8047. case NID_brainpoolP192r1:
  8048. id = ECC_BRAINPOOLP192R1;
  8049. break;
  8050. case NID_brainpoolP224r1:
  8051. id = ECC_BRAINPOOLP224R1;
  8052. break;
  8053. case NID_brainpoolP256r1:
  8054. id = ECC_BRAINPOOLP256R1;
  8055. break;
  8056. case NID_brainpoolP320r1:
  8057. id = ECC_BRAINPOOLP320R1;
  8058. break;
  8059. case NID_brainpoolP384r1:
  8060. id = ECC_BRAINPOOLP384R1;
  8061. break;
  8062. case NID_brainpoolP512r1:
  8063. id = ECC_BRAINPOOLP512R1;
  8064. break;
  8065. default:
  8066. WOLFSSL_MSG("NID not found");
  8067. }
  8068. return id;
  8069. }
  8070. /* Set the fields of the EC group based on numeric ID.
  8071. *
  8072. * @param [in, out] group EC group.
  8073. * @param [in] nid Numeric ID of an EC curve.
  8074. */
  8075. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  8076. {
  8077. int eccEnum;
  8078. int realNid;
  8079. /* Convert ecc_curve_id enum to NID. */
  8080. if ((realNid = EccEnumToNID(nid)) != -1) {
  8081. /* ecc_curve_id enum passed in - have real NID value set. */
  8082. eccEnum = nid;
  8083. }
  8084. else {
  8085. /* NID passed in is OpenSSL type. */
  8086. realNid = nid;
  8087. /* Convert NID to ecc_curve_id enum. */
  8088. eccEnum = NIDToEccEnum(nid);
  8089. }
  8090. /* Set the numeric ID of the curve */
  8091. group->curve_nid = realNid;
  8092. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  8093. group->curve_idx = -1;
  8094. /* Find index and OID sum for curve if wolfCrypt supports it. */
  8095. if (eccEnum != -1) {
  8096. int i;
  8097. /* Find id and set the internal curve idx and OID sum. */
  8098. for (i = 0; ecc_sets[i].size != 0; i++) {
  8099. if (ecc_sets[i].id == eccEnum) {
  8100. /* Found id in wolfCrypt supported EC curves. */
  8101. group->curve_idx = i;
  8102. group->curve_oid = (int)ecc_sets[i].oidSum;
  8103. break;
  8104. }
  8105. }
  8106. }
  8107. }
  8108. /* Create a new EC group with the numeric ID for an EC curve.
  8109. *
  8110. * @param [in] nid Numeric ID of an EC curve.
  8111. * @return New, allocated EC group on success.
  8112. * @return NULL on error.
  8113. */
  8114. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  8115. {
  8116. int err = 0;
  8117. WOLFSSL_EC_GROUP* group;
  8118. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  8119. /* Allocate EC group. */
  8120. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  8121. DYNAMIC_TYPE_ECC);
  8122. if (group == NULL) {
  8123. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  8124. err = 1;
  8125. }
  8126. if (!err) {
  8127. /* Reset all fields. */
  8128. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  8129. /* Set the fields of group based on the numeric ID. */
  8130. ec_group_set_nid(group, nid);
  8131. }
  8132. return group;
  8133. }
  8134. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8135. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8136. /* Dispose of the EC group.
  8137. *
  8138. * Cannot use group after this call.
  8139. *
  8140. * @param [in] group EC group to free.
  8141. */
  8142. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8143. {
  8144. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8145. /* Dispose of EC group. */
  8146. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8147. }
  8148. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8149. #ifdef OPENSSL_EXTRA
  8150. #ifndef NO_BIO
  8151. /* Creates an EC group from the DER encoding.
  8152. *
  8153. * Only named curves supported.
  8154. *
  8155. * @param [out] group Reference to EC group object.
  8156. * @param [in] in Buffer holding DER encoding of curve.
  8157. * @param [in] inSz Length of data in buffer.
  8158. * @return EC group on success.
  8159. * @return NULL on error.
  8160. */
  8161. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  8162. const unsigned char* in, long inSz)
  8163. {
  8164. int err = 0;
  8165. WOLFSSL_EC_GROUP* ret = NULL;
  8166. word32 idx = 0;
  8167. word32 oid = 0;
  8168. int id = 0;
  8169. /* Use the group passed in. */
  8170. if ((group != NULL) && (*group != NULL)) {
  8171. ret = *group;
  8172. }
  8173. /* Only support named curves. */
  8174. if (in[0] != ASN_OBJECT_ID) {
  8175. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8176. err = 1;
  8177. }
  8178. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8179. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8180. 0)) {
  8181. err = 1;
  8182. }
  8183. if (!err) {
  8184. /* Get the internal ID for OID. */
  8185. id = wc_ecc_get_oid(oid, NULL, NULL);
  8186. if (id < 0) {
  8187. err = 1;
  8188. }
  8189. }
  8190. if (!err) {
  8191. /* Get the NID for the internal ID. */
  8192. int nid = EccEnumToNID(id);
  8193. if (ret == NULL) {
  8194. /* Create a new EC group with the numeric ID. */
  8195. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8196. if (ret == NULL) {
  8197. err = 1;
  8198. }
  8199. }
  8200. else {
  8201. ec_group_set_nid(ret, nid);
  8202. }
  8203. }
  8204. if ((!err) && (group != NULL)) {
  8205. /* Return the EC group through reference. */
  8206. *group = ret;
  8207. }
  8208. if (err) {
  8209. if ((ret != NULL) && (ret != *group)) {
  8210. wolfSSL_EC_GROUP_free(ret);
  8211. }
  8212. ret = NULL;
  8213. }
  8214. return ret;
  8215. }
  8216. /* Creates a new EC group from the PEM encoding in the BIO.
  8217. *
  8218. * @param [in] bio BIO to read PEM encoding from.
  8219. * @param [out] group Reference to EC group object.
  8220. * @param [in] cb Password callback when PEM encrypted.
  8221. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8222. * @return EC group on success.
  8223. * @return NULL on error.
  8224. */
  8225. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8226. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8227. {
  8228. int err = 0;
  8229. WOLFSSL_EC_GROUP* ret = NULL;
  8230. DerBuffer* der = NULL;
  8231. int keyFormat = 0;
  8232. if (bio == NULL) {
  8233. err = 1;
  8234. }
  8235. /* Read parameters from BIO and convert PEM to DER. */
  8236. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8237. &keyFormat, &der) < 0)) {
  8238. err = 1;
  8239. }
  8240. if (!err) {
  8241. /* Create EC group from DER encoding. */
  8242. ret = wolfssl_ec_group_d2i(group, der->buffer, der->length);
  8243. if (ret == NULL) {
  8244. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8245. }
  8246. }
  8247. /* Dispose of any allocated data. */
  8248. FreeDer(&der);
  8249. return ret;
  8250. }
  8251. #endif /* !NO_BIO */
  8252. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8253. /* Copy an EC group.
  8254. *
  8255. * Only used by wolfSSL_EC_KEY_dup at this time.
  8256. *
  8257. * @param [in, out] dst Destination EC group.
  8258. * @param [in] src Source EC group.
  8259. * @return 0 on success.
  8260. */
  8261. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8262. const WOLFSSL_EC_GROUP* src)
  8263. {
  8264. /* Copy the fields. */
  8265. dst->curve_idx = src->curve_idx;
  8266. dst->curve_nid = src->curve_nid;
  8267. dst->curve_oid = src->curve_oid;
  8268. return 0;
  8269. }
  8270. #endif /* OPENSSL_ALL && !NO_CERTS */
  8271. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8272. *
  8273. * @param [in] src EC group to duplicate.
  8274. *
  8275. * @return EC group on success.
  8276. * @return NULL on error.
  8277. */
  8278. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8279. {
  8280. WOLFSSL_EC_GROUP* newGroup = NULL;
  8281. if (src != NULL) {
  8282. /* Create new group base on NID in original EC group. */
  8283. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8284. }
  8285. return newGroup;
  8286. }
  8287. /* Compare two EC groups.
  8288. *
  8289. * Return code compliant with OpenSSL.
  8290. *
  8291. * @param [in] a First EC group.
  8292. * @param [in] b Second EC group.
  8293. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8294. *
  8295. * @return 0 if equal.
  8296. * @return 1 if not equal.
  8297. * @return -1 on error.
  8298. */
  8299. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8300. WOLFSSL_BN_CTX *ctx)
  8301. {
  8302. int ret;
  8303. /* No BN operations performed. */
  8304. (void)ctx;
  8305. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8306. /* Validate parameters. */
  8307. if ((a == NULL) || (b == NULL)) {
  8308. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8309. /* Return error value. */
  8310. ret = -1;
  8311. }
  8312. /* Compare NID and wolfSSL curve index. */
  8313. else {
  8314. /* 0 when same, 1 when not. */
  8315. ret = ((a->curve_nid == b->curve_nid) &&
  8316. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8317. }
  8318. return ret;
  8319. }
  8320. #ifndef NO_WOLFSSL_STUB
  8321. /* Set the ASN.1 flag that indicate encoding of curve.
  8322. *
  8323. * Stub function - flag not used elsewhere.
  8324. * Always encoded as named curve.
  8325. *
  8326. * @param [in] group EC group to modify.
  8327. * @param [in] flag ASN.1 flag to set. Valid values:
  8328. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8329. */
  8330. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8331. {
  8332. (void)group;
  8333. (void)flag;
  8334. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8335. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8336. }
  8337. #endif
  8338. /* Get the curve NID of the group.
  8339. *
  8340. * Return code compliant with OpenSSL.
  8341. *
  8342. * @param [in] group EC group.
  8343. * @return Curve NID on success.
  8344. * @return 0 on error.
  8345. */
  8346. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8347. {
  8348. int nid = 0;
  8349. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8350. if (group == NULL) {
  8351. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8352. }
  8353. else {
  8354. nid = group->curve_nid;
  8355. }
  8356. return nid;
  8357. }
  8358. /* Get the degree (curve size in bits) of the EC group.
  8359. *
  8360. * Return code compliant with OpenSSL.
  8361. *
  8362. * @return Degree of the curve on success.
  8363. * @return 0 on error.
  8364. */
  8365. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8366. {
  8367. int degree = 0;
  8368. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8369. if (group == NULL) {
  8370. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8371. }
  8372. else {
  8373. switch (group->curve_nid) {
  8374. case NID_secp112r1:
  8375. case NID_secp112r2:
  8376. degree = 112;
  8377. break;
  8378. case NID_secp128r1:
  8379. case NID_secp128r2:
  8380. degree = 128;
  8381. break;
  8382. case NID_secp160k1:
  8383. case NID_secp160r1:
  8384. case NID_secp160r2:
  8385. case NID_brainpoolP160r1:
  8386. degree = 160;
  8387. break;
  8388. case NID_secp192k1:
  8389. case NID_brainpoolP192r1:
  8390. case NID_X9_62_prime192v1:
  8391. case NID_X9_62_prime192v2:
  8392. case NID_X9_62_prime192v3:
  8393. degree = 192;
  8394. break;
  8395. case NID_secp224k1:
  8396. case NID_secp224r1:
  8397. case NID_brainpoolP224r1:
  8398. degree = 224;
  8399. break;
  8400. case NID_X9_62_prime239v1:
  8401. case NID_X9_62_prime239v2:
  8402. case NID_X9_62_prime239v3:
  8403. degree = 239;
  8404. break;
  8405. case NID_secp256k1:
  8406. case NID_brainpoolP256r1:
  8407. case NID_X9_62_prime256v1:
  8408. degree = 256;
  8409. break;
  8410. case NID_brainpoolP320r1:
  8411. degree = 320;
  8412. break;
  8413. case NID_secp384r1:
  8414. case NID_brainpoolP384r1:
  8415. degree = 384;
  8416. break;
  8417. case NID_brainpoolP512r1:
  8418. degree = 512;
  8419. break;
  8420. case NID_secp521r1:
  8421. degree = 521;
  8422. break;
  8423. }
  8424. }
  8425. return degree;
  8426. }
  8427. #endif /* OPENSSL_EXTRA */
  8428. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8429. /* Get the length of the order in bits of the EC group.
  8430. *
  8431. * TODO: consider switch statement or calculating directly from hex string
  8432. * array instead of using mp_int.
  8433. *
  8434. * @param [in] group EC group.
  8435. * @return Length of order in bits on success.
  8436. * @return 0 on error.
  8437. */
  8438. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8439. {
  8440. int ret = 0;
  8441. #ifdef WOLFSSL_SMALL_STACK
  8442. mp_int *order = NULL;
  8443. #else
  8444. mp_int order[1];
  8445. #endif
  8446. /* Validate parameter. */
  8447. if ((group == NULL) || (group->curve_idx < 0)) {
  8448. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8449. ret = -1;
  8450. }
  8451. #ifdef WOLFSSL_SMALL_STACK
  8452. if (ret == 0) {
  8453. /* Allocate memory for mp_int that will hold order value. */
  8454. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8455. DYNAMIC_TYPE_TMP_BUFFER);
  8456. if (order == NULL) {
  8457. ret = -1;
  8458. }
  8459. }
  8460. #endif
  8461. if (ret == 0) {
  8462. /* Initialize mp_int. */
  8463. ret = mp_init(order);
  8464. }
  8465. if (ret == 0) {
  8466. /* Read hex string of order from wolfCrypt array of curves. */
  8467. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8468. MP_RADIX_HEX);
  8469. if (ret == 0) {
  8470. /* Get bits of order. */
  8471. ret = mp_count_bits(order);
  8472. }
  8473. /* Clear and free mp_int. */
  8474. mp_clear(order);
  8475. }
  8476. #ifdef WOLFSSL_SMALL_STACK
  8477. /* Deallocate order. */
  8478. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8479. #endif
  8480. /* Convert error code to length of 0. */
  8481. if (ret < 0) {
  8482. ret = 0;
  8483. }
  8484. return ret;
  8485. }
  8486. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8487. #if defined(OPENSSL_EXTRA)
  8488. /* Get the order of the group as a BN.
  8489. *
  8490. * Return code compliant with OpenSSL.
  8491. *
  8492. * @param [in] group EC group.
  8493. * @param [in, out] order BN to hold order value.
  8494. * @param [in] ctx Context to use for BN operations. Unused.
  8495. * @return 1 on success.
  8496. * @return 0 on error.
  8497. */
  8498. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8499. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8500. {
  8501. int ret = 1;
  8502. mp_int* mp = NULL;
  8503. /* No BN operations performed - done with mp_int in BN. */
  8504. (void)ctx;
  8505. /* Validate parameters. */
  8506. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8507. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8508. ret = 0;
  8509. }
  8510. if (ret == 1) {
  8511. mp = (mp_int*)order->internal;
  8512. }
  8513. /* Initialize */
  8514. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8515. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8516. ret = 0;
  8517. }
  8518. /* Read hex string of order from wolfCrypt array of curves. */
  8519. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8520. MP_RADIX_HEX) != MP_OKAY)) {
  8521. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8522. /* Zero out any partial value but don't free. */
  8523. mp_zero(mp);
  8524. ret = 0;
  8525. }
  8526. return ret;
  8527. }
  8528. #endif /* OPENSSL_EXTRA */
  8529. /* End EC_GROUP */
  8530. /* Start EC_POINT */
  8531. #if defined(OPENSSL_EXTRA)
  8532. /* Set data of EC point into internal, wolfCrypt EC point object.
  8533. *
  8534. * EC_POINT Openssl -> WolfSSL
  8535. *
  8536. * @param [in, out] p EC point to update.
  8537. * @return 1 on success.
  8538. * @return -1 on failure.
  8539. */
  8540. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8541. {
  8542. int ret = 1;
  8543. WOLFSSL_ENTER("ec_point_internal_set");
  8544. /* Validate parameter. */
  8545. if ((p == NULL) || (p->internal == NULL)) {
  8546. WOLFSSL_MSG("ECPoint NULL error");
  8547. ret = -1;
  8548. }
  8549. else {
  8550. /* Get internal point as a wolfCrypt EC point. */
  8551. ecc_point* point = (ecc_point*)p->internal;
  8552. /* Set X ordinate if available. */
  8553. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8554. WOLFSSL_MSG("ecc point X error");
  8555. ret = -1;
  8556. }
  8557. /* Set Y ordinate if available. */
  8558. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8559. point->y) != 1)) {
  8560. WOLFSSL_MSG("ecc point Y error");
  8561. ret = -1;
  8562. }
  8563. /* Set Z ordinate if available. */
  8564. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8565. point->z) != 1)) {
  8566. WOLFSSL_MSG("ecc point Z error");
  8567. ret = -1;
  8568. }
  8569. /* Internal values set when operations succeeded. */
  8570. p->inSet = (ret == 1);
  8571. }
  8572. return ret;
  8573. }
  8574. /* Set data of internal, wolfCrypt EC point object into EC point.
  8575. *
  8576. * EC_POINT WolfSSL -> OpenSSL
  8577. *
  8578. * @param [in, out] p EC point to update.
  8579. * @return 1 on success.
  8580. * @return -1 on failure.
  8581. */
  8582. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8583. {
  8584. int ret = 1;
  8585. WOLFSSL_ENTER("ec_point_external_set");
  8586. /* Validate parameter. */
  8587. if ((p == NULL) || (p->internal == NULL)) {
  8588. WOLFSSL_MSG("ECPoint NULL error");
  8589. ret = -1;
  8590. }
  8591. else {
  8592. /* Get internal point as a wolfCrypt EC point. */
  8593. ecc_point* point = (ecc_point*)p->internal;
  8594. /* Set X ordinate. */
  8595. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8596. WOLFSSL_MSG("ecc point X error");
  8597. ret = -1;
  8598. }
  8599. /* Set Y ordinate. */
  8600. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8601. WOLFSSL_MSG("ecc point Y error");
  8602. ret = -1;
  8603. }
  8604. /* Set Z ordinate. */
  8605. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8606. WOLFSSL_MSG("ecc point Z error");
  8607. ret = -1;
  8608. }
  8609. /* External values set when operations succeeded. */
  8610. p->exSet = (ret == 1);
  8611. }
  8612. return ret;
  8613. }
  8614. /* Setup internals of EC point.
  8615. *
  8616. * Assumes point is not NULL.
  8617. *
  8618. * @param [in, out] point EC point to update.
  8619. * @return 1 on success.
  8620. * @return 0 on failure.
  8621. */
  8622. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8623. int ret = 1;
  8624. /* Check if internal values need setting. */
  8625. if (!point->inSet) {
  8626. WOLFSSL_MSG("No ECPoint internal set, do it");
  8627. /* Forcing to non-constant type to update internals. */
  8628. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8629. WOLFSSL_MSG("ec_point_internal_set failed");
  8630. ret = 0;
  8631. }
  8632. }
  8633. return ret;
  8634. }
  8635. /* Create a new EC point from the group.
  8636. *
  8637. * @param [in] group EC group.
  8638. * @return EC point on success.
  8639. * @return NULL on error.
  8640. */
  8641. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8642. {
  8643. int err = 0;
  8644. WOLFSSL_EC_POINT* point = NULL;
  8645. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8646. /* Validate parameter. */
  8647. if (group == NULL) {
  8648. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8649. err = 1;
  8650. }
  8651. if (!err) {
  8652. /* Allocate memory for new EC point. */
  8653. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8654. DYNAMIC_TYPE_ECC);
  8655. if (point == NULL) {
  8656. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8657. err = 1;
  8658. }
  8659. }
  8660. if (!err) {
  8661. /* Clear fields of EC point. */
  8662. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8663. /* Allocate internal EC point. */
  8664. point->internal = wc_ecc_new_point();
  8665. if (point->internal == NULL) {
  8666. WOLFSSL_MSG("ecc_new_point failure");
  8667. err = 1;
  8668. }
  8669. }
  8670. if (err) {
  8671. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8672. point = NULL;
  8673. }
  8674. return point;
  8675. }
  8676. #endif /* OPENSSL_EXTRA */
  8677. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8678. /* Dispose of the EC point.
  8679. *
  8680. * Cannot use point after this call.
  8681. *
  8682. * @param [in, out] point EC point to free.
  8683. */
  8684. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8685. {
  8686. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8687. if (point != NULL) {
  8688. if (point->internal != NULL) {
  8689. wc_ecc_del_point((ecc_point*)point->internal);
  8690. point->internal = NULL;
  8691. }
  8692. /* Free ordinates. */
  8693. wolfSSL_BN_free(point->X);
  8694. wolfSSL_BN_free(point->Y);
  8695. wolfSSL_BN_free(point->Z);
  8696. /* Clear fields. */
  8697. point->X = NULL;
  8698. point->Y = NULL;
  8699. point->Z = NULL;
  8700. point->inSet = 0;
  8701. point->exSet = 0;
  8702. /* Dispose of EC point. */
  8703. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8704. }
  8705. }
  8706. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8707. #ifdef OPENSSL_EXTRA
  8708. /* Clear and dispose of the EC point.
  8709. *
  8710. * Cannot use point after this call.
  8711. *
  8712. * @param [in, out] point EC point to free.
  8713. */
  8714. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8715. {
  8716. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8717. if (point != NULL) {
  8718. if (point->internal != NULL) {
  8719. /* Force internal point to be zeros. */
  8720. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8721. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8722. #else
  8723. ecc_point* p = (ecc_point*)point->internal;
  8724. mp_forcezero(p->x);
  8725. mp_forcezero(p->y);
  8726. mp_forcezero(p->z);
  8727. #endif
  8728. wc_ecc_del_point((ecc_point*)point->internal);
  8729. point->internal = NULL;
  8730. }
  8731. /* Clear the ordinates before freeing. */
  8732. wolfSSL_BN_clear_free(point->X);
  8733. wolfSSL_BN_clear_free(point->Y);
  8734. wolfSSL_BN_clear_free(point->Z);
  8735. /* Clear fields. */
  8736. point->X = NULL;
  8737. point->Y = NULL;
  8738. point->Z = NULL;
  8739. point->inSet = 0;
  8740. point->exSet = 0;
  8741. /* Dispose of EC point. */
  8742. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8743. }
  8744. }
  8745. /* Print out the internals of EC point in debug and when logging callback set.
  8746. *
  8747. * Not an OpenSSL API.
  8748. *
  8749. * TODO: Use WOLFSSL_MSG_EX()?
  8750. *
  8751. * @param [in] msg Message to prepend.
  8752. * @param [in] point EC point to print.
  8753. */
  8754. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8755. {
  8756. #if defined(DEBUG_WOLFSSL)
  8757. char *num;
  8758. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8759. /* Only print when debugging on. */
  8760. if (WOLFSSL_IS_DEBUG_ON()) {
  8761. if (point == NULL) {
  8762. /* No point passed in so just put out "NULL". */
  8763. WOLFSSL_MSG_EX("%s = NULL\n", msg);
  8764. }
  8765. else {
  8766. /* Put out message and status of internal/external data set. */
  8767. WOLFSSL_MSG_EX("%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8768. point->exSet);
  8769. /* Get x-ordinate as a hex string and print. */
  8770. num = wolfSSL_BN_bn2hex(point->X);
  8771. WOLFSSL_MSG_EX("\tX = %s\n", num);
  8772. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8773. /* Get x-ordinate as a hex string and print. */
  8774. num = wolfSSL_BN_bn2hex(point->Y);
  8775. WOLFSSL_MSG_EX("\tY = %s\n", num);
  8776. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8777. /* Get z-ordinate as a hex string and print. */
  8778. num = wolfSSL_BN_bn2hex(point->Z);
  8779. WOLFSSL_MSG_EX("\tZ = %s\n", num);
  8780. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8781. }
  8782. }
  8783. #else
  8784. (void)msg;
  8785. (void)point;
  8786. #endif
  8787. }
  8788. #ifndef HAVE_SELFTEST
  8789. /* Convert EC point to hex string that as either uncompressed or compressed.
  8790. *
  8791. * ECC point compression types were not included in selftest ecc.h
  8792. *
  8793. * @param [in] group EC group for point.
  8794. * @param [in] point EC point to encode.
  8795. * @param [in] form Format of encoding. Valid values:
  8796. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8797. * @param [in] ctx Context to use for BN operations. Unused.
  8798. * @return Allocated hex string on success.
  8799. * @return NULL on error.
  8800. */
  8801. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8802. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8803. {
  8804. static const char* hexDigit = "0123456789ABCDEF";
  8805. char* hex = NULL;
  8806. int i;
  8807. int sz = 0;
  8808. int len = 0;
  8809. int err = 0;
  8810. /* No BN operations performed. */
  8811. (void)ctx;
  8812. /* Validate parameters. */
  8813. if ((group == NULL) || (point == NULL)) {
  8814. err = 1;
  8815. }
  8816. /* Get curve id expects a positive index. */
  8817. if ((!err) && (group->curve_idx < 0)) {
  8818. err = 1;
  8819. }
  8820. if (!err) {
  8821. /* Get curve id to look up ordinate size. */
  8822. int id = wc_ecc_get_curve_id(group->curve_idx);
  8823. /* Get size of ordinate. */
  8824. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8825. err = 1;
  8826. }
  8827. }
  8828. if (!err) {
  8829. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8830. len = sz + 1;
  8831. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8832. /* Include y ordinate when uncompressed. */
  8833. len += sz;
  8834. }
  8835. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8836. */
  8837. hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC);
  8838. if (hex == NULL) {
  8839. err = 1;
  8840. }
  8841. }
  8842. if (!err) {
  8843. /* Make bytes all zeros to allow for ordinate values less than max size.
  8844. */
  8845. XMEMSET(hex, 0, (size_t)(2 * len + 1));
  8846. /* Calculate offset as leading zeros not encoded. */
  8847. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8848. /* Put in x-ordinate after format byte. */
  8849. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8850. 0) {
  8851. err = 1;
  8852. }
  8853. }
  8854. if (!err) {
  8855. if (form == POINT_CONVERSION_COMPRESSED) {
  8856. /* Compressed format byte value dependent on whether y-ordinate is
  8857. * odd.
  8858. */
  8859. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8860. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8861. /* No y-ordinate. */
  8862. }
  8863. else {
  8864. /* Put in uncompressed format byte. */
  8865. hex[0] = ECC_POINT_UNCOMP;
  8866. /* Calculate offset as leading zeros not encoded. */
  8867. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8868. /* Put in y-ordinate after x-ordinate. */
  8869. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8870. (byte*)(hex + i)) < 0) {
  8871. err = 1;
  8872. }
  8873. }
  8874. }
  8875. if (!err) {
  8876. /* Convert binary encoding to hex string. */
  8877. /* Start at end so as not to overwrite. */
  8878. for (i = len-1; i >= 0; i--) {
  8879. /* Get byte value and store has hex string. */
  8880. byte b = (byte)hex[i];
  8881. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8882. hex[i * 2 ] = hexDigit[b >> 4];
  8883. }
  8884. /* Memset put trailing zero or '\0' on end of string. */
  8885. }
  8886. if (err && (hex != NULL)) {
  8887. /* Dispose of allocated data not being returned. */
  8888. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8889. hex = NULL;
  8890. }
  8891. /* Return hex string encoding. */
  8892. return hex;
  8893. }
  8894. #endif /* HAVE_SELFTEST */
  8895. /* Encode the EC point as an uncompressed point in DER.
  8896. *
  8897. * Return code compliant with OpenSSL.
  8898. * Not OpenSSL API.
  8899. *
  8900. * @param [in] group EC group point belongs to.
  8901. * @param [in] point EC point to encode.
  8902. * @param [out] out Buffer to encode into. May be NULL.
  8903. * @param [in, out] len On in, length of buffer in bytes.
  8904. * On out, length of encoding in bytes.
  8905. * @return 1 on success.
  8906. * @return 0 on error.
  8907. */
  8908. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8909. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  8910. {
  8911. int res = 1;
  8912. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8913. /* Validate parameters. */
  8914. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  8915. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8916. res = 0;
  8917. }
  8918. /* Ensure points internals are set up. */
  8919. if ((res == 1) && (ec_point_setup(point) != 1)) {
  8920. res = 0;
  8921. }
  8922. /* Dump the point if encoding. */
  8923. if ((res == 1) && (out != NULL)) {
  8924. wolfSSL_EC_POINT_dump("i2d p", point);
  8925. }
  8926. if (res == 1) {
  8927. /* DER encode point in uncompressed format. */
  8928. int ret = wc_ecc_export_point_der(group->curve_idx,
  8929. (ecc_point*)point->internal, out, len);
  8930. /* Check return. When out is NULL, return will be length only error. */
  8931. if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) {
  8932. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8933. res = 0;
  8934. }
  8935. }
  8936. return res;
  8937. }
  8938. /* Decode the uncompressed point in DER into EC point.
  8939. *
  8940. * Return code compliant with OpenSSL.
  8941. * Not OpenSSL API.
  8942. *
  8943. * @param [in] in Buffer containing DER encoded point.
  8944. * @param [in] len Length of data in bytes.
  8945. * @param [in] group EC group associated with point.
  8946. * @param [in, out] point EC point to set data into.
  8947. * @return 1 on success.
  8948. * @return 0 on error.
  8949. */
  8950. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  8951. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  8952. {
  8953. int ret = 1;
  8954. WOLFSSL_BIGNUM* x = NULL;
  8955. WOLFSSL_BIGNUM* y = NULL;
  8956. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8957. /* Validate parameters. */
  8958. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  8959. (point->internal == NULL)) {
  8960. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8961. ret = 0;
  8962. }
  8963. if (ret == 1) {
  8964. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8965. /* Import point into internal EC point. */
  8966. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8967. (ecc_point*)point->internal, 0) != MP_OKAY) {
  8968. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8969. ret = 0;
  8970. }
  8971. #else
  8972. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8973. if (in[0] == 0x04) {
  8974. /* Import point into internal EC point. */
  8975. if (wc_ecc_import_point_der((unsigned char *)in, len,
  8976. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  8977. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8978. ret = 0;
  8979. }
  8980. }
  8981. else {
  8982. WOLFSSL_MSG("Only uncompressed points supported with "
  8983. "HAVE_SELFTEST");
  8984. ret = 0;
  8985. }
  8986. #endif
  8987. }
  8988. if (ret == 1)
  8989. point->inSet = 1;
  8990. /* Set new external point. */
  8991. if (ret == 1 && ec_point_external_set(point) != 1) {
  8992. WOLFSSL_MSG("ec_point_external_set failed");
  8993. ret = 0;
  8994. }
  8995. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  8996. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  8997. x = wolfSSL_BN_new();
  8998. y = wolfSSL_BN_new();
  8999. if (x == NULL || y == NULL)
  9000. ret = 0;
  9001. if (ret == 1 && wolfSSL_EC_POINT_get_affine_coordinates_GFp(group,
  9002. point, x, y, NULL) != 1) {
  9003. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp failed");
  9004. ret = 0;
  9005. }
  9006. /* wolfSSL_EC_POINT_set_affine_coordinates_GFp check that the point is
  9007. * on the curve. */
  9008. if (ret == 1 && wolfSSL_EC_POINT_set_affine_coordinates_GFp(group,
  9009. point, x, y, NULL) != 1) {
  9010. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp failed");
  9011. ret = 0;
  9012. }
  9013. #else
  9014. WOLFSSL_MSG("Importing non-affine point. This may cause issues in math "
  9015. "operations later on.");
  9016. #endif
  9017. }
  9018. if (ret == 1) {
  9019. /* Dump new point. */
  9020. wolfSSL_EC_POINT_dump("d2i p", point);
  9021. }
  9022. wolfSSL_BN_free(x);
  9023. wolfSSL_BN_free(y);
  9024. return ret;
  9025. }
  9026. /* Encode point as octet string.
  9027. *
  9028. * HYBRID not supported.
  9029. *
  9030. * @param [in] group EC group that point belongs to.
  9031. * @param [in] point EC point to encode.
  9032. * @param [in] form Format of encoding. Valid values:
  9033. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  9034. * @param [out] buf Buffer to write encoding into.
  9035. * @param [in] len Length of buffer.
  9036. * @param [in] ctx Context to use for BN operations. Unused.
  9037. * @return Length of encoded data on success.
  9038. * @return 0 on error.
  9039. */
  9040. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  9041. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  9042. WOLFSSL_BN_CTX *ctx)
  9043. {
  9044. int err = 0;
  9045. word32 enc_len = (word32)len;
  9046. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9047. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  9048. #endif /* !HAVE_SELFTEST */
  9049. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  9050. /* No BN operations performed. */
  9051. (void)ctx;
  9052. /* Validate parameters. */
  9053. if ((group == NULL) || (point == NULL)) {
  9054. err = 1;
  9055. }
  9056. /* Ensure points internals are set up. */
  9057. if ((!err) && (ec_point_setup(point) != 1)) {
  9058. err = 1;
  9059. }
  9060. /* Special case when point is infinity. */
  9061. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9062. /* Encoding is a single octet: 0x00. */
  9063. enc_len = 1;
  9064. if (buf != NULL) {
  9065. /* Check whether buffer has space. */
  9066. if (len < 1) {
  9067. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  9068. err = 1;
  9069. }
  9070. else {
  9071. /* Put in encoding of infinity. */
  9072. buf[0] = 0x00;
  9073. }
  9074. }
  9075. }
  9076. /* Not infinity. */
  9077. else if (!err) {
  9078. /* Validate format. */
  9079. if (form != POINT_CONVERSION_UNCOMPRESSED
  9080. #ifndef HAVE_SELFTEST
  9081. && form != POINT_CONVERSION_COMPRESSED
  9082. #endif /* !HAVE_SELFTEST */
  9083. ) {
  9084. WOLFSSL_MSG("Unsupported point form");
  9085. err = 1;
  9086. }
  9087. if (!err) {
  9088. int ret;
  9089. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9090. /* Encode as compressed or uncompressed. */
  9091. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  9092. (ecc_point*)point->internal, buf, &enc_len, compressed);
  9093. #else
  9094. /* Encode uncompressed point in DER format. */
  9095. ret = wc_ecc_export_point_der(group->curve_idx,
  9096. (ecc_point*)point->internal, buf, &enc_len);
  9097. #endif /* !HAVE_SELFTEST */
  9098. /* Check return. When buf is NULL, return will be length only
  9099. * error.
  9100. */
  9101. if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) {
  9102. err = 1;
  9103. }
  9104. }
  9105. }
  9106. #if defined(DEBUG_WOLFSSL)
  9107. if (!err) {
  9108. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_point2oct point", point);
  9109. WOLFSSL_MSG("\twolfSSL_EC_POINT_point2oct output:");
  9110. WOLFSSL_BUFFER(buf, enc_len);
  9111. }
  9112. #endif
  9113. /* On error, return encoding length of 0. */
  9114. if (err) {
  9115. enc_len = 0;
  9116. }
  9117. return (size_t)enc_len;
  9118. }
  9119. /* Convert octet string to EC point.
  9120. *
  9121. * @param [in] group EC group.
  9122. * @param [in, out] point EC point to set data into.
  9123. * @param [in] buf Buffer holding octet string.
  9124. * @param [in] len Length of data in buffer in bytes.
  9125. * @param [in] ctx Context to use for BN operations. Unused.
  9126. */
  9127. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  9128. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  9129. WOLFSSL_BN_CTX *ctx)
  9130. {
  9131. int ret;
  9132. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9133. /* No BN operations performed. */
  9134. (void)ctx;
  9135. /* Validate parameters. */
  9136. if ((group == NULL) || (point == NULL)) {
  9137. ret = 0;
  9138. }
  9139. else {
  9140. /* Decode DER encoding into EC point. */
  9141. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  9142. point);
  9143. }
  9144. return ret;
  9145. }
  9146. /* Convert an EC point to a single BN.
  9147. *
  9148. * @param [in] group EC group.
  9149. * @param [in] point EC point.
  9150. * @param [in] form Format of encoding. Valid values:
  9151. * POINT_CONVERSION_UNCOMPRESSED,
  9152. * POINT_CONVERSION_COMPRESSED.
  9153. * @param [in, out] bn BN to hold point value.
  9154. * When NULL a new BN is allocated otherwise this is
  9155. * returned on success.
  9156. * @param [in] ctx Context to use for BN operations. Unused.
  9157. * @return BN object with point as a value on success.
  9158. * @return NULL on error.
  9159. */
  9160. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  9161. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  9162. WOLFSSL_BN_CTX* ctx)
  9163. {
  9164. int err = 0;
  9165. size_t len = 0;
  9166. byte *buf = NULL;
  9167. WOLFSSL_BIGNUM *ret = NULL;
  9168. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9169. /* Validate parameters. */
  9170. if ((group == NULL) || (point == NULL)) {
  9171. err = 1;
  9172. }
  9173. /* Calculate length of octet encoding. */
  9174. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  9175. 0, ctx)) == 0)) {
  9176. err = 1;
  9177. }
  9178. /* Allocate buffer to hold octet encoding. */
  9179. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  9180. NULL)) {
  9181. WOLFSSL_MSG("malloc failed");
  9182. err = 1;
  9183. }
  9184. /* Encode EC point as an octet string. */
  9185. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  9186. ctx) != len)) {
  9187. err = 1;
  9188. }
  9189. /* Load BN with octet string data. */
  9190. if (!err) {
  9191. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  9192. }
  9193. /* Dispose of any allocated data. */
  9194. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9195. return ret;
  9196. }
  9197. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9198. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9199. /* Check if EC point is on the the curve defined by the EC group.
  9200. *
  9201. * @param [in] group EC group defining curve.
  9202. * @param [in] point EC point to check.
  9203. * @param [in] ctx Context to use for BN operations. Unused.
  9204. * @return 1 when point is on curve.
  9205. * @return 0 when point is not on curve or error.
  9206. */
  9207. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9208. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9209. {
  9210. int err = 0;
  9211. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9212. /* No BN operations performed. */
  9213. (void)ctx;
  9214. /* Validate parameters. */
  9215. if ((group == NULL) || (point == NULL)) {
  9216. WOLFSSL_MSG("Invalid arguments");
  9217. err = 1;
  9218. }
  9219. /* Ensure internal EC point set. */
  9220. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9221. (WOLFSSL_EC_POINT*)point) != 1) {
  9222. WOLFSSL_MSG("ec_point_internal_set error");
  9223. err = 1;
  9224. }
  9225. /* Check point is on curve from group. */
  9226. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9227. group->curve_idx) != MP_OKAY)) {
  9228. err = 1;
  9229. }
  9230. /* Return boolean of on curve. No error means on curve. */
  9231. return !err;
  9232. }
  9233. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9234. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9235. /* Convert Jacobian ordinates to affine.
  9236. *
  9237. * @param [in] group EC group.
  9238. * @param [in] point EC point to get coordinates from.
  9239. * @return 1 on success.
  9240. * @return 0 on error.
  9241. */
  9242. int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9243. WOLFSSL_EC_POINT *point)
  9244. {
  9245. int err = 0;
  9246. mp_digit mp = 0;
  9247. #ifdef WOLFSSL_SMALL_STACK
  9248. mp_int* modulus;
  9249. #else
  9250. mp_int modulus[1];
  9251. #endif
  9252. #ifdef WOLFSSL_SMALL_STACK
  9253. /* Allocate memory for curve's prime modulus. */
  9254. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9255. if (modulus == NULL) {
  9256. err = 1;
  9257. }
  9258. #endif
  9259. /* Initialize the MP integer. */
  9260. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9261. WOLFSSL_MSG("mp_init failed");
  9262. err = 1;
  9263. }
  9264. if (!err) {
  9265. /* Get the modulus from the hex string in the EC curve set. */
  9266. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9267. MP_RADIX_HEX) != MP_OKAY) {
  9268. WOLFSSL_MSG("mp_read_radix failed");
  9269. err = 1;
  9270. }
  9271. /* Get Montgomery multiplier for the modulus as ordinates in
  9272. * Montgomery form.
  9273. */
  9274. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9275. WOLFSSL_MSG("mp_montgomery_setup failed");
  9276. err = 1;
  9277. }
  9278. /* Map internal EC point from Jacobian to affine. */
  9279. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9280. MP_OKAY)) {
  9281. WOLFSSL_MSG("ecc_map failed");
  9282. err = 1;
  9283. }
  9284. /* Set new ordinates into external EC point. */
  9285. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9286. WOLFSSL_MSG("ec_point_external_set failed");
  9287. err = 1;
  9288. }
  9289. point->exSet = !err;
  9290. mp_clear(modulus);
  9291. }
  9292. #ifdef WOLFSSL_SMALL_STACK
  9293. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9294. #endif
  9295. return err;
  9296. }
  9297. /* Get the affine coordinates of the EC point on a Prime curve.
  9298. *
  9299. * When z-ordinate is not one then coordinates are Jacobian and need to be
  9300. * converted to affine before storing in BNs.
  9301. *
  9302. * Return code compliant with OpenSSL.
  9303. *
  9304. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9305. *
  9306. * @param [in] group EC group.
  9307. * @param [in] point EC point to get coordinates from.
  9308. * @param [in, out] x BN to hold x-ordinate.
  9309. * @param [in, out] y BN to hold y-ordinate.
  9310. * @param [in] ctx Context to use for BN operations. Unused.
  9311. * @return 1 on success.
  9312. * @return 0 on error.
  9313. */
  9314. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9315. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9316. WOLFSSL_BN_CTX* ctx)
  9317. {
  9318. int ret = 1;
  9319. /* BN operations don't need context. */
  9320. (void)ctx;
  9321. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9322. /* Validate parameters. */
  9323. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9324. (x == NULL) || (y == NULL)) {
  9325. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9326. ret = 0;
  9327. }
  9328. /* Don't return point at infinity. */
  9329. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9330. ret = 0;
  9331. }
  9332. /* Ensure internal EC point has values of external EC point. */
  9333. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9334. ret = 0;
  9335. }
  9336. /* Check whether ordinates are in Jacobian form. */
  9337. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9338. /* Convert from Jacobian to affine. */
  9339. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9340. ret = 0;
  9341. }
  9342. }
  9343. /* Copy the externally set x and y ordinates. */
  9344. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9345. ret = 0;
  9346. }
  9347. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9348. ret = 0;
  9349. }
  9350. return ret;
  9351. }
  9352. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9353. /* Sets the affine coordinates that belong on a prime curve.
  9354. *
  9355. * @param [in] group EC group.
  9356. * @param [in, out] point EC point to set coordinates into.
  9357. * @param [in] x BN holding x-ordinate.
  9358. * @param [in] y BN holding y-ordinate.
  9359. * @param [in] ctx Context to use for BN operations. Unused.
  9360. * @return 1 on success.
  9361. * @return 0 on error.
  9362. */
  9363. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9364. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9365. WOLFSSL_BN_CTX* ctx)
  9366. {
  9367. int ret = 1;
  9368. /* BN operations don't need context. */
  9369. (void)ctx;
  9370. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9371. /* Validate parameters. */
  9372. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9373. (x == NULL) || (y == NULL)) {
  9374. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9375. ret = 0;
  9376. }
  9377. /* Ensure we have a object for x-ordinate. */
  9378. if ((ret == 1) && (point->X == NULL) &&
  9379. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9380. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9381. ret = 0;
  9382. }
  9383. /* Ensure we have a object for y-ordinate. */
  9384. if ((ret == 1) && (point->Y == NULL) &&
  9385. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9386. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9387. ret = 0;
  9388. }
  9389. /* Ensure we have a object for z-ordinate. */
  9390. if ((ret == 1) && (point->Z == NULL) &&
  9391. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9392. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9393. ret = 0;
  9394. }
  9395. /* Copy the x-ordinate. */
  9396. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9397. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9398. ret = 0;
  9399. }
  9400. /* Copy the y-ordinate. */
  9401. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9402. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9403. ret = 0;
  9404. }
  9405. /* z-ordinate is one for affine coordinates. */
  9406. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9407. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9408. ret = 0;
  9409. }
  9410. /* Copy the new point data to internal object. */
  9411. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9412. WOLFSSL_MSG("ec_point_internal_set failed");
  9413. ret = 0;
  9414. }
  9415. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9416. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9417. /* Check that the point is valid. */
  9418. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9419. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9420. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9421. ret = 0;
  9422. }
  9423. #endif
  9424. return ret;
  9425. }
  9426. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9427. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9428. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9429. /* Add two points on the same together.
  9430. *
  9431. * @param [in] curveIdx Index of curve in ecc_set.
  9432. * @param [out] r Result point.
  9433. * @param [in] p1 First point to add.
  9434. * @param [in] p2 Second point to add.
  9435. * @return 1 on success.
  9436. * @return 0 on error.
  9437. */
  9438. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9439. ecc_point* p2)
  9440. {
  9441. int ret = 1;
  9442. #ifdef WOLFSSL_SMALL_STACK
  9443. mp_int* a = NULL;
  9444. mp_int* prime = NULL;
  9445. mp_int* mu = NULL;
  9446. #else
  9447. mp_int a[1];
  9448. mp_int prime[1];
  9449. mp_int mu[1];
  9450. #endif
  9451. mp_digit mp = 0;
  9452. ecc_point* montP1 = NULL;
  9453. ecc_point* montP2 = NULL;
  9454. #ifdef WOLFSSL_SMALL_STACK
  9455. if (ret == 1) {
  9456. /* Allocate memory for curve parameter: a. */
  9457. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9458. if (a == NULL) {
  9459. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9460. ret = 0;
  9461. }
  9462. }
  9463. if (ret == 1) {
  9464. /* Allocate memory for curve parameter: prime. */
  9465. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9466. if (prime == NULL) {
  9467. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9468. ret = 0;
  9469. }
  9470. }
  9471. if (ret == 1) {
  9472. /* Allocate memory for mu (Montgomery normalizer). */
  9473. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9474. if (mu == NULL) {
  9475. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9476. ret = 0;
  9477. }
  9478. }
  9479. if (ret == 1) {
  9480. /* Zero out all MP int data in case initialization fails. */
  9481. XMEMSET(a, 0, sizeof(mp_int));
  9482. XMEMSET(prime, 0, sizeof(mp_int));
  9483. XMEMSET(mu, 0, sizeof(mp_int));
  9484. }
  9485. #endif
  9486. /* Initialize the MP ints. */
  9487. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9488. MP_OKAY)) {
  9489. WOLFSSL_MSG("mp_init_multi error");
  9490. ret = 0;
  9491. }
  9492. /* Read the curve parameter: a. */
  9493. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9494. MP_OKAY)) {
  9495. WOLFSSL_MSG("mp_read_radix a error");
  9496. ret = 0;
  9497. }
  9498. /* Read the curve parameter: prime. */
  9499. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9500. MP_RADIX_HEX) != MP_OKAY)) {
  9501. WOLFSSL_MSG("mp_read_radix prime error");
  9502. ret = 0;
  9503. }
  9504. /* Calculate the Montgomery product. */
  9505. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9506. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9507. ret = 0;
  9508. }
  9509. /* TODO: use the heap filed of one of the points? */
  9510. /* Allocate new points to hold the Montgomery form values. */
  9511. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9512. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9513. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9514. ret = 0;
  9515. }
  9516. /* Calculate the Montgomery normalizer. */
  9517. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9518. MP_OKAY)) {
  9519. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9520. ret = 0;
  9521. }
  9522. /* Convert to Montgomery form. */
  9523. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9524. /* Copy the points if the normalizer is 1. */
  9525. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9526. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9527. WOLFSSL_MSG("wc_ecc_copy_point error");
  9528. ret = 0;
  9529. }
  9530. }
  9531. else if (ret == 1) {
  9532. /* Multiply each ordinate by the Montgomery normalizer. */
  9533. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9534. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9535. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9536. WOLFSSL_MSG("mp_mulmod error");
  9537. ret = 0;
  9538. }
  9539. /* Multiply each ordinate by the Montgomery normalizer. */
  9540. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9541. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9542. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9543. WOLFSSL_MSG("mp_mulmod error");
  9544. ret = 0;
  9545. }
  9546. }
  9547. /* Perform point addition with internal EC point objects - Jacobian form
  9548. * result.
  9549. */
  9550. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9551. mp) != MP_OKAY)) {
  9552. WOLFSSL_MSG("ecc_projective_add_point error");
  9553. ret = 0;
  9554. }
  9555. /* Map point back to affine coordinates. Converts from Montogomery form. */
  9556. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9557. WOLFSSL_MSG("ecc_map error");
  9558. ret = 0;
  9559. }
  9560. /* Dispose of allocated memory. */
  9561. mp_clear(a);
  9562. mp_clear(prime);
  9563. mp_clear(mu);
  9564. wc_ecc_del_point_h(montP1, NULL);
  9565. wc_ecc_del_point_h(montP2, NULL);
  9566. #ifdef WOLFSSL_SMALL_STACK
  9567. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9568. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9569. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9570. #endif
  9571. return ret;
  9572. }
  9573. /* Add two points on the same curve together.
  9574. *
  9575. * @param [in] group EC group.
  9576. * @param [out] r EC point that is result of point addition.
  9577. * @param [in] p1 First EC point to add.
  9578. * @param [in] p2 Second EC point to add.
  9579. * @param [in] ctx Context to use for BN operations. Unused.
  9580. * @return 1 on success.
  9581. * @return 0 on error.
  9582. */
  9583. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9584. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9585. {
  9586. int ret = 1;
  9587. /* No BN operations performed. */
  9588. (void)ctx;
  9589. /* Validate parameters. */
  9590. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9591. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9592. ret = 0;
  9593. }
  9594. /* Ensure the internal objects of the EC points are setup. */
  9595. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9596. (ec_point_setup(p2) != 1))) {
  9597. WOLFSSL_MSG("ec_point_setup error");
  9598. ret = 0;
  9599. }
  9600. #ifdef DEBUG_WOLFSSL
  9601. if (ret == 1) {
  9602. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9603. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9604. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9605. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p1", p1);
  9606. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p2", p2);
  9607. if (curve != NULL)
  9608. WOLFSSL_MSG_EX("curve name: %s", curve);
  9609. if (nistName != NULL)
  9610. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9611. }
  9612. #endif
  9613. if (ret == 1) {
  9614. /* Add points using wolfCrypt objects. */
  9615. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9616. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9617. }
  9618. /* Copy internal EC point values out to external EC point. */
  9619. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9620. WOLFSSL_MSG("ec_point_external_set error");
  9621. ret = 0;
  9622. }
  9623. #ifdef DEBUG_WOLFSSL
  9624. if (ret == 1) {
  9625. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add result", r);
  9626. }
  9627. #endif
  9628. return ret;
  9629. }
  9630. /* Sum the scalar multiplications of the base point and n, and q and m.
  9631. *
  9632. * r = base point * n + q * m
  9633. *
  9634. * @param [out] r EC point that is result of operation.
  9635. * @param [in] b Base point of curve.
  9636. * @param [in] n Scalar to multiply by base point.
  9637. * @param [in] q EC point to be scalar multiplied.
  9638. * @param [in] m Scalar to multiply q by.
  9639. * @param [in] a Parameter A of curve.
  9640. * @param [in] prime Prime (modulus) of curve.
  9641. * @return 1 on success.
  9642. * @return 0 on error.
  9643. */
  9644. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9645. mp_int* m, mp_int* a, mp_int* prime)
  9646. {
  9647. int ret = 1;
  9648. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9649. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9650. WOLFSSL_MSG("ecc_mul2add error");
  9651. ret = 0;
  9652. }
  9653. #else
  9654. ecc_point* tmp = NULL;
  9655. mp_digit mp = 0;
  9656. /* Calculate Montgomery product. */
  9657. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9658. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9659. ret = 0;
  9660. }
  9661. /* Create temporary point to hold: q * m */
  9662. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9663. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9664. ret = 0;
  9665. }
  9666. /* r = base point * n */
  9667. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9668. MP_OKAY)) {
  9669. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9670. ret = 0;
  9671. }
  9672. /* tmp = q * m */
  9673. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9674. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9675. ret = 0;
  9676. }
  9677. /* r = r + tmp */
  9678. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9679. MP_OKAY)) {
  9680. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9681. ret = 0;
  9682. }
  9683. /* Map point back to affine coordinates. Converts from Montogomery
  9684. * form. */
  9685. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9686. WOLFSSL_MSG("ecc_map nqm error");
  9687. ret = 0;
  9688. }
  9689. /* Dispose of allocated temporary point. */
  9690. wc_ecc_del_point(tmp);
  9691. #endif
  9692. return ret;
  9693. }
  9694. /* Sum the scalar multiplications of the base point and n, and q and m.
  9695. *
  9696. * r = base point * n + q * m
  9697. *
  9698. * @param [in] curveIdx Index of curve in ecc_set.
  9699. * @param [out] r EC point that is result of operation.
  9700. * @param [in] n Scalar to multiply by base point. May be NULL.
  9701. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9702. * @param [in] m Scalar to multiply q by. May be NULL.
  9703. * @return 1 on success.
  9704. * @return 0 on error.
  9705. */
  9706. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9707. ecc_point* q, mp_int* m)
  9708. {
  9709. int ret = 1;
  9710. #ifdef WOLFSSL_SMALL_STACK
  9711. mp_int* a = NULL;
  9712. mp_int* prime = NULL;
  9713. #else
  9714. mp_int a[1], prime[1];
  9715. #endif
  9716. #ifdef WOLFSSL_SMALL_STACK
  9717. /* Allocate MP integer for curve parameter: a. */
  9718. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9719. if (a == NULL) {
  9720. ret = 0;
  9721. }
  9722. if (ret == 1) {
  9723. /* Allocate MP integer for curve parameter: prime. */
  9724. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9725. if (prime == NULL) {
  9726. ret = 0;
  9727. }
  9728. }
  9729. #endif
  9730. /* Initialize the MP ints. */
  9731. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9732. MP_OKAY)) {
  9733. WOLFSSL_MSG("mp_init_multi error");
  9734. ret = 0;
  9735. }
  9736. /* Read the curve parameter: prime. */
  9737. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9738. MP_RADIX_HEX) != MP_OKAY)) {
  9739. WOLFSSL_MSG("mp_read_radix prime error");
  9740. ret = 0;
  9741. }
  9742. /* Read the curve parameter: a. */
  9743. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9744. MP_RADIX_HEX) != MP_OKAY)) {
  9745. WOLFSSL_MSG("mp_read_radix a error");
  9746. ret = 0;
  9747. }
  9748. if ((ret == 1) && (n != NULL)) {
  9749. /* Get generator - base point. */
  9750. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9751. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9752. WOLFSSL_MSG("wc_ecc_get_generator error");
  9753. ret = 0;
  9754. }
  9755. #else
  9756. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9757. /* Read generator (base point) x-ordinate. */
  9758. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9759. MP_RADIX_HEX) != MP_OKAY)) {
  9760. WOLFSSL_MSG("mp_read_radix Gx error");
  9761. ret = 0;
  9762. }
  9763. /* Read generator (base point) y-ordinate. */
  9764. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9765. MP_RADIX_HEX) != MP_OKAY)) {
  9766. WOLFSSL_MSG("mp_read_radix Gy error");
  9767. ret = 0;
  9768. }
  9769. /* z-ordinate is one as point is affine. */
  9770. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9771. WOLFSSL_MSG("mp_set Gz error");
  9772. ret = 0;
  9773. }
  9774. #endif /* NOPT_FIPS_VERSION == 2 */
  9775. }
  9776. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9777. /* r = base point * n + q * m */
  9778. ret = ec_mul2add(r, r, n, q, m, a, prime);
  9779. }
  9780. /* Not all values present, see if we are only doing base point * n. */
  9781. else if ((ret == 1) && (n != NULL)) {
  9782. /* r = base point * n */
  9783. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9784. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9785. ret = 0;
  9786. }
  9787. }
  9788. /* Not all values present, see if we are only doing q * m. */
  9789. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9790. /* r = q * m */
  9791. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9792. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9793. ret = 0;
  9794. }
  9795. }
  9796. /* No values to use. */
  9797. else if (ret == 1) {
  9798. /* Set result to infinity as no values passed in. */
  9799. mp_zero(r->x);
  9800. mp_zero(r->y);
  9801. mp_zero(r->z);
  9802. }
  9803. mp_clear(a);
  9804. mp_clear(prime);
  9805. #ifdef WOLFSSL_SMALL_STACK
  9806. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9807. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9808. #endif
  9809. return ret;
  9810. }
  9811. /* Sum the scalar multiplications of the base point and n, and q and m.
  9812. *
  9813. * r = base point * n + q * m
  9814. *
  9815. * Return code compliant with OpenSSL.
  9816. *
  9817. * @param [in] group EC group.
  9818. * @param [out] r EC point that is result of operation.
  9819. * @param [in] n Scalar to multiply by base point. May be NULL.
  9820. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9821. * @param [in] m Scalar to multiply q by. May be NULL.
  9822. * @param [in] ctx Context to use for BN operations. Unused.
  9823. * @return 1 on success.
  9824. * @return 0 on error.
  9825. */
  9826. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9827. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  9828. WOLFSSL_BN_CTX *ctx)
  9829. {
  9830. int ret = 1;
  9831. /* No BN operations performed. */
  9832. (void)ctx;
  9833. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9834. /* Validate parameters. */
  9835. if ((group == NULL) || (r == NULL)) {
  9836. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9837. ret = 0;
  9838. }
  9839. /* Ensure the internal representation of the EC point q is setup. */
  9840. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  9841. WOLFSSL_MSG("ec_point_setup error");
  9842. ret = 0;
  9843. }
  9844. #ifdef DEBUG_WOLFSSL
  9845. if (ret == 1) {
  9846. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9847. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9848. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9849. char* num;
  9850. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul input q", q);
  9851. num = wolfSSL_BN_bn2hex(n);
  9852. WOLFSSL_MSG_EX("\tn = %s", num);
  9853. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9854. num = wolfSSL_BN_bn2hex(m);
  9855. WOLFSSL_MSG_EX("\tm = %s", num);
  9856. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9857. if (curve != NULL)
  9858. WOLFSSL_MSG_EX("curve name: %s", curve);
  9859. if (nistName != NULL)
  9860. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9861. }
  9862. #endif
  9863. if (ret == 1) {
  9864. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  9865. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  9866. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  9867. /* Perform multiplication with wolfCrypt objects. */
  9868. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  9869. ni, qi, mi);
  9870. }
  9871. /* Only on success is the internal point guaranteed to be set. */
  9872. if (r != NULL) {
  9873. r->inSet = (ret == 1);
  9874. }
  9875. /* Copy internal EC point values out to external EC point. */
  9876. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9877. WOLFSSL_MSG("ec_point_external_set error");
  9878. ret = 0;
  9879. }
  9880. #ifdef DEBUG_WOLFSSL
  9881. if (ret == 1) {
  9882. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul result", r);
  9883. }
  9884. #endif
  9885. return ret;
  9886. }
  9887. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9888. * !WOLFSSL_SP_MATH */
  9889. /* Invert the point on the curve.
  9890. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9891. *
  9892. * @param [in] curveIdx Index of curve in ecc_set.
  9893. * @param [in, out] point EC point to invert.
  9894. * @return 1 on success.
  9895. * @return 0 on error.
  9896. */
  9897. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  9898. {
  9899. int ret = 1;
  9900. #ifdef WOLFSSL_SMALL_STACK
  9901. mp_int* prime = NULL;
  9902. #else
  9903. mp_int prime[1];
  9904. #endif
  9905. #ifdef WOLFSSL_SMALL_STACK
  9906. /* Allocate memory for an MP int to hold the prime of the curve. */
  9907. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9908. if (prime == NULL) {
  9909. ret = 0;
  9910. }
  9911. #endif
  9912. /* Initialize MP int. */
  9913. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  9914. WOLFSSL_MSG("mp_init_multi error");
  9915. ret = 0;
  9916. }
  9917. /* Read the curve parameter: prime. */
  9918. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9919. MP_RADIX_HEX) != MP_OKAY)) {
  9920. WOLFSSL_MSG("mp_read_radix prime error");
  9921. ret = 0;
  9922. }
  9923. /* y = (prime - y) mod prime. */
  9924. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  9925. point->y) != MP_OKAY)) {
  9926. WOLFSSL_MSG("mp_sub error");
  9927. ret = 0;
  9928. }
  9929. /* Dispose of memory associated with MP. */
  9930. mp_free(prime);
  9931. #ifdef WOLFSSL_SMALL_STACK
  9932. /* Dispose of dynamically allocated temporaries. */
  9933. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9934. #endif
  9935. return ret;
  9936. }
  9937. /* Invert the point on the curve.
  9938. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9939. *
  9940. * @param [in] group EC group.
  9941. * @param [in, out] point EC point to invert.
  9942. * @param [in] ctx Context to use for BN operations. Unused.
  9943. * @return 1 on success.
  9944. * @return 0 on error.
  9945. */
  9946. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  9947. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9948. {
  9949. int ret = 1;
  9950. /* No BN operations performed. */
  9951. (void)ctx;
  9952. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9953. /* Validate parameters. */
  9954. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9955. ret = 0;
  9956. }
  9957. /* Ensure internal representation of point is setup. */
  9958. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9959. ret = 0;
  9960. }
  9961. #ifdef DEBUG_WOLFSSL
  9962. if (ret == 1) {
  9963. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9964. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9965. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9966. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert input", point);
  9967. if (curve != NULL)
  9968. WOLFSSL_MSG_EX("curve name: %s", curve);
  9969. if (nistName != NULL)
  9970. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9971. }
  9972. #endif
  9973. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  9974. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9975. if (ec_point_convert_to_affine(group, point) != 0)
  9976. ret = 0;
  9977. #else
  9978. WOLFSSL_MSG("wolfSSL_EC_POINT_invert called on non-affine point");
  9979. ret = 0;
  9980. #endif
  9981. }
  9982. if (ret == 1) {
  9983. /* Perform inversion using wolfCrypt objects. */
  9984. ret = wolfssl_ec_point_invert(group->curve_idx,
  9985. (ecc_point*)point->internal);
  9986. }
  9987. /* Set the external EC point representation based on internal. */
  9988. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  9989. WOLFSSL_MSG("ec_point_external_set error");
  9990. ret = 0;
  9991. }
  9992. #ifdef DEBUG_WOLFSSL
  9993. if (ret == 1) {
  9994. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert result", point);
  9995. }
  9996. #endif
  9997. return ret;
  9998. }
  9999. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10000. /* Compare two points on a the same curve.
  10001. *
  10002. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  10003. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10004. * When equal:
  10005. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  10006. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  10007. *
  10008. * @param [in] group EC group.
  10009. * @param [in] a EC point to compare.
  10010. * @param [in] b EC point to compare.
  10011. * @return 0 when equal.
  10012. * @return 1 when different.
  10013. * @return -1 on error.
  10014. */
  10015. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  10016. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10017. {
  10018. int ret = 0;
  10019. BIGNUM* at = BN_new();
  10020. BIGNUM* bt = BN_new();
  10021. BIGNUM* az = BN_new();
  10022. BIGNUM* bz = BN_new();
  10023. BIGNUM* mod = BN_new();
  10024. /* Check that the big numbers were allocated. */
  10025. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  10026. (mod == NULL)) {
  10027. ret = -1;
  10028. }
  10029. /* Get the modulus for the curve. */
  10030. if ((ret == 0) &&
  10031. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  10032. ret = -1;
  10033. }
  10034. if (ret == 0) {
  10035. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  10036. if (BN_is_one(a->Z)) {
  10037. if (BN_copy(bt, b->X) == NULL) {
  10038. ret = -1;
  10039. }
  10040. }
  10041. /* az = Az ^ 2 */
  10042. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  10043. ret = -1;
  10044. }
  10045. /* bt = Bx * az = Bx * (Az ^ 2) */
  10046. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  10047. ret = -1;
  10048. }
  10049. }
  10050. if (ret == 0) {
  10051. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  10052. if (BN_is_one(b->Z)) {
  10053. if (BN_copy(at, a->X) == NULL) {
  10054. ret = -1;
  10055. }
  10056. }
  10057. /* bz = Bz ^ 2 */
  10058. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  10059. ret = -1;
  10060. }
  10061. /* at = Ax * bz = Ax * (Bz ^ 2) */
  10062. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  10063. ret = -1;
  10064. }
  10065. }
  10066. /* Compare x-ordinates. */
  10067. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10068. ret = 1;
  10069. }
  10070. if (ret == 0) {
  10071. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  10072. if (BN_is_one(a->Z)) {
  10073. if (BN_copy(bt, b->Y) == NULL) {
  10074. ret = -1;
  10075. }
  10076. }
  10077. /* az = az * Az = Az ^ 3 */
  10078. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  10079. ret = -1;
  10080. }
  10081. /* bt = By * az = By * (Az ^ 3) */
  10082. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  10083. ret = -1;
  10084. }
  10085. }
  10086. if (ret == 0) {
  10087. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  10088. if (BN_is_one(b->Z)) {
  10089. if (BN_copy(at, a->Y) == NULL) {
  10090. ret = -1;
  10091. }
  10092. }
  10093. /* bz = bz * Bz = Bz ^ 3 */
  10094. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  10095. ret = -1;
  10096. }
  10097. /* at = Ay * bz = Ay * (Bz ^ 3) */
  10098. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  10099. ret = -1;
  10100. }
  10101. }
  10102. /* Compare y-ordinates. */
  10103. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  10104. ret = 1;
  10105. }
  10106. BN_free(mod);
  10107. BN_free(bz);
  10108. BN_free(az);
  10109. BN_free(bt);
  10110. BN_free(at);
  10111. return ret;
  10112. }
  10113. #endif
  10114. /* Compare two points on a the same curve.
  10115. *
  10116. * Return code compliant with OpenSSL.
  10117. *
  10118. * @param [in] group EC group.
  10119. * @param [in] a EC point to compare.
  10120. * @param [in] b EC point to compare.
  10121. * @param [in] ctx Context to use for BN operations. Unused.
  10122. * @return 0 when equal.
  10123. * @return 1 when different.
  10124. * @return -1 on error.
  10125. */
  10126. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  10127. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  10128. {
  10129. int ret = 0;
  10130. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  10131. /* Validate parameters. */
  10132. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  10133. (b == NULL) || (b->internal == NULL)) {
  10134. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  10135. ret = -1;
  10136. }
  10137. if (ret != -1) {
  10138. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  10139. /* If same Z ordinate then no need to convert to affine. */
  10140. if (BN_cmp(a->Z, b->Z) == 0) {
  10141. /* Compare */
  10142. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  10143. }
  10144. else {
  10145. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  10146. }
  10147. #else
  10148. /* No BN operations performed. */
  10149. (void)ctx;
  10150. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  10151. (ecc_point*)b->internal) != MP_EQ);
  10152. #endif
  10153. }
  10154. return ret;
  10155. }
  10156. /* Copy EC point.
  10157. *
  10158. * @param [out] dest EC point to copy into.
  10159. * @param [in] src EC point to copy.
  10160. * @return 1 on success.
  10161. * @return 0 on error.
  10162. */
  10163. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  10164. {
  10165. int ret = 1;
  10166. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  10167. /* Validate parameters. */
  10168. if ((dest == NULL) || (src == NULL)) {
  10169. ret = 0;
  10170. }
  10171. /* Ensure internal EC point of src is setup. */
  10172. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  10173. ret = 0;
  10174. }
  10175. /* Copy internal EC points. */
  10176. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  10177. (ecc_point*)dest->internal) != MP_OKAY)) {
  10178. ret = 0;
  10179. }
  10180. if (ret == 1) {
  10181. /* Destinatation internal point is set. */
  10182. dest->inSet = 1;
  10183. /* Set the external EC point of dest based on internal. */
  10184. if (ec_point_external_set(dest) != 1) {
  10185. ret = 0;
  10186. }
  10187. }
  10188. return ret;
  10189. }
  10190. /* Checks whether point is at infinity.
  10191. *
  10192. * Return code compliant with OpenSSL.
  10193. *
  10194. * @param [in] group EC group.
  10195. * @param [in] point EC point to check.
  10196. * @return 1 when at infinity.
  10197. * @return 0 when not at infinity.
  10198. */
  10199. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  10200. const WOLFSSL_EC_POINT *point)
  10201. {
  10202. int ret = 1;
  10203. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  10204. /* Validate parameters. */
  10205. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10206. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  10207. ret = 0;
  10208. }
  10209. /* Ensure internal EC point is setup. */
  10210. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10211. ret = 0;
  10212. }
  10213. if (ret == 1) {
  10214. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10215. /* Check for infinity. */
  10216. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  10217. if (ret < 0) {
  10218. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  10219. /* Error return is 0 by OpenSSL. */
  10220. ret = 0;
  10221. }
  10222. #else
  10223. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  10224. ret = 0;
  10225. #endif
  10226. }
  10227. return ret;
  10228. }
  10229. #endif /* OPENSSL_EXTRA */
  10230. /* End EC_POINT */
  10231. /* Start EC_KEY */
  10232. #ifdef OPENSSL_EXTRA
  10233. /*
  10234. * EC key constructor/deconstructor APIs
  10235. */
  10236. /* Allocate a new EC key.
  10237. *
  10238. * Not OpenSSL API.
  10239. *
  10240. * @param [in] heap Heap hint for dynamic memory allocation.
  10241. * @param [in] devId Device identifier value.
  10242. * @return New, allocated EC key on success.
  10243. * @return NULL on error.
  10244. */
  10245. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  10246. {
  10247. WOLFSSL_EC_KEY *key = NULL;
  10248. int err = 0;
  10249. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  10250. /* Allocate memory for EC key. */
  10251. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  10252. DYNAMIC_TYPE_ECC);
  10253. if (key == NULL) {
  10254. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  10255. err = 1;
  10256. }
  10257. if (!err) {
  10258. /* Reset all fields to 0. */
  10259. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  10260. /* Cache heap hint. */
  10261. key->heap = heap;
  10262. /* Initialize fields to defaults. */
  10263. key->form = POINT_CONVERSION_UNCOMPRESSED;
  10264. /* Initialize reference count. */
  10265. wolfSSL_RefInit(&key->ref, &err);
  10266. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  10267. }
  10268. if (!err) {
  10269. #endif
  10270. /* Allocate memory for internal EC key representation. */
  10271. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  10272. DYNAMIC_TYPE_ECC);
  10273. if (key->internal == NULL) {
  10274. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10275. err = 1;
  10276. }
  10277. }
  10278. if (!err) {
  10279. /* Initialize wolfCrypt EC key. */
  10280. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10281. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10282. err = 1;
  10283. }
  10284. }
  10285. if (!err) {
  10286. /* Group unknown at creation */
  10287. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10288. if (key->group == NULL) {
  10289. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10290. err = 1;
  10291. }
  10292. }
  10293. if (!err) {
  10294. /* Allocate a point as public key. */
  10295. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10296. if (key->pub_key == NULL) {
  10297. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10298. err = 1;
  10299. }
  10300. }
  10301. if (!err) {
  10302. /* Allocate a BN as private key. */
  10303. key->priv_key = wolfSSL_BN_new();
  10304. if (key->priv_key == NULL) {
  10305. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10306. err = 1;
  10307. }
  10308. }
  10309. if (err) {
  10310. /* Dispose of EC key on error. */
  10311. wolfSSL_EC_KEY_free(key);
  10312. key = NULL;
  10313. }
  10314. /* Return new EC key object. */
  10315. return key;
  10316. }
  10317. /* Allocate a new EC key.
  10318. *
  10319. * @return New, allocated EC key on success.
  10320. * @return NULL on error.
  10321. */
  10322. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10323. {
  10324. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10325. }
  10326. /* Create new EC key with the group having the specified numeric ID.
  10327. *
  10328. * @param [in] nid Numeric ID.
  10329. * @return New, allocated EC key on success.
  10330. * @return NULL on error.
  10331. */
  10332. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10333. {
  10334. WOLFSSL_EC_KEY *key;
  10335. int err = 0;
  10336. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10337. /* Allocate empty, EC key. */
  10338. key = wolfSSL_EC_KEY_new();
  10339. if (key == NULL) {
  10340. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10341. err = 1;
  10342. }
  10343. if (!err) {
  10344. /* Set group to be nid. */
  10345. ec_group_set_nid(key->group, nid);
  10346. if (key->group->curve_idx == -1) {
  10347. wolfSSL_EC_KEY_free(key);
  10348. key = NULL;
  10349. }
  10350. }
  10351. /* Return the new EC key object. */
  10352. return key;
  10353. }
  10354. /* Dispose of the EC key and allocated data.
  10355. *
  10356. * Cannot use key after this call.
  10357. *
  10358. * @param [in] key EC key to free.
  10359. */
  10360. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10361. {
  10362. int doFree = 0;
  10363. int err;
  10364. (void)err;
  10365. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10366. if (key != NULL) {
  10367. void* heap = key->heap;
  10368. /* Decrement reference count. */
  10369. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10370. if (doFree) {
  10371. /* Dispose of allocated reference counting data. */
  10372. wolfSSL_RefFree(&key->ref);
  10373. /* Dispose of private key. */
  10374. wolfSSL_BN_free(key->priv_key);
  10375. wolfSSL_EC_POINT_free(key->pub_key);
  10376. wolfSSL_EC_GROUP_free(key->group);
  10377. if (key->internal != NULL) {
  10378. /* Dispose of wolfCrypt representation of EC key. */
  10379. wc_ecc_free((ecc_key*)key->internal);
  10380. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10381. }
  10382. /* Set back to NULLs for safety. */
  10383. ForceZero(key, sizeof(*key));
  10384. /* Dispose of the memory associated with the EC key. */
  10385. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10386. (void)heap;
  10387. }
  10388. }
  10389. }
  10390. /* Increments ref count of EC key.
  10391. *
  10392. * @param [in, out] key EC key.
  10393. * @return 1 on success
  10394. * @return 0 on error
  10395. */
  10396. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10397. {
  10398. int err = 1;
  10399. if (key != NULL) {
  10400. wolfSSL_RefInc(&key->ref, &err);
  10401. }
  10402. return !err;
  10403. }
  10404. #ifndef NO_CERTS
  10405. #if defined(OPENSSL_ALL)
  10406. /* Copy the internal, wolfCrypt EC key.
  10407. *
  10408. * @param [in, out] dst Destination wolfCrypt EC key.
  10409. * @param [in] src Source wolfCrypt EC key.
  10410. * @return 0 on success.
  10411. * @return Negative on error.
  10412. */
  10413. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10414. {
  10415. int ret;
  10416. /* Copy public key. */
  10417. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10418. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10419. #else
  10420. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10421. #endif
  10422. if (ret != MP_OKAY) {
  10423. WOLFSSL_MSG("wc_ecc_copy_point error");
  10424. }
  10425. if (ret == 0) {
  10426. /* Copy private key. */
  10427. ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst));
  10428. if (ret != MP_OKAY) {
  10429. WOLFSSL_MSG("mp_copy error");
  10430. }
  10431. }
  10432. if (ret == 0) {
  10433. /* Copy domain parameters. */
  10434. if (src->dp) {
  10435. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10436. if (ret != 0) {
  10437. WOLFSSL_MSG("wc_ecc_set_curve error");
  10438. }
  10439. }
  10440. }
  10441. if (ret == 0) {
  10442. /* Copy the other components. */
  10443. dst->type = src->type;
  10444. dst->idx = src->idx;
  10445. dst->state = src->state;
  10446. dst->flags = src->flags;
  10447. }
  10448. return ret;
  10449. }
  10450. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10451. *
  10452. * Copies the internal representation as well.
  10453. *
  10454. * @param [in] src EC key to duplicate.
  10455. *
  10456. * @return EC key on success.
  10457. * @return NULL on error.
  10458. */
  10459. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10460. {
  10461. int err = 0;
  10462. WOLFSSL_EC_KEY* newKey = NULL;
  10463. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10464. /* Validate EC key. */
  10465. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10466. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10467. WOLFSSL_MSG("src NULL error");
  10468. err = 1;
  10469. }
  10470. if (!err) {
  10471. /* Create a new, empty key. */
  10472. newKey = wolfSSL_EC_KEY_new();
  10473. if (newKey == NULL) {
  10474. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10475. err = 1;
  10476. }
  10477. }
  10478. if (!err) {
  10479. /* Copy internal EC key. */
  10480. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10481. (ecc_key*)src->internal) != 0) {
  10482. WOLFSSL_MSG("Copying internal EC key error");
  10483. err = 1;
  10484. }
  10485. }
  10486. if (!err) {
  10487. /* Internal key set. */
  10488. newKey->inSet = 1;
  10489. /* Copy group */
  10490. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10491. }
  10492. /* Copy public key. */
  10493. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10494. WOLFSSL_MSG("Copying EC public key error");
  10495. err = 1;
  10496. }
  10497. if (!err) {
  10498. /* Set header size of private key in PKCS#8 format.*/
  10499. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10500. /* Copy private key. */
  10501. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10502. WOLFSSL_MSG("Copying EC private key error");
  10503. err = 1;
  10504. }
  10505. }
  10506. if (err) {
  10507. /* Dispose of EC key on error. */
  10508. wolfSSL_EC_KEY_free(newKey);
  10509. newKey = NULL;
  10510. }
  10511. /* Return the new EC key. */
  10512. return newKey;
  10513. }
  10514. #endif /* OPENSSL_ALL */
  10515. #endif /* !NO_CERTS */
  10516. /*
  10517. * EC key to/from bin/octet APIs
  10518. */
  10519. /* Create an EC key from the octet encoded public key.
  10520. *
  10521. * Behaviour checked against OpenSSL.
  10522. *
  10523. * @param [out] key Reference to EC key. Must pass in a valid object with
  10524. * group set.
  10525. * @param [in, out] in On in, reference to buffer that contains data.
  10526. * On out, reference to buffer after public key data.
  10527. * @param [in] len Length of data in the buffer. Must be length of the
  10528. * encoded public key.
  10529. * @return Allocated EC key on success.
  10530. * @return NULL on error.
  10531. */
  10532. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10533. const unsigned char **in, long len)
  10534. {
  10535. int err = 0;
  10536. WOLFSSL_EC_KEY* ret = NULL;
  10537. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10538. /* Validate parameters: EC group needed to perform import. */
  10539. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10540. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10541. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10542. err = 1;
  10543. }
  10544. if (!err) {
  10545. /* Return the EC key object passed in. */
  10546. ret = *key;
  10547. /* Import point into public key field. */
  10548. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in,
  10549. (size_t)len, NULL) != 1) {
  10550. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10551. ret = NULL;
  10552. err = 1;
  10553. }
  10554. }
  10555. if (!err) {
  10556. /* Assumed length passed in is all the data. */
  10557. *in += len;
  10558. }
  10559. return ret;
  10560. }
  10561. /* Puts the encoded public key into out.
  10562. *
  10563. * Passing in NULL for out returns length only.
  10564. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10565. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10566. *
  10567. * @param [in] key EC key to encode.
  10568. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10569. * point to NULL.
  10570. * @return Length of encoding in bytes on success.
  10571. * @return 0 on error.
  10572. */
  10573. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10574. {
  10575. int ret = 1;
  10576. size_t len = 0;
  10577. int form = POINT_CONVERSION_UNCOMPRESSED;
  10578. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10579. /* Validate parameters. */
  10580. if (key == NULL) {
  10581. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10582. ret = 0;
  10583. }
  10584. /* Ensure the external key data is set from the internal EC key. */
  10585. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10586. key) != 1)) {
  10587. WOLFSSL_MSG("SetECKeyExternal failure");
  10588. ret = 0;
  10589. }
  10590. if (ret == 1) {
  10591. #ifdef HAVE_COMP_KEY
  10592. /* Default to compressed form if not set */
  10593. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10594. POINT_CONVERSION_UNCOMPRESSED :
  10595. POINT_CONVERSION_COMPRESSED;
  10596. #endif
  10597. /* Calculate length of point encoding. */
  10598. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10599. 0, NULL);
  10600. }
  10601. /* Encode if length calculated and pointer supplied to update. */
  10602. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10603. unsigned char *tmp = NULL;
  10604. /* Allocate buffer for encoding if no buffer supplied. */
  10605. if (*out == NULL) {
  10606. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10607. if (tmp == NULL) {
  10608. WOLFSSL_MSG("malloc failed");
  10609. ret = 0;
  10610. }
  10611. }
  10612. else {
  10613. /* Get buffer to encode into. */
  10614. tmp = *out;
  10615. }
  10616. /* Encode public key into buffer. */
  10617. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10618. form, tmp, len, NULL) == 0)) {
  10619. ret = 0;
  10620. }
  10621. if (ret == 1) {
  10622. /* Return buffer if allocated. */
  10623. if (*out == NULL) {
  10624. *out = tmp;
  10625. }
  10626. else {
  10627. /* Step over encoded data if not allocated. */
  10628. *out += len;
  10629. }
  10630. }
  10631. else if (*out == NULL) {
  10632. /* Dispose of allocated buffer. */
  10633. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10634. }
  10635. }
  10636. if (ret == 1) {
  10637. /* Return length on success. */
  10638. ret = (int)len;
  10639. }
  10640. return ret;
  10641. }
  10642. #ifdef HAVE_ECC_KEY_IMPORT
  10643. /* Create a EC key from the DER encoded private key.
  10644. *
  10645. * @param [out] key Reference to EC key.
  10646. * @param [in, out] in On in, reference to buffer that contains DER data.
  10647. * On out, reference to buffer after private key data.
  10648. * @param [in] long Length of data in the buffer. May be larger than the
  10649. * length of the encoded private key.
  10650. * @return Allocated EC key on success.
  10651. * @return NULL on error.
  10652. */
  10653. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10654. const unsigned char** in, long len)
  10655. {
  10656. int err = 0;
  10657. word32 idx = 0;
  10658. WOLFSSL_EC_KEY* ret = NULL;
  10659. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10660. /* Validate parameters. */
  10661. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10662. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10663. err = 1;
  10664. }
  10665. /* Create a new, empty EC key. */
  10666. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10667. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10668. err = 1;
  10669. }
  10670. /* Decode the private key DER data into internal EC key. */
  10671. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10672. (word32)len) != 0)) {
  10673. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10674. err = 1;
  10675. }
  10676. if (!err) {
  10677. /* Internal EC key setup. */
  10678. ret->inSet = 1;
  10679. /* Set the EC key from the internal values. */
  10680. if (SetECKeyExternal(ret) != 1) {
  10681. WOLFSSL_MSG("SetECKeyExternal error");
  10682. err = 1;
  10683. }
  10684. }
  10685. if (!err) {
  10686. /* Move buffer on to next byte after data used. */
  10687. *in += idx;
  10688. if (key) {
  10689. /* Return new EC key through reference. */
  10690. *key = ret;
  10691. }
  10692. }
  10693. if (err && (ret != NULL)) {
  10694. /* Dispose of allocated EC key. */
  10695. wolfSSL_EC_KEY_free(ret);
  10696. ret = NULL;
  10697. }
  10698. return ret;
  10699. }
  10700. #endif /* HAVE_ECC_KEY_IMPORT */
  10701. /* Enecode the private key of the EC key into the buffer as DER.
  10702. *
  10703. * @param [in] key EC key to encode.
  10704. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10705. * On out, reference to buffer adter the encoding.
  10706. * May be NULL.
  10707. * @return Length of DER encoding on success.
  10708. * @return 0 on error.
  10709. */
  10710. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10711. {
  10712. int err = 0;
  10713. word32 len = 0;
  10714. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10715. /* Validate parameters. */
  10716. if (key == NULL) {
  10717. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10718. err = 1;
  10719. }
  10720. /* Update the internal EC key if not set. */
  10721. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10722. 1)) {
  10723. WOLFSSL_MSG("SetECKeyInternal error");
  10724. err = 1;
  10725. }
  10726. /* Calculate the length of the private key DER encoding using internal EC
  10727. * key. */
  10728. if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal,
  10729. 0)) <= 0)) {
  10730. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10731. err = 1;
  10732. }
  10733. /* Only return length when out is NULL. */
  10734. if ((!err) && (out != NULL)) {
  10735. unsigned char* buf = NULL;
  10736. /* Must have a buffer to encode into. */
  10737. if (*out == NULL) {
  10738. /* Allocate a new buffer of appropriate length. */
  10739. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10740. if (buf == NULL) {
  10741. /* Error and return 0. */
  10742. err = 1;
  10743. len = 0;
  10744. }
  10745. else {
  10746. /* Return the allocated buffer. */
  10747. *out = buf;
  10748. }
  10749. }
  10750. /* Encode the internal EC key as a private key in DER format. */
  10751. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10752. len) < 0) {
  10753. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10754. err = 1;
  10755. }
  10756. else if (buf != *out) {
  10757. /* Move the reference to byte past encoded private key. */
  10758. *out += len;
  10759. }
  10760. /* Dispose of any allocated buffer on error. */
  10761. if (err && (*out == buf)) {
  10762. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10763. *out = NULL;
  10764. }
  10765. }
  10766. return (int)len;
  10767. }
  10768. /* Load private key into EC key from DER encoding.
  10769. *
  10770. * Not an OpenSSL compatibility API.
  10771. *
  10772. * @param [in, out] key EC key to put private key values into.
  10773. * @param [in] derBuf Buffer holding DER encoding.
  10774. * @param [in] derSz Size of DER encoding in bytes.
  10775. * @return 1 on success.
  10776. * @return -1 on error.
  10777. */
  10778. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10779. int derSz)
  10780. {
  10781. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10782. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10783. }
  10784. /* Load private/public key into EC key from DER encoding.
  10785. *
  10786. * Not an OpenSSL compatibility API.
  10787. *
  10788. * @param [in, out] key EC key to put private/public key values into.
  10789. * @param [in] derBuf Buffer holding DER encoding.
  10790. * @param [in] derSz Size of DER encoding in bytes.
  10791. * @param [in] opt Key type option. Valid values:
  10792. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10793. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10794. * @return 1 on success.
  10795. * @return -1 on error.
  10796. */
  10797. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10798. int derSz, int opt)
  10799. {
  10800. int res = 1;
  10801. int ret;
  10802. word32 idx = 0;
  10803. word32 algId;
  10804. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10805. /* Validate parameters. */
  10806. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10807. (derSz <= 0)) {
  10808. WOLFSSL_MSG("Bad function arguments");
  10809. res = -1;
  10810. }
  10811. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10812. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10813. res = -1;
  10814. }
  10815. if (res == 1) {
  10816. /* Assume no PKCS#8 header. */
  10817. key->pkcs8HeaderSz = 0;
  10818. /* Check if input buffer has PKCS8 header. In the case that it does not
  10819. * have a PKCS8 header then do not error out.
  10820. */
  10821. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10822. (word32)derSz, &algId)) > 0) {
  10823. WOLFSSL_MSG("Found PKCS8 header");
  10824. key->pkcs8HeaderSz = (word16)idx;
  10825. res = 1;
  10826. }
  10827. /* Error out on parsing error. */
  10828. else if (ret != ASN_PARSE_E) {
  10829. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10830. res = -1;
  10831. }
  10832. }
  10833. if (res == 1) {
  10834. /* Load into internal EC key based on key type option. */
  10835. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10836. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10837. (word32)derSz);
  10838. }
  10839. else {
  10840. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10841. (word32)derSz);
  10842. if (ret < 0) {
  10843. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  10844. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  10845. if (tmp == NULL) {
  10846. ret = -1;
  10847. }
  10848. else {
  10849. /* We now try again as x.963 [point type][x][opt y]. */
  10850. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  10851. INVALID_DEVID);
  10852. if (ret == 0) {
  10853. ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp);
  10854. if (ret == 0) {
  10855. /* Take ownership of new key - set tmp to the old
  10856. * key which will then be freed below. */
  10857. ecc_key *old = (ecc_key *)key->internal;
  10858. key->internal = tmp;
  10859. tmp = old;
  10860. idx = (word32)derSz;
  10861. }
  10862. wc_ecc_free(tmp);
  10863. }
  10864. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  10865. DYNAMIC_TYPE_ECC);
  10866. }
  10867. }
  10868. }
  10869. if (ret < 0) {
  10870. /* Error returned from wolfSSL. */
  10871. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10872. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10873. }
  10874. else {
  10875. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10876. }
  10877. res = -1;
  10878. }
  10879. /* Internal key updated - update whether it is a valid key. */
  10880. key->inSet = (res == 1);
  10881. }
  10882. /* Set the external EC key based on value in internal. */
  10883. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  10884. WOLFSSL_MSG("SetECKeyExternal failed");
  10885. res = -1;
  10886. }
  10887. return res;
  10888. }
  10889. /*
  10890. * EC key PEM APIs
  10891. */
  10892. #ifdef HAVE_ECC_KEY_EXPORT
  10893. #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_FILESYSTEM) || !defined(NO_BIO))
  10894. /* Encode the EC public key as DER.
  10895. *
  10896. * @param [in] key EC key to encode.
  10897. * @param [out] der Pointer through which buffer is returned.
  10898. * @param [in] heap Heap hint.
  10899. * @return Size of encoding on success.
  10900. * @return 0 on error.
  10901. */
  10902. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  10903. unsigned char** der, void* heap)
  10904. {
  10905. int sz;
  10906. unsigned char* buf = NULL;
  10907. (void)heap;
  10908. /* Calculate encoded size to allocate. */
  10909. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  10910. if (sz <= 0) {
  10911. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  10912. sz = 0;
  10913. }
  10914. if (sz > 0) {
  10915. /* Allocate memory to hold encoding. */
  10916. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10917. if (buf == NULL) {
  10918. WOLFSSL_MSG("malloc failed");
  10919. sz = 0;
  10920. }
  10921. }
  10922. if (sz > 0) {
  10923. /* Encode public key to DER using wolfSSL. */
  10924. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1);
  10925. if (sz < 0) {
  10926. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  10927. sz = 0;
  10928. }
  10929. }
  10930. /* Return buffer on success. */
  10931. if (sz > 0) {
  10932. *der = buf;
  10933. }
  10934. else {
  10935. /* Dispose of any dynamically allocated data not returned. */
  10936. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10937. }
  10938. return sz;
  10939. }
  10940. #endif
  10941. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  10942. /*
  10943. * Return code compliant with OpenSSL.
  10944. *
  10945. * @param [in] fp File pointer to write PEM encoding to.
  10946. * @param [in] key EC key to encode and write.
  10947. * @return 1 on success.
  10948. * @return 0 on error.
  10949. */
  10950. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10951. {
  10952. int ret = 1;
  10953. unsigned char* derBuf = NULL;
  10954. int derSz = 0;
  10955. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10956. /* Validate parameters. */
  10957. if ((fp == XBADFILE) || (key == NULL)) {
  10958. WOLFSSL_MSG("Bad argument.");
  10959. return 0;
  10960. }
  10961. /* Encode public key in EC key as DER. */
  10962. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  10963. if (derSz == 0) {
  10964. ret = 0;
  10965. }
  10966. /* Write out to file the PEM encoding of the DER. */
  10967. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  10968. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  10969. ret = 0;
  10970. }
  10971. /* Dispose of any dynamically allocated data. */
  10972. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10973. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10974. return ret;
  10975. }
  10976. #endif
  10977. #endif
  10978. #ifndef NO_BIO
  10979. /* Read a PEM encoded EC public key from a BIO.
  10980. *
  10981. * @param [in] bio BIO to read EC public key from.
  10982. * @param [out] out Pointer to return EC key object through. May be NULL.
  10983. * @param [in] cb Password callback when PEM encrypted.
  10984. * @param [in] pass NUL terminated string for passphrase when PEM
  10985. * encrypted.
  10986. * @return New EC key object on success.
  10987. * @return NULL on error.
  10988. */
  10989. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10990. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10991. {
  10992. int err = 0;
  10993. WOLFSSL_EC_KEY* ec = NULL;
  10994. DerBuffer* der = NULL;
  10995. int keyFormat = 0;
  10996. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10997. /* Validate parameters. */
  10998. if (bio == NULL) {
  10999. err = 1;
  11000. }
  11001. if (!err) {
  11002. /* Create an empty EC key. */
  11003. ec = wolfSSL_EC_KEY_new();
  11004. if (ec == NULL) {
  11005. err = 1;
  11006. }
  11007. }
  11008. /* Read a PEM key in to a new DER buffer. */
  11009. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  11010. &keyFormat, &der) <= 0)) {
  11011. err = 1;
  11012. }
  11013. /* Load the EC key with the public key from the DER encoding. */
  11014. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11015. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  11016. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11017. err = 1;
  11018. }
  11019. /* Dispose of dynamically allocated data not needed anymore. */
  11020. FreeDer(&der);
  11021. if (err) {
  11022. wolfSSL_EC_KEY_free(ec);
  11023. ec = NULL;
  11024. }
  11025. /* Return EC key through out if required. */
  11026. if ((out != NULL) && (ec != NULL)) {
  11027. *out = ec;
  11028. }
  11029. return ec;
  11030. }
  11031. /* Read a PEM encoded EC private key from a BIO.
  11032. *
  11033. * @param [in] bio BIO to read EC private key from.
  11034. * @param [out] out Pointer to return EC key object through. May be NULL.
  11035. * @param [in] cb Password callback when PEM encrypted.
  11036. * @param [in] pass NUL terminated string for passphrase when PEM
  11037. * encrypted.
  11038. * @return New EC key object on success.
  11039. * @return NULL on error.
  11040. */
  11041. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  11042. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  11043. {
  11044. int err = 0;
  11045. WOLFSSL_EC_KEY* ec = NULL;
  11046. DerBuffer* der = NULL;
  11047. int keyFormat = 0;
  11048. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  11049. /* Validate parameters. */
  11050. if (bio == NULL) {
  11051. err = 1;
  11052. }
  11053. if (!err) {
  11054. /* Create an empty EC key. */
  11055. ec = wolfSSL_EC_KEY_new();
  11056. if (ec == NULL) {
  11057. err = 1;
  11058. }
  11059. }
  11060. /* Read a PEM key in to a new DER buffer.
  11061. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  11062. * pem_read_bio_key(), and then check key format if it is EC.
  11063. */
  11064. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  11065. &keyFormat, &der) <= 0)) {
  11066. err = 1;
  11067. }
  11068. if (keyFormat != ECDSAk) {
  11069. WOLFSSL_ERROR_MSG("Error not EC key format");
  11070. err = 1;
  11071. }
  11072. /* Load the EC key with the private key from the DER encoding. */
  11073. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  11074. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  11075. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  11076. err = 1;
  11077. }
  11078. /* Dispose of dynamically allocated data not needed anymore. */
  11079. FreeDer(&der);
  11080. if (err) {
  11081. wolfSSL_EC_KEY_free(ec);
  11082. ec = NULL;
  11083. }
  11084. /* Return EC key through out if required. */
  11085. if ((out != NULL) && (ec != NULL)) {
  11086. *out = ec;
  11087. }
  11088. return ec;
  11089. }
  11090. #endif /* !NO_BIO */
  11091. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ECC_KEY_EXPORT)
  11092. #ifndef NO_BIO
  11093. /* Write out the EC public key as PEM to the BIO.
  11094. *
  11095. * @param [in] bio BIO to write PEM encoding to.
  11096. * @param [in] ec EC public key to encode.
  11097. * @return 1 on success.
  11098. * @return 0 on error.
  11099. */
  11100. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  11101. {
  11102. int ret = 1;
  11103. unsigned char* derBuf = NULL;
  11104. int derSz = 0;
  11105. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  11106. /* Validate parameters. */
  11107. if ((bio == NULL) || (ec == NULL)) {
  11108. WOLFSSL_MSG("Bad Function Arguments");
  11109. return 0;
  11110. }
  11111. /* Encode public key in EC key as DER. */
  11112. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  11113. if (derSz == 0) {
  11114. ret = 0;
  11115. }
  11116. /* Write out to BIO the PEM encoding of the EC public key. */
  11117. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  11118. ECC_PUBLICKEY_TYPE) != 1)) {
  11119. ret = 0;
  11120. }
  11121. /* Dispose of any dynamically allocated data. */
  11122. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  11123. return ret;
  11124. }
  11125. /* Write out the EC private key as PEM to the BIO.
  11126. *
  11127. * Return code compliant with OpenSSL.
  11128. *
  11129. * @param [in] bio BIO to write PEM encoding to.
  11130. * @param [in] ec EC private key to encode.
  11131. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11132. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11133. * @param [in] passwdSz Length of password string when PEM encrypted.
  11134. * @param [in] cb Password callback when PEM encrypted. Unused.
  11135. * @param [in] pass NUL terminated string for passphrase when PEM
  11136. * encrypted. Unused.
  11137. * @return 1 on success.
  11138. * @return 0 on error.
  11139. */
  11140. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  11141. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11142. wc_pem_password_cb* cb, void* arg)
  11143. {
  11144. int ret = 1;
  11145. unsigned char* pem = NULL;
  11146. int pLen = 0;
  11147. (void)cb;
  11148. (void)arg;
  11149. /* Validate parameters. */
  11150. if ((bio == NULL) || (ec == NULL)) {
  11151. ret = 0;
  11152. }
  11153. /* Write EC private key to PEM. */
  11154. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11155. passwdSz, &pem, &pLen) != 1)) {
  11156. ret = 0;
  11157. }
  11158. /* Write PEM to BIO. */
  11159. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  11160. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  11161. ret = 0;
  11162. }
  11163. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11164. return ret;
  11165. }
  11166. #endif /* !NO_BIO */
  11167. /* Encode the EC private key as PEM into buffer.
  11168. *
  11169. * Return code compliant with OpenSSL.
  11170. * Not an OpenSSL API.
  11171. *
  11172. * @param [in] ec EC private key to encode.
  11173. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11174. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11175. * @param [in] passwdSz Length of password string when PEM encrypted.
  11176. * @param [out] pem Newly allocated buffer holding PEM encoding.
  11177. * @param [out] pLen Length of PEM encoding in bytes.
  11178. * @return 1 on success.
  11179. * @return 0 on error.
  11180. */
  11181. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  11182. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11183. unsigned char **pem, int *pLen)
  11184. {
  11185. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  11186. int ret = 1;
  11187. byte* derBuf = NULL;
  11188. word32 der_max_len = 0;
  11189. int derSz = 0;
  11190. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  11191. /* Validate parameters. */
  11192. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  11193. (ec->internal == NULL)) {
  11194. WOLFSSL_MSG("Bad function arguments");
  11195. ret = 0;
  11196. }
  11197. /* Ensure internal EC key is set from external. */
  11198. if ((ret == 1) && (ec->inSet == 0)) {
  11199. WOLFSSL_MSG("No ECC internal set, do it");
  11200. if (SetECKeyInternal(ec) != 1) {
  11201. WOLFSSL_MSG("SetECKeyInternal failed");
  11202. ret = 0;
  11203. }
  11204. }
  11205. if (ret == 1) {
  11206. /* Calculate maximum size of DER encoding.
  11207. * 4 > size of pub, priv + ASN.1 additional information */
  11208. der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) +
  11209. AES_BLOCK_SIZE;
  11210. /* Allocate buffer big enough to hold encoding. */
  11211. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL,
  11212. DYNAMIC_TYPE_TMP_BUFFER);
  11213. if (derBuf == NULL) {
  11214. WOLFSSL_MSG("malloc failed");
  11215. ret = 0;
  11216. }
  11217. }
  11218. if (ret == 1) {
  11219. /* Encode EC private key as DER. */
  11220. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  11221. if (derSz < 0) {
  11222. WOLFSSL_MSG("wc_EccKeyToDer failed");
  11223. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  11224. ret = 0;
  11225. }
  11226. }
  11227. /* Convert DER to PEM - possibly encrypting. */
  11228. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  11229. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  11230. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  11231. ret = 0;
  11232. }
  11233. return ret;
  11234. #else
  11235. (void)ec;
  11236. (void)cipher;
  11237. (void)passwd;
  11238. (void)passwdSz;
  11239. (void)pem;
  11240. (void)pLen;
  11241. return 0;
  11242. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  11243. }
  11244. #ifndef NO_FILESYSTEM
  11245. /* Write out the EC private key as PEM to file.
  11246. *
  11247. * Return code compliant with OpenSSL.
  11248. *
  11249. * @param [in] fp File pointer to write PEM encoding to.
  11250. * @param [in] ec EC private key to encode.
  11251. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11252. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11253. * @param [in] passwdSz Length of password string when PEM encrypted.
  11254. * @param [in] cb Password callback when PEM encrypted. Unused.
  11255. * @param [in] pass NUL terminated string for passphrase when PEM
  11256. * encrypted. Unused.
  11257. * @return 1 on success.
  11258. * @return 0 on error.
  11259. */
  11260. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  11261. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  11262. wc_pem_password_cb *cb, void *pass)
  11263. {
  11264. int ret = 1;
  11265. byte *pem = NULL;
  11266. int pLen = 0;
  11267. (void)cb;
  11268. (void)pass;
  11269. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  11270. /* Validate parameters. */
  11271. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  11272. WOLFSSL_MSG("Bad function arguments");
  11273. ret = 0;
  11274. }
  11275. /* Write EC private key to PEM. */
  11276. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11277. passwdSz, &pem, &pLen) != 1)) {
  11278. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11279. ret = 0;
  11280. }
  11281. /* Write out to file the PEM encoding of the EC private key. */
  11282. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  11283. WOLFSSL_MSG("ECC private key file write failed");
  11284. ret = 0;
  11285. }
  11286. /* Dispose of any dynamically allocated data. */
  11287. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11288. return ret;
  11289. }
  11290. #endif /* NO_FILESYSTEM */
  11291. #endif /* WOLFSSL_KEY_GEN && HAVE_ECC_KEY_EXPORT */
  11292. /*
  11293. * EC key print APIs
  11294. */
  11295. #ifndef NO_CERTS
  11296. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11297. !defined(NO_STDIO_FILESYSTEM)
  11298. /* Print the EC key to a file pointer as text.
  11299. *
  11300. * @param [in] fp File pointer.
  11301. * @param [in] key EC key to print.
  11302. * @param [in] indent Number of spaces to place before each line printed.
  11303. * @return 1 on success.
  11304. * @return 0 on failure.
  11305. */
  11306. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11307. {
  11308. int ret = 1;
  11309. int bits = 0;
  11310. int priv = 0;
  11311. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11312. /* Validate parameters. */
  11313. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11314. (indent < 0)) {
  11315. ret = 0;
  11316. }
  11317. if (ret == 1) {
  11318. /* Get EC groups order size in bits. */
  11319. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11320. if (bits <= 0) {
  11321. WOLFSSL_MSG("Failed to get group order bits.");
  11322. ret = 0;
  11323. }
  11324. }
  11325. if (ret == 1) {
  11326. const char* keyType;
  11327. /* Determine whether this is a private or public key. */
  11328. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11329. keyType = "Private-Key";
  11330. priv = 1;
  11331. }
  11332. else {
  11333. keyType = "Public-Key";
  11334. }
  11335. /* Print key header. */
  11336. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11337. ret = 0;
  11338. }
  11339. }
  11340. if ((ret == 1) && priv) {
  11341. /* Print the private key BN. */
  11342. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11343. }
  11344. /* Check for public key data in EC key. */
  11345. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11346. /* Get the public key point as one BN. */
  11347. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11348. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11349. if (pubBn == NULL) {
  11350. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11351. ret = 0;
  11352. }
  11353. else {
  11354. /* Print the public key in a BN. */
  11355. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11356. wolfSSL_BN_free(pubBn);
  11357. }
  11358. }
  11359. if (ret == 1) {
  11360. /* Get the NID of the group. */
  11361. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11362. if (nid > 0) {
  11363. /* Convert the NID into a long name and NIST name. */
  11364. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11365. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11366. /* Print OID name if known. */
  11367. if ((curve != NULL) &&
  11368. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11369. ret = 0;
  11370. }
  11371. /* Print NIST curve name if known. */
  11372. if ((nistName != NULL) &&
  11373. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11374. nistName) < 0)) {
  11375. ret = 0;
  11376. }
  11377. }
  11378. }
  11379. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11380. return ret;
  11381. }
  11382. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11383. #endif /* !NO_CERTS */
  11384. /*
  11385. * EC_KEY get/set/test APIs
  11386. */
  11387. /* Set data of internal, wolfCrypt EC key object into EC key.
  11388. *
  11389. * EC_KEY wolfSSL -> OpenSSL
  11390. *
  11391. * @param [in, out] p EC key to update.
  11392. * @return 1 on success.
  11393. * @return -1 on failure.
  11394. */
  11395. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11396. {
  11397. int ret = 1;
  11398. WOLFSSL_ENTER("SetECKeyExternal");
  11399. /* Validate parameter. */
  11400. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11401. WOLFSSL_MSG("ec key NULL error");
  11402. ret = -1;
  11403. }
  11404. else {
  11405. ecc_key* key = (ecc_key*)eckey->internal;
  11406. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11407. eckey->group->curve_oid = (int)key->dp->oidSum;
  11408. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11409. eckey->group->curve_idx = key->idx;
  11410. if (eckey->pub_key->internal != NULL) {
  11411. /* Copy internal public point from internal key's public point. */
  11412. if (wc_ecc_copy_point(&key->pubkey,
  11413. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11414. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11415. ret = -1;
  11416. }
  11417. /* Set external public key from internal wolfCrypt, public key. */
  11418. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11419. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11420. ret = -1;
  11421. }
  11422. }
  11423. /* set the external privkey */
  11424. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11425. (wolfssl_bn_set_value(&eckey->priv_key,
  11426. wc_ecc_key_get_priv(key)) != 1)) {
  11427. WOLFSSL_MSG("ec priv key error");
  11428. ret = -1;
  11429. }
  11430. /* External values set when operations succeeded. */
  11431. eckey->exSet = (ret == 1);
  11432. }
  11433. return ret;
  11434. }
  11435. /* Set data of EC key into internal, wolfCrypt EC key object.
  11436. *
  11437. * EC_KEY Openssl -> WolfSSL
  11438. *
  11439. * @param [in, out] p EC key to update.
  11440. * @return 1 on success.
  11441. * @return -1 on failure.
  11442. */
  11443. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11444. {
  11445. int ret = 1;
  11446. WOLFSSL_ENTER("SetECKeyInternal");
  11447. /* Validate parameter. */
  11448. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11449. (eckey->group == NULL)) {
  11450. WOLFSSL_MSG("ec key NULL error");
  11451. ret = -1;
  11452. }
  11453. else {
  11454. ecc_key* key = (ecc_key*)eckey->internal;
  11455. int pubSet = 0;
  11456. /* Validate group. */
  11457. if ((eckey->group->curve_idx < 0) ||
  11458. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11459. WOLFSSL_MSG("invalid curve idx");
  11460. ret = -1;
  11461. }
  11462. if (ret == 1) {
  11463. /* Set group (idx of curve and corresponding domain parameters). */
  11464. key->idx = eckey->group->curve_idx;
  11465. key->dp = &ecc_sets[key->idx];
  11466. pubSet = (eckey->pub_key != NULL);
  11467. }
  11468. /* Set public key (point). */
  11469. if ((ret == 1) && pubSet) {
  11470. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11471. WOLFSSL_MSG("ec key pub error");
  11472. ret = -1;
  11473. }
  11474. /* Copy public point to key. */
  11475. if ((ret == 1) && (wc_ecc_copy_point(
  11476. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11477. MP_OKAY)) {
  11478. WOLFSSL_MSG("wc_ecc_copy_point error");
  11479. ret = -1;
  11480. }
  11481. if (ret == 1) {
  11482. /* Set that the internal key is a public key */
  11483. key->type = ECC_PUBLICKEY;
  11484. }
  11485. }
  11486. /* set privkey */
  11487. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11488. if (wolfssl_bn_get_value(eckey->priv_key,
  11489. wc_ecc_key_get_priv(key)) != 1) {
  11490. WOLFSSL_MSG("ec key priv error");
  11491. ret = -1;
  11492. }
  11493. /* private key */
  11494. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11495. if (pubSet) {
  11496. key->type = ECC_PRIVATEKEY;
  11497. }
  11498. else {
  11499. key->type = ECC_PRIVATEKEY_ONLY;
  11500. }
  11501. }
  11502. }
  11503. /* Internal values set when operations succeeded. */
  11504. eckey->inSet = (ret == 1);
  11505. }
  11506. return ret;
  11507. }
  11508. /* Get point conversion format of EC key.
  11509. *
  11510. * @param [in] key EC key.
  11511. * @return Point conversion format on success.
  11512. * @return -1 on error.
  11513. */
  11514. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11515. {
  11516. int ret = -1;
  11517. if (key != NULL) {
  11518. ret = key->form;
  11519. }
  11520. return ret;
  11521. }
  11522. /* Set point conversion format into EC key.
  11523. *
  11524. * @param [in, out] key EC key to set format into.
  11525. * @param [in] form Point conversion format. Valid values:
  11526. * POINT_CONVERSION_UNCOMPRESSED,
  11527. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11528. */
  11529. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11530. {
  11531. if (key == NULL) {
  11532. WOLFSSL_MSG("Key passed in NULL");
  11533. }
  11534. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11535. #ifdef HAVE_COMP_KEY
  11536. || form == POINT_CONVERSION_COMPRESSED
  11537. #endif
  11538. ) {
  11539. key->form = (unsigned char)form;
  11540. }
  11541. else {
  11542. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11543. }
  11544. }
  11545. /* Get the EC group object that is in EC key.
  11546. *
  11547. * @param [in] key EC key.
  11548. * @return EC group object on success.
  11549. * @return NULL when key is NULL.
  11550. */
  11551. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11552. {
  11553. WOLFSSL_EC_GROUP* group = NULL;
  11554. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11555. if (key != NULL) {
  11556. group = key->group;
  11557. }
  11558. return group;
  11559. }
  11560. /* Set the group in WOLFSSL_EC_KEY
  11561. *
  11562. * @param [in, out] key EC key to update.
  11563. * @param [in] group EC group to copy.
  11564. * @return 1 on success
  11565. * @return 0 on failure.
  11566. */
  11567. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11568. {
  11569. int ret = 1;
  11570. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11571. /* Validate parameters. */
  11572. if ((key == NULL) || (group == NULL)) {
  11573. ret = 0;
  11574. }
  11575. if (ret == 1) {
  11576. /* Dispose of the current group. */
  11577. if (key->group != NULL) {
  11578. wolfSSL_EC_GROUP_free(key->group);
  11579. }
  11580. /* Duplicate the passed in group into EC key. */
  11581. key->group = wolfSSL_EC_GROUP_dup(group);
  11582. if (key->group == NULL) {
  11583. ret = 0;
  11584. }
  11585. }
  11586. return ret;
  11587. }
  11588. /* Get the BN object that is the private key in the EC key.
  11589. *
  11590. * @param [in] key EC key.
  11591. * @return BN object on success.
  11592. * @return NULL when key is NULL or private key is not set.
  11593. */
  11594. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11595. {
  11596. WOLFSSL_BIGNUM* priv_key = NULL;
  11597. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11598. /* Validate parameter. */
  11599. if (key == NULL) {
  11600. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11601. }
  11602. /* Only return private key if it is not 0. */
  11603. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11604. priv_key = key->priv_key;
  11605. }
  11606. return priv_key;
  11607. }
  11608. /* Sets the private key value into EC key.
  11609. *
  11610. * Return code compliant with OpenSSL.
  11611. *
  11612. * @param [in, out] key EC key to set.
  11613. * @param [in] priv_key Private key value in a BN.
  11614. * @return 1 on success
  11615. * @return 0 on failure.
  11616. */
  11617. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11618. const WOLFSSL_BIGNUM *priv_key)
  11619. {
  11620. int ret = 1;
  11621. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11622. /* Validate parameters. */
  11623. if ((key == NULL) || (priv_key == NULL)) {
  11624. WOLFSSL_MSG("Bad arguments");
  11625. ret = 0;
  11626. }
  11627. /* Check for obvious invalid values. */
  11628. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11629. wolfSSL_BN_is_one(priv_key)) {
  11630. WOLFSSL_MSG("Invalid private key value");
  11631. ret = 0;
  11632. }
  11633. if (ret == 1) {
  11634. /* Free key if previously set. */
  11635. if (key->priv_key != NULL) {
  11636. wolfSSL_BN_free(key->priv_key);
  11637. }
  11638. /* Duplicate the BN passed in. */
  11639. key->priv_key = wolfSSL_BN_dup(priv_key);
  11640. if (key->priv_key == NULL) {
  11641. WOLFSSL_MSG("key ecc priv key NULL");
  11642. ret = 0;
  11643. }
  11644. }
  11645. /* Set the external values into internal EC key. */
  11646. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11647. WOLFSSL_MSG("SetECKeyInternal failed");
  11648. /* Dispose of new private key on error. */
  11649. wolfSSL_BN_free(key->priv_key);
  11650. key->priv_key = NULL;
  11651. ret = 0;
  11652. }
  11653. return ret;
  11654. }
  11655. /* Get the public key EC point object that is in EC key.
  11656. *
  11657. * @param [in] key EC key.
  11658. * @return EC point object that is the public key on success.
  11659. * @return NULL when key is NULL.
  11660. */
  11661. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11662. {
  11663. WOLFSSL_EC_POINT* pub_key = NULL;
  11664. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11665. if (key != NULL) {
  11666. pub_key = key->pub_key;
  11667. }
  11668. return pub_key;
  11669. }
  11670. /*
  11671. * Return code compliant with OpenSSL.
  11672. *
  11673. * @param [in, out] key EC key.
  11674. * @param [in] pub Public key as an EC point.
  11675. * @return 1 on success
  11676. * @return 0 on failure.
  11677. */
  11678. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11679. const WOLFSSL_EC_POINT *pub)
  11680. {
  11681. int ret = 1;
  11682. ecc_point *pub_p = NULL;
  11683. ecc_point *key_p = NULL;
  11684. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11685. /* Validate parameters. */
  11686. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11687. (pub->internal == NULL)) {
  11688. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11689. ret = 0;
  11690. }
  11691. /* Ensure the internal EC key is set. */
  11692. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11693. WOLFSSL_MSG("SetECKeyInternal failed");
  11694. ret = 0;
  11695. }
  11696. /* Ensure the internal EC point of pub is setup. */
  11697. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11698. ret = 0;
  11699. }
  11700. if (ret == 1) {
  11701. /* Get the internal point of pub and the public key in key. */
  11702. pub_p = (ecc_point*)pub->internal;
  11703. key_p = (ecc_point*)key->pub_key->internal;
  11704. /* Create new point if required. */
  11705. if (key_p == NULL) {
  11706. key_p = wc_ecc_new_point();
  11707. key->pub_key->internal = (void*)key_p;
  11708. }
  11709. /* Check point available. */
  11710. if (key_p == NULL) {
  11711. WOLFSSL_MSG("key ecc point NULL");
  11712. ret = 0;
  11713. }
  11714. }
  11715. /* Copy the internal pub point into internal key point. */
  11716. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11717. WOLFSSL_MSG("ecc_copy_point failure");
  11718. ret = 0;
  11719. }
  11720. /* Copy the internal point data into external. */
  11721. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11722. WOLFSSL_MSG("SetECKeyInternal failed");
  11723. ret = 0;
  11724. }
  11725. /* Copy the internal key into external. */
  11726. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11727. WOLFSSL_MSG("SetECKeyInternal failed");
  11728. ret = 0;
  11729. }
  11730. if (ret == 1) {
  11731. /* Dump out the point and the key's public key for debug. */
  11732. wolfSSL_EC_POINT_dump("pub", pub);
  11733. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11734. }
  11735. return ret;
  11736. }
  11737. #ifndef NO_WOLFSSL_STUB
  11738. /* Set the ASN.1 encoding flag against the EC key.
  11739. *
  11740. * No implementation as only named curves supported for encoding.
  11741. *
  11742. * @param [in, out] key EC key.
  11743. * @param [in] flag ASN.1 flag to set. Valid values:
  11744. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11745. */
  11746. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11747. {
  11748. (void)key;
  11749. (void)asn1_flag;
  11750. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11751. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11752. }
  11753. #endif
  11754. /*
  11755. * EC key generate key APIs
  11756. */
  11757. /* Generate an EC key.
  11758. *
  11759. * Uses the internal curve index set in the EC key or the default.
  11760. *
  11761. * @param [in, out] key EC key.
  11762. * @return 1 on success
  11763. * @return 0 on failure.
  11764. */
  11765. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11766. {
  11767. int res = 1;
  11768. int initTmpRng = 0;
  11769. WC_RNG* rng = NULL;
  11770. #ifdef WOLFSSL_SMALL_STACK
  11771. WC_RNG* tmpRng = NULL;
  11772. #else
  11773. WC_RNG tmpRng[1];
  11774. #endif
  11775. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11776. /* Validate parameters. */
  11777. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11778. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11779. res = 0;
  11780. }
  11781. if (res == 1) {
  11782. /* Check if we know which internal curve index to use. */
  11783. if (key->group->curve_idx < 0) {
  11784. /* Generate key using the default curve. */
  11785. #if FIPS_VERSION3_GE(6,0,0)
  11786. key->group->curve_idx = ECC_SECP256R1; /* FIPS default to 256 */
  11787. #else
  11788. key->group->curve_idx = ECC_CURVE_DEF;
  11789. #endif
  11790. }
  11791. /* Create a random number generator. */
  11792. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  11793. if (rng == NULL) {
  11794. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  11795. res = 0;
  11796. }
  11797. }
  11798. if (res == 1) {
  11799. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  11800. * is 0 then pass ECC_CURVE_DEF as arg */
  11801. int eccEnum = key->group->curve_nid ?
  11802. #if FIPS_VERSION3_GE(6,0,0)
  11803. NIDToEccEnum(key->group->curve_nid) : ECC_SECP256R1;
  11804. #else
  11805. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  11806. #endif
  11807. /* Get the internal EC key. */
  11808. ecc_key* ecKey = (ecc_key*)key->internal;
  11809. /* Make the key using internal API. */
  11810. int ret = 0;
  11811. #if FIPS_VERSION3_GE(6,0,0)
  11812. /* In the case of FIPS only allow key generation with approved curves */
  11813. if (eccEnum != ECC_SECP256R1 && eccEnum != ECC_SECP224R1 &&
  11814. eccEnum != ECC_SECP384R1 && eccEnum != ECC_SECP521R1) {
  11815. WOLFSSL_MSG("Unsupported curve selected in FIPS mode");
  11816. res = 0;
  11817. }
  11818. if (res == 1) {
  11819. #endif
  11820. ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  11821. #if FIPS_VERSION3_GE(6,0,0)
  11822. }
  11823. #endif
  11824. #if defined(WOLFSSL_ASYNC_CRYPT)
  11825. /* Wait on asynchronouse operation. */
  11826. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  11827. #endif
  11828. if (ret != 0) {
  11829. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  11830. res = 0;
  11831. }
  11832. }
  11833. /* Dispose of local random number generator if initialized. */
  11834. if (initTmpRng) {
  11835. wc_FreeRng(rng);
  11836. #ifdef WOLFSSL_SMALL_STACK
  11837. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  11838. #endif
  11839. }
  11840. /* Set the external key from new internal key values. */
  11841. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11842. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  11843. res = 0;
  11844. }
  11845. return res;
  11846. }
  11847. /*
  11848. * EC key check key APIs
  11849. */
  11850. /* Check that the EC key is valid.
  11851. *
  11852. * @param [in] key EC key.
  11853. * @return 1 on valid.
  11854. * @return 0 on invalid or error.
  11855. */
  11856. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  11857. {
  11858. int ret = 1;
  11859. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  11860. /* Validate parameter. */
  11861. if ((key == NULL) || (key->internal == NULL)) {
  11862. WOLFSSL_MSG("Bad parameter");
  11863. ret = 0;
  11864. }
  11865. /* Set the external EC key values into internal if not already. */
  11866. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  11867. (WOLFSSL_EC_KEY*)key) != 1)) {
  11868. WOLFSSL_MSG("SetECKeyInternal failed");
  11869. ret = 0;
  11870. }
  11871. if (ret == 1) {
  11872. /* Have internal EC implementation check key. */
  11873. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  11874. }
  11875. return ret;
  11876. }
  11877. /* End EC_KEY */
  11878. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  11879. /* Get the supported, built-in EC curves
  11880. *
  11881. * @param [in, out] curves Pre-allocated list to put supported curves into.
  11882. * @param [in] len Maximum number of items to place in list.
  11883. * @return Number of built-in EC curves when curves is NULL or len is 0.
  11884. * @return Number of items placed in list otherwise.
  11885. */
  11886. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  11887. size_t len)
  11888. {
  11889. size_t i;
  11890. size_t cnt;
  11891. #ifdef HAVE_SELFTEST
  11892. /* Defined in ecc.h when available. */
  11893. size_t ecc_sets_count;
  11894. /* Count the pre-defined curves since global not available. */
  11895. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  11896. /* Do nothing. */
  11897. }
  11898. ecc_sets_count = i;
  11899. #endif
  11900. /* Assume we are going to return total count. */
  11901. cnt = ecc_sets_count;
  11902. /* Check we have a list that can hold data. */
  11903. if ((curves != NULL) && (len != 0)) {
  11904. /* Limit count to length of list. */
  11905. if (cnt > len) {
  11906. cnt = len;
  11907. }
  11908. /* Put in built-in EC curve nid and short name. */
  11909. for (i = 0; i < cnt; i++) {
  11910. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  11911. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  11912. }
  11913. }
  11914. return cnt;
  11915. }
  11916. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  11917. /* Start ECDSA_SIG */
  11918. /* Allocate a new ECDSA signature object.
  11919. *
  11920. * @return New, allocated ECDSA signature object on success.
  11921. * @return NULL on error.
  11922. */
  11923. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  11924. {
  11925. int err = 0;
  11926. WOLFSSL_ECDSA_SIG *sig;
  11927. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  11928. /* Allocate memory for ECDSA signature object. */
  11929. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  11930. DYNAMIC_TYPE_ECC);
  11931. if (sig == NULL) {
  11932. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  11933. err = 1;
  11934. }
  11935. if (!err) {
  11936. /* Set s to NULL in case of error. */
  11937. sig->s = NULL;
  11938. /* Allocate BN into r. */
  11939. sig->r = wolfSSL_BN_new();
  11940. if (sig->r == NULL) {
  11941. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  11942. err = 1;
  11943. }
  11944. }
  11945. if (!err) {
  11946. /* Allocate BN into s. */
  11947. sig->s = wolfSSL_BN_new();
  11948. if (sig->s == NULL) {
  11949. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  11950. err = 1;
  11951. }
  11952. }
  11953. if (err && (sig != NULL)) {
  11954. /* Dispose of allocated memory. */
  11955. wolfSSL_ECDSA_SIG_free(sig);
  11956. sig = NULL;
  11957. }
  11958. return sig;
  11959. }
  11960. /* Dispose of ECDSA signature object.
  11961. *
  11962. * Cannot use object after this call.
  11963. *
  11964. * @param [in] sig ECDSA signature object to free.
  11965. */
  11966. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  11967. {
  11968. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  11969. if (sig != NULL) {
  11970. /* Dispose of BNs allocated for r and s. */
  11971. wolfSSL_BN_free(sig->r);
  11972. wolfSSL_BN_free(sig->s);
  11973. /* Dispose of memory associated with ECDSA signature object. */
  11974. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  11975. }
  11976. }
  11977. /* Create an ECDSA signature from the DER encoding.
  11978. *
  11979. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  11980. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  11981. * On out, reference to buffer after signature data.
  11982. * @param [in] len Length of the data in the buffer. May be more than
  11983. * the length of the signature.
  11984. * @return ECDSA signature object on success.
  11985. * @return NULL on error.
  11986. */
  11987. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  11988. const unsigned char** pp, long len)
  11989. {
  11990. int err = 0;
  11991. /* ECDSA signature object to return. */
  11992. WOLFSSL_ECDSA_SIG *s = NULL;
  11993. /* Validate parameter. */
  11994. if (pp == NULL) {
  11995. err = 1;
  11996. }
  11997. if (!err) {
  11998. if (sig != NULL) {
  11999. /* Use the ECDSA signature object passed in. */
  12000. s = *sig;
  12001. }
  12002. if (s == NULL) {
  12003. /* No ECDSA signature object passed in - create a new one. */
  12004. s = wolfSSL_ECDSA_SIG_new();
  12005. if (s == NULL) {
  12006. err = 1;
  12007. }
  12008. }
  12009. }
  12010. if (!err) {
  12011. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  12012. mp_free((mp_int*)s->r->internal);
  12013. mp_free((mp_int*)s->s->internal);
  12014. /* Decode the signature into internal r and s fields. */
  12015. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  12016. (mp_int*)s->s->internal) != MP_OKAY) {
  12017. err = 1;
  12018. }
  12019. }
  12020. if (!err) {
  12021. /* Move pointer passed signature data successfully decoded. */
  12022. *pp += wolfssl_der_length(*pp, (int)len);
  12023. if (sig != NULL) {
  12024. /* Update reference to ECDSA signature object. */
  12025. *sig = s;
  12026. }
  12027. }
  12028. /* Dispose of newly allocated object on error. */
  12029. if (err) {
  12030. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  12031. wolfSSL_ECDSA_SIG_free(s);
  12032. }
  12033. /* Return NULL for object on error. */
  12034. s = NULL;
  12035. }
  12036. return s;
  12037. }
  12038. /* Encode the ECDSA signature as DER.
  12039. *
  12040. * @param [in] sig ECDSA signature object.
  12041. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  12042. * On out, reference to buffer after encoding.
  12043. * May be NULL or point to NULL in which case no encoding
  12044. * is done.
  12045. * @return Length of encoding on success.
  12046. * @return 0 on error.
  12047. */
  12048. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  12049. {
  12050. word32 len = 0;
  12051. /* Validate parameter. */
  12052. if (sig != NULL) {
  12053. /* ASN.1: SEQ + INT + INT
  12054. * ASN.1 Integer must be a positive value - prepend zero if number has
  12055. * top bit set.
  12056. */
  12057. /* Get total length of r including any prepended zero. */
  12058. word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) +
  12059. mp_unsigned_bin_size((mp_int*)sig->r->internal));
  12060. /* Get total length of s including any prepended zero. */
  12061. word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) +
  12062. mp_unsigned_bin_size((mp_int*)sig->s->internal));
  12063. /* Calculate length of data in sequence. */
  12064. len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen +
  12065. (word32)1 + ASN_LEN_SIZE(sLen) + sLen;
  12066. /* Add in the length of the SEQUENCE. */
  12067. len += (word32)1 + ASN_LEN_SIZE(len);
  12068. /* Encode only if there is a buffer to encode into. */
  12069. if ((pp != NULL) && (*pp != NULL)) {
  12070. /* Encode using the internal representations of r and s. */
  12071. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  12072. (mp_int*)sig->s->internal) != MP_OKAY) {
  12073. /* No bytes encoded. */
  12074. len = 0;
  12075. }
  12076. else {
  12077. /* Update pointer to after encoding. */
  12078. *pp += len;
  12079. }
  12080. }
  12081. }
  12082. return (int)len;
  12083. }
  12084. /* Get the pointer to the fields of the ECDSA signature.
  12085. *
  12086. * r and s untouched when sig is NULL.
  12087. *
  12088. * @param [in] sig ECDSA signature object.
  12089. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  12090. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  12091. */
  12092. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  12093. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  12094. {
  12095. /* Validate parameter. */
  12096. if (sig != NULL) {
  12097. /* Return the r BN when pointer to return through. */
  12098. if (r != NULL) {
  12099. *r = sig->r;
  12100. }
  12101. /* Return the s BN when pointer to return through. */
  12102. if (s != NULL) {
  12103. *s = sig->s;
  12104. }
  12105. }
  12106. }
  12107. /* Set the pointers to the fields of the ECDSA signature.
  12108. *
  12109. * @param [in, out] sig ECDSA signature object to update.
  12110. * @param [in] r R field of ECDSA signature as a BN.
  12111. * @param [in] s S field of ECDSA signature as a BN.
  12112. * @return 1 on success.
  12113. * @return 0 on error.
  12114. */
  12115. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  12116. WOLFSSL_BIGNUM* s)
  12117. {
  12118. int ret = 1;
  12119. /* Validate parameters. */
  12120. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  12121. ret = 0;
  12122. }
  12123. if (ret == 1) {
  12124. /* Dispose of old BN objects. */
  12125. wolfSSL_BN_free(sig->r);
  12126. wolfSSL_BN_free(sig->s);
  12127. /* Assign new BN objects. */
  12128. sig->r = r;
  12129. sig->s = s;
  12130. }
  12131. return ret;
  12132. }
  12133. /* End ECDSA_SIG */
  12134. /* Start ECDSA */
  12135. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  12136. *
  12137. * @param [in] key EC key.
  12138. * @return Size of DER encoded signature on success.
  12139. * @return 0 on error.
  12140. */
  12141. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  12142. {
  12143. int err = 0;
  12144. int len = 0;
  12145. const EC_GROUP *group = NULL;
  12146. int bits = 0;
  12147. /* Validate parameter. */
  12148. if (key == NULL) {
  12149. err = 1;
  12150. }
  12151. /* Get group from key to get order bits. */
  12152. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  12153. err = 1;
  12154. }
  12155. /* Get order bits of group. */
  12156. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  12157. /* Group is not set. */
  12158. err = 1;
  12159. }
  12160. if (!err) {
  12161. /* r and s are mod order. */
  12162. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  12163. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  12164. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  12165. bytes + bytes; /* max r and s in bytes */
  12166. }
  12167. return len;
  12168. }
  12169. /* Create ECDSA signature by signing digest with key.
  12170. *
  12171. * @param [in] dgst Digest to sign.
  12172. * @param [in] dLen Length of digest in bytes.
  12173. * @param [in] key EC key to sign with.
  12174. * @return ECDSA signature object on success.
  12175. * @return NULL on error.
  12176. */
  12177. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  12178. WOLFSSL_EC_KEY *key)
  12179. {
  12180. int err = 0;
  12181. WOLFSSL_ECDSA_SIG *sig = NULL;
  12182. #ifdef WOLFSSL_SMALL_STACK
  12183. byte* out = NULL;
  12184. #else
  12185. byte out[ECC_BUFSIZE];
  12186. #endif
  12187. unsigned int outLen = ECC_BUFSIZE;
  12188. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  12189. /* Validate parameters. */
  12190. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  12191. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  12192. err = 1;
  12193. }
  12194. /* Ensure internal EC key is set from external. */
  12195. if ((!err) && (key->inSet == 0)) {
  12196. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  12197. if (SetECKeyInternal(key) != 1) {
  12198. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  12199. err = 1;
  12200. }
  12201. }
  12202. #ifdef WOLFSSL_SMALL_STACK
  12203. if (!err) {
  12204. /* Allocate buffer to hold encoded signature. */
  12205. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12206. if (out == NULL) {
  12207. err = 1;
  12208. }
  12209. }
  12210. #endif
  12211. /* Sign the digest with the key to create encoded ECDSA signature. */
  12212. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  12213. err = 1;
  12214. }
  12215. if (!err) {
  12216. const byte* p = out;
  12217. /* Decode the ECDSA signature into a new object. */
  12218. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  12219. }
  12220. #ifdef WOLFSSL_SMALL_STACK
  12221. /* Dispose of any temporary dynamically allocated data. */
  12222. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12223. #endif
  12224. return sig;
  12225. }
  12226. /* Verify ECDSA signature in the object using digest and key.
  12227. *
  12228. * Return code compliant with OpenSSL.
  12229. *
  12230. * @param [in] dgst Digest to verify.
  12231. * @param [in] dLen Length of the digest in bytes.
  12232. * @param [in] sig ECDSA signature object.
  12233. * @param [in] key EC key containing public key.
  12234. * @return 1 when signature is valid.
  12235. * @return 0 when signature is invalid.
  12236. * @return -1 on error.
  12237. */
  12238. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  12239. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  12240. {
  12241. int ret = 1;
  12242. int verified = 0;
  12243. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  12244. byte signature[ECC_MAX_SIG_SIZE];
  12245. int signatureLen;
  12246. byte* p = signature;
  12247. #endif
  12248. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  12249. /* Validate parameters. */
  12250. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  12251. (key->internal == NULL)) {
  12252. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  12253. ret = -1;
  12254. }
  12255. /* Ensure internal EC key is set from external. */
  12256. if ((ret == 1) && (key->inSet == 0)) {
  12257. WOLFSSL_MSG("No EC key internal set, do it");
  12258. if (SetECKeyInternal(key) != 1) {
  12259. WOLFSSL_MSG("SetECKeyInternal failed");
  12260. ret = -1;
  12261. }
  12262. }
  12263. if (ret == 1) {
  12264. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12265. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  12266. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  12267. (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified,
  12268. (ecc_key *)key->internal) != MP_OKAY) {
  12269. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12270. ret = -1;
  12271. }
  12272. else if (verified == 0) {
  12273. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12274. ret = 0;
  12275. }
  12276. #else
  12277. signatureLen = i2d_ECDSA_SIG(sig, &p);
  12278. if (signatureLen > 0) {
  12279. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  12280. ret = wc_ecc_verify_hash(signature, signatureLen, dgst,
  12281. (word32)dLen, &verified, (ecc_key*)key->internal);
  12282. if (ret != MP_OKAY) {
  12283. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12284. ret = -1;
  12285. }
  12286. else if (verified == 0) {
  12287. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12288. ret = 0;
  12289. }
  12290. }
  12291. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12292. }
  12293. return ret;
  12294. }
  12295. /* Sign the digest with the key to produce a DER encode signature.
  12296. *
  12297. * @param [in] type Digest algorithm used to create digest. Unused.
  12298. * @param [in] digest Digest of the message to sign.
  12299. * @param [in] digestSz Size of the digest in bytes.
  12300. * @param [out] sig Buffer to hold signature.
  12301. * @param [in, out] sigSz On in, size of buffer in bytes.
  12302. * On out, size of signatre in bytes.
  12303. * @param [in] key EC key containing private key.
  12304. * @return 1 on success.
  12305. * @return 0 on error.
  12306. */
  12307. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12308. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12309. {
  12310. int ret = 1;
  12311. WC_RNG* rng = NULL;
  12312. #ifdef WOLFSSL_SMALL_STACK
  12313. WC_RNG* tmpRng = NULL;
  12314. #else
  12315. WC_RNG tmpRng[1];
  12316. #endif
  12317. int initTmpRng = 0;
  12318. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12319. /* Digest algorithm not used in DER encoding. */
  12320. (void)type;
  12321. /* Validate parameters. */
  12322. if (key == NULL) {
  12323. ret = 0;
  12324. }
  12325. if (ret == 1) {
  12326. /* Make an RNG - create local or get global. */
  12327. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12328. if (rng == NULL) {
  12329. ret = 0;
  12330. }
  12331. }
  12332. /* Sign the digest with the key using the RNG and put signature into buffer
  12333. * update sigSz to be actual length.
  12334. */
  12335. if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz,
  12336. rng, (ecc_key*)key->internal) != 0)) {
  12337. ret = 0;
  12338. }
  12339. if (initTmpRng) {
  12340. wc_FreeRng(rng);
  12341. #ifdef WOLFSSL_SMALL_STACK
  12342. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12343. #endif
  12344. }
  12345. return ret;
  12346. }
  12347. /* Verify the signature with the digest and key.
  12348. *
  12349. * @param [in] type Digest algorithm used to create digest. Unused.
  12350. * @param [in] digest Digest of the message to verify.
  12351. * @param [in] digestSz Size of the digest in bytes.
  12352. * @param [in] sig Buffer holding signature.
  12353. * @param [in] sigSz Size of signature data in bytes.
  12354. * @param [in] key EC key containing public key.
  12355. * @return 1 when signature is valid.
  12356. * @return 0 when signature is invalid or error.
  12357. */
  12358. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12359. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12360. {
  12361. int ret = 1;
  12362. int verify = 0;
  12363. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12364. /* Digest algorithm not used in DER encoding. */
  12365. (void)type;
  12366. /* Validate parameters. */
  12367. if (key == NULL) {
  12368. ret = 0;
  12369. }
  12370. /* Verify signature using digest and key. */
  12371. if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest,
  12372. (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) {
  12373. ret = 0;
  12374. }
  12375. /* When no error, verification may still have failed - check now. */
  12376. if ((ret == 1) && (verify != 1)) {
  12377. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12378. ret = 0;
  12379. }
  12380. return ret;
  12381. }
  12382. /* End ECDSA */
  12383. /* Start ECDH */
  12384. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12385. /* Compute the shared secret (key) using ECDH.
  12386. *
  12387. * KDF not supported.
  12388. *
  12389. * Return code compliant with OpenSSL.
  12390. *
  12391. * @param [out] out Buffer to hold key.
  12392. * @param [in] outLen Length of buffer in bytes.
  12393. * @param [in] pubKey Public key as an EC point.
  12394. * @param [in] privKey EC key holding a private key.
  12395. * @param [in] kdf Key derivation function to apply to secret.
  12396. * @return Length of computed key on success
  12397. * @return 0 on error.
  12398. */
  12399. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12400. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12401. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12402. {
  12403. int err = 0;
  12404. word32 len = 0;
  12405. ecc_key* key = NULL;
  12406. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12407. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12408. int setGlobalRNG = 0;
  12409. #endif
  12410. /* TODO: support using the KDF. */
  12411. (void)kdf;
  12412. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12413. /* Validate parameters. */
  12414. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12415. (privKey == NULL) || (privKey->internal == NULL)) {
  12416. WOLFSSL_MSG("Bad function arguments");
  12417. err = 1;
  12418. }
  12419. /* Ensure internal EC key is set from external. */
  12420. if ((!err) && (privKey->inSet == 0)) {
  12421. WOLFSSL_MSG("No EC key internal set, do it");
  12422. if (SetECKeyInternal(privKey) != 1) {
  12423. WOLFSSL_MSG("SetECKeyInternal failed");
  12424. err = 1;
  12425. }
  12426. }
  12427. if (!err) {
  12428. int ret;
  12429. /* Get the internal key. */
  12430. key = (ecc_key*)privKey->internal;
  12431. /* Set length into variable of type suitable for wolfSSL API. */
  12432. len = (word32)outLen;
  12433. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12434. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12435. /* An RNG is needed. */
  12436. if (key->rng == NULL) {
  12437. key->rng = wolfssl_make_global_rng();
  12438. /* RNG set and needs to be unset. */
  12439. setGlobalRNG = 1;
  12440. }
  12441. #endif
  12442. PRIVATE_KEY_UNLOCK();
  12443. /* Create secret using wolfSSL. */
  12444. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12445. (byte *)out, &len);
  12446. PRIVATE_KEY_LOCK();
  12447. if (ret != MP_OKAY) {
  12448. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12449. err = 1;
  12450. }
  12451. }
  12452. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12453. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12454. /* Remove global from key. */
  12455. if (setGlobalRNG) {
  12456. key->rng = NULL;
  12457. }
  12458. #endif
  12459. if (err) {
  12460. /* Make returned value zero. */
  12461. len = 0;
  12462. }
  12463. return (int)len;
  12464. }
  12465. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12466. /* End ECDH */
  12467. #endif /* OPENSSL_EXTRA */
  12468. #endif /* HAVE_ECC */
  12469. /*******************************************************************************
  12470. * END OF EC API
  12471. ******************************************************************************/
  12472. /*******************************************************************************
  12473. * START OF EC25519 API
  12474. ******************************************************************************/
  12475. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE25519)
  12476. /* Generate an EC25519 key pair.
  12477. *
  12478. * Output keys are in little endian format.
  12479. *
  12480. * @param [out] priv EC25519 private key data.
  12481. * @param [in, out] privSz On in, the size of priv in bytes.
  12482. * On out, the length of the private key data in bytes.
  12483. * @param [out] pub EC25519 public key data.
  12484. * @param [in, out] pubSz On in, the size of pub in bytes.
  12485. * On out, the length of the public key data in bytes.
  12486. * @return 1 on success
  12487. * @return 0 on failure.
  12488. */
  12489. int wolfSSL_EC25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12490. unsigned char *pub, unsigned int *pubSz)
  12491. {
  12492. #ifdef WOLFSSL_KEY_GEN
  12493. int res = 1;
  12494. int initTmpRng = 0;
  12495. WC_RNG *rng = NULL;
  12496. #ifdef WOLFSSL_SMALL_STACK
  12497. WC_RNG *tmpRng = NULL;
  12498. #else
  12499. WC_RNG tmpRng[1];
  12500. #endif
  12501. curve25519_key key;
  12502. WOLFSSL_ENTER("wolfSSL_EC25519_generate_key");
  12503. /* Validate parameters. */
  12504. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE25519_KEYSIZE) ||
  12505. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE25519_KEYSIZE)) {
  12506. WOLFSSL_MSG("Bad arguments");
  12507. res = 0;
  12508. }
  12509. if (res) {
  12510. /* Create a random number generator. */
  12511. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12512. if (rng == NULL) {
  12513. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12514. res = 0;
  12515. }
  12516. }
  12517. /* Initialize a Curve25519 key. */
  12518. if (res && (wc_curve25519_init(&key) != 0)) {
  12519. WOLFSSL_MSG("wc_curve25519_init failed");
  12520. res = 0;
  12521. }
  12522. if (res) {
  12523. /* Make a Curve25519 key pair. */
  12524. int ret = wc_curve25519_make_key(rng, CURVE25519_KEYSIZE, &key);
  12525. if (ret != MP_OKAY) {
  12526. WOLFSSL_MSG("wc_curve25519_make_key failed");
  12527. res = 0;
  12528. }
  12529. if (res) {
  12530. /* Export Curve25519 key pair to buffers. */
  12531. ret = wc_curve25519_export_key_raw_ex(&key, priv, privSz, pub,
  12532. pubSz, EC25519_LITTLE_ENDIAN);
  12533. if (ret != MP_OKAY) {
  12534. WOLFSSL_MSG("wc_curve25519_export_key_raw_ex failed");
  12535. res = 0;
  12536. }
  12537. }
  12538. /* Dispose of key. */
  12539. wc_curve25519_free(&key);
  12540. }
  12541. if (initTmpRng) {
  12542. wc_FreeRng(rng);
  12543. #ifdef WOLFSSL_SMALL_STACK
  12544. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12545. #endif
  12546. }
  12547. return res;
  12548. #else
  12549. WOLFSSL_MSG("No Key Gen built in");
  12550. (void)priv;
  12551. (void)privSz;
  12552. (void)pub;
  12553. (void)pubSz;
  12554. return 0;
  12555. #endif /* WOLFSSL_KEY_GEN */
  12556. }
  12557. /* Compute a shared secret from private and public EC25519 keys.
  12558. *
  12559. * Input and output keys are in little endian format
  12560. *
  12561. * @param [out] shared Shared secret buffer.
  12562. * @param [in, out] sharedSz On in, the size of shared in bytes.
  12563. * On out, the length of the secret in bytes.
  12564. * @param [in] priv EC25519 private key data.
  12565. * @param [in] privSz Length of the private key data in bytes.
  12566. * @param [in] pub EC25519 public key data.
  12567. * @param [in] pubSz Length of the public key data in bytes.
  12568. * @return 1 on success
  12569. * @return 0 on failure.
  12570. */
  12571. int wolfSSL_EC25519_shared_key(unsigned char *shared, unsigned int *sharedSz,
  12572. const unsigned char *priv, unsigned int privSz, const unsigned char *pub,
  12573. unsigned int pubSz)
  12574. {
  12575. #ifdef WOLFSSL_KEY_GEN
  12576. int res = 1;
  12577. curve25519_key privkey;
  12578. curve25519_key pubkey;
  12579. WOLFSSL_ENTER("wolfSSL_EC25519_shared_key");
  12580. /* Validate parameters. */
  12581. if ((shared == NULL) || (sharedSz == NULL) ||
  12582. (*sharedSz < CURVE25519_KEYSIZE) || (priv == NULL) ||
  12583. (privSz < CURVE25519_KEYSIZE) || (pub == NULL) ||
  12584. (pubSz < CURVE25519_KEYSIZE)) {
  12585. WOLFSSL_MSG("Bad arguments");
  12586. res = 0;
  12587. }
  12588. /* Initialize private key object. */
  12589. if (res && (wc_curve25519_init(&privkey) != 0)) {
  12590. WOLFSSL_MSG("wc_curve25519_init privkey failed");
  12591. res = 0;
  12592. }
  12593. if (res) {
  12594. /* Initialize public key object. */
  12595. if (wc_curve25519_init(&pubkey) != MP_OKAY) {
  12596. WOLFSSL_MSG("wc_curve25519_init pubkey failed");
  12597. res = 0;
  12598. }
  12599. if (res) {
  12600. /* Import our private key. */
  12601. int ret = wc_curve25519_import_private_ex(priv, privSz, &privkey,
  12602. EC25519_LITTLE_ENDIAN);
  12603. if (ret != 0) {
  12604. WOLFSSL_MSG("wc_curve25519_import_private_ex failed");
  12605. res = 0;
  12606. }
  12607. if (res) {
  12608. /* Import peer's public key. */
  12609. ret = wc_curve25519_import_public_ex(pub, pubSz, &pubkey,
  12610. EC25519_LITTLE_ENDIAN);
  12611. if (ret != 0) {
  12612. WOLFSSL_MSG("wc_curve25519_import_public_ex failed");
  12613. res = 0;
  12614. }
  12615. }
  12616. if (res) {
  12617. /* Compute shared secret. */
  12618. ret = wc_curve25519_shared_secret_ex(&privkey, &pubkey, shared,
  12619. sharedSz, EC25519_LITTLE_ENDIAN);
  12620. if (ret != 0) {
  12621. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  12622. res = 0;
  12623. }
  12624. }
  12625. wc_curve25519_free(&pubkey);
  12626. }
  12627. wc_curve25519_free(&privkey);
  12628. }
  12629. return res;
  12630. #else
  12631. WOLFSSL_MSG("No Key Gen built in");
  12632. (void)shared;
  12633. (void)sharedSz;
  12634. (void)priv;
  12635. (void)privSz;
  12636. (void)pub;
  12637. (void)pubSz;
  12638. return 0;
  12639. #endif /* WOLFSSL_KEY_GEN */
  12640. }
  12641. #endif /* OPENSSL_EXTRA && HAVE_CURVE25519 */
  12642. /*******************************************************************************
  12643. * END OF EC25519 API
  12644. ******************************************************************************/
  12645. /*******************************************************************************
  12646. * START OF ED25519 API
  12647. ******************************************************************************/
  12648. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED25519)
  12649. /* Generate an ED25519 key pair.
  12650. *
  12651. * Output keys are in little endian format.
  12652. *
  12653. * @param [out] priv ED25519 private key data.
  12654. * @param [in, out] privSz On in, the size of priv in bytes.
  12655. * On out, the length of the private key data in bytes.
  12656. * @param [out] pub ED25519 public key data.
  12657. * @param [in, out] pubSz On in, the size of pub in bytes.
  12658. * On out, the length of the public key data in bytes.
  12659. * @return 1 on success
  12660. * @return 0 on failure.
  12661. */
  12662. int wolfSSL_ED25519_generate_key(unsigned char *priv, unsigned int *privSz,
  12663. unsigned char *pub, unsigned int *pubSz)
  12664. {
  12665. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED25519_KEY_EXPORT)
  12666. int res = 1;
  12667. int initTmpRng = 0;
  12668. WC_RNG *rng = NULL;
  12669. #ifdef WOLFSSL_SMALL_STACK
  12670. WC_RNG *tmpRng = NULL;
  12671. #else
  12672. WC_RNG tmpRng[1];
  12673. #endif
  12674. ed25519_key key;
  12675. WOLFSSL_ENTER("wolfSSL_ED25519_generate_key");
  12676. /* Validate parameters. */
  12677. if ((priv == NULL) || (privSz == NULL) ||
  12678. (*privSz < ED25519_PRV_KEY_SIZE) || (pub == NULL) ||
  12679. (pubSz == NULL) || (*pubSz < ED25519_PUB_KEY_SIZE)) {
  12680. WOLFSSL_MSG("Bad arguments");
  12681. res = 0;
  12682. }
  12683. if (res) {
  12684. /* Create a random number generator. */
  12685. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12686. if (rng == NULL) {
  12687. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12688. res = 0;
  12689. }
  12690. }
  12691. /* Initialize an Ed25519 key. */
  12692. if (res && (wc_ed25519_init(&key) != 0)) {
  12693. WOLFSSL_MSG("wc_ed25519_init failed");
  12694. res = 0;
  12695. }
  12696. if (res) {
  12697. /* Make an Ed25519 key pair. */
  12698. int ret = wc_ed25519_make_key(rng, ED25519_KEY_SIZE, &key);
  12699. if (ret != 0) {
  12700. WOLFSSL_MSG("wc_ed25519_make_key failed");
  12701. res = 0;
  12702. }
  12703. if (res) {
  12704. /* Export Curve25519 key pair to buffers. */
  12705. ret = wc_ed25519_export_key(&key, priv, privSz, pub, pubSz);
  12706. if (ret != 0) {
  12707. WOLFSSL_MSG("wc_ed25519_export_key failed");
  12708. res = 0;
  12709. }
  12710. }
  12711. wc_ed25519_free(&key);
  12712. }
  12713. if (initTmpRng) {
  12714. wc_FreeRng(rng);
  12715. #ifdef WOLFSSL_SMALL_STACK
  12716. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12717. #endif
  12718. }
  12719. return res;
  12720. #else
  12721. #ifndef WOLFSSL_KEY_GEN
  12722. WOLFSSL_MSG("No Key Gen built in");
  12723. #else
  12724. WOLFSSL_MSG("No ED25519 key export built in");
  12725. #endif
  12726. (void)priv;
  12727. (void)privSz;
  12728. (void)pub;
  12729. (void)pubSz;
  12730. return 0;
  12731. #endif /* WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_EXPORT */
  12732. }
  12733. /* Sign a message with Ed25519 using the private key.
  12734. *
  12735. * Input and output keys are in little endian format.
  12736. * Priv is a buffer containing private and public part of key.
  12737. *
  12738. * @param [in] msg Message to be signed.
  12739. * @param [in] msgSz Length of message in bytes.
  12740. * @param [in] priv ED25519 private key data.
  12741. * @param [in] privSz Length in bytes of private key data.
  12742. * @param [out] sig Signature buffer.
  12743. * @param [in, out] sigSz On in, the length of the siganture buffer in bytes.
  12744. * On out, the length of the signature in bytes.
  12745. * @return 1 on success
  12746. * @return 0 on failure.
  12747. */
  12748. int wolfSSL_ED25519_sign(const unsigned char *msg, unsigned int msgSz,
  12749. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  12750. unsigned int *sigSz)
  12751. {
  12752. #if defined(HAVE_ED25519_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  12753. defined(HAVE_ED25519_KEY_IMPORT)
  12754. ed25519_key key;
  12755. int res = 1;
  12756. WOLFSSL_ENTER("wolfSSL_ED25519_sign");
  12757. /* Validate parameters. */
  12758. if ((priv == NULL) || (privSz != ED25519_PRV_KEY_SIZE) ||
  12759. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  12760. (*sigSz < ED25519_SIG_SIZE)) {
  12761. WOLFSSL_MSG("Bad arguments");
  12762. res = 0;
  12763. }
  12764. /* Initialize Ed25519 key. */
  12765. if (res && (wc_ed25519_init(&key) != 0)) {
  12766. WOLFSSL_MSG("wc_curve25519_init failed");
  12767. res = 0;
  12768. }
  12769. if (res) {
  12770. /* Import private and public key. */
  12771. int ret = wc_ed25519_import_private_key(priv, privSz / 2,
  12772. priv + (privSz / 2), ED25519_PUB_KEY_SIZE, &key);
  12773. if (ret != 0) {
  12774. WOLFSSL_MSG("wc_ed25519_import_private failed");
  12775. res = 0;
  12776. }
  12777. if (res) {
  12778. /* Sign message with Ed25519. */
  12779. ret = wc_ed25519_sign_msg(msg, msgSz, sig, sigSz, &key);
  12780. if (ret != 0) {
  12781. WOLFSSL_MSG("wc_curve25519_shared_secret_ex failed");
  12782. res = 0;
  12783. }
  12784. }
  12785. wc_ed25519_free(&key);
  12786. }
  12787. return res;
  12788. #else
  12789. #if !defined(HAVE_ED25519_SIGN)
  12790. WOLFSSL_MSG("No ED25519 sign built in");
  12791. #elif !defined(WOLFSSL_KEY_GEN)
  12792. WOLFSSL_MSG("No Key Gen built in");
  12793. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  12794. WOLFSSL_MSG("No ED25519 Key import built in");
  12795. #endif
  12796. (void)msg;
  12797. (void)msgSz;
  12798. (void)priv;
  12799. (void)privSz;
  12800. (void)sig;
  12801. (void)sigSz;
  12802. return 0;
  12803. #endif /* HAVE_ED25519_SIGN && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  12804. }
  12805. /* Verify a message with Ed25519 using the public key.
  12806. *
  12807. * Input keys are in little endian format.
  12808. *
  12809. * @param [in] msg Message to be verified.
  12810. * @param [in] msgSz Length of message in bytes.
  12811. * @param [in] pub ED25519 public key data.
  12812. * @param [in] privSz Length in bytes of public key data.
  12813. * @param [in] sig Signature buffer.
  12814. * @param [in] sigSz Length of the signature in bytes.
  12815. * @return 1 on success
  12816. * @return 0 on failure.
  12817. */
  12818. int wolfSSL_ED25519_verify(const unsigned char *msg, unsigned int msgSz,
  12819. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  12820. unsigned int sigSz)
  12821. {
  12822. #if defined(HAVE_ED25519_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  12823. defined(HAVE_ED25519_KEY_IMPORT)
  12824. ed25519_key key;
  12825. int res = 1;
  12826. WOLFSSL_ENTER("wolfSSL_ED25519_verify");
  12827. /* Validate parameters. */
  12828. if ((pub == NULL) || (pubSz != ED25519_PUB_KEY_SIZE) || (msg == NULL) ||
  12829. (sig == NULL) || (sigSz != ED25519_SIG_SIZE)) {
  12830. WOLFSSL_MSG("Bad arguments");
  12831. res = 0;
  12832. }
  12833. /* Initialize Ed25519 key. */
  12834. if (res && (wc_ed25519_init(&key) != 0)) {
  12835. WOLFSSL_MSG("wc_curve25519_init failed");
  12836. res = 0;
  12837. }
  12838. if (res) {
  12839. /* Import public key. */
  12840. int ret = wc_ed25519_import_public(pub, pubSz, &key);
  12841. if (ret != 0) {
  12842. WOLFSSL_MSG("wc_ed25519_import_public failed");
  12843. res = 0;
  12844. }
  12845. if (res) {
  12846. int check = 0;
  12847. /* Verify signature with message and public key. */
  12848. ret = wc_ed25519_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  12849. &key);
  12850. /* Check for errors in verification process. */
  12851. if (ret != 0) {
  12852. WOLFSSL_MSG("wc_ed25519_verify_msg failed");
  12853. res = 0;
  12854. }
  12855. /* Check signature is valid. */
  12856. else if (!check) {
  12857. WOLFSSL_MSG("wc_ed25519_verify_msg failed (signature invalid)");
  12858. res = 0;
  12859. }
  12860. }
  12861. wc_ed25519_free(&key);
  12862. }
  12863. return res;
  12864. #else
  12865. #if !defined(HAVE_ED25519_VERIFY)
  12866. WOLFSSL_MSG("No ED25519 verify built in");
  12867. #elif !defined(WOLFSSL_KEY_GEN)
  12868. WOLFSSL_MSG("No Key Gen built in");
  12869. #elif !defined(HAVE_ED25519_KEY_IMPORT)
  12870. WOLFSSL_MSG("No ED25519 Key import built in");
  12871. #endif
  12872. (void)msg;
  12873. (void)msgSz;
  12874. (void)pub;
  12875. (void)pubSz;
  12876. (void)sig;
  12877. (void)sigSz;
  12878. return 0;
  12879. #endif /* HAVE_ED25519_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED25519_KEY_IMPORT */
  12880. }
  12881. #endif /* OPENSSL_EXTRA && HAVE_ED25519 */
  12882. /*******************************************************************************
  12883. * END OF ED25519 API
  12884. ******************************************************************************/
  12885. /*******************************************************************************
  12886. * START OF EC448 API
  12887. ******************************************************************************/
  12888. #if defined(OPENSSL_EXTRA) && defined(HAVE_CURVE448)
  12889. /* Generate an EC448 key pair.
  12890. *
  12891. * Output keys are in little endian format.
  12892. *
  12893. * @param [out] priv EC448 private key data.
  12894. * @param [in, out] privSz On in, the size of priv in bytes.
  12895. * On out, the length of the private key data in bytes.
  12896. * @param [out] pub EC448 public key data.
  12897. * @param [in, out] pubSz On in, the size of pub in bytes.
  12898. * On out, the length of the public key data in bytes.
  12899. * @return 1 on success
  12900. * @return 0 on failure.
  12901. */
  12902. int wolfSSL_EC448_generate_key(unsigned char *priv, unsigned int *privSz,
  12903. unsigned char *pub, unsigned int *pubSz)
  12904. {
  12905. #ifdef WOLFSSL_KEY_GEN
  12906. int res = 1;
  12907. int initTmpRng = 0;
  12908. WC_RNG *rng = NULL;
  12909. #ifdef WOLFSSL_SMALL_STACK
  12910. WC_RNG *tmpRng = NULL;
  12911. #else
  12912. WC_RNG tmpRng[1];
  12913. #endif
  12914. curve448_key key;
  12915. WOLFSSL_ENTER("wolfSSL_EC448_generate_key");
  12916. /* Validate parameters. */
  12917. if ((priv == NULL) || (privSz == NULL) || (*privSz < CURVE448_KEY_SIZE) ||
  12918. (pub == NULL) || (pubSz == NULL) || (*pubSz < CURVE448_KEY_SIZE)) {
  12919. WOLFSSL_MSG("Bad arguments");
  12920. res = 0;
  12921. }
  12922. if (res) {
  12923. /* Create a random number generator. */
  12924. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12925. if (rng == NULL) {
  12926. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  12927. res = 0;
  12928. }
  12929. }
  12930. /* Initialize a Curve448 key. */
  12931. if (res && (wc_curve448_init(&key) != 0)) {
  12932. WOLFSSL_MSG("wc_curve448_init failed");
  12933. res = 0;
  12934. }
  12935. if (res) {
  12936. /* Make a Curve448 key pair. */
  12937. int ret = wc_curve448_make_key(rng, CURVE448_KEY_SIZE, &key);
  12938. if (ret != 0) {
  12939. WOLFSSL_MSG("wc_curve448_make_key failed");
  12940. res = 0;
  12941. }
  12942. if (res) {
  12943. /* Export Curve448 key pair to buffers. */
  12944. ret = wc_curve448_export_key_raw_ex(&key, priv, privSz, pub, pubSz,
  12945. EC448_LITTLE_ENDIAN);
  12946. if (ret != 0) {
  12947. WOLFSSL_MSG("wc_curve448_export_key_raw_ex failed");
  12948. res = 0;
  12949. }
  12950. }
  12951. /* Dispose of key. */
  12952. wc_curve448_free(&key);
  12953. }
  12954. if (initTmpRng) {
  12955. wc_FreeRng(rng);
  12956. #ifdef WOLFSSL_SMALL_STACK
  12957. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12958. #endif
  12959. }
  12960. return res;
  12961. #else
  12962. WOLFSSL_MSG("No Key Gen built in");
  12963. (void)priv;
  12964. (void)privSz;
  12965. (void)pub;
  12966. (void)pubSz;
  12967. return 0;
  12968. #endif /* WOLFSSL_KEY_GEN */
  12969. }
  12970. /* Compute a shared secret from private and public EC448 keys.
  12971. *
  12972. * Input and output keys are in little endian format
  12973. *
  12974. * @param [out] shared Shared secret buffer.
  12975. * @param [in, out] sharedSz On in, the size of shared in bytes.
  12976. * On out, the length of the secret in bytes.
  12977. * @param [in] priv EC448 private key data.
  12978. * @param [in] privSz Length of the private key data in bytes.
  12979. * @param [in] pub EC448 public key data.
  12980. * @param [in] pubSz Length of the public key data in bytes.
  12981. * @return 1 on success
  12982. * @return 0 on failure.
  12983. */
  12984. int wolfSSL_EC448_shared_key(unsigned char *shared, unsigned int *sharedSz,
  12985. const unsigned char *priv, unsigned int privSz,
  12986. const unsigned char *pub, unsigned int pubSz)
  12987. {
  12988. #ifdef WOLFSSL_KEY_GEN
  12989. int res = 1;
  12990. curve448_key privkey;
  12991. curve448_key pubkey;
  12992. WOLFSSL_ENTER("wolfSSL_EC448_shared_key");
  12993. /* Validate parameters. */
  12994. if ((shared == NULL) || (sharedSz == NULL) ||
  12995. (*sharedSz < CURVE448_KEY_SIZE) || (priv == NULL) ||
  12996. (privSz < CURVE448_KEY_SIZE) || (pub == NULL) ||
  12997. (pubSz < CURVE448_KEY_SIZE)) {
  12998. WOLFSSL_MSG("Bad arguments");
  12999. res = 0;
  13000. }
  13001. /* Initialize private key object. */
  13002. if (res && (wc_curve448_init(&privkey) != 0)) {
  13003. WOLFSSL_MSG("wc_curve448_init privkey failed");
  13004. res = 0;
  13005. }
  13006. if (res) {
  13007. /* Initialize public key object. */
  13008. if (wc_curve448_init(&pubkey) != MP_OKAY) {
  13009. WOLFSSL_MSG("wc_curve448_init pubkey failed");
  13010. res = 0;
  13011. }
  13012. if (res) {
  13013. /* Import our private key. */
  13014. int ret = wc_curve448_import_private_ex(priv, privSz, &privkey,
  13015. EC448_LITTLE_ENDIAN);
  13016. if (ret != 0) {
  13017. WOLFSSL_MSG("wc_curve448_import_private_ex failed");
  13018. res = 0;
  13019. }
  13020. if (res) {
  13021. /* Import peer's public key. */
  13022. ret = wc_curve448_import_public_ex(pub, pubSz, &pubkey,
  13023. EC448_LITTLE_ENDIAN);
  13024. if (ret != 0) {
  13025. WOLFSSL_MSG("wc_curve448_import_public_ex failed");
  13026. res = 0;
  13027. }
  13028. }
  13029. if (res) {
  13030. /* Compute shared secret. */
  13031. ret = wc_curve448_shared_secret_ex(&privkey, &pubkey, shared,
  13032. sharedSz, EC448_LITTLE_ENDIAN);
  13033. if (ret != 0) {
  13034. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13035. res = 0;
  13036. }
  13037. }
  13038. wc_curve448_free(&pubkey);
  13039. }
  13040. wc_curve448_free(&privkey);
  13041. }
  13042. return res;
  13043. #else
  13044. WOLFSSL_MSG("No Key Gen built in");
  13045. (void)shared;
  13046. (void)sharedSz;
  13047. (void)priv;
  13048. (void)privSz;
  13049. (void)pub;
  13050. (void)pubSz;
  13051. return 0;
  13052. #endif /* WOLFSSL_KEY_GEN */
  13053. }
  13054. #endif /* OPENSSL_EXTRA && HAVE_CURVE448 */
  13055. /*******************************************************************************
  13056. * END OF EC448 API
  13057. ******************************************************************************/
  13058. /*******************************************************************************
  13059. * START OF ED448 API
  13060. ******************************************************************************/
  13061. #if defined(OPENSSL_EXTRA) && defined(HAVE_ED448)
  13062. /* Generate an ED448 key pair.
  13063. *
  13064. * Output keys are in little endian format.
  13065. *
  13066. * @param [out] priv ED448 private key data.
  13067. * @param [in, out] privSz On in, the size of priv in bytes.
  13068. * On out, the length of the private key data in bytes.
  13069. * @param [out] pub ED448 public key data.
  13070. * @param [in, out] pubSz On in, the size of pub in bytes.
  13071. * On out, the length of the public key data in bytes.
  13072. * @return 1 on success
  13073. * @return 0 on failure.
  13074. */
  13075. int wolfSSL_ED448_generate_key(unsigned char *priv, unsigned int *privSz,
  13076. unsigned char *pub, unsigned int *pubSz)
  13077. {
  13078. #if defined(WOLFSSL_KEY_GEN) && defined(HAVE_ED448_KEY_EXPORT)
  13079. int res = 1;
  13080. int initTmpRng = 0;
  13081. WC_RNG *rng = NULL;
  13082. #ifdef WOLFSSL_SMALL_STACK
  13083. WC_RNG *tmpRng = NULL;
  13084. #else
  13085. WC_RNG tmpRng[1];
  13086. #endif
  13087. ed448_key key;
  13088. WOLFSSL_ENTER("wolfSSL_ED448_generate_key");
  13089. /* Validate parameters. */
  13090. if ((priv == NULL) || (privSz == NULL) ||
  13091. (*privSz < ED448_PRV_KEY_SIZE) || (pub == NULL) ||
  13092. (pubSz == NULL) || (*pubSz < ED448_PUB_KEY_SIZE)) {
  13093. WOLFSSL_MSG("Bad arguments");
  13094. res = 0;
  13095. }
  13096. if (res) {
  13097. /* Create a random number generator. */
  13098. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  13099. if (rng == NULL) {
  13100. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to make RNG");
  13101. res = 0;
  13102. }
  13103. }
  13104. /* Initialize an Ed448 key. */
  13105. if (res && (wc_ed448_init(&key) != 0)) {
  13106. WOLFSSL_MSG("wc_ed448_init failed");
  13107. res = 0;
  13108. }
  13109. if (res) {
  13110. /* Make an Ed448 key pair. */
  13111. int ret = wc_ed448_make_key(rng, ED448_KEY_SIZE, &key);
  13112. if (ret != 0) {
  13113. WOLFSSL_MSG("wc_ed448_make_key failed");
  13114. res = 0;
  13115. }
  13116. if (res) {
  13117. /* Export Curve448 key pair to buffers. */
  13118. ret = wc_ed448_export_key(&key, priv, privSz, pub, pubSz);
  13119. if (ret != 0) {
  13120. WOLFSSL_MSG("wc_ed448_export_key failed");
  13121. res = 0;
  13122. }
  13123. }
  13124. wc_ed448_free(&key);
  13125. }
  13126. if (initTmpRng) {
  13127. wc_FreeRng(rng);
  13128. #ifdef WOLFSSL_SMALL_STACK
  13129. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  13130. #endif
  13131. }
  13132. return res;
  13133. #else
  13134. #ifndef WOLFSSL_KEY_GEN
  13135. WOLFSSL_MSG("No Key Gen built in");
  13136. #else
  13137. WOLFSSL_MSG("No ED448 key export built in");
  13138. #endif
  13139. (void)priv;
  13140. (void)privSz;
  13141. (void)pub;
  13142. (void)pubSz;
  13143. return 0;
  13144. #endif /* WOLFSSL_KEY_GEN && HAVE_ED448_KEY_EXPORT */
  13145. }
  13146. /* Sign a message with Ed448 using the private key.
  13147. *
  13148. * Input and output keys are in little endian format.
  13149. * Priv is a buffer containing private and public part of key.
  13150. *
  13151. * @param [in] msg Message to be signed.
  13152. * @param [in] msgSz Length of message in bytes.
  13153. * @param [in] priv ED448 private key data.
  13154. * @param [in] privSz Length in bytes of private key data.
  13155. * @param [out] sig Signature buffer.
  13156. * @param [in, out] sigSz On in, the length of the siganture buffer in bytes.
  13157. * On out, the length of the signature in bytes.
  13158. * @return 1 on success
  13159. * @return 0 on failure.
  13160. */
  13161. int wolfSSL_ED448_sign(const unsigned char *msg, unsigned int msgSz,
  13162. const unsigned char *priv, unsigned int privSz, unsigned char *sig,
  13163. unsigned int *sigSz)
  13164. {
  13165. #if defined(HAVE_ED448_SIGN) && defined(WOLFSSL_KEY_GEN) && \
  13166. defined(HAVE_ED448_KEY_IMPORT)
  13167. ed448_key key;
  13168. int res = 1;
  13169. WOLFSSL_ENTER("wolfSSL_ED448_sign");
  13170. /* Validate parameters. */
  13171. if ((priv == NULL) || (privSz != ED448_PRV_KEY_SIZE) ||
  13172. (msg == NULL) || (sig == NULL) || (sigSz == NULL) ||
  13173. (*sigSz < ED448_SIG_SIZE)) {
  13174. WOLFSSL_MSG("Bad arguments");
  13175. res = 0;
  13176. }
  13177. /* Initialize Ed448 key. */
  13178. if (res && (wc_ed448_init(&key) != 0)) {
  13179. WOLFSSL_MSG("wc_curve448_init failed");
  13180. res = 0;
  13181. }
  13182. if (res) {
  13183. /* Import private and public key. */
  13184. int ret = wc_ed448_import_private_key(priv, privSz / 2,
  13185. priv + (privSz / 2), ED448_PUB_KEY_SIZE, &key);
  13186. if (ret != 0) {
  13187. WOLFSSL_MSG("wc_ed448_import_private failed");
  13188. res = 0;
  13189. }
  13190. if (res) {
  13191. /* Sign message with Ed448 - no context. */
  13192. ret = wc_ed448_sign_msg(msg, msgSz, sig, sigSz, &key, NULL, 0);
  13193. if (ret != 0) {
  13194. WOLFSSL_MSG("wc_curve448_shared_secret_ex failed");
  13195. res = 0;
  13196. }
  13197. }
  13198. wc_ed448_free(&key);
  13199. }
  13200. return res;
  13201. #else
  13202. #if !defined(HAVE_ED448_SIGN)
  13203. WOLFSSL_MSG("No ED448 sign built in");
  13204. #elif !defined(WOLFSSL_KEY_GEN)
  13205. WOLFSSL_MSG("No Key Gen built in");
  13206. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13207. WOLFSSL_MSG("No ED448 Key import built in");
  13208. #endif
  13209. (void)msg;
  13210. (void)msgSz;
  13211. (void)priv;
  13212. (void)privSz;
  13213. (void)sig;
  13214. (void)sigSz;
  13215. return 0;
  13216. #endif /* HAVE_ED448_SIGN && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13217. }
  13218. /* Verify a message with Ed448 using the public key.
  13219. *
  13220. * Input keys are in little endian format.
  13221. *
  13222. * @param [in] msg Message to be verified.
  13223. * @param [in] msgSz Length of message in bytes.
  13224. * @param [in] pub ED448 public key data.
  13225. * @param [in] privSz Length in bytes of public key data.
  13226. * @param [in] sig Signature buffer.
  13227. * @param [in] sigSz Length of the signature in bytes.
  13228. * @return 1 on success
  13229. * @return 0 on failure.
  13230. */
  13231. int wolfSSL_ED448_verify(const unsigned char *msg, unsigned int msgSz,
  13232. const unsigned char *pub, unsigned int pubSz, const unsigned char *sig,
  13233. unsigned int sigSz)
  13234. {
  13235. #if defined(HAVE_ED448_VERIFY) && defined(WOLFSSL_KEY_GEN) && \
  13236. defined(HAVE_ED448_KEY_IMPORT)
  13237. ed448_key key;
  13238. int res = 1;
  13239. WOLFSSL_ENTER("wolfSSL_ED448_verify");
  13240. /* Validate parameters. */
  13241. if ((pub == NULL) || (pubSz != ED448_PUB_KEY_SIZE) || (msg == NULL) ||
  13242. (sig == NULL) || (sigSz != ED448_SIG_SIZE)) {
  13243. WOLFSSL_MSG("Bad arguments");
  13244. res = 0;
  13245. }
  13246. /* Initialize Ed448 key. */
  13247. if (res && (wc_ed448_init(&key) != 0)) {
  13248. WOLFSSL_MSG("wc_curve448_init failed");
  13249. res = 0;
  13250. }
  13251. if (res) {
  13252. /* Import public key. */
  13253. int ret = wc_ed448_import_public(pub, pubSz, &key);
  13254. if (ret != 0) {
  13255. WOLFSSL_MSG("wc_ed448_import_public failed");
  13256. res = 0;
  13257. }
  13258. if (res) {
  13259. int check = 0;
  13260. /* Verify signature with message and public key - no context. */
  13261. ret = wc_ed448_verify_msg((byte*)sig, sigSz, msg, msgSz, &check,
  13262. &key, NULL, 0);
  13263. /* Check for errors in verification process. */
  13264. if (ret != 0) {
  13265. WOLFSSL_MSG("wc_ed448_verify_msg failed");
  13266. res = 0;
  13267. }
  13268. /* Check signature is valid. */
  13269. else if (!check) {
  13270. WOLFSSL_MSG("wc_ed448_verify_msg failed (signature invalid)");
  13271. res = 0;
  13272. }
  13273. }
  13274. wc_ed448_free(&key);
  13275. }
  13276. return res;
  13277. #else
  13278. #if !defined(HAVE_ED448_VERIFY)
  13279. WOLFSSL_MSG("No ED448 verify built in");
  13280. #elif !defined(WOLFSSL_KEY_GEN)
  13281. WOLFSSL_MSG("No Key Gen built in");
  13282. #elif !defined(HAVE_ED448_KEY_IMPORT)
  13283. WOLFSSL_MSG("No ED448 Key import built in");
  13284. #endif
  13285. (void)msg;
  13286. (void)msgSz;
  13287. (void)pub;
  13288. (void)pubSz;
  13289. (void)sig;
  13290. (void)sigSz;
  13291. return 0;
  13292. #endif /* HAVE_ED448_VERIFY && WOLFSSL_KEY_GEN && HAVE_ED448_KEY_IMPORT */
  13293. }
  13294. #endif /* OPENSSL_EXTRA && HAVE_ED448 */
  13295. /*******************************************************************************
  13296. * END OF ED448 API
  13297. ******************************************************************************/
  13298. /*******************************************************************************
  13299. * START OF GENERIC PUBLIC KEY PEM APIs
  13300. ******************************************************************************/
  13301. #ifdef OPENSSL_EXTRA
  13302. /* Sets default callback password for PEM.
  13303. *
  13304. * @param [out] buf Buffer to hold password.
  13305. * @param [in] num Number of characters in buffer.
  13306. * @param [in] rwFlag Read/write flag. Ignored.
  13307. * @param [in] userData User data - assumed to be default password.
  13308. * @return Password size on success.
  13309. * @return 0 on failure.
  13310. */
  13311. int wolfSSL_PEM_def_callback(char* buf, int num, int rwFlag, void* userData)
  13312. {
  13313. int sz = 0;
  13314. WOLFSSL_ENTER("wolfSSL_PEM_def_callback");
  13315. (void)rwFlag;
  13316. /* We assume that the user passes a default password as userdata */
  13317. if ((buf != NULL) && (userData != NULL)) {
  13318. sz = (int)XSTRLEN((const char*)userData);
  13319. sz = min(sz, num);
  13320. XMEMCPY(buf, userData, sz);
  13321. }
  13322. else {
  13323. WOLFSSL_MSG("Error, default password cannot be created.");
  13324. }
  13325. return sz;
  13326. }
  13327. #ifndef NO_BIO
  13328. /* Writes a public key to a WOLFSSL_BIO encoded in PEM format.
  13329. *
  13330. * @param [in] bio BIO to write to.
  13331. * @param [in] key Public key to write in PEM format.
  13332. * @return 1 on success.
  13333. * @return 0 on failure.
  13334. */
  13335. int wolfSSL_PEM_write_bio_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key)
  13336. {
  13337. int ret = 0;
  13338. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PUBKEY");
  13339. if ((bio != NULL) && (key != NULL)) {
  13340. switch (key->type) {
  13341. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)
  13342. case EVP_PKEY_RSA:
  13343. ret = wolfSSL_PEM_write_bio_RSA_PUBKEY(bio, key->rsa);
  13344. break;
  13345. #endif /* WOLFSSL_KEY_GEN && !NO_RSA */
  13346. #if !defined(NO_DSA) && !defined(HAVE_SELFTEST) && \
  13347. (defined(WOLFSSL_KEY_GEN) || defined(WOLFSSL_CERT_GEN))
  13348. case EVP_PKEY_DSA:
  13349. ret = wolfSSL_PEM_write_bio_DSA_PUBKEY(bio, key->dsa);
  13350. break;
  13351. #endif /* !NO_DSA && !HAVE_SELFTEST && (WOLFSSL_KEY_GEN || WOLFSSL_CERT_GEN) */
  13352. #if defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT) && \
  13353. defined(WOLFSSL_KEY_GEN)
  13354. case EVP_PKEY_EC:
  13355. ret = wolfSSL_PEM_write_bio_EC_PUBKEY(bio, key->ecc);
  13356. break;
  13357. #endif /* HAVE_ECC && HAVE_ECC_KEY_EXPORT */
  13358. #if !defined(NO_DH) && (defined(WOLFSSL_QT) || defined(OPENSSL_ALL))
  13359. case EVP_PKEY_DH:
  13360. /* DH public key not supported. */
  13361. WOLFSSL_MSG("Writing DH PUBKEY not supported!");
  13362. break;
  13363. #endif /* !NO_DH && (WOLFSSL_QT || OPENSSL_ALL) */
  13364. default:
  13365. /* Key type not supported. */
  13366. WOLFSSL_MSG("Unknown Key type!");
  13367. break;
  13368. }
  13369. }
  13370. return ret;
  13371. }
  13372. /* Writes a private key to a WOLFSSL_BIO encoded in PEM format.
  13373. *
  13374. * @param [in] bio BIO to write to.
  13375. * @param [in] key Public key to write in PEM format.
  13376. * @param [in] cipher Encryption cipher to use.
  13377. * @param [in] passwd Password to use when encrypting.
  13378. * @param [in] len Length of password.
  13379. * @param [in] cb Password callback.
  13380. * @param [in] arg Password callback arguement.
  13381. * @return 1 on success.
  13382. * @return 0 on failure.
  13383. */
  13384. int wolfSSL_PEM_write_bio_PrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key,
  13385. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  13386. wc_pem_password_cb* cb, void* arg)
  13387. {
  13388. int ret = 1;
  13389. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_PrivateKey");
  13390. (void)cipher;
  13391. (void)passwd;
  13392. (void)len;
  13393. (void)cb;
  13394. (void)arg;
  13395. /* Validate parameters. */
  13396. if ((bio == NULL) || (key == NULL)) {
  13397. WOLFSSL_MSG("Bad Function Arguments");
  13398. ret = 0;
  13399. }
  13400. if (ret == 1) {
  13401. #ifdef WOLFSSL_KEY_GEN
  13402. switch (key->type) {
  13403. #ifndef NO_RSA
  13404. case EVP_PKEY_RSA:
  13405. /* Write using RSA specific API. */
  13406. ret = wolfSSL_PEM_write_bio_RSAPrivateKey(bio, key->rsa,
  13407. cipher, passwd, len, cb, arg);
  13408. break;
  13409. #endif
  13410. #ifndef NO_DSA
  13411. case EVP_PKEY_DSA:
  13412. /* Write using DSA specific API. */
  13413. ret = wolfSSL_PEM_write_bio_DSAPrivateKey(bio, key->dsa,
  13414. cipher, passwd, len, cb, arg);
  13415. break;
  13416. #endif
  13417. #ifdef HAVE_ECC
  13418. case EVP_PKEY_EC:
  13419. #if defined(HAVE_ECC_KEY_EXPORT)
  13420. /* Write using EC specific API. */
  13421. ret = wolfSSL_PEM_write_bio_ECPrivateKey(bio, key->ecc,
  13422. cipher, passwd, len, cb, arg);
  13423. #else
  13424. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13425. key->pkey_sz, bio, EC_PRIVATEKEY_TYPE);
  13426. #endif
  13427. break;
  13428. #endif
  13429. #ifndef NO_DH
  13430. case EVP_PKEY_DH:
  13431. /* Write using generic API with DH type. */
  13432. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr,
  13433. key->pkey_sz, bio, DH_PRIVATEKEY_TYPE);
  13434. break;
  13435. #endif
  13436. default:
  13437. WOLFSSL_MSG("Unknown Key type!");
  13438. ret = 0;
  13439. break;
  13440. }
  13441. #else
  13442. int type = 0;
  13443. switch (key->type) {
  13444. #ifndef NO_DSA
  13445. case EVP_PKEY_DSA:
  13446. type = DSA_PRIVATEKEY_TYPE;
  13447. break;
  13448. #endif
  13449. #ifdef HAVE_ECC
  13450. case EVP_PKEY_EC:
  13451. type = ECC_PRIVATEKEY_TYPE;
  13452. break;
  13453. #endif
  13454. #ifndef NO_DH
  13455. case EVP_PKEY_DH:
  13456. type = DH_PRIVATEKEY_TYPE;
  13457. break;
  13458. #endif
  13459. #ifndef NO_RSA
  13460. case EVP_PKEY_RSA:
  13461. type = PRIVATEKEY_TYPE;
  13462. break;
  13463. #endif
  13464. default:
  13465. ret = 0;
  13466. break;
  13467. }
  13468. if (ret == 1) {
  13469. /* Write using generic API with generic type. */
  13470. ret = der_write_to_bio_as_pem((byte*)key->pkey.ptr, key->pkey_sz,
  13471. bio, type);
  13472. }
  13473. #endif
  13474. }
  13475. return ret;
  13476. }
  13477. #endif /* !NO_BIO */
  13478. #ifndef NO_BIO
  13479. /* Create a private key object from the data in the BIO.
  13480. *
  13481. * @param [in] bio BIO to read from.
  13482. * @param [in, out] key Public key object. Object used if passed in.
  13483. * @param [in] cb Password callback.
  13484. * @param [in] arg Password callback arguement.
  13485. * @return A WOLFSSL_EVP_PKEY object on success.
  13486. * @return NULL on failure.
  13487. */
  13488. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PUBKEY(WOLFSSL_BIO* bio,
  13489. WOLFSSL_EVP_PKEY **key, wc_pem_password_cb *cb, void *arg)
  13490. {
  13491. int err = 0;
  13492. WOLFSSL_EVP_PKEY* pkey = NULL;
  13493. DerBuffer* der = NULL;
  13494. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PUBKEY");
  13495. if (bio == NULL) {
  13496. err = 1;
  13497. }
  13498. /* Read the PEM public key from the BIO and convert to DER. */
  13499. if ((!err) && (pem_read_bio_key(bio, cb, arg, PUBLICKEY_TYPE, NULL,
  13500. &der) < 0)) {
  13501. err = 1;
  13502. }
  13503. if (!err) {
  13504. const unsigned char* ptr = der->buffer;
  13505. /* Use key passed in if set. */
  13506. if ((key != NULL) && (*key != NULL)) {
  13507. pkey = *key;
  13508. }
  13509. /* Convert DER data to a public key object. */
  13510. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13511. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13512. pkey = NULL;
  13513. err = 1;
  13514. }
  13515. }
  13516. /* Return the key if possible. */
  13517. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13518. *key = pkey;
  13519. }
  13520. /* Dispose of the DER encoding. */
  13521. FreeDer(&der);
  13522. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PUBKEY", 0);
  13523. return pkey;
  13524. }
  13525. /* Create a private key object from the data in the BIO.
  13526. *
  13527. * @param [in] bio BIO to read from.
  13528. * @param [in, out] key Private key object. Object used if passed in.
  13529. * @param [in] cb Password callback.
  13530. * @param [in] arg Password callback arguement.
  13531. * @return A WOLFSSL_EVP_PKEY object on success.
  13532. * @return NULL on failure.
  13533. */
  13534. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_bio_PrivateKey(WOLFSSL_BIO* bio,
  13535. WOLFSSL_EVP_PKEY** key, wc_pem_password_cb* cb, void* arg)
  13536. {
  13537. int err = 0;
  13538. WOLFSSL_EVP_PKEY* pkey = NULL;
  13539. DerBuffer* der = NULL;
  13540. int keyFormat = 0;
  13541. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_PrivateKey");
  13542. /* Validate parameters. */
  13543. if (bio == NULL) {
  13544. err = 1;
  13545. }
  13546. /* Read the PEM private key from the BIO and convert to DER. */
  13547. if ((!err) && (pem_read_bio_key(bio, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13548. &der) < 0)) {
  13549. err = 1;
  13550. }
  13551. if (!err) {
  13552. const unsigned char* ptr = der->buffer;
  13553. int type = -1;
  13554. /* Set key type based on format returned. */
  13555. switch (keyFormat) {
  13556. /* No key format set - default to RSA. */
  13557. case 0:
  13558. case RSAk:
  13559. type = EVP_PKEY_RSA;
  13560. break;
  13561. case DSAk:
  13562. type = EVP_PKEY_DSA;
  13563. break;
  13564. case ECDSAk:
  13565. type = EVP_PKEY_EC;
  13566. break;
  13567. case DHk:
  13568. type = EVP_PKEY_DH;
  13569. break;
  13570. default:
  13571. break;
  13572. }
  13573. /* Use key passed in if set. */
  13574. if ((key != NULL) && (*key != NULL)) {
  13575. pkey = *key;
  13576. }
  13577. /* Convert DER data to a private key object. */
  13578. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13579. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13580. pkey = NULL;
  13581. err = 1;
  13582. }
  13583. }
  13584. /* Return the key if possible. */
  13585. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13586. *key = pkey;
  13587. }
  13588. /* Dispose of the DER encoding. */
  13589. FreeDer(&der);
  13590. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_PrivateKey", err);
  13591. return pkey;
  13592. }
  13593. #endif /* !NO_BIO */
  13594. #if !defined(NO_FILESYSTEM)
  13595. /* Create a private key object from the data in a file.
  13596. *
  13597. * @param [in] fp File pointer.
  13598. * @param [in, out] key Public key object. Object used if passed in.
  13599. * @param [in] cb Password callback.
  13600. * @param [in] arg Password callback arguement.
  13601. * @return A WOLFSSL_EVP_PKEY object on success.
  13602. * @return NULL on failure.
  13603. */
  13604. WOLFSSL_EVP_PKEY *wolfSSL_PEM_read_PUBKEY(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13605. wc_pem_password_cb *cb, void *arg)
  13606. {
  13607. int err = 0;
  13608. WOLFSSL_EVP_PKEY* pkey = NULL;
  13609. DerBuffer* der = NULL;
  13610. WOLFSSL_ENTER("wolfSSL_PEM_read_PUBKEY");
  13611. /* Validate parameters. */
  13612. if (fp == XBADFILE) {
  13613. err = 1;
  13614. }
  13615. /* Read the PEM public key from the file and convert to DER. */
  13616. if ((!err) && ((pem_read_file_key(fp, cb, arg, PUBLICKEY_TYPE, NULL,
  13617. &der) < 0) || (der == NULL))) {
  13618. err = 1;
  13619. }
  13620. if (!err) {
  13621. const unsigned char* ptr = der->buffer;
  13622. /* Use key passed in if set. */
  13623. if ((key != NULL) && (*key != NULL)) {
  13624. pkey = *key;
  13625. }
  13626. /* Convert DER data to a public key object. */
  13627. if (wolfSSL_d2i_PUBKEY(&pkey, &ptr, der->length) == NULL) {
  13628. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13629. pkey = NULL;
  13630. err = 1;
  13631. }
  13632. }
  13633. /* Return the key if possible. */
  13634. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13635. *key = pkey;
  13636. }
  13637. /* Dispose of the DER encoding. */
  13638. FreeDer(&der);
  13639. WOLFSSL_LEAVE("wolfSSL_PEM_read_PUBKEY", 0);
  13640. return pkey;
  13641. }
  13642. #ifndef NO_CERTS
  13643. /* Create a private key object from the data in a file.
  13644. *
  13645. * @param [in] fp File pointer.
  13646. * @param [in, out] key Private key object. Object used if passed in.
  13647. * @param [in] cb Password callback.
  13648. * @param [in] arg Password callback arguement.
  13649. * @return A WOLFSSL_EVP_PKEY object on success.
  13650. * @return NULL on failure.
  13651. */
  13652. WOLFSSL_EVP_PKEY* wolfSSL_PEM_read_PrivateKey(XFILE fp, WOLFSSL_EVP_PKEY **key,
  13653. wc_pem_password_cb *cb, void *arg)
  13654. {
  13655. int err = 0;
  13656. WOLFSSL_EVP_PKEY* pkey = NULL;
  13657. DerBuffer* der = NULL;
  13658. int keyFormat = 0;
  13659. WOLFSSL_ENTER("wolfSSL_PEM_read_PrivateKey");
  13660. /* Validate parameters. */
  13661. if (fp == XBADFILE) {
  13662. err = 1;
  13663. }
  13664. /* Read the PEM private key from the file and convert to DER. */
  13665. if ((!err) && (pem_read_file_key(fp, cb, arg, PRIVATEKEY_TYPE, &keyFormat,
  13666. &der)) < 0) {
  13667. err = 1;
  13668. }
  13669. if (!err) {
  13670. const unsigned char* ptr = der->buffer;
  13671. int type = -1;
  13672. /* Set key type based on format returned. */
  13673. switch (keyFormat) {
  13674. /* No key format set - default to RSA. */
  13675. case 0:
  13676. case RSAk:
  13677. type = EVP_PKEY_RSA;
  13678. break;
  13679. case DSAk:
  13680. type = EVP_PKEY_DSA;
  13681. break;
  13682. case ECDSAk:
  13683. type = EVP_PKEY_EC;
  13684. break;
  13685. case DHk:
  13686. type = EVP_PKEY_DH;
  13687. break;
  13688. default:
  13689. break;
  13690. }
  13691. /* Use key passed in if set. */
  13692. if ((key != NULL) && (*key != NULL)) {
  13693. pkey = *key;
  13694. }
  13695. /* Convert DER data to a private key object. */
  13696. if (wolfSSL_d2i_PrivateKey(type, &pkey, &ptr, der->length) == NULL) {
  13697. WOLFSSL_MSG("Error loading DER buffer into WOLFSSL_EVP_PKEY");
  13698. pkey = NULL;
  13699. err = 1;
  13700. }
  13701. }
  13702. /* Return the key if possible. */
  13703. if ((!err) && (key != NULL) && (pkey != NULL)) {
  13704. *key = pkey;
  13705. }
  13706. /* Dispose of the DER encoding. */
  13707. FreeDer(&der);
  13708. WOLFSSL_LEAVE("wolfSSL_PEM_read_PrivateKey", 0);
  13709. return pkey;
  13710. }
  13711. #endif /* !NO_CERTS */
  13712. #endif /* !NO_FILESYSTEM */
  13713. #ifndef NO_CERTS
  13714. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  13715. #define PEM_BEGIN "-----BEGIN "
  13716. #define PEM_BEGIN_SZ 11
  13717. #define PEM_END "-----END "
  13718. #define PEM_END_SZ 9
  13719. #define PEM_HDR_FIN "-----"
  13720. #define PEM_HDR_FIN_SZ 5
  13721. #define PEM_HDR_FIN_EOL_NEWLINE "-----\n"
  13722. #define PEM_HDR_FIN_EOL_NULL_TERM "-----\0"
  13723. #define PEM_HDR_FIN_EOL_SZ 6
  13724. /* Find strings and return middle offsets.
  13725. *
  13726. * Find first string in pem as a prefix and then locate second string as a
  13727. * postfix.
  13728. * len returning with 0 indicates not found.
  13729. *
  13730. * @param [in] pem PEM data.
  13731. * @param [in] pemLen Length of PEM data.
  13732. * @param [in] idx Current index.
  13733. * @param [in] prefix First string to find.
  13734. * @param [in] postfix Second string to find after first.
  13735. * @param [out] start Start index of data between strings.
  13736. * @param [out] len Length of data between strings.
  13737. */
  13738. static void pem_find_pattern(char* pem, int pemLen, int idx, const char* prefix,
  13739. const char* postfix, int* start, int* len)
  13740. {
  13741. int prefixLen = (int)XSTRLEN(prefix);
  13742. int postfixLen = (int)XSTRLEN(postfix);
  13743. *start = *len = 0;
  13744. /* Find prefix part. */
  13745. for (; idx < pemLen - prefixLen; idx++) {
  13746. if ((pem[idx] == prefix[0]) &&
  13747. (XMEMCMP(pem + idx, prefix, prefixLen) == 0)) {
  13748. idx += prefixLen;
  13749. *start = idx;
  13750. break;
  13751. }
  13752. }
  13753. /* Find postfix part. */
  13754. for (; idx < pemLen - postfixLen; idx++) {
  13755. if ((pem[idx] == postfix[0]) &&
  13756. (XMEMCMP(pem + idx, postfix, postfixLen) == 0)) {
  13757. *len = idx - *start;
  13758. break;
  13759. }
  13760. }
  13761. }
  13762. /* Parse out content type name, any encryption headers and DER encoding.
  13763. *
  13764. * @param [in] pem PEM data.
  13765. * @param [in] pemLen Length of PEM data.
  13766. * @param [out] name Name of content type.
  13767. * @param [out] header Encryption headers.
  13768. * @param [out] data DER encoding from PEM.
  13769. * @param [out] len Length of DER data.
  13770. * @return 0 on success.
  13771. * @return MEMORY_E when dynamic memory allocation fails.
  13772. * @return ASN_NO_PEM_HEADER when no header found or different names found.
  13773. */
  13774. static int pem_read_data(char* pem, int pemLen, char **name, char **header,
  13775. unsigned char **data, long *len)
  13776. {
  13777. int ret = 0;
  13778. int start;
  13779. int nameLen;
  13780. int startHdr = 0;
  13781. int hdrLen = 0;
  13782. int startEnd = 0;
  13783. int endLen;
  13784. *name = NULL;
  13785. *header = NULL;
  13786. /* Find header. */
  13787. pem_find_pattern(pem, pemLen, 0, PEM_BEGIN, PEM_HDR_FIN, &start, &nameLen);
  13788. /* Allocate memory for header name. */
  13789. *name = (char*)XMALLOC(nameLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13790. if (*name == NULL) {
  13791. ret = MEMORY_E;
  13792. }
  13793. if (ret == 0) {
  13794. /* Put in header name. */
  13795. (*name)[nameLen] = '\0';
  13796. if (nameLen == 0) {
  13797. ret = ASN_NO_PEM_HEADER;
  13798. }
  13799. else {
  13800. XMEMCPY(*name, pem + start, nameLen);
  13801. }
  13802. }
  13803. if (ret == 0) {
  13804. /* Find encryption headers after header. */
  13805. start += nameLen + PEM_HDR_FIN_SZ;
  13806. pem_find_pattern(pem, pemLen, start, "\n", "\n\n", &startHdr, &hdrLen);
  13807. if (hdrLen > 0) {
  13808. /* Include first of two '\n' characters. */
  13809. hdrLen++;
  13810. }
  13811. /* Allocate memory for encryption header string. */
  13812. *header = (char*)XMALLOC(hdrLen + 1, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13813. if (*header == NULL) {
  13814. ret = MEMORY_E;
  13815. }
  13816. }
  13817. if (ret == 0) {
  13818. /* Put in encryption header string. */
  13819. (*header)[hdrLen] = '\0';
  13820. if (hdrLen > 0) {
  13821. XMEMCPY(*header, pem + startHdr, hdrLen);
  13822. start = startHdr + hdrLen + 1;
  13823. }
  13824. /* Find footer. */
  13825. pem_find_pattern(pem, pemLen, start, PEM_END, PEM_HDR_FIN, &startEnd,
  13826. &endLen);
  13827. /* Validate header name and footer name are the same. */
  13828. if ((endLen != nameLen) ||
  13829. (XMEMCMP(*name, pem + startEnd, nameLen) != 0)) {
  13830. ret = ASN_NO_PEM_HEADER;
  13831. }
  13832. }
  13833. if (ret == 0) {
  13834. unsigned char* der = (unsigned char*)pem;
  13835. word32 derLen;
  13836. /* Convert PEM body to DER. */
  13837. derLen = startEnd - PEM_END_SZ - start;
  13838. ret = Base64_Decode(der + start, derLen, der, &derLen);
  13839. if (ret == 0) {
  13840. /* Return the DER data. */
  13841. *data = der;
  13842. *len = derLen;
  13843. }
  13844. }
  13845. return ret;
  13846. }
  13847. /* Encode the DER data in PEM foramt into a newly allocated buffer.
  13848. *
  13849. * @param [in] name Header/footer name.
  13850. * @param [in] header Encryption header.
  13851. * @param [in] data DER data.
  13852. * @param [in] len Length of DER data.
  13853. * @param [out] pemOut PEM encoded data.
  13854. * @param [out] pemOutLen Length of PEM encoded data.
  13855. * @return 0 on success.
  13856. * @return MEMORY_E when dynamic memory allocation fails.
  13857. */
  13858. static int pem_write_data(const char *name, const char *header,
  13859. const unsigned char *data, long len, char** pemOut, word32* pemOutLen)
  13860. {
  13861. int ret = 0;
  13862. int nameLen;
  13863. int headerLen;
  13864. char* pem = NULL;
  13865. word32 pemLen;
  13866. word32 derLen = (word32)len;
  13867. byte* p;
  13868. nameLen = (int)XSTRLEN(name);
  13869. headerLen = (int)XSTRLEN(header);
  13870. /* DER encode for PEM. */
  13871. pemLen = (derLen + 2) / 3 * 4;
  13872. pemLen += (pemLen + 63) / 64;
  13873. /* Header */
  13874. pemLen += PEM_BEGIN_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  13875. if (headerLen > 0) {
  13876. /* Encryption lines plus extra carriage return. */
  13877. pemLen += headerLen + 1;
  13878. }
  13879. /* Trailer */
  13880. pemLen += PEM_END_SZ + nameLen + PEM_HDR_FIN_EOL_SZ;
  13881. pem = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13882. if (pem == NULL) {
  13883. ret = MEMORY_E;
  13884. }
  13885. p = (byte*)pem;
  13886. if (ret == 0) {
  13887. /* Add header. */
  13888. XMEMCPY(p, PEM_BEGIN, PEM_BEGIN_SZ);
  13889. p += PEM_BEGIN_SZ;
  13890. XMEMCPY(p, name, nameLen);
  13891. p += nameLen;
  13892. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  13893. p += PEM_HDR_FIN_EOL_SZ;
  13894. if (headerLen > 0) {
  13895. /* Add encryption header. */
  13896. XMEMCPY(p, header, headerLen);
  13897. p += headerLen;
  13898. /* Blank line after a header and before body. */
  13899. *(p++) = '\n';
  13900. }
  13901. /* Add DER data as PEM. */
  13902. pemLen -= (word32)((size_t)p - (size_t)pem);
  13903. ret = Base64_Encode(data, derLen, p, &pemLen);
  13904. }
  13905. if (ret == 0) {
  13906. p += pemLen;
  13907. /* Add trailer. */
  13908. XMEMCPY(p, PEM_END, PEM_END_SZ);
  13909. p += PEM_END_SZ;
  13910. XMEMCPY(p, name, nameLen);
  13911. p += nameLen;
  13912. XMEMCPY(p, PEM_HDR_FIN_EOL_NEWLINE, PEM_HDR_FIN_EOL_SZ);
  13913. p += PEM_HDR_FIN_EOL_SZ;
  13914. /* Return buffer and length of data. */
  13915. *pemOut = pem;
  13916. *pemOutLen = (word32)((size_t)p - (size_t)pem);
  13917. }
  13918. return ret;
  13919. }
  13920. #endif /* !NO_BIO || !NO_FILESYSTEM */
  13921. #ifndef NO_BIO
  13922. /* Read PEM encoded data from a BIO.
  13923. *
  13924. * Reads the entire contents in.
  13925. *
  13926. * @param [in] bio BIO to read from.
  13927. * @param [out] name Name of content type.
  13928. * @param [out] header Encryption headers.
  13929. * @param [out] data DER encoding from PEM.
  13930. * @param [out] len Length of DER data.
  13931. * @return 1 on success.
  13932. * @return 0 on failure.
  13933. */
  13934. int wolfSSL_PEM_read_bio(WOLFSSL_BIO* bio, char **name, char **header,
  13935. unsigned char **data, long *len)
  13936. {
  13937. int res = 1;
  13938. char* pem = NULL;
  13939. int pemLen = 0;
  13940. int memAlloced = 1;
  13941. /* Validate parameters. */
  13942. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL) ||
  13943. (len == NULL)) {
  13944. res = 0;
  13945. }
  13946. /* Load all the data from the BIO. */
  13947. if ((res == 1) && (wolfssl_read_bio(bio, &pem, &pemLen, &memAlloced) !=
  13948. 0)) {
  13949. res = 0;
  13950. }
  13951. if ((res == 1) && (!memAlloced)) {
  13952. /* Need to return allocated memory - make sure it is allocated. */
  13953. char* p = (char*)XMALLOC(pemLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13954. if (p == NULL) {
  13955. res = 0;
  13956. }
  13957. else {
  13958. /* Copy the data into new buffer. */
  13959. XMEMCPY(p, pem, pemLen);
  13960. pem = p;
  13961. }
  13962. }
  13963. /* Read the PEM data. */
  13964. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  13965. 0)) {
  13966. /* Dispose of any allocated memory. */
  13967. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13968. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13969. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  13970. *name = NULL;
  13971. *header = NULL;
  13972. res = 0;
  13973. }
  13974. return res;
  13975. }
  13976. /* Encode the DER data in PEM foramt into a BIO.
  13977. *
  13978. * @param [in] bio BIO to write to.
  13979. * @param [in] name Header/footer name.
  13980. * @param [in] header Encryption header.
  13981. * @param [in] data DER data.
  13982. * @param [in] len Length of DER data.
  13983. * @return 0 on success.
  13984. * @return MEMORY_E when dynamic memory allocation fails.
  13985. */
  13986. int wolfSSL_PEM_write_bio(WOLFSSL_BIO* bio, const char *name,
  13987. const char *header, const unsigned char *data, long len)
  13988. {
  13989. int err = 0;
  13990. char* pem = NULL;
  13991. word32 pemLen = 0;
  13992. /* Validate parameters. */
  13993. if ((bio == NULL) || (name == NULL) || (header == NULL) || (data == NULL)) {
  13994. err = 1;
  13995. }
  13996. /* Encode into a buffer. */
  13997. if ((!err) && (pem_write_data(name, header, data, len, &pem, &pemLen) !=
  13998. 0)) {
  13999. pemLen = 0;
  14000. err = 1;
  14001. }
  14002. /* Write PEM into BIO. */
  14003. if ((!err) && (wolfSSL_BIO_write(bio, pem, pemLen) != (int)pemLen)) {
  14004. pemLen = 0;
  14005. }
  14006. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14007. return pemLen;
  14008. }
  14009. #endif /* !NO_BIO */
  14010. #if !defined(NO_FILESYSTEM)
  14011. /* Read PEM encoded data from a file.
  14012. *
  14013. * Reads the entire contents in.
  14014. *
  14015. * @param [in] bio BIO to read from.
  14016. * @param [out] name Name of content type.
  14017. * @param [out] header Encryption headers.
  14018. * @param [out] data DER encoding from PEM.
  14019. * @param [out] len Length of DER data.
  14020. * @return 1 on success.
  14021. * @return 0 on failure.
  14022. */
  14023. int wolfSSL_PEM_read(XFILE fp, char **name, char **header, unsigned char **data,
  14024. long *len)
  14025. {
  14026. int res = 1;
  14027. char* pem = NULL;
  14028. int pemLen = 0;
  14029. /* Validate parameters. */
  14030. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14031. (data == NULL) || (len == NULL)) {
  14032. res = 0;
  14033. }
  14034. /* Load all the data from the file. */
  14035. if ((res == 1) && (wolfssl_read_file(fp, &pem, &pemLen) != 0)) {
  14036. res = 0;
  14037. }
  14038. /* Read the PEM data. */
  14039. if ((res == 1) && (pem_read_data(pem, pemLen, name, header, data, len) !=
  14040. 0)) {
  14041. /* Dispose of any allocated memory. */
  14042. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14043. XFREE(*name, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14044. XFREE(*header, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14045. *name = NULL;
  14046. *header = NULL;
  14047. res = 0;
  14048. }
  14049. return res;
  14050. }
  14051. /* Encode the DER data in PEM foramt into a file.
  14052. *
  14053. * @param [in] fp File pointer to write to.
  14054. * @param [in] name Header/footer name.
  14055. * @param [in] header Encryption header.
  14056. * @param [in] data DER data.
  14057. * @param [in] len Length of DER data.
  14058. * @return 0 on success.
  14059. * @return MEMORY_E when dynamic memory allocation fails.
  14060. */
  14061. int wolfSSL_PEM_write(XFILE fp, const char *name, const char *header,
  14062. const unsigned char *data, long len)
  14063. {
  14064. int err = 0;
  14065. char* pem = NULL;
  14066. word32 pemLen = 0;
  14067. /* Validate parameters. */
  14068. if ((fp == XBADFILE) || (name == NULL) || (header == NULL) ||
  14069. (data == NULL)) {
  14070. err = 1;
  14071. }
  14072. /* Encode into a buffer. */
  14073. if ((!err) && (pem_write_data(name, header, data, len, &pem, &pemLen) !=
  14074. 0)) {
  14075. pemLen = 0;
  14076. err = 1;
  14077. }
  14078. /* Write PEM to a file. */
  14079. if ((!err) && (XFWRITE(pem, 1, pemLen, fp) != pemLen)) {
  14080. pemLen = 0;
  14081. }
  14082. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14083. return pemLen;
  14084. }
  14085. #endif
  14086. /* Get EVP cipher info from encryption header string.
  14087. *
  14088. * @param [in] header Encryption header.
  14089. * @param [out] cipher EVP Cipher info.
  14090. * @return 1 on success.
  14091. * @return 0 on failure.
  14092. */
  14093. int wolfSSL_PEM_get_EVP_CIPHER_INFO(const char* header, EncryptedInfo* cipher)
  14094. {
  14095. int res = 1;
  14096. /* Validate parameters. */
  14097. if ((header == NULL) || (cipher == NULL)) {
  14098. res = 0;
  14099. }
  14100. if (res == 1) {
  14101. XMEMSET(cipher, 0, sizeof(*cipher));
  14102. if (wc_EncryptedInfoParse(cipher, &header, XSTRLEN(header)) != 0) {
  14103. res = 0;
  14104. }
  14105. }
  14106. return res;
  14107. }
  14108. /* Apply cipher to DER data.
  14109. *
  14110. * @param [in] cipher EVP cipher info.
  14111. * @param [in, out] data On in, encrypted DER data.
  14112. * On out, unencrypted DER data.
  14113. * @param [in, out] len On in, length of encrypted DER data.
  14114. * On out, length of unencrypted DER data.
  14115. * @param [in] cb Password callback.
  14116. * @param [in] ctx Context for password callback.
  14117. * @return 1 on success.
  14118. * @return 0 on failure.
  14119. */
  14120. int wolfSSL_PEM_do_header(EncryptedInfo* cipher, unsigned char* data, long* len,
  14121. wc_pem_password_cb* cb, void* ctx)
  14122. {
  14123. int ret = 1;
  14124. char password[NAME_SZ];
  14125. int passwordSz = 0;
  14126. /* Validate parameters. */
  14127. if ((cipher == NULL) || (data == NULL) || (len == NULL) || (cb == NULL)) {
  14128. ret = 0;
  14129. }
  14130. if (ret == 1) {
  14131. /* Get password and length. */
  14132. passwordSz = cb(password, sizeof(password), PEM_PASS_READ, ctx);
  14133. if (passwordSz < 0) {
  14134. ret = 0;
  14135. }
  14136. }
  14137. if (ret == 1) {
  14138. /* Decrypt the data using password and MD5. */
  14139. if (wc_BufferKeyDecrypt(cipher, data, (word32)*len, (byte*)password,
  14140. passwordSz, WC_MD5) != 0) {
  14141. ret = WOLFSSL_FAILURE;
  14142. }
  14143. }
  14144. if (passwordSz > 0) {
  14145. /* Ensure password is erased from memory. */
  14146. ForceZero(password, passwordSz);
  14147. }
  14148. return ret;
  14149. }
  14150. #endif /* !NO_CERTS */
  14151. #endif /* OPENSSL_EXTRA */
  14152. #ifdef OPENSSL_ALL
  14153. #if !defined(NO_PWDBASED) && defined(HAVE_PKCS8)
  14154. #if !defined(NO_BIO) || (!defined(NO_FILESYSTEM) && \
  14155. !defined(NO_STDIO_FILESYSTEM))
  14156. /* Encrypt the key into a buffer using PKCS$8 and a password.
  14157. *
  14158. * @param [in] pkey Private key to encrypt.
  14159. * @param [in] enc EVP cipher.
  14160. * @param [in] passwd Password to encrypt with.
  14161. * @param [in] passwdSz Number of bytes in password.
  14162. * @param [in] key Buffer to hold encrypted key.
  14163. * @param [in, out] keySz On in, size of buffer in bytes.
  14164. * On out, size of encrypted key in bytes.
  14165. * @return 0 on success.
  14166. * @return BAD_FUNC_ARG when EVP cipher not supported.
  14167. */
  14168. static int pem_pkcs8_encrypt(WOLFSSL_EVP_PKEY* pkey,
  14169. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz, byte* key,
  14170. word32* keySz)
  14171. {
  14172. int ret;
  14173. WC_RNG rng;
  14174. /* Initialize a new random number generator. */
  14175. ret = wc_InitRng(&rng);
  14176. if (ret == 0) {
  14177. int encAlgId = 0;
  14178. /* Convert EVP cipher to a support encryption id. */
  14179. #ifndef NO_DES3
  14180. if (enc == EVP_DES_CBC) {
  14181. encAlgId = DESb;
  14182. }
  14183. else if (enc == EVP_DES_EDE3_CBC) {
  14184. encAlgId = DES3b;
  14185. }
  14186. else
  14187. #endif
  14188. #if !defined(NO_AES) && defined(HAVE_AES_CBC)
  14189. #ifdef WOLFSSL_AES_128
  14190. if (enc == EVP_AES_128_CBC) {
  14191. encAlgId = AES128CBCb;
  14192. }
  14193. else
  14194. #endif
  14195. #ifdef WOLFSSL_AES_256
  14196. if (enc == EVP_AES_256_CBC) {
  14197. encAlgId = AES256CBCb;
  14198. }
  14199. else
  14200. #endif
  14201. #endif
  14202. {
  14203. ret = BAD_FUNC_ARG;
  14204. }
  14205. if (ret == 0) {
  14206. /* Encrypt private into buffer. */
  14207. ret = TraditionalEnc((byte*)pkey->pkey.ptr, pkey->pkey_sz,
  14208. key, keySz, passwd, passwdSz, PKCS5, PBES2, encAlgId,
  14209. NULL, 0, WC_PKCS12_ITT_DEFAULT, &rng, NULL);
  14210. if (ret > 0) {
  14211. *keySz = ret;
  14212. }
  14213. }
  14214. /* Dispose of random number generator. */
  14215. wc_FreeRng(&rng);
  14216. }
  14217. return ret;
  14218. }
  14219. /* Encode private key in PKCS#8 format.
  14220. *
  14221. * @param [in] pkey Private key.
  14222. * @param [out] key Buffer to hold encoding.
  14223. * @param [in, out] keySz On in, size of buffer in bytes.
  14224. * @param On out, size of encoded key in bytes.
  14225. * @return 0 on success.
  14226. */
  14227. static int pem_pkcs8_encode(WOLFSSL_EVP_PKEY* pkey, byte* key, word32* keySz)
  14228. {
  14229. int ret = 0;
  14230. int algId;
  14231. const byte* curveOid;
  14232. word32 oidSz;
  14233. /* Get the details of the private key. */
  14234. #ifdef HAVE_ECC
  14235. if (pkey->type == EVP_PKEY_EC) {
  14236. /* ECC private and get curve OID information. */
  14237. algId = ECDSAk;
  14238. ret = wc_ecc_get_oid(pkey->ecc->group->curve_oid, &curveOid,
  14239. &oidSz);
  14240. }
  14241. else
  14242. #endif
  14243. if (pkey->type == EVP_PKEY_RSA) {
  14244. /* RSA private has no curve information. */
  14245. algId = RSAk;
  14246. curveOid = NULL;
  14247. oidSz = 0;
  14248. }
  14249. else {
  14250. ret = NOT_COMPILED_IN;
  14251. }
  14252. if (ret >= 0) {
  14253. /* Encode private key in PKCS#8 format. */
  14254. ret = wc_CreatePKCS8Key(key, keySz, (byte*)pkey->pkey.ptr,
  14255. pkey->pkey_sz, algId, curveOid, oidSz);
  14256. }
  14257. return ret;
  14258. }
  14259. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14260. *
  14261. * @param [out] pem Buffer holding PEM encoding.
  14262. * @param [out] pemSz Size of data in buffer in bytes.
  14263. * @param [in] pkey Private key to write.
  14264. * @param [in] enc Encryption information to use. May be NULL.
  14265. * @param [in] passwd Pasword to use when encrypting. May be NULL.
  14266. * @param [in] passwdSz Size of password in bytes.
  14267. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14268. * NULL.
  14269. * @param [in] ctx Context for password callback.
  14270. * @return Length of PEM encoding on success.
  14271. * @return 0 on failure.
  14272. */
  14273. static int pem_write_mem_pkcs8privatekey(byte** pem, int* pemSz,
  14274. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14275. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14276. {
  14277. int res = 1;
  14278. int ret = 0;
  14279. char password[NAME_SZ];
  14280. byte* key = NULL;
  14281. word32 keySz;
  14282. int type = PKCS8_PRIVATEKEY_TYPE;
  14283. /* Validate parameters. */
  14284. if (pkey == NULL) {
  14285. res = 0;
  14286. }
  14287. if (res == 1) {
  14288. /* Guestimate key size and PEM size. */
  14289. if (pem_pkcs8_encode(pkey, NULL, &keySz) != LENGTH_ONLY_E) {
  14290. res = 0;
  14291. }
  14292. }
  14293. if (res == 1) {
  14294. if (enc != NULL) {
  14295. /* Add on enough for extra DER data when encrypting. */
  14296. keySz += 128;
  14297. }
  14298. /* PEM encoding size from DER size. */
  14299. *pemSz = (keySz + 2) / 3 * 4;
  14300. *pemSz += (*pemSz + 63) / 64;
  14301. /* Header and footer. */
  14302. if (enc != NULL) {
  14303. /* Name is: 'ENCRYPTED PRIVATE KEY'. */
  14304. *pemSz += 74;
  14305. }
  14306. else {
  14307. /* Name is: 'PRIVATE KEY'. */
  14308. *pemSz += 54;
  14309. }
  14310. /* Allocate enough memory to hold PEM encoded encrypted key. */
  14311. *pem = (byte*)XMALLOC(*pemSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14312. if (*pem == NULL) {
  14313. res = 0;
  14314. }
  14315. else {
  14316. /* Use end of PEM buffer for key data. */
  14317. key = *pem + *pemSz - keySz;
  14318. }
  14319. }
  14320. if ((res == 1) && (enc != NULL)) {
  14321. /* Set type for PEM. */
  14322. type = PKCS8_ENC_PRIVATEKEY_TYPE;
  14323. if (passwd == NULL) {
  14324. /* Get the password by using callback. */
  14325. passwdSz = cb(password, sizeof(password), 1, ctx);
  14326. if (passwdSz < 0) {
  14327. res = 0;
  14328. }
  14329. passwd = password;
  14330. }
  14331. if (res == 1) {
  14332. /* Encrypt the private key. */
  14333. ret = pem_pkcs8_encrypt(pkey, enc, passwd, passwdSz, key, &keySz);
  14334. if (ret <= 0) {
  14335. res = 0;
  14336. }
  14337. }
  14338. /* Zeroize the password from memory. */
  14339. if ((password == passwd) && (passwdSz > 0)) {
  14340. ForceZero(password, passwdSz);
  14341. }
  14342. }
  14343. else if ((res == 1) && (enc == NULL)) {
  14344. /* Set type for PEM. */
  14345. type = PKCS8_PRIVATEKEY_TYPE;
  14346. /* Encode private key in PKCS#8 format. */
  14347. ret = pem_pkcs8_encode(pkey, key, &keySz);
  14348. if (ret < 0) {
  14349. res = 0;
  14350. }
  14351. }
  14352. if (res == 1) {
  14353. /* Encode PKCS#8 formatted key to PEM. */
  14354. ret = wc_DerToPemEx(key, keySz, *pem, *pemSz, NULL, type);
  14355. if (ret < 0) {
  14356. res = 0;
  14357. }
  14358. else {
  14359. *pemSz = ret;
  14360. }
  14361. }
  14362. /* Return appropriate return code. */
  14363. return (res == 0) ? 0 : ret;
  14364. }
  14365. #endif /* !NO_BIO || (!NO_FILESYSTEM && !NO_STDIO_FILESYSTEM) */
  14366. #ifndef NO_BIO
  14367. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14368. *
  14369. * TODO: OpenSSL returns 1 and 0 only.
  14370. *
  14371. * @param [in] bio BIO to write to.
  14372. * @param [in] pkey Private key to write.
  14373. * @param [in] enc Encryption information to use. May be NULL.
  14374. * @param [in] passwd Pasword to use when encrypting. May be NULL.
  14375. * @param [in] passwdSz Size of password in bytes.
  14376. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14377. * NULL.
  14378. * @param [in] ctx Context for password callback.
  14379. * @return Length of PEM encoding on success.
  14380. * @return 0 on failure.
  14381. */
  14382. int wolfSSL_PEM_write_bio_PKCS8PrivateKey(WOLFSSL_BIO* bio,
  14383. WOLFSSL_EVP_PKEY* pkey, const WOLFSSL_EVP_CIPHER* enc, char* passwd,
  14384. int passwdSz, wc_pem_password_cb* cb, void* ctx)
  14385. {
  14386. byte* pem = NULL;
  14387. int pemSz = 0;
  14388. int res = 1;
  14389. /* Validate parameters. */
  14390. if (bio == NULL) {
  14391. res = 0;
  14392. }
  14393. if (res == 1) {
  14394. /* Write private key to memory. */
  14395. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14396. passwdSz, cb, ctx);
  14397. }
  14398. /* Write encoded key to BIO. */
  14399. if ((res >= 1) && (wolfSSL_BIO_write(bio, pem, pemSz) != pemSz)) {
  14400. res = 0;
  14401. }
  14402. /* Dispose of dynamically allocated memory (pem and key). */
  14403. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14404. return res;
  14405. }
  14406. #endif /* !NO_BIO */
  14407. #if !defined(NO_FILESYSTEM) && !defined(NO_STDIO_FILESYSTEM)
  14408. /* Write PEM encoded, PKCS#8 formatted private key to BIO.
  14409. *
  14410. * TODO: OpenSSL returns 1 and 0 only.
  14411. *
  14412. * @param [in] f File pointer.
  14413. * @param [in] pkey Private key to write.
  14414. * @param [in] enc Encryption information to use. May be NULL.
  14415. * @param [in] passwd Pasword to use when encrypting. May be NULL.
  14416. * @param [in] passwdSz Size of password in bytes.
  14417. * @param [in] cb Password callback. Used when passwd is NULL. May be
  14418. * NULL.
  14419. * @param [in] ctx Context for password callback.
  14420. * @return Length of PEM encoding on success.
  14421. * @return 0 on failure.
  14422. */
  14423. int wolfSSL_PEM_write_PKCS8PrivateKey(XFILE f, WOLFSSL_EVP_PKEY* pkey,
  14424. const WOLFSSL_EVP_CIPHER* enc, char* passwd, int passwdSz,
  14425. wc_pem_password_cb* cb, void* ctx)
  14426. {
  14427. byte* pem = NULL;
  14428. int pemSz = 0;
  14429. int res = 1;
  14430. /* Validate parameters. */
  14431. if (f == XBADFILE) {
  14432. res = 0;
  14433. }
  14434. if (res == 1) {
  14435. /* Write private key to memory. */
  14436. res = pem_write_mem_pkcs8privatekey(&pem, &pemSz, pkey, enc, passwd,
  14437. passwdSz, cb, ctx);
  14438. }
  14439. /* Write encoded key to file. */
  14440. if ((res >= 1) && (XFWRITE(pem, 1, pemSz, f) != (size_t)pemSz)) {
  14441. res = 0;
  14442. }
  14443. /* Dispose of dynamically allocated memory (pem and key). */
  14444. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  14445. return res;
  14446. }
  14447. #endif /* !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  14448. #endif /* !NO_PWDBASED && HAVE_PKCS8 */
  14449. #endif /* OPENSSL_ALL */
  14450. /*******************************************************************************
  14451. * END OF GENERIC PUBLIC KEY PEM APIs
  14452. ******************************************************************************/
  14453. #endif /* !WOLFSSL_PK_INCLUDED */