pk.c 339 KB

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