pk.c 395 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873
  1. /* pk.c
  2. *
  3. * Copyright (C) 2006-2023 wolfSSL Inc.
  4. *
  5. * This file is part of wolfSSL.
  6. *
  7. * wolfSSL is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * wolfSSL is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20. */
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24. #include <wolfssl/wolfcrypt/settings.h>
  25. #include <wolfssl/internal.h>
  26. #ifndef WC_NO_RNG
  27. #include <wolfssl/wolfcrypt/random.h>
  28. #endif
  29. #ifdef HAVE_ECC
  30. #include <wolfssl/wolfcrypt/ecc.h>
  31. #endif
  32. #ifndef WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  33. /* FIPS build has replaced ecc.h. */
  34. #define wc_ecc_key_get_priv(key) (&((key)->k))
  35. #define WOLFSSL_HAVE_ECC_KEY_GET_PRIV
  36. #endif
  37. #if !defined(WOLFSSL_PK_INCLUDED)
  38. #ifndef WOLFSSL_IGNORE_FILE_WARN
  39. #warning pk.c does not need to be compiled separately from ssl.c
  40. #endif
  41. #else
  42. #ifndef NO_RSA
  43. #include <wolfssl/wolfcrypt/rsa.h>
  44. #endif
  45. #if defined(OPENSSL_EXTRA) && !defined(NO_BIO) && defined(WOLFSSL_KEY_GEN) && \
  46. (defined(HAVE_ECC) || (!defined(NO_DSA) && !defined(HAVE_SELFTEST)))
  47. /* Forward declaration for wolfSSL_PEM_write_bio_DSA_PUBKEY.
  48. * Implementation in ssl.c.
  49. */
  50. static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key);
  51. #endif
  52. /*******************************************************************************
  53. * COMMON FUNCTIONS
  54. ******************************************************************************/
  55. /* Calculate the number of bytes require to represent a length value in ASN.
  56. *
  57. * @param [in] l Length value to use.
  58. * @return Number of bytes required to represent length value.
  59. */
  60. #define ASN_LEN_SIZE(l) \
  61. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  62. #if defined(OPENSSL_EXTRA)
  63. #ifndef NO_ASN
  64. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  65. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  66. /* Convert the PEM encoding in the buffer to DER.
  67. *
  68. * @param [in] pem Buffer containing PEM encoded data.
  69. * @param [in] pemSz Size of data in buffer in bytes.
  70. * @param [in] cb Password callback when PEM encrypted.
  71. * @param [in] pass NUL terminated string for passphrase when PEM
  72. * encrypted.
  73. * @param [in] keyType Type of key to match against PEM header/footer.
  74. * @param [out] keyFormat Format of key.
  75. * @param [out] der Buffer holding DER encoding.
  76. * @return Negative on failure.
  77. * @return Number of bytes consumed on success.
  78. */
  79. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  80. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  81. {
  82. #ifdef WOLFSSL_SMALL_STACK
  83. EncryptedInfo* info = NULL;
  84. #else
  85. EncryptedInfo info[1];
  86. #endif /* WOLFSSL_SMALL_STACK */
  87. wc_pem_password_cb* localCb = NULL;
  88. int ret = 0;
  89. if (cb != NULL) {
  90. localCb = cb;
  91. }
  92. else if (pass != NULL) {
  93. localCb = wolfSSL_PEM_def_callback;
  94. }
  95. #ifdef WOLFSSL_SMALL_STACK
  96. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  97. DYNAMIC_TYPE_ENCRYPTEDINFO);
  98. if (info == NULL) {
  99. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  100. ret = MEMORY_E;
  101. }
  102. #endif /* WOLFSSL_SMALL_STACK */
  103. if (ret == 0) {
  104. XMEMSET(info, 0, sizeof(EncryptedInfo));
  105. info->passwd_cb = localCb;
  106. info->passwd_userdata = pass;
  107. /* Do not strip PKCS8 header */
  108. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  109. info, keyFormat);
  110. if (ret < 0) {
  111. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  112. }
  113. }
  114. if (ret >= 0) {
  115. ret = (int)info->consumed;
  116. }
  117. #ifdef WOLFSSL_SMALL_STACK
  118. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  119. #endif
  120. return ret;
  121. }
  122. #endif
  123. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  124. #ifndef NO_BIO
  125. /* Read PEM data from a BIO and decode to DER in a new buffer.
  126. *
  127. * @param [in, out] bio BIO object to read with.
  128. * @param [in] cb Password callback when PEM encrypted.
  129. * @param [in] pass NUL terminated string for passphrase when PEM
  130. * encrypted.
  131. * @param [in] keyType Type of key to match against PEM header/footer.
  132. * @param [out] keyFormat Format of key.
  133. * @param [out] der Buffer holding DER encoding.
  134. * @return Negative on failure.
  135. * @return Number of bytes consumed on success.
  136. */
  137. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  138. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  139. {
  140. int ret;
  141. char* mem = NULL;
  142. int memSz;
  143. int alloced = 0;
  144. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  145. if (ret == 0) {
  146. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  147. /* Write left over data back to BIO if not a file BIO */
  148. if ((ret > 0) && ((memSz - ret) > 0) &&
  149. (bio->type != WOLFSSL_BIO_FILE)) {
  150. int res;
  151. res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  152. if (res != memSz - ret) {
  153. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  154. if (res < 0) {
  155. ret = res;
  156. }
  157. else {
  158. ret = MEMORY_E;
  159. }
  160. }
  161. }
  162. if (alloced) {
  163. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  164. }
  165. }
  166. return ret;
  167. }
  168. #endif /* !NO_BIO */
  169. #if !defined(NO_FILESYSTEM)
  170. /* Read PEM data from a file and decode to DER in a new buffer.
  171. *
  172. * @param [in] fp File pointer to read with.
  173. * @param [in] cb Password callback when PEM encrypted.
  174. * @param [in] pass NUL terminated string for passphrase when PEM
  175. * encrypted.
  176. * @param [in] keyType Type of key to match against PEM header/footer.
  177. * @param [out] keyFormat Format of key.
  178. * @param [out] der Buffer holding DER encoding.
  179. * @return Negative on failure.
  180. * @return Number of bytes consumed on success.
  181. */
  182. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  183. int keyType, int* keyFormat, DerBuffer** der)
  184. {
  185. int ret;
  186. char* mem = NULL;
  187. int memSz;
  188. ret = wolfssl_read_file(fp, &mem, &memSz);
  189. if (ret == 0) {
  190. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  191. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  192. }
  193. return ret;
  194. }
  195. #endif /* !NO_FILESYSTEM */
  196. #endif
  197. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) \
  198. || !defined(WOLFCRYPT_ONLY))
  199. /* Convert DER data to PEM in an allocated buffer.
  200. *
  201. * @param [in] der Buffer containing DER data.
  202. * @param [in] derSz Size of DER data in bytes.
  203. * @param [in] type Type of key being encoded.
  204. * @param [in] heap Heap hint for dynamic memory allocation.
  205. * @param [out] out Allocated buffer containing PEM.
  206. * @param [out] outSz Size of PEM encoding.
  207. * @return WOLFSSL_FAILURE on error.
  208. * @return WOLFSSL_SUCCESS on success.
  209. */
  210. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  211. void* heap, byte** out, int* outSz)
  212. {
  213. int ret = WOLFSSL_SUCCESS;
  214. int pemSz;
  215. byte* pem = NULL;
  216. (void)heap;
  217. pemSz = wc_DerToPem(der, (word32)derSz, NULL, 0, type);
  218. if (pemSz < 0) {
  219. ret = WOLFSSL_FAILURE;
  220. }
  221. if (ret == WOLFSSL_SUCCESS) {
  222. pem = (byte*)XMALLOC((size_t)pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  223. if (pem == NULL) {
  224. ret = WOLFSSL_FAILURE;
  225. }
  226. }
  227. if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, (word32)derSz, pem,
  228. (word32)pemSz, type) < 0)) {
  229. ret = WOLFSSL_FAILURE;
  230. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  231. pem = NULL;
  232. }
  233. *out = pem;
  234. *outSz = pemSz;
  235. return ret;
  236. }
  237. #ifndef NO_BIO
  238. /* Write the DER data as PEM into BIO.
  239. *
  240. * @param [in] der Buffer containing DER data.
  241. * @param [in] derSz Size of DER data in bytes.
  242. * @param [in, out] bio BIO object to write with.
  243. * @param [in] type Type of key being encoded.
  244. * @return WOLFSSL_FAILURE on error.
  245. * @return WOLFSSL_SUCCESS on success.
  246. */
  247. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  248. WOLFSSL_BIO* bio, int type)
  249. {
  250. int ret;
  251. int pemSz;
  252. byte* pem = NULL;
  253. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  254. if (ret == WOLFSSL_SUCCESS) {
  255. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  256. if (len != pemSz) {
  257. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  258. ret = WOLFSSL_FAILURE;
  259. }
  260. }
  261. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  262. return ret;
  263. }
  264. #endif
  265. #endif
  266. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN)) || \
  267. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  268. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  269. #if !defined(NO_FILESYSTEM)
  270. /* Write the DER data as PEM into file pointer.
  271. *
  272. * @param [in] der Buffer containing DER data.
  273. * @param [in] derSz Size of DER data in bytes.
  274. * @param [in] fp File pointer to write with.
  275. * @param [in] type Type of key being encoded.
  276. * @param [in] heap Heap hint for dynamic memory allocation.
  277. * @return WOLFSSL_FAILURE on error.
  278. * @return WOLFSSL_SUCCESS on success.
  279. */
  280. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  281. XFILE fp, int type, void* heap)
  282. {
  283. int ret;
  284. int pemSz;
  285. byte* pem = NULL;
  286. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  287. if (ret == WOLFSSL_SUCCESS) {
  288. int len = (int)XFWRITE(pem, 1, (size_t)pemSz, fp);
  289. if (len != pemSz) {
  290. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  291. ret = WOLFSSL_FAILURE;
  292. }
  293. }
  294. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  295. return ret;
  296. }
  297. #endif
  298. #endif
  299. #if defined(WOLFSSL_KEY_GEN) && \
  300. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  301. (!defined(NO_RSA) || defined(HAVE_ECC))
  302. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  303. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  304. void* heap, byte** out, int* outSz)
  305. {
  306. int ret = 1;
  307. byte* tmp = NULL;
  308. byte* cipherInfo = NULL;
  309. int pemSz = 0;
  310. /* Macro doesn't always use it. */
  311. (void)heap;
  312. /* Encrypt DER buffer if required. */
  313. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  314. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  315. byte *tmpBuf;
  316. /* Add space for padding. */
  317. tmpBuf = (byte*)XREALLOC(der, (size_t)(derSz + blockSz), heap,
  318. DYNAMIC_TYPE_TMP_BUFFER);
  319. if (tmpBuf == NULL) {
  320. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  321. ret = 0; /* der buffer is free'd at the end of the function */
  322. }
  323. else {
  324. der = tmpBuf;
  325. /* Encrypt DER inline. */
  326. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  327. &cipherInfo, derSz + blockSz);
  328. if (ret != 1) {
  329. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  330. }
  331. }
  332. }
  333. if (ret == 1) {
  334. /* Calculate PEM encoding size. */
  335. pemSz = wc_DerToPemEx(der, (word32)derSz, NULL, 0, cipherInfo, type);
  336. if (pemSz <= 0) {
  337. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  338. ret = 0;
  339. }
  340. }
  341. if (ret == 1) {
  342. /* Allocate space for PEM encoding plus a NUL terminator. */
  343. tmp = (byte*)XMALLOC((size_t)(pemSz + 1), NULL, DYNAMIC_TYPE_KEY);
  344. if (tmp == NULL) {
  345. WOLFSSL_ERROR_MSG("malloc failed");
  346. ret = 0;
  347. }
  348. }
  349. if (ret == 1) {
  350. /* DER to PEM */
  351. pemSz = wc_DerToPemEx(der, (word32)derSz, tmp, (word32)pemSz,
  352. cipherInfo, type);
  353. if (pemSz <= 0) {
  354. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  355. ret = 0;
  356. }
  357. }
  358. if (ret == 1) {
  359. /* NUL terminate string - PEM. */
  360. tmp[pemSz] = 0x00;
  361. /* Return allocated buffer and size. */
  362. *out = tmp;
  363. *outSz = pemSz;
  364. /* Don't free returning buffer. */
  365. tmp = NULL;
  366. }
  367. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  368. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  369. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  370. return ret;
  371. }
  372. #endif
  373. #endif /* !NO_ASN */
  374. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  375. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  376. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  377. /* Print the number bn in hex with name field and indentation indent to file fp.
  378. *
  379. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  380. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  381. *
  382. * @param [in] fp File pointer to write to.
  383. * @param [in] indent Number of spaces to prepend to each line.
  384. * @param [in] field Name of field.
  385. * @param [in] bn Big number to print.
  386. * @return 1 on success.
  387. * @return 0 on failure.
  388. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  389. * bn or NULL.
  390. */
  391. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  392. const WOLFSSL_BIGNUM* bn)
  393. {
  394. static const int HEX_INDENT = 4;
  395. static const int MAX_DIGITS_PER_LINE = 30;
  396. int ret = 1;
  397. int i = 0;
  398. char* buf = NULL;
  399. /* Internal function - assume parameters are valid. */
  400. /* Convert BN to hexadecimal character array (allocates buffer). */
  401. buf = wolfSSL_BN_bn2hex(bn);
  402. if (buf == NULL) {
  403. ret = 0;
  404. }
  405. if (ret == 1) {
  406. /* Print leading spaces, name and spaces before data. */
  407. if (indent > 0) {
  408. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  409. ret = 0;
  410. }
  411. }
  412. if (ret == 1) {
  413. if (XFPRINTF(fp, "%s:\n", field) < 0)
  414. ret = 0;
  415. }
  416. if (ret == 1) {
  417. if (indent > 0) {
  418. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  419. ret = 0;
  420. }
  421. }
  422. if (ret == 1) {
  423. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  424. ret = 0;
  425. }
  426. if (ret == 1) {
  427. /* Print first byte - should always exist. */
  428. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  429. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  430. ret = 0;
  431. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  432. ret = 0;
  433. }
  434. }
  435. if (ret == 1) {
  436. /* Print each hexadecimal character with byte separator. */
  437. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  438. /* Byte separator every two nibbles - one byte. */
  439. if (XFPRINTF(fp, ":") < 0) {
  440. ret = 0;
  441. break;
  442. }
  443. /* New line after every 15 bytes - 30 nibbles. */
  444. if (i % MAX_DIGITS_PER_LINE == 0) {
  445. if (XFPRINTF(fp, "\n") < 0) {
  446. ret = 0;
  447. break;
  448. }
  449. if (indent > 0) {
  450. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  451. ret = 0;
  452. break;
  453. }
  454. }
  455. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  456. ret = 0;
  457. break;
  458. }
  459. }
  460. /* Print two nibbles - one byte. */
  461. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  462. ret = 0;
  463. break;
  464. }
  465. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  466. ret = 0;
  467. break;
  468. }
  469. }
  470. /* Ensure on new line after data. */
  471. if (XFPRINTF(fp, "\n") < 0) {
  472. ret = 0;
  473. }
  474. }
  475. /* Dispose of any allocated character array. */
  476. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  477. return ret;
  478. }
  479. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  480. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  481. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA)
  482. /* snprintf() must be available */
  483. /* Maximum number of extra indent spaces on each line. */
  484. #define PRINT_NUM_MAX_INDENT 48
  485. /* Maximum size of a line containing a value. */
  486. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  487. /* Number of leading spaces on each line. */
  488. #define PRINT_NUM_INDENT_CNT 4
  489. /* Indent spaces for number lines. */
  490. #define PRINT_NUM_INDENT " "
  491. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  492. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  493. /* Print indent to BIO.
  494. *
  495. * @param [in] bio BIO object to write to.
  496. * @param [in] line Buffer to put characters to before writing to BIO.
  497. * @param [in] lineLen Length of buffer.
  498. * @return 1 on success.
  499. * @return 0 on failure.
  500. */
  501. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  502. int indent)
  503. {
  504. int ret = 1;
  505. if (indent > 0) {
  506. /* Print indent spaces. */
  507. int len_wanted = XSNPRINTF(line, (size_t)lineLen, "%*s", indent, " ");
  508. if (len_wanted >= lineLen) {
  509. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  510. ret = 0;
  511. }
  512. else {
  513. /* Write indents string to BIO */
  514. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  515. ret = 0;
  516. }
  517. }
  518. }
  519. return ret;
  520. }
  521. /* Print out name, and value in decimal and hex to BIO.
  522. *
  523. * @param [in] bio BIO object to write to.
  524. * @param [in] value MP integer to write.
  525. * @param [in] name Name of value.
  526. * @param [in] indent Number of leading spaces before line.
  527. * @return 1 on success.
  528. * @return 0 on failure.
  529. */
  530. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  531. const char* name, int indent)
  532. {
  533. int ret = 1;
  534. int len;
  535. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  536. /* Get the length of hex encoded value. */
  537. len = mp_unsigned_bin_size(value);
  538. /* Value must no more than 32-bits - 4 bytes. */
  539. if ((len < 0) || (len > 4)) {
  540. WOLFSSL_ERROR_MSG("Error getting exponent size");
  541. ret = 0;
  542. }
  543. if (ret == 1) {
  544. /* Print any indent spaces. */
  545. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  546. }
  547. if (ret == 1) {
  548. /* Get 32-bits of value. */
  549. word32 v = (word32)value->dp[0];
  550. /* Print the line to the string. */
  551. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  552. v);
  553. if (len >= (int)sizeof(line)) {
  554. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  555. ret = 0;
  556. } else {
  557. /* Write string to BIO */
  558. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  559. ret = 0;
  560. }
  561. }
  562. }
  563. return ret;
  564. }
  565. /* Print out name and multi-precision number to BIO.
  566. *
  567. * @param [in] bio BIO object to write to.
  568. * @param [in] num MP integer to write.
  569. * @param [in] name Name of value.
  570. * @param [in] indent Number of leading spaces before each line.
  571. * @return 1 on success.
  572. * @return 0 on failure.
  573. */
  574. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  575. int indent)
  576. {
  577. int ret = 1;
  578. int rawLen = 0;
  579. byte* rawKey = NULL;
  580. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  581. int li = 0; /* Line index. */
  582. int i;
  583. /* Allocate a buffer to hold binary encoded data. */
  584. rawLen = mp_unsigned_bin_size(num);
  585. if (rawLen == 0) {
  586. WOLFSSL_ERROR_MSG("Invalid number");
  587. ret = 0;
  588. }
  589. if (ret == 1) {
  590. rawKey = (byte*)XMALLOC((size_t)rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  591. if (rawKey == NULL) {
  592. WOLFSSL_ERROR_MSG("Memory allocation error");
  593. ret = 0;
  594. }
  595. }
  596. /* Encode number as big-endian byte array. */
  597. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  598. ret = 0;
  599. }
  600. if (ret == 1) {
  601. /* Print any indent spaces. */
  602. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  603. }
  604. if (ret == 1) {
  605. /* Print header string line to string. */
  606. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  607. if (li >= (int)sizeof(line)) {
  608. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  609. ret = 0;
  610. }
  611. else {
  612. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  613. ret = 0;
  614. }
  615. }
  616. }
  617. if (ret == 1) {
  618. /* Print any indent spaces. */
  619. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  620. }
  621. if (ret == 1) {
  622. /* Start first digit line with spaces.
  623. * Writing out zeros ensures number is a positive value. */
  624. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  625. mp_leading_bit(num) ? "00:" : "");
  626. if (li >= (int)sizeof(line)) {
  627. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  628. ret = 0;
  629. }
  630. }
  631. /* Put out each line of numbers. */
  632. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  633. /* Encode another byte as 2 hex digits and append colon. */
  634. int len_wanted = XSNPRINTF(line + li, sizeof(line) - (size_t)li,
  635. "%02x:", rawKey[i]);
  636. /* Check if there was room -- if not, print the current line, not
  637. * including the newest octet.
  638. */
  639. if (len_wanted >= (int)sizeof(line) - li) {
  640. /* bump current octet to the next line. */
  641. --i;
  642. /* More bytes coming so add a line break. */
  643. line[li++] = '\n';
  644. /* Write out the line. */
  645. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  646. ret = 0;
  647. }
  648. if (ret == 1) {
  649. /* Print any indent spaces. */
  650. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  651. }
  652. /* Put the leading spaces on new line. */
  653. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  654. li = PRINT_NUM_INDENT_CNT;
  655. }
  656. else {
  657. li += len_wanted;
  658. }
  659. }
  660. if (ret == 1) {
  661. /* Put out last line - replace last colon with carriage return. */
  662. line[li-1] = '\n';
  663. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  664. ret = 0;
  665. }
  666. }
  667. /* Dispose of any allocated data. */
  668. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  669. return ret;
  670. }
  671. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA */
  672. #if !defined(NO_RSA) || (!defined(NO_DH) && !defined(NO_CERTS) && \
  673. defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || defined(HAVE_ECC)
  674. /* Uses the DER SEQUENCE to determine size of DER data.
  675. *
  676. * Outer SEQUENCE encapsulates all the DER encoding.
  677. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  678. *
  679. * @param [in] seq Buffer holding DER encoded sequence.
  680. * @param [in] len Length of data in buffer (may be larger than SEQ).
  681. * @return Size of complete DER encoding on success.
  682. * @return 0 on failure.
  683. */
  684. static int wolfssl_der_length(const unsigned char* seq, int len)
  685. {
  686. int ret = 0;
  687. word32 i = 0;
  688. /* Check it is a SEQUENCE and get the length of the underlying data.
  689. * i is updated to be after SEQUENCE header bytes.
  690. */
  691. if (GetSequence_ex(seq, &i, &ret, (word32)len, 0) >= 0) {
  692. /* Add SEQUENCE header length to underlying data length. */
  693. ret += (int)i;
  694. }
  695. return ret;
  696. }
  697. #endif /* !NO_RSA */
  698. #endif /* OPENSSL_EXTRA */
  699. /*******************************************************************************
  700. * START OF RSA API
  701. ******************************************************************************/
  702. #ifndef NO_RSA
  703. /*
  704. * RSA METHOD
  705. * Could be used to hold function pointers to implementations of RSA operations.
  706. */
  707. #if defined(OPENSSL_EXTRA)
  708. /* Return a blank RSA method and set the name and flags.
  709. *
  710. * Only one implementation of RSA operations.
  711. * name is duplicated.
  712. *
  713. * @param [in] name Name to use in method.
  714. * @param [in] flags Flags to set into method.
  715. * @return Newly allocated RSA method on success.
  716. * @return NULL on failure.
  717. */
  718. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  719. {
  720. WOLFSSL_RSA_METHOD* meth = NULL;
  721. int name_len = 0;
  722. int err;
  723. /* Validate name is not NULL. */
  724. err = (name == NULL);
  725. if (!err) {
  726. /* Allocate an RSA METHOD to return. */
  727. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  728. DYNAMIC_TYPE_OPENSSL);
  729. err = (meth == NULL);
  730. }
  731. if (!err) {
  732. XMEMSET(meth, 0, sizeof(*meth));
  733. meth->flags = flags;
  734. meth->dynamic = 1;
  735. name_len = (int)XSTRLEN(name);
  736. meth->name = (char*)XMALLOC((size_t)(name_len + 1), NULL,
  737. DYNAMIC_TYPE_OPENSSL);
  738. err = (meth->name == NULL);
  739. }
  740. if (!err) {
  741. XMEMCPY(meth->name, name, (size_t)(name_len + 1));
  742. }
  743. if (err) {
  744. /* meth->name won't be allocated on error. */
  745. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  746. meth = NULL;
  747. }
  748. return meth;
  749. }
  750. /* Default RSA method is one with wolfSSL name and no flags.
  751. *
  752. * @return Newly allocated wolfSSL RSA method on success.
  753. * @return NULL on failure.
  754. */
  755. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  756. {
  757. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  758. 0, /* No flags. */
  759. (char*)"wolfSSL RSA",
  760. 0 /* Static definition. */
  761. };
  762. return &wolfssl_rsa_meth;
  763. }
  764. /* Dispose of RSA method and allocated data.
  765. *
  766. * @param [in] meth RSA method to free.
  767. */
  768. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  769. {
  770. /* Free method if available and dynamically allocated. */
  771. if ((meth != NULL) && meth->dynamic) {
  772. /* Name was duplicated and must be freed. */
  773. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  774. /* Dispose of RSA method. */
  775. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  776. }
  777. }
  778. #ifndef NO_WOLFSSL_STUB
  779. /* Stub function for any RSA method setting function.
  780. *
  781. * Nothing is stored - not even flags or name.
  782. *
  783. * @param [in] meth RSA method.
  784. * @param [in] p A pointer.
  785. * @return 1 to indicate success.
  786. */
  787. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  788. {
  789. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  790. (void)meth;
  791. (void)p;
  792. return 1;
  793. }
  794. #endif /* !NO_WOLFSSL_STUB */
  795. #endif /* OPENSSL_EXTRA */
  796. /*
  797. * RSA constructor/deconstructor APIs
  798. */
  799. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  800. /* Dispose of RSA key and allocated data.
  801. *
  802. * Cannot use rsa after this call.
  803. *
  804. * @param [in] rsa RSA key to free.
  805. */
  806. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  807. {
  808. int doFree = 1;
  809. WOLFSSL_ENTER("wolfSSL_RSA_free");
  810. /* Validate parameter. */
  811. if (rsa == NULL) {
  812. doFree = 0;
  813. }
  814. if (doFree) {
  815. int err;
  816. /* Decrement reference count. */
  817. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  818. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  819. (void)err;
  820. #endif
  821. }
  822. if (doFree) {
  823. void* heap = rsa->heap;
  824. /* Dispose of allocated reference counting data. */
  825. wolfSSL_RefFree(&rsa->ref);
  826. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  827. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  828. #endif
  829. if (rsa->internal != NULL) {
  830. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  831. /* Check if RNG is owned before freeing it. */
  832. if (rsa->ownRng) {
  833. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  834. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  835. wc_FreeRng(rng);
  836. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  837. }
  838. /* RNG isn't freed by wolfCrypt RSA free. */
  839. }
  840. #endif
  841. /* Dispose of allocated data in wolfCrypt RSA key. */
  842. wc_FreeRsaKey((RsaKey*)rsa->internal);
  843. /* Dispose of memory for wolfCrypt RSA key. */
  844. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  845. }
  846. /* Dispose of external representation of RSA values. */
  847. wolfSSL_BN_clear_free(rsa->iqmp);
  848. wolfSSL_BN_clear_free(rsa->dmq1);
  849. wolfSSL_BN_clear_free(rsa->dmp1);
  850. wolfSSL_BN_clear_free(rsa->q);
  851. wolfSSL_BN_clear_free(rsa->p);
  852. wolfSSL_BN_clear_free(rsa->d);
  853. wolfSSL_BN_free(rsa->e);
  854. wolfSSL_BN_free(rsa->n);
  855. #if defined(OPENSSL_EXTRA)
  856. if (rsa->meth) {
  857. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  858. }
  859. #endif
  860. /* Set back to NULLs for safety. */
  861. ForceZero(rsa, sizeof(*rsa));
  862. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  863. (void)heap;
  864. }
  865. }
  866. /* Allocate and initialize a new RSA key.
  867. *
  868. * Not OpenSSL API.
  869. *
  870. * @param [in] heap Heap hint for dynamic memory allocation.
  871. * @param [in] devId Device identifier value.
  872. * @return RSA key on success.
  873. * @return NULL on failure.
  874. */
  875. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  876. {
  877. WOLFSSL_RSA* rsa = NULL;
  878. RsaKey* key = NULL;
  879. int err = 0;
  880. int rsaKeyInited = 0;
  881. WOLFSSL_ENTER("wolfSSL_RSA_new");
  882. /* Allocate memory for new wolfCrypt RSA key. */
  883. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  884. if (key == NULL) {
  885. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  886. err = 1;
  887. }
  888. if (!err) {
  889. /* Allocate memory for new RSA key. */
  890. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  891. DYNAMIC_TYPE_RSA);
  892. if (rsa == NULL) {
  893. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  894. err = 1;
  895. }
  896. }
  897. if (!err) {
  898. /* Clear all fields of RSA key. */
  899. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  900. /* Cache heap to use for all allocations. */
  901. rsa->heap = heap;
  902. #ifdef OPENSSL_EXTRA
  903. /* Always have a method set. */
  904. rsa->meth = wolfSSL_RSA_get_default_method();
  905. #endif
  906. /* Initialize reference counting. */
  907. wolfSSL_RefInit(&rsa->ref, &err);
  908. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  909. }
  910. if (!err) {
  911. #endif
  912. /* Initialize wolfCrypt RSA key. */
  913. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  914. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  915. err = 1;
  916. }
  917. else {
  918. rsaKeyInited = 1;
  919. }
  920. }
  921. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  922. if (!err) {
  923. WC_RNG* rng;
  924. /* Create a local RNG. */
  925. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  926. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  927. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  928. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  929. rng = NULL;
  930. }
  931. rsa->ownRng = 1;
  932. if (rng == NULL) {
  933. /* Get the wolfSSL global RNG - not thread safe. */
  934. rng = wolfssl_get_global_rng();
  935. rsa->ownRng = 0;
  936. }
  937. if (rng == NULL) {
  938. /* Couldn't create global either. */
  939. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  940. err = 1;
  941. }
  942. else {
  943. /* Set the local or global RNG into the wolfCrypt RSA key. */
  944. (void)wc_RsaSetRNG(key, rng);
  945. /* Won't fail as key and rng are not NULL. */
  946. }
  947. }
  948. #endif /* !HAVE_FIPS && WC_RSA_BLINDING */
  949. if (!err) {
  950. /* Set wolfCrypt RSA key into RSA key. */
  951. rsa->internal = key;
  952. /* Data from external RSA key has not been set into internal one. */
  953. rsa->inSet = 0;
  954. }
  955. if (err) {
  956. /* Dispose of any allocated data on error. */
  957. /* No failure after RNG allocation - no need to free RNG. */
  958. if (rsaKeyInited) {
  959. wc_FreeRsaKey(key);
  960. }
  961. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  962. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  963. /* Return NULL. */
  964. rsa = NULL;
  965. }
  966. return rsa;
  967. }
  968. /* Allocate and initialize a new RSA key.
  969. *
  970. * @return RSA key on success.
  971. * @return NULL on failure.
  972. */
  973. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  974. {
  975. /* Call wolfSSL API to do work. */
  976. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  977. }
  978. /* Increments ref count of RSA key.
  979. *
  980. * @param [in, out] rsa RSA key.
  981. * @return 1 on success
  982. * @return 0 on error
  983. */
  984. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  985. {
  986. int err = 0;
  987. if (rsa != NULL) {
  988. wolfSSL_RefInc(&rsa->ref, &err);
  989. }
  990. return !err;
  991. }
  992. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  993. #ifdef OPENSSL_EXTRA
  994. #if defined(WOLFSSL_KEY_GEN)
  995. /* Allocate a new RSA key and make it a copy.
  996. *
  997. * Encodes to and from DER to copy.
  998. *
  999. * @param [in] rsa RSA key to duplicate.
  1000. * @return RSA key on success.
  1001. * @return NULL on error.
  1002. */
  1003. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1004. {
  1005. WOLFSSL_RSA* ret = NULL;
  1006. int derSz = 0;
  1007. byte* derBuf = NULL;
  1008. int err;
  1009. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1010. err = (rsa == NULL);
  1011. if (!err) {
  1012. /* Create a new RSA key to return. */
  1013. ret = wolfSSL_RSA_new();
  1014. if (ret == NULL) {
  1015. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1016. err = 1;
  1017. }
  1018. }
  1019. if (!err) {
  1020. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1021. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1022. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1023. err = 1;
  1024. }
  1025. }
  1026. if (!err) {
  1027. /* Decode DER of the RSA public key into new key. */
  1028. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1029. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1030. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1031. err = 1;
  1032. }
  1033. }
  1034. /* Dispose of any allocated DER buffer. */
  1035. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1036. if (err) {
  1037. /* Disposes of any created RSA key - on error. */
  1038. wolfSSL_RSA_free(ret);
  1039. ret = NULL;
  1040. }
  1041. return ret;
  1042. }
  1043. /* wolfSSL_RSAPrivateKey_dup not supported */
  1044. #endif /* WOLFSSL_KEY_GEN */
  1045. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1046. void* heap);
  1047. /*
  1048. * RSA to/from bin APIs
  1049. */
  1050. /* Convert RSA public key data to internal.
  1051. *
  1052. * Creates new RSA key from the DER encoded RSA public key.
  1053. *
  1054. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1055. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1056. * @param [in] derSz Length of the data in the DER buffer.
  1057. * @return RSA key on success.
  1058. * @return NULL on failure.
  1059. */
  1060. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1061. const unsigned char **derBuf, long derSz)
  1062. {
  1063. WOLFSSL_RSA *rsa = NULL;
  1064. int err = 0;
  1065. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1066. /* Validate parameters. */
  1067. if (derBuf == NULL) {
  1068. WOLFSSL_ERROR_MSG("Bad argument");
  1069. err = 1;
  1070. }
  1071. /* Create a new RSA key to return. */
  1072. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1073. WOLFSSL_ERROR_MSG("RSA_new failed");
  1074. err = 1;
  1075. }
  1076. /* Decode RSA key from DER. */
  1077. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1078. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1079. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1080. err = 1;
  1081. }
  1082. if ((!err) && (out != NULL)) {
  1083. /* Return through parameter too. */
  1084. *out = rsa;
  1085. /* Move buffer on by the used amount. */
  1086. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1087. }
  1088. if (err) {
  1089. /* Dispose of any created RSA key. */
  1090. wolfSSL_RSA_free(rsa);
  1091. rsa = NULL;
  1092. }
  1093. return rsa;
  1094. }
  1095. /* Convert RSA private key data to internal.
  1096. *
  1097. * Create a new RSA key from the DER encoded RSA private key.
  1098. *
  1099. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1100. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1101. * @param [in] derSz Length of the data in the DER buffer.
  1102. * @return RSA key on success.
  1103. * @return NULL on failure.
  1104. */
  1105. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1106. const unsigned char **derBuf, long derSz)
  1107. {
  1108. WOLFSSL_RSA *rsa = NULL;
  1109. int err = 0;
  1110. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1111. /* Validate parameters. */
  1112. if (derBuf == NULL) {
  1113. WOLFSSL_ERROR_MSG("Bad argument");
  1114. err = 1;
  1115. }
  1116. /* Create a new RSA key to return. */
  1117. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1118. WOLFSSL_ERROR_MSG("RSA_new failed");
  1119. err = 1;
  1120. }
  1121. /* Decode RSA key from DER. */
  1122. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1123. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1124. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1125. err = 1;
  1126. }
  1127. if ((!err) && (out != NULL)) {
  1128. /* Return through parameter too. */
  1129. *out = rsa;
  1130. /* Move buffer on by the used amount. */
  1131. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1132. }
  1133. if (err) {
  1134. /* Dispose of any created RSA key. */
  1135. wolfSSL_RSA_free(rsa);
  1136. rsa = NULL;
  1137. }
  1138. return rsa;
  1139. }
  1140. /* Converts an internal RSA structure to DER format for the private key.
  1141. *
  1142. * If "pp" is null then buffer size only is returned.
  1143. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1144. * responsible for free'ing it.
  1145. *
  1146. * @param [in] rsa RSA key.
  1147. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1148. * May be NULL.
  1149. * On out, newly allocated buffer or pointer to byte after
  1150. * encoding in passed in buffer.
  1151. *
  1152. * @return Size of DER encoding on success
  1153. * @return BAD_FUNC_ARG when rsa is NULL.
  1154. * @return 0 on failure.
  1155. */
  1156. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1157. {
  1158. int ret;
  1159. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1160. /* Validate parameters. */
  1161. if (rsa == NULL) {
  1162. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1163. ret = BAD_FUNC_ARG;
  1164. }
  1165. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1166. * No heap hint as this gets returned to the user */
  1167. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1168. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1169. ret = 0;
  1170. }
  1171. /* Size of DER encoding. */
  1172. return ret;
  1173. }
  1174. /* Converts an internal RSA structure to DER format for the public key.
  1175. *
  1176. * If "pp" is null then buffer size only is returned.
  1177. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1178. * responsible for free'ing it.
  1179. *
  1180. * @param [in] rsa RSA key.
  1181. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1182. * May be NULL.
  1183. * On out, newly allocated buffer or pointer to byte after
  1184. * encoding in passed in buffer.
  1185. * @return Size of DER encoding on success
  1186. * @return BAD_FUNC_ARG when rsa is NULL.
  1187. * @return 0 on failure.
  1188. */
  1189. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1190. {
  1191. int ret;
  1192. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1193. /* check for bad functions arguments */
  1194. if (rsa == NULL) {
  1195. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1196. ret = BAD_FUNC_ARG;
  1197. }
  1198. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1199. * No heap hint as this gets returned to the user */
  1200. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1201. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1202. ret = 0;
  1203. }
  1204. return ret;
  1205. }
  1206. #endif /* OPENSSL_EXTRA */
  1207. /*
  1208. * RSA to/from BIO APIs
  1209. */
  1210. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1211. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1212. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1213. #if defined(WOLFSSL_KEY_GEN) && !defined(NO_BIO)
  1214. /* Read DER data from a BIO.
  1215. *
  1216. * DER structures start with a constructed sequence. Use this to calculate the
  1217. * total length of the DER data.
  1218. *
  1219. * @param [in] bio BIO object to read from.
  1220. * @param [out] out Buffer holding DER encoding.
  1221. * @return Number of bytes to DER encoding on success.
  1222. * @return 0 on failure.
  1223. */
  1224. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1225. {
  1226. int err = 0;
  1227. unsigned char seq[MAX_SEQ_SZ];
  1228. unsigned char* der = NULL;
  1229. int derLen = 0;
  1230. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1231. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1232. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1233. err = 1;
  1234. }
  1235. /* Calculate complete DER encoding length. */
  1236. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1237. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1238. err = 1;
  1239. }
  1240. /* Allocate a buffer to read DER data into. */
  1241. if ((!err) && ((der = (unsigned char*)XMALLOC((size_t)derLen, bio->heap,
  1242. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1243. WOLFSSL_ERROR_MSG("Malloc failure");
  1244. err = 1;
  1245. }
  1246. if (!err) {
  1247. /* Calculate the unread amount. */
  1248. int len = derLen - (int)sizeof(seq);
  1249. /* Copy the previously read data into the buffer. */
  1250. XMEMCPY(der, seq, sizeof(seq));
  1251. /* Read rest of DER data from BIO. */
  1252. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1253. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1254. err = 1;
  1255. }
  1256. }
  1257. if (!err) {
  1258. /* Return buffer through parameter. */
  1259. *out = der;
  1260. }
  1261. if (err) {
  1262. /* Dispose of any allocated buffer on error. */
  1263. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1264. derLen = 0;
  1265. }
  1266. return derLen;
  1267. }
  1268. /* Reads the RSA private key data from a BIO to the internal form.
  1269. *
  1270. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1271. *
  1272. * @param [in] bio BIO object to read from.
  1273. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1274. * @return RSA key on success.
  1275. * @return NULL on failure.
  1276. */
  1277. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1278. {
  1279. WOLFSSL_RSA* key = NULL;
  1280. unsigned char* der = NULL;
  1281. int derLen = 0;
  1282. int err;
  1283. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1284. /* Validate parameters. */
  1285. err = (bio == NULL);
  1286. /* Read just DER encoding from BIO - buffer allocated in call. */
  1287. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1288. err = 1;
  1289. }
  1290. if (!err) {
  1291. /* Keep der for call to deallocate. */
  1292. const unsigned char* cder = der;
  1293. /* Create an RSA key from the data from the BIO. */
  1294. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1295. err = (key == NULL);
  1296. }
  1297. if ((!err) && (out != NULL)) {
  1298. /* Return the created RSA key through the parameter. */
  1299. *out = key;
  1300. }
  1301. if (err) {
  1302. /* Dispose of created key on error. */
  1303. wolfSSL_RSA_free(key);
  1304. key = NULL;
  1305. }
  1306. /* Dispose of allocated data. */
  1307. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1308. return key;
  1309. }
  1310. #endif /* defined(WOLFSSL_KEY_GEN) && !NO_BIO */
  1311. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1312. /*
  1313. * RSA DER APIs
  1314. */
  1315. #ifdef OPENSSL_EXTRA
  1316. /* Create a DER encoding of key.
  1317. *
  1318. * Not OpenSSL API.
  1319. *
  1320. * @param [in] rsa RSA key.
  1321. * @param [out] outBuf Allocated buffer containing DER encoding.
  1322. * May be NULL.
  1323. * @param [in] publicKey Whether to encode as public key.
  1324. * @param [in] heap Heap hint.
  1325. * @return Encoding size on success.
  1326. * @return Negative on failure.
  1327. */
  1328. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1329. void* heap)
  1330. {
  1331. byte* p = NULL;
  1332. int ret;
  1333. if (outBuf != NULL) {
  1334. p = *outBuf;
  1335. }
  1336. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1337. if ((ret > 0) && (p != NULL)) {
  1338. *outBuf = p;
  1339. }
  1340. return ret;
  1341. }
  1342. /* Create a DER encoding of key.
  1343. *
  1344. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1345. *
  1346. * @param [in] rsa RSA key.
  1347. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1348. * May be NULL.
  1349. * On out, newly allocated buffer or pointer to byte
  1350. * after encoding in passed in buffer.
  1351. * @param [in] publicKey Whether to encode as public key.
  1352. * @param [in] heap Heap hint.
  1353. * @return Encoding size on success.
  1354. * @return Negative on failure.
  1355. */
  1356. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1357. void* heap)
  1358. {
  1359. int ret = 1;
  1360. int derSz = 0;
  1361. byte* derBuf = NULL;
  1362. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1363. /* Unused if memory is disabled. */
  1364. (void)heap;
  1365. /* Validate parameters. */
  1366. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1367. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1368. ret = BAD_FUNC_ARG;
  1369. }
  1370. /* Push external RSA data into internal RSA key if not set. */
  1371. if ((ret == 1) && (!rsa->inSet)) {
  1372. ret = SetRsaInternal(rsa);
  1373. }
  1374. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1375. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1376. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1377. ret = BAD_FUNC_ARG;
  1378. }
  1379. if (ret == 1) {
  1380. if (publicKey) {
  1381. /* Calculate length of DER encoded RSA public key. */
  1382. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1383. if (derSz < 0) {
  1384. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1385. ret = derSz;
  1386. }
  1387. }
  1388. else {
  1389. /* Calculate length of DER encoded RSA private key. */
  1390. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1391. if (derSz < 0) {
  1392. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1393. ret = derSz;
  1394. }
  1395. }
  1396. }
  1397. if ((ret == 1) && (outBuf != NULL)) {
  1398. derBuf = *outBuf;
  1399. if (derBuf == NULL) {
  1400. /* Allocate buffer to hold DER encoded RSA key. */
  1401. derBuf = (byte*)XMALLOC((size_t)derSz, heap,
  1402. DYNAMIC_TYPE_TMP_BUFFER);
  1403. if (derBuf == NULL) {
  1404. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1405. ret = MEMORY_ERROR;
  1406. }
  1407. }
  1408. }
  1409. if ((ret == 1) && (outBuf != NULL)) {
  1410. if (publicKey > 0) {
  1411. /* RSA public key to DER. */
  1412. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf,
  1413. (word32)derSz);
  1414. }
  1415. else {
  1416. /* RSA private key to DER. */
  1417. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf,
  1418. (word32)derSz);
  1419. }
  1420. if (derSz < 0) {
  1421. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1422. ret = derSz;
  1423. }
  1424. else if ((*outBuf) != NULL) {
  1425. derBuf = NULL;
  1426. *outBuf += derSz;
  1427. }
  1428. else {
  1429. /* Return allocated buffer. */
  1430. *outBuf = derBuf;
  1431. }
  1432. }
  1433. if (ret == 1) {
  1434. /* Success - return DER encoding size. */
  1435. ret = derSz;
  1436. }
  1437. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1438. /* Not returning buffer, needs to be disposed of. */
  1439. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1440. }
  1441. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1442. return ret;
  1443. }
  1444. #endif /* OPENSSL_EXTRA */
  1445. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1446. /* Load the DER encoded private RSA key.
  1447. *
  1448. * Not OpenSSL API.
  1449. *
  1450. * @param [in] rsa RSA key.
  1451. * @param [in] derBuf Buffer holding DER encoding.
  1452. * @param [in] derSz Length of DER encoding.
  1453. * @return 1 on success.
  1454. * @return -1 on failure.
  1455. */
  1456. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1457. int derSz)
  1458. {
  1459. /* Call implementation that handles both private and public keys. */
  1460. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1461. }
  1462. /* Load the DER encoded public or private RSA key.
  1463. *
  1464. * Not OpenSSL API.
  1465. *
  1466. * @param [in] rsa RSA key.
  1467. * @param [in] derBuf Buffer holding DER encoding.
  1468. * @param [in] derSz Length of DER encoding.
  1469. * @param [in] opt Indicates public or private key.
  1470. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1471. * @return 1 on success.
  1472. * @return -1 on failure.
  1473. */
  1474. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1475. int derSz, int opt)
  1476. {
  1477. int ret = 1;
  1478. int res;
  1479. word32 idx = 0;
  1480. word32 algId;
  1481. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1482. /* Validate parameters. */
  1483. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1484. (derSz <= 0)) {
  1485. WOLFSSL_ERROR_MSG("Bad function arguments");
  1486. ret = -1;
  1487. }
  1488. if (ret == 1) {
  1489. rsa->pkcs8HeaderSz = 0;
  1490. /* Check if input buffer has PKCS8 header. In the case that it does not
  1491. * have a PKCS8 header then do not error out. */
  1492. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1493. &algId);
  1494. if (res > 0) {
  1495. /* Store size of PKCS#8 header for encoding. */
  1496. WOLFSSL_MSG("Found PKCS8 header");
  1497. rsa->pkcs8HeaderSz = (word16)idx;
  1498. }
  1499. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1500. else if (res != ASN_PARSE_E) {
  1501. /* Something went wrong while decoding. */
  1502. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1503. "header");
  1504. ret = -1;
  1505. }
  1506. }
  1507. if (ret == 1) {
  1508. /* Decode private or public key data. */
  1509. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1510. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1511. (word32)derSz);
  1512. }
  1513. else {
  1514. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1515. (word32)derSz);
  1516. }
  1517. /* Check for error. */
  1518. if (res < 0) {
  1519. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1520. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1521. }
  1522. else {
  1523. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1524. }
  1525. WOLFSSL_ERROR_VERBOSE(res);
  1526. ret = -1;
  1527. }
  1528. }
  1529. if (ret == 1) {
  1530. /* Set external RSA key data from wolfCrypt key. */
  1531. if (SetRsaExternal(rsa) != 1) {
  1532. ret = -1;
  1533. }
  1534. else {
  1535. rsa->inSet = 1;
  1536. }
  1537. }
  1538. return ret;
  1539. }
  1540. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1541. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1542. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1543. /* Load DER encoded data into WOLFSSL_RSA object.
  1544. *
  1545. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1546. *
  1547. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1548. * When rsa or *rsa is NULL a new object is created.
  1549. * When not NULL and *rsa is NULL then new object
  1550. * returned through pointer.
  1551. * @param [in] in DER encoded RSA key data.
  1552. * @param [in] inSz Size of DER encoded data in bytes.
  1553. * @param [in] opt Public or private key encoded in data. Valid values:
  1554. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1555. * @return NULL on failure.
  1556. * @return WOLFSSL_RSA object on success.
  1557. */
  1558. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1559. long inSz, int opt)
  1560. {
  1561. WOLFSSL_RSA* ret = NULL;
  1562. if ((rsa != NULL) && (*rsa != NULL)) {
  1563. ret = *rsa;
  1564. }
  1565. else {
  1566. ret = wolfSSL_RSA_new();
  1567. }
  1568. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1569. != 1)) {
  1570. if ((rsa == NULL) || (ret != *rsa)) {
  1571. wolfSSL_RSA_free(ret);
  1572. }
  1573. ret = NULL;
  1574. }
  1575. if ((rsa != NULL) && (*rsa == NULL)) {
  1576. *rsa = ret;
  1577. }
  1578. return ret;
  1579. }
  1580. #endif
  1581. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1582. /*
  1583. * RSA PEM APIs
  1584. */
  1585. #ifdef OPENSSL_EXTRA
  1586. #ifndef NO_BIO
  1587. #if defined(WOLFSSL_KEY_GEN)
  1588. /* Writes PEM encoding of an RSA public key to a BIO.
  1589. *
  1590. * @param [in] bio BIO object to write to.
  1591. * @param [in] rsa RSA key to write.
  1592. * @return 1 on success.
  1593. * @return 0 on failure.
  1594. */
  1595. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1596. {
  1597. int ret = 1;
  1598. int derSz = 0;
  1599. byte* derBuf = NULL;
  1600. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1601. /* Validate parameters. */
  1602. if ((bio == NULL) || (rsa == NULL)) {
  1603. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1604. return 0;
  1605. }
  1606. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1607. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1608. ret = 0;
  1609. }
  1610. if (derBuf == NULL) {
  1611. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1612. ret = 0;
  1613. }
  1614. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1615. PUBLICKEY_TYPE) != WOLFSSL_SUCCESS)) {
  1616. ret = 0;
  1617. }
  1618. /* Dispose of DER buffer. */
  1619. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1620. return ret;
  1621. }
  1622. #endif /* WOLFSSL_KEY_GEN */
  1623. #endif /* !NO_BIO */
  1624. #if defined(WOLFSSL_KEY_GEN)
  1625. #ifndef NO_FILESYSTEM
  1626. /* Writes PEM encoding of an RSA public key to a file pointer.
  1627. *
  1628. * @param [in] fp File pointer to write to.
  1629. * @param [in] rsa RSA key to write.
  1630. * @param [in] type PEM type to write out.
  1631. * @return 1 on success.
  1632. * @return 0 on failure.
  1633. */
  1634. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1635. int type)
  1636. {
  1637. int ret = 1;
  1638. int derSz;
  1639. byte* derBuf = NULL;
  1640. /* Validate parameters. */
  1641. if ((fp == XBADFILE) || (rsa == NULL)) {
  1642. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1643. return 0;
  1644. }
  1645. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1646. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1647. ret = 0;
  1648. }
  1649. if (derBuf == NULL) {
  1650. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1651. ret = 0;
  1652. }
  1653. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1654. rsa->heap) != WOLFSSL_SUCCESS)) {
  1655. ret = 0;
  1656. }
  1657. /* Dispose of DER buffer. */
  1658. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1659. return ret;
  1660. }
  1661. /* Writes PEM encoding of an RSA public key to a file pointer.
  1662. *
  1663. * Header/footer will contain: PUBLIC KEY
  1664. *
  1665. * @param [in] fp File pointer to write to.
  1666. * @param [in] rsa RSA key to write.
  1667. * @return 1 on success.
  1668. * @return 0 on failure.
  1669. */
  1670. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1671. {
  1672. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1673. }
  1674. /* Writes PEM encoding of an RSA public key to a file pointer.
  1675. *
  1676. * Header/footer will contain: RSA PUBLIC KEY
  1677. *
  1678. * @param [in] fp File pointer to write to.
  1679. * @param [in] rsa RSA key to write.
  1680. * @return 1 on success.
  1681. * @return 0 on failure.
  1682. */
  1683. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1684. {
  1685. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1686. }
  1687. #endif /* !NO_FILESYSTEM */
  1688. #endif /* WOLFSSL_KEY_GEN */
  1689. #ifndef NO_BIO
  1690. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1691. *
  1692. * @param [in] bio BIO object to read from.
  1693. * @param [out] out RSA key created.
  1694. * @param [in] cb Password callback when PEM encrypted.
  1695. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1696. * @return RSA key on success.
  1697. * @return NULL on failure.
  1698. */
  1699. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1700. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1701. {
  1702. WOLFSSL_RSA* rsa = NULL;
  1703. DerBuffer* der = NULL;
  1704. int keyFormat = 0;
  1705. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1706. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1707. &keyFormat, &der) >= 0)) {
  1708. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1709. WOLFSSL_RSA_LOAD_PUBLIC);
  1710. if (rsa == NULL) {
  1711. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1712. }
  1713. }
  1714. FreeDer(&der);
  1715. if ((out != NULL) && (rsa != NULL)) {
  1716. *out = rsa;
  1717. }
  1718. return rsa;
  1719. }
  1720. #endif /* !NO_BIO */
  1721. #ifndef NO_FILESYSTEM
  1722. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1723. *
  1724. * Header/footer should contain: PUBLIC KEY
  1725. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1726. *
  1727. * @param [in] fp File pointer to read from.
  1728. * @param [out] out RSA key created.
  1729. * @param [in] cb Password callback when PEM encrypted.
  1730. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1731. * @return RSA key on success.
  1732. * @return NULL on failure.
  1733. */
  1734. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1735. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1736. {
  1737. WOLFSSL_RSA* rsa = NULL;
  1738. DerBuffer* der = NULL;
  1739. int keyFormat = 0;
  1740. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1741. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1742. &keyFormat, &der) >= 0)) {
  1743. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1744. WOLFSSL_RSA_LOAD_PUBLIC);
  1745. if (rsa == NULL) {
  1746. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1747. }
  1748. }
  1749. FreeDer(&der);
  1750. if ((out != NULL) && (rsa != NULL)) {
  1751. *out = rsa;
  1752. }
  1753. return rsa;
  1754. }
  1755. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1756. *
  1757. * Header/footer should contain: RSA PUBLIC KEY
  1758. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1759. *
  1760. * @param [in] fp File pointer to read from.
  1761. * @param [out] rsa RSA key created.
  1762. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1763. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1764. * May be NULL.
  1765. * @return RSA key on success.
  1766. * @return NULL on failure.
  1767. */
  1768. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1769. wc_pem_password_cb* cb, void* pass)
  1770. {
  1771. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1772. }
  1773. #endif /* NO_FILESYSTEM */
  1774. #if defined(WOLFSSL_KEY_GEN) && \
  1775. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1776. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1777. *
  1778. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1779. *
  1780. * @param [in] rsa RSA key to write.
  1781. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1782. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1783. * @param [in] passwdSz Length of password string when PEM encrypted.
  1784. * @param [out] pem Allocated buffer with PEM encoding.
  1785. * @param [out] pLen Length of PEM encoding.
  1786. * @return 1 on success.
  1787. * @return 0 on failure.
  1788. */
  1789. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1790. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1791. {
  1792. int ret = 1;
  1793. byte* derBuf = NULL;
  1794. int derSz = 0;
  1795. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1796. /* Validate parameters. */
  1797. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1798. (rsa->internal == NULL)) {
  1799. WOLFSSL_ERROR_MSG("Bad function arguments");
  1800. ret = 0;
  1801. }
  1802. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1803. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1804. ret = 0;
  1805. }
  1806. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1807. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1808. rsa->heap)) < 0)) {
  1809. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1810. ret = 0;
  1811. }
  1812. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1813. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1814. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1815. ret = 0;
  1816. }
  1817. return ret;
  1818. }
  1819. #ifndef NO_BIO
  1820. /* Writes PEM encoding of an RSA private key to a BIO.
  1821. *
  1822. * @param [in] bio BIO object to write to.
  1823. * @param [in] rsa RSA key to write.
  1824. * @param [in] cipher Cipher to use when PEM encrypted.
  1825. * @param [in] passwd Password string when PEM encrypted.
  1826. * @param [in] len Length of password string when PEM encrypted.
  1827. * @param [in] cb Password callback to use when PEM encrypted.
  1828. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1829. * @return 1 on success.
  1830. * @return 0 on failure.
  1831. */
  1832. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1833. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1834. wc_pem_password_cb* cb, void* arg)
  1835. {
  1836. int ret = 1;
  1837. byte* pem = NULL;
  1838. int pLen = 0;
  1839. (void)cb;
  1840. (void)arg;
  1841. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1842. /* Validate parameters. */
  1843. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1844. WOLFSSL_ERROR_MSG("Bad function arguments");
  1845. ret = 0;
  1846. }
  1847. if (ret == 1) {
  1848. /* Write PEM to buffer that is allocated in the call. */
  1849. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1850. &pem, &pLen);
  1851. if (ret != 1) {
  1852. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1853. }
  1854. }
  1855. /* Write PEM to BIO. */
  1856. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  1857. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1858. ret = 0;
  1859. }
  1860. /* Dispose of any allocated PEM buffer. */
  1861. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1862. return ret;
  1863. }
  1864. #endif /* !NO_BIO */
  1865. #ifndef NO_FILESYSTEM
  1866. /* Writes PEM encoding of an RSA private key to a file pointer.
  1867. *
  1868. * TODO: Support use of the password callback and callback context.
  1869. *
  1870. * @param [in] fp File pointer to write to.
  1871. * @param [in] rsa RSA key to write.
  1872. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1873. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1874. * @param [in] passwdSz Length of password string when PEM encrypted.
  1875. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  1876. * @param [in] arg NUL terminated string for passphrase when PEM
  1877. * encrypted. Unused.
  1878. * @return 1 on success.
  1879. * @return 0 on failure.
  1880. */
  1881. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  1882. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  1883. wc_pem_password_cb *cb, void *arg)
  1884. {
  1885. int ret = 1;
  1886. byte* pem = NULL;
  1887. int pLen = 0;
  1888. (void)cb;
  1889. (void)arg;
  1890. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  1891. /* Validate parameters. */
  1892. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  1893. WOLFSSL_ERROR_MSG("Bad function arguments");
  1894. ret = 0;
  1895. }
  1896. if (ret == 1) {
  1897. /* Write PEM to buffer that is allocated in the call. */
  1898. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  1899. &pem, &pLen);
  1900. if (ret != 1) {
  1901. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1902. }
  1903. }
  1904. /* Write PEM to file pointer. */
  1905. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  1906. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  1907. ret = 0;
  1908. }
  1909. /* Dispose of any allocated PEM buffer. */
  1910. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1911. return ret;
  1912. }
  1913. #endif /* NO_FILESYSTEM */
  1914. #endif /* WOLFSSL_KEY_GEN && WOLFSSL_PEM_TO_DER */
  1915. #ifndef NO_BIO
  1916. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  1917. *
  1918. * @param [in] bio BIO object to read from.
  1919. * @param [out] out RSA key created.
  1920. * @param [in] cb Password callback when PEM encrypted.
  1921. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1922. * @return RSA key on success.
  1923. * @return NULL on failure.
  1924. */
  1925. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  1926. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  1927. {
  1928. WOLFSSL_RSA* rsa = NULL;
  1929. DerBuffer* der = NULL;
  1930. int keyFormat = 0;
  1931. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  1932. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  1933. &keyFormat, &der) >= 0)) {
  1934. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1935. WOLFSSL_RSA_LOAD_PRIVATE);
  1936. if (rsa == NULL) {
  1937. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1938. }
  1939. }
  1940. FreeDer(&der);
  1941. if ((out != NULL) && (rsa != NULL)) {
  1942. *out = rsa;
  1943. }
  1944. return rsa;
  1945. }
  1946. #endif /* !NO_BIO */
  1947. /* Create an RSA private key by reading the PEM encoded data from the file
  1948. * pointer.
  1949. *
  1950. * @param [in] fp File pointer to read from.
  1951. * @param [out] out RSA key created.
  1952. * @param [in] cb Password callback when PEM encrypted.
  1953. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1954. * @return RSA key on success.
  1955. * @return NULL on failure.
  1956. */
  1957. #ifndef NO_FILESYSTEM
  1958. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  1959. wc_pem_password_cb* cb, void* pass)
  1960. {
  1961. WOLFSSL_RSA* rsa = NULL;
  1962. DerBuffer* der = NULL;
  1963. int keyFormat = 0;
  1964. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  1965. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  1966. &keyFormat, &der) >= 0)) {
  1967. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1968. WOLFSSL_RSA_LOAD_PRIVATE);
  1969. if (rsa == NULL) {
  1970. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1971. }
  1972. }
  1973. FreeDer(&der);
  1974. if ((out != NULL) && (rsa != NULL)) {
  1975. *out = rsa;
  1976. }
  1977. return rsa;
  1978. }
  1979. #endif /* !NO_FILESYSTEM */
  1980. /*
  1981. * RSA print APIs
  1982. */
  1983. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  1984. !defined(NO_STDIO_FILESYSTEM)
  1985. /* Print an RSA key to a file pointer.
  1986. *
  1987. * @param [in] fp File pointer to write to.
  1988. * @param [in] rsa RSA key to write.
  1989. * @param [in] indent Number of spaces to prepend to each line.
  1990. * @return 1 on success.
  1991. * @return 0 on failure.
  1992. */
  1993. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  1994. {
  1995. int ret = 1;
  1996. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  1997. /* Validate parameters. */
  1998. if ((fp == XBADFILE) || (rsa == NULL)) {
  1999. ret = 0;
  2000. }
  2001. /* Set the external data from the wolfCrypt RSA key if not done. */
  2002. if ((ret == 1) && (!rsa->exSet)) {
  2003. ret = SetRsaExternal(rsa);
  2004. }
  2005. /* Get the key size from modulus if available. */
  2006. if ((ret == 1) && (rsa->n != NULL)) {
  2007. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2008. if (keySize == 0) {
  2009. ret = 0;
  2010. }
  2011. else {
  2012. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2013. ret = 0;
  2014. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2015. keySize) < 0)
  2016. ret = 0;
  2017. }
  2018. }
  2019. /* Print out any components available. */
  2020. if ((ret == 1) && (rsa->n != NULL)) {
  2021. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2022. }
  2023. if ((ret == 1) && (rsa->d != NULL)) {
  2024. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2025. }
  2026. if ((ret == 1) && (rsa->p != NULL)) {
  2027. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2028. }
  2029. if ((ret == 1) && (rsa->q != NULL)) {
  2030. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2031. }
  2032. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2033. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2034. }
  2035. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2036. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2037. }
  2038. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2039. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2040. }
  2041. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2042. return ret;
  2043. }
  2044. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2045. #if defined(XSNPRINTF) && !defined(NO_BIO)
  2046. /* snprintf() must be available */
  2047. /* Maximum size of a header line. */
  2048. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2049. /* Writes the human readable form of RSA to a BIO.
  2050. *
  2051. * @param [in] bio BIO object to write to.
  2052. * @param [in] rsa RSA key to write.
  2053. * @param [in] indent Number of spaces before each line.
  2054. * @return 1 on success.
  2055. * @return 0 on failure.
  2056. */
  2057. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2058. {
  2059. int ret = 1;
  2060. int sz = 0;
  2061. RsaKey* key = NULL;
  2062. char line[RSA_PRINT_MAX_HEADER_LINE];
  2063. int i = 0;
  2064. mp_int *num = NULL;
  2065. /* Header strings. */
  2066. const char *name[] = {
  2067. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2068. "Exponent1:", "Exponent2:", "Coefficient:"
  2069. };
  2070. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2071. /* Validate parameters. */
  2072. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2073. ret = -1;
  2074. }
  2075. if (ret == 1) {
  2076. key = (RsaKey*)rsa->internal;
  2077. /* Get size in bits of key for printing out. */
  2078. sz = wolfSSL_RSA_bits(rsa);
  2079. if (sz <= 0) {
  2080. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2081. ret = 0;
  2082. }
  2083. }
  2084. if (ret == 1) {
  2085. /* Print any indent spaces. */
  2086. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2087. }
  2088. if (ret == 1) {
  2089. /* Print header line. */
  2090. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2091. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2092. if (len >= (int)sizeof(line)) {
  2093. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2094. ret = 0;
  2095. }
  2096. else {
  2097. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2098. ret = 0;
  2099. }
  2100. }
  2101. }
  2102. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2103. /* Get mp_int for index. */
  2104. switch (i) {
  2105. case 0:
  2106. /* Print out modulus */
  2107. num = &key->n;
  2108. break;
  2109. case 1:
  2110. num = &key->e;
  2111. break;
  2112. case 2:
  2113. num = &key->d;
  2114. break;
  2115. case 3:
  2116. num = &key->p;
  2117. break;
  2118. case 4:
  2119. num = &key->q;
  2120. break;
  2121. case 5:
  2122. num = &key->dP;
  2123. break;
  2124. case 6:
  2125. num = &key->dQ;
  2126. break;
  2127. case 7:
  2128. num = &key->u;
  2129. break;
  2130. default:
  2131. WOLFSSL_ERROR_MSG("Bad index value");
  2132. }
  2133. if (i == 1) {
  2134. /* Print exponent as a 32-bit value. */
  2135. ret = wolfssl_print_value(bio, num, name[i], indent);
  2136. }
  2137. else if (!mp_iszero(num)) {
  2138. /* Print name and MP integer. */
  2139. ret = wolfssl_print_number(bio, num, name[i], indent);
  2140. }
  2141. }
  2142. return ret;
  2143. }
  2144. #endif /* XSNPRINTF && !NO_BIO */
  2145. #endif /* OPENSSL_EXTRA */
  2146. /*
  2147. * RSA get/set/test APIs
  2148. */
  2149. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2150. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2151. *
  2152. * @param [in, out] rsa RSA key.
  2153. * @return 1 on success.
  2154. * @return 0 on failure.
  2155. */
  2156. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2157. {
  2158. int ret = 1;
  2159. WOLFSSL_ENTER("SetRsaExternal");
  2160. /* Validate parameters. */
  2161. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2162. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2163. ret = -1;
  2164. }
  2165. if (ret == 1) {
  2166. RsaKey* key = (RsaKey*)rsa->internal;
  2167. /* Copy modulus. */
  2168. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2169. if (ret != 1) {
  2170. WOLFSSL_ERROR_MSG("rsa n error");
  2171. }
  2172. if (ret == 1) {
  2173. /* Copy public exponent. */
  2174. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2175. if (ret != 1) {
  2176. WOLFSSL_ERROR_MSG("rsa e error");
  2177. }
  2178. }
  2179. if (key->type == RSA_PRIVATE) {
  2180. if (ret == 1) {
  2181. /* Copy private exponent. */
  2182. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2183. if (ret != 1) {
  2184. WOLFSSL_ERROR_MSG("rsa d error");
  2185. }
  2186. }
  2187. if (ret == 1) {
  2188. /* Copy first prime. */
  2189. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2190. if (ret != 1) {
  2191. WOLFSSL_ERROR_MSG("rsa p error");
  2192. }
  2193. }
  2194. if (ret == 1) {
  2195. /* Copy second prime. */
  2196. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2197. if (ret != 1) {
  2198. WOLFSSL_ERROR_MSG("rsa q error");
  2199. }
  2200. }
  2201. #ifndef RSA_LOW_MEM
  2202. if (ret == 1) {
  2203. /* Copy d mod p-1. */
  2204. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2205. if (ret != 1) {
  2206. WOLFSSL_ERROR_MSG("rsa dP error");
  2207. }
  2208. }
  2209. if (ret == 1) {
  2210. /* Copy d mod q-1. */
  2211. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2212. if (ret != 1) {
  2213. WOLFSSL_ERROR_MSG("rsa dq error");
  2214. }
  2215. }
  2216. if (ret == 1) {
  2217. /* Copy 1/q mod p. */
  2218. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2219. if (ret != 1) {
  2220. WOLFSSL_ERROR_MSG("rsa u error");
  2221. }
  2222. }
  2223. #endif /* !RSA_LOW_MEM */
  2224. }
  2225. }
  2226. if (ret == 1) {
  2227. /* External values set. */
  2228. rsa->exSet = 1;
  2229. }
  2230. else {
  2231. /* Return 0 on failure. */
  2232. ret = 0;
  2233. }
  2234. return ret;
  2235. }
  2236. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2237. #ifdef OPENSSL_EXTRA
  2238. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2239. *
  2240. * @param [in, out] rsa RSA key.
  2241. * @return 1 on success.
  2242. * @return 0 on failure.
  2243. */
  2244. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2245. {
  2246. int ret = 1;
  2247. WOLFSSL_ENTER("SetRsaInternal");
  2248. /* Validate parameters. */
  2249. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2250. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2251. ret = -1;
  2252. }
  2253. if (ret == 1) {
  2254. RsaKey* key = (RsaKey*)rsa->internal;
  2255. /* Copy down modulus if available. */
  2256. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2257. WOLFSSL_ERROR_MSG("rsa n key error");
  2258. ret = -1;
  2259. }
  2260. /* Copy down public exponent if available. */
  2261. if ((ret == 1) && (rsa->e != NULL) &&
  2262. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2263. WOLFSSL_ERROR_MSG("rsa e key error");
  2264. ret = -1;
  2265. }
  2266. /* Enough numbers for public key */
  2267. key->type = RSA_PUBLIC;
  2268. /* Copy down private exponent if available. */
  2269. if ((ret == 1) && (rsa->d != NULL)) {
  2270. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2271. WOLFSSL_ERROR_MSG("rsa d key error");
  2272. ret = -1;
  2273. }
  2274. else {
  2275. /* Enough numbers for private key */
  2276. key->type = RSA_PRIVATE;
  2277. }
  2278. }
  2279. /* Copy down first prime if available. */
  2280. if ((ret == 1) && (rsa->p != NULL) &&
  2281. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2282. WOLFSSL_ERROR_MSG("rsa p key error");
  2283. ret = -1;
  2284. }
  2285. /* Copy down second prime if available. */
  2286. if ((ret == 1) && (rsa->q != NULL) &&
  2287. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2288. WOLFSSL_ERROR_MSG("rsa q key error");
  2289. ret = -1;
  2290. }
  2291. #ifndef RSA_LOW_MEM
  2292. /* Copy down d mod p-1 if available. */
  2293. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2294. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2295. WOLFSSL_ERROR_MSG("rsa dP key error");
  2296. ret = -1;
  2297. }
  2298. /* Copy down d mod q-1 if available. */
  2299. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2300. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2301. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2302. ret = -1;
  2303. }
  2304. /* Copy down 1/q mod p if available. */
  2305. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2306. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2307. WOLFSSL_ERROR_MSG("rsa u key error");
  2308. ret = -1;
  2309. }
  2310. #endif /* !RSA_LOW_MEM */
  2311. if (ret == 1) {
  2312. /* All available numbers have been set down. */
  2313. rsa->inSet = 1;
  2314. }
  2315. }
  2316. return ret;
  2317. }
  2318. /* Set the RSA method into object.
  2319. *
  2320. * @param [in, out] rsa RSA key.
  2321. * @param [in] meth RSA method.
  2322. * @return 1 always.
  2323. */
  2324. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2325. {
  2326. if (rsa != NULL) {
  2327. /* Store the method into object. */
  2328. rsa->meth = meth;
  2329. /* Copy over flags. */
  2330. rsa->flags = meth->flags;
  2331. }
  2332. /* OpenSSL always assumes it will work. */
  2333. return 1;
  2334. }
  2335. /* Get the RSA method from the RSA object.
  2336. *
  2337. * @param [in] rsa RSA key.
  2338. * @return RSA method on success.
  2339. * @return NULL when RSA is NULL or no method set.
  2340. */
  2341. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2342. {
  2343. return (rsa != NULL) ? rsa->meth : NULL;
  2344. }
  2345. /* Get the size in bytes of the RSA key.
  2346. *
  2347. * Return compliant with OpenSSL
  2348. *
  2349. * @param [in] rsa RSA key.
  2350. * @return RSA modulus size in bytes.
  2351. * @return 0 on error.
  2352. */
  2353. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2354. {
  2355. int ret = 0;
  2356. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2357. if (rsa != NULL) {
  2358. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2359. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2360. /* Get key size in bytes using wolfCrypt RSA key. */
  2361. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2362. }
  2363. }
  2364. return ret;
  2365. }
  2366. /* Get the size in bits of the RSA key.
  2367. *
  2368. * Uses external modulus field.
  2369. *
  2370. * @param [in] rsa RSA key.
  2371. * @return RSA modulus size in bits.
  2372. * @return 0 on error.
  2373. */
  2374. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2375. {
  2376. int ret = 0;
  2377. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2378. if (rsa != NULL) {
  2379. /* Get number of bits in external modulus. */
  2380. ret = wolfSSL_BN_num_bits(rsa->n);
  2381. }
  2382. return ret;
  2383. }
  2384. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2385. *
  2386. * Only for those that are not NULL parameters.
  2387. *
  2388. * @param [in] rsa RSA key.
  2389. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2390. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2391. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2392. */
  2393. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2394. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2395. const WOLFSSL_BIGNUM **iqmp)
  2396. {
  2397. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2398. /* For any parameters not NULL, return the BN from the key or NULL. */
  2399. if (dmp1 != NULL) {
  2400. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2401. }
  2402. if (dmq1 != NULL) {
  2403. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2404. }
  2405. if (iqmp != NULL) {
  2406. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2407. }
  2408. }
  2409. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2410. * into RSA key.
  2411. *
  2412. * If CRT parameter is NULL then there must be one in the RSA key already.
  2413. *
  2414. * @param [in, out] rsa RSA key.
  2415. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2416. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2417. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2418. * @return 1 on success.
  2419. * @return 0 on failure.
  2420. */
  2421. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2422. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2423. {
  2424. int ret = 1;
  2425. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2426. /* If a param is NULL in rsa then it must be non-NULL in the
  2427. * corresponding user input. */
  2428. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2429. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2430. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2431. WOLFSSL_ERROR_MSG("Bad parameters");
  2432. ret = 0;
  2433. }
  2434. if (ret == 1) {
  2435. /* Replace the BNs. */
  2436. if (dmp1 != NULL) {
  2437. wolfSSL_BN_clear_free(rsa->dmp1);
  2438. rsa->dmp1 = dmp1;
  2439. }
  2440. if (dmq1 != NULL) {
  2441. wolfSSL_BN_clear_free(rsa->dmq1);
  2442. rsa->dmq1 = dmq1;
  2443. }
  2444. if (iqmp != NULL) {
  2445. wolfSSL_BN_clear_free(rsa->iqmp);
  2446. rsa->iqmp = iqmp;
  2447. }
  2448. /* Set the values into the wolfCrypt RSA key. */
  2449. if (SetRsaInternal(rsa) != 1) {
  2450. if (dmp1 != NULL) {
  2451. rsa->dmp1 = NULL;
  2452. }
  2453. if (dmq1 != NULL) {
  2454. rsa->dmq1 = NULL;
  2455. }
  2456. if (iqmp != NULL) {
  2457. rsa->iqmp = NULL;
  2458. }
  2459. ret = 0;
  2460. }
  2461. }
  2462. return ret;
  2463. }
  2464. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2465. *
  2466. * @param [in] rsa RSA key.
  2467. * @param [out] p BN that is first prime. May be NULL.
  2468. * @param [out] q BN that is second prime. May be NULL.
  2469. */
  2470. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2471. const WOLFSSL_BIGNUM **q)
  2472. {
  2473. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2474. /* For any primes not NULL, return the BN from the key or NULL. */
  2475. if (p != NULL) {
  2476. *p = (rsa != NULL) ? rsa->p : NULL;
  2477. }
  2478. if (q != NULL) {
  2479. *q = (rsa != NULL) ? rsa->q : NULL;
  2480. }
  2481. }
  2482. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2483. *
  2484. * If factor parameter is NULL then there must be one in the RSA key already.
  2485. *
  2486. * @param [in, out] rsa RSA key.
  2487. * @param [in] p BN that is first prime. May be NULL.
  2488. * @param [in] q BN that is second prime. May be NULL.
  2489. * @return 1 on success.
  2490. * @return 0 on failure.
  2491. */
  2492. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2493. WOLFSSL_BIGNUM *q)
  2494. {
  2495. int ret = 1;
  2496. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2497. /* If a param is null in r then it must be non-null in the
  2498. * corresponding user input. */
  2499. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2500. ((rsa->q == NULL) && (q == NULL))) {
  2501. WOLFSSL_ERROR_MSG("Bad parameters");
  2502. ret = 0;
  2503. }
  2504. if (ret == 1) {
  2505. /* Replace the BNs. */
  2506. if (p != NULL) {
  2507. wolfSSL_BN_clear_free(rsa->p);
  2508. rsa->p = p;
  2509. }
  2510. if (q != NULL) {
  2511. wolfSSL_BN_clear_free(rsa->q);
  2512. rsa->q = q;
  2513. }
  2514. /* Set the values into the wolfCrypt RSA key. */
  2515. if (SetRsaInternal(rsa) != 1) {
  2516. if (p != NULL) {
  2517. rsa->p = NULL;
  2518. }
  2519. if (q != NULL) {
  2520. rsa->q = NULL;
  2521. }
  2522. ret = 0;
  2523. }
  2524. }
  2525. return ret;
  2526. }
  2527. /* Get the BN objects for the basic key numbers of the RSA key (modulus, public
  2528. * exponent, private exponent).
  2529. *
  2530. * @param [in] rsa RSA key.
  2531. * @param [out] n BN that is the modulus. May be NULL.
  2532. * @param [out] e BN that is the public exponent. May be NULL.
  2533. * @param [out] d BN that is the private exponent. May be NULL.
  2534. */
  2535. void wolfSSL_RSA_get0_key(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **n,
  2536. const WOLFSSL_BIGNUM **e, const WOLFSSL_BIGNUM **d)
  2537. {
  2538. WOLFSSL_ENTER("wolfSSL_RSA_get0_key");
  2539. /* For any parameters not NULL, return the BN from the key or NULL. */
  2540. if (n != NULL) {
  2541. *n = (rsa != NULL) ? rsa->n : NULL;
  2542. }
  2543. if (e != NULL) {
  2544. *e = (rsa != NULL) ? rsa->e : NULL;
  2545. }
  2546. if (d != NULL) {
  2547. *d = (rsa != NULL) ? rsa->d : NULL;
  2548. }
  2549. }
  2550. /* Set the BN objects for the basic key numbers into the RSA key (modulus,
  2551. * public exponent, private exponent).
  2552. *
  2553. * If BN parameter is NULL then there must be one in the RSA key already.
  2554. *
  2555. * @param [in,out] rsa RSA key.
  2556. * @param [in] n BN that is the modulus. May be NULL.
  2557. * @param [in] e BN that is the public exponent. May be NULL.
  2558. * @param [in] d BN that is the private exponent. May be NULL.
  2559. * @return 1 on success.
  2560. * @return 0 on failure.
  2561. */
  2562. int wolfSSL_RSA_set0_key(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *n, WOLFSSL_BIGNUM *e,
  2563. WOLFSSL_BIGNUM *d)
  2564. {
  2565. int ret = 1;
  2566. /* If the fields n and e in r are NULL, the corresponding input
  2567. * parameters MUST be non-NULL for n and e. d may be
  2568. * left NULL (in case only the public key is used).
  2569. */
  2570. if ((rsa == NULL) || ((rsa->n == NULL) && (n == NULL)) ||
  2571. ((rsa->e == NULL) && (e == NULL))) {
  2572. ret = 0;
  2573. }
  2574. if (ret == 1) {
  2575. /* Replace the BNs. */
  2576. if (n != NULL) {
  2577. wolfSSL_BN_free(rsa->n);
  2578. rsa->n = n;
  2579. }
  2580. if (e != NULL) {
  2581. wolfSSL_BN_free(rsa->e);
  2582. rsa->e = e;
  2583. }
  2584. if (d != NULL) {
  2585. /* Private key is sensitive data. */
  2586. wolfSSL_BN_clear_free(rsa->d);
  2587. rsa->d = d;
  2588. }
  2589. /* Set the values into the wolfCrypt RSA key. */
  2590. if (SetRsaInternal(rsa) != 1) {
  2591. if (n != NULL) {
  2592. rsa->n = NULL;
  2593. }
  2594. if (e != NULL) {
  2595. rsa->e = NULL;
  2596. }
  2597. if (d != NULL) {
  2598. rsa->d = NULL;
  2599. }
  2600. ret = 0;
  2601. }
  2602. }
  2603. return ret;
  2604. }
  2605. /* Get the flags of the RSA key.
  2606. *
  2607. * @param [in] rsa RSA key.
  2608. * @return Flags set in RSA key on success.
  2609. * @return 0 when RSA key is NULL.
  2610. */
  2611. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2612. {
  2613. int ret = 0;
  2614. /* Get flags from the RSA key if available. */
  2615. if (rsa != NULL) {
  2616. ret = rsa->flags;
  2617. }
  2618. return ret;
  2619. }
  2620. /* Set the flags into the RSA key.
  2621. *
  2622. * @param [in, out] rsa RSA key.
  2623. * @param [in] flags Flags to set.
  2624. */
  2625. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2626. {
  2627. /* Add the flags into RSA key if available. */
  2628. if (rsa != NULL) {
  2629. rsa->flags |= flags;
  2630. }
  2631. }
  2632. /* Clear the flags in the RSA key.
  2633. *
  2634. * @param [in, out] rsa RSA key.
  2635. * @param [in] flags Flags to clear.
  2636. */
  2637. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2638. {
  2639. /* Clear the flags passed in that are on the RSA key if available. */
  2640. if (rsa != NULL) {
  2641. rsa->flags &= ~flags;
  2642. }
  2643. }
  2644. /* Test the flags in the RSA key.
  2645. *
  2646. * @param [in] rsa RSA key.
  2647. * @return Matching flags of RSA key on success.
  2648. * @return 0 when RSA key is NULL.
  2649. */
  2650. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2651. {
  2652. /* Return the flags passed in that are set on the RSA key if available. */
  2653. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2654. }
  2655. /* Get the extra data, by index, associated with the RSA key.
  2656. *
  2657. * @param [in] rsa RSA key.
  2658. * @param [in] idx Index of extra data.
  2659. * @return Extra data (anonymous type) on success.
  2660. * @return NULL on failure.
  2661. */
  2662. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2663. {
  2664. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2665. #ifdef HAVE_EX_DATA
  2666. return (rsa == NULL) ? NULL :
  2667. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2668. #else
  2669. (void)rsa;
  2670. (void)idx;
  2671. return NULL;
  2672. #endif
  2673. }
  2674. /* Set extra data against the RSA key at an index.
  2675. *
  2676. * @param [in, out] rsa RSA key.
  2677. * @param [in] idx Index set set extra data at.
  2678. * @param [in] data Extra data of anonymous type.
  2679. * @return 1 on success.
  2680. * @return 0 on failure.
  2681. */
  2682. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2683. {
  2684. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2685. #ifdef HAVE_EX_DATA
  2686. return (rsa == NULL) ? 0 :
  2687. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2688. #else
  2689. (void)rsa;
  2690. (void)idx;
  2691. (void)data;
  2692. return 0;
  2693. #endif
  2694. }
  2695. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2696. /* Set the extra data and cleanup callback against the RSA key at an index.
  2697. *
  2698. * Not OpenSSL API.
  2699. *
  2700. * @param [in, out] rsa RSA key.
  2701. * @param [in] idx Index set set extra data at.
  2702. * @param [in] data Extra data of anonymous type.
  2703. * @param [in] freeCb Callback function to free extra data.
  2704. * @return 1 on success.
  2705. * @return 0 on failure.
  2706. */
  2707. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2708. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2709. {
  2710. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2711. return (rsa == NULL) ? 0 :
  2712. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2713. freeCb);
  2714. }
  2715. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2716. /*
  2717. * RSA check key APIs
  2718. */
  2719. #ifdef WOLFSSL_RSA_KEY_CHECK
  2720. /* Check that the RSA key is valid using wolfCrypt.
  2721. *
  2722. * @param [in] rsa RSA key.
  2723. * @return 1 on success.
  2724. * @return 0 on failure.
  2725. */
  2726. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2727. {
  2728. int ret = 1;
  2729. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2730. /* Validate parameters. */
  2731. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2732. ret = 0;
  2733. }
  2734. /* Constant RSA - assume internal data has been set. */
  2735. /* Check wolfCrypt RSA key. */
  2736. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2737. ret = 0;
  2738. }
  2739. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2740. return ret;
  2741. }
  2742. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2743. /*
  2744. * RSA generate APIs
  2745. */
  2746. /* Get a random number generator associated with the RSA key.
  2747. *
  2748. * If not able, then get the global if possible.
  2749. * *tmpRng must not be an initialized RNG.
  2750. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2751. * associated with the wolfCrypt RSA key.
  2752. *
  2753. * @param [in] rsa RSA key.
  2754. * @param [out] tmpRng Temporary random number generator.
  2755. * @param [out] initTmpRng Temporary random number generator was initialized.
  2756. *
  2757. * @return A wolfCrypt RNG to use on success.
  2758. * @return NULL on error.
  2759. */
  2760. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2761. {
  2762. WC_RNG* rng = NULL;
  2763. int err = 0;
  2764. /* Check validity of parameters. */
  2765. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2766. err = 1;
  2767. }
  2768. if (!err) {
  2769. /* Haven't initialized any RNG passed through tmpRng. */
  2770. *initTmpRng = 0;
  2771. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2772. /* Use wolfCrypt RSA key's RNG if available/set. */
  2773. rng = ((RsaKey*)rsa->internal)->rng;
  2774. #endif
  2775. }
  2776. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2777. /* Make an RNG with tmpRng or get global. */
  2778. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2779. if ((rng != NULL) && *initTmpRng) {
  2780. *tmpRng = rng;
  2781. }
  2782. }
  2783. return rng;
  2784. }
  2785. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2786. *
  2787. * @param [in, out] rsa RSA key.
  2788. * @param [in] bits Number of bits that the modulus must have.
  2789. * @param [in] e A BN object holding the public exponent to use.
  2790. * @param [in] cb Status callback. Unused.
  2791. * @return 0 on success.
  2792. * @return wolfSSL native error code on error.
  2793. */
  2794. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2795. WOLFSSL_BIGNUM* e, void* cb)
  2796. {
  2797. #ifdef WOLFSSL_KEY_GEN
  2798. int ret = 0;
  2799. #ifdef WOLFSSL_SMALL_STACK
  2800. WC_RNG* tmpRng = NULL;
  2801. #else
  2802. WC_RNG _tmpRng[1];
  2803. WC_RNG* tmpRng = _tmpRng;
  2804. #endif
  2805. int initTmpRng = 0;
  2806. WC_RNG* rng = NULL;
  2807. #endif
  2808. (void)cb;
  2809. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2810. #ifdef WOLFSSL_KEY_GEN
  2811. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2812. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2813. if (rng == NULL) {
  2814. /* Something went wrong so return memory error. */
  2815. ret = MEMORY_E;
  2816. }
  2817. if (ret == 0) {
  2818. /* Generate an RSA key. */
  2819. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2820. (long)wolfSSL_BN_get_word(e), rng);
  2821. if (ret != MP_OKAY) {
  2822. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2823. }
  2824. }
  2825. if (ret == 0) {
  2826. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2827. ret = SetRsaExternal(rsa);
  2828. if (ret == 1) {
  2829. /* Internal matches external. */
  2830. rsa->inSet = 1;
  2831. /* Return success. */
  2832. ret = 0;
  2833. }
  2834. else {
  2835. /* Something went wrong so return memory error. */
  2836. ret = MEMORY_E;
  2837. }
  2838. }
  2839. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2840. if (initTmpRng) {
  2841. wc_FreeRng(tmpRng);
  2842. }
  2843. #ifdef WOLFSSL_SMALL_STACK
  2844. /* Dispose of any allocated RNG. */
  2845. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2846. #endif
  2847. return ret;
  2848. #else
  2849. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2850. (void)rsa;
  2851. (void)e;
  2852. (void)bits;
  2853. return NOT_COMPILED_IN;
  2854. #endif
  2855. }
  2856. /* Generate an RSA key that has the specified modulus size and public exponent.
  2857. *
  2858. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2859. * down to nearest multiple of 8. For example generating a key of size
  2860. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2861. *
  2862. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2863. * @param [in] e Public exponent to use i.e. 65537.
  2864. * @param [in] cb Status callback. Unused.
  2865. * @param [in] data Data to pass to status callback. Unused.
  2866. * @return A new RSA key on success.
  2867. * @return NULL on failure.
  2868. */
  2869. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2870. void(*cb)(int, int, void*), void* data)
  2871. {
  2872. WOLFSSL_RSA* rsa = NULL;
  2873. WOLFSSL_BIGNUM* bn = NULL;
  2874. int err = 0;
  2875. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  2876. (void)cb;
  2877. (void)data;
  2878. /* Validate bits. */
  2879. if (bits < 0) {
  2880. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  2881. err = 1;
  2882. }
  2883. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  2884. * longer values. */
  2885. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  2886. WOLFSSL_ERROR_MSG("Error creating big number");
  2887. err = 1;
  2888. }
  2889. /* Set public exponent. */
  2890. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  2891. WOLFSSL_ERROR_MSG("Error using e value");
  2892. err = 1;
  2893. }
  2894. /* Create an RSA key object to hold generated key. */
  2895. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  2896. WOLFSSL_ERROR_MSG("memory error");
  2897. err = 1;
  2898. }
  2899. while (!err) {
  2900. int ret;
  2901. /* Use wolfCrypt to generate RSA key. */
  2902. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  2903. #ifdef HAVE_FIPS
  2904. /* Keep trying if failed to find a prime. */
  2905. if (ret == PRIME_GEN_E) {
  2906. continue;
  2907. }
  2908. #endif
  2909. if (ret != WOLFSSL_ERROR_NONE) {
  2910. /* Unrecoverable error in generation. */
  2911. err = 1;
  2912. }
  2913. /* Done generating - unrecoverable error or success. */
  2914. break;
  2915. }
  2916. if (err) {
  2917. /* Dispose of RSA key object if generation didn't work. */
  2918. wolfSSL_RSA_free(rsa);
  2919. /* Returning NULL on error. */
  2920. rsa = NULL;
  2921. }
  2922. /* Dispose of the temporary BN used for the public exponent. */
  2923. wolfSSL_BN_free(bn);
  2924. return rsa;
  2925. }
  2926. /* Generate an RSA key that has the specified modulus size and public exponent.
  2927. *
  2928. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2929. * down to nearest multiple of 8. For example generating a key of size
  2930. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2931. *
  2932. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2933. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  2934. * @param [in] cb Status callback. Unused.
  2935. * @return 1 on success.
  2936. * @return 0 on failure.
  2937. */
  2938. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  2939. void* cb)
  2940. {
  2941. int ret = 1;
  2942. /* Validate parameters. */
  2943. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2944. WOLFSSL_ERROR_MSG("bad arguments");
  2945. ret = 0;
  2946. }
  2947. else {
  2948. for (;;) {
  2949. /* Use wolfCrypt to generate RSA key. */
  2950. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  2951. #ifdef HAVE_FIPS
  2952. /* Keep trying again if public key value didn't work. */
  2953. if (gen_ret == PRIME_GEN_E) {
  2954. continue;
  2955. }
  2956. #endif
  2957. if (gen_ret != WOLFSSL_ERROR_NONE) {
  2958. /* Unrecoverable error in generation. */
  2959. ret = 0;
  2960. }
  2961. /* Done generating - unrecoverable error or success. */
  2962. break;
  2963. }
  2964. }
  2965. return ret;
  2966. }
  2967. #endif /* OPENSSL_EXTRA */
  2968. /*
  2969. * RSA padding APIs
  2970. */
  2971. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  2972. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  2973. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  2974. /* Add PKCS#1 PSS padding to hash.
  2975. *
  2976. *
  2977. * +-----------+
  2978. * | M |
  2979. * +-----------+
  2980. * |
  2981. * V
  2982. * Hash
  2983. * |
  2984. * V
  2985. * +--------+----------+----------+
  2986. * M' = |Padding1| mHash | salt |
  2987. * +--------+----------+----------+
  2988. * |
  2989. * +--------+----------+ V
  2990. * DB = |Padding2|maskedseed| Hash
  2991. * +--------+----------+ |
  2992. * | |
  2993. * V | +--+
  2994. * xor <--- MGF <---| |bc|
  2995. * | | +--+
  2996. * | | |
  2997. * V V V
  2998. * +-------------------+----------+--+
  2999. * EM = | maskedDB |maskedseed|bc|
  3000. * +-------------------+----------+--+
  3001. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  3002. *
  3003. * @param [in] rsa RSA key.
  3004. * @param [out] em Encoded message.
  3005. * @param [in[ mHash Message hash.
  3006. * @param [in] hashAlg Hash algorithm.
  3007. * @param [in] saltLen Length of salt to generate.
  3008. * @return 1 on success.
  3009. * @return 0 on failure.
  3010. */
  3011. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3012. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3013. {
  3014. int ret = 1;
  3015. enum wc_HashType hashType;
  3016. int hashLen = 0;
  3017. int emLen = 0;
  3018. int mgf = 0;
  3019. int initTmpRng = 0;
  3020. WC_RNG *rng = NULL;
  3021. #ifdef WOLFSSL_SMALL_STACK
  3022. WC_RNG* tmpRng = NULL;
  3023. #else
  3024. WC_RNG _tmpRng[1];
  3025. WC_RNG* tmpRng = _tmpRng;
  3026. #endif
  3027. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3028. /* Validate parameters. */
  3029. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3030. ret = 0;
  3031. }
  3032. if (ret == 1) {
  3033. /* Get/create an RNG. */
  3034. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3035. if (rng == NULL) {
  3036. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3037. ret = 0;
  3038. }
  3039. }
  3040. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3041. /* Set the external data from the wolfCrypt RSA key if not done. */
  3042. if ((ret == 1) && (!rsa->exSet)) {
  3043. ret = SetRsaExternal(rsa);
  3044. }
  3045. if (ret == 1) {
  3046. /* Get the wolfCrypt hash algorithm type. */
  3047. hashType = EvpMd2MacType(hashAlg);
  3048. if (hashType > WC_HASH_TYPE_MAX) {
  3049. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3050. ret = 0;
  3051. }
  3052. }
  3053. if (ret == 1) {
  3054. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3055. mgf = wc_hash2mgf(hashType);
  3056. if (mgf == WC_MGF1NONE) {
  3057. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3058. ret = 0;
  3059. }
  3060. }
  3061. if (ret == 1) {
  3062. /* Get the length of the hash output. */
  3063. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3064. if (hashLen < 0) {
  3065. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3066. ret = 0;
  3067. }
  3068. }
  3069. if (ret == 1) {
  3070. /* Get length of RSA key - encrypted message length. */
  3071. emLen = wolfSSL_RSA_size(rsa);
  3072. if (ret <= 0) {
  3073. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3074. ret = 0;
  3075. }
  3076. }
  3077. if (ret == 1) {
  3078. /* Calculate the salt length to use for special cases. */
  3079. /* TODO: use special case wolfCrypt values? */
  3080. switch (saltLen) {
  3081. /* Negative saltLen values are treated differently. */
  3082. case RSA_PSS_SALTLEN_DIGEST:
  3083. saltLen = hashLen;
  3084. break;
  3085. case RSA_PSS_SALTLEN_MAX_SIGN:
  3086. case RSA_PSS_SALTLEN_MAX:
  3087. #ifdef WOLFSSL_PSS_LONG_SALT
  3088. saltLen = emLen - hashLen - 2;
  3089. #else
  3090. saltLen = hashLen;
  3091. #endif
  3092. break;
  3093. default:
  3094. if (saltLen < 0) {
  3095. /* No other negative values implemented. */
  3096. WOLFSSL_ERROR_MSG("invalid saltLen");
  3097. ret = 0;
  3098. }
  3099. }
  3100. }
  3101. if (ret == 1) {
  3102. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3103. if (wc_RsaPad_ex(mHash, (word32)hashLen, em, (word32)emLen,
  3104. RSA_BLOCK_TYPE_1, rng, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0,
  3105. saltLen, wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3106. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3107. ret = 0;
  3108. }
  3109. }
  3110. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3111. if (initTmpRng) {
  3112. wc_FreeRng(tmpRng);
  3113. }
  3114. #ifdef WOLFSSL_SMALL_STACK
  3115. /* Dispose of any allocated RNG. */
  3116. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3117. #endif
  3118. return ret;
  3119. }
  3120. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3121. *
  3122. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3123. *
  3124. * @param [in] rsa RSA key.
  3125. * @param [in[ mHash Message hash.
  3126. * @param [in] hashAlg Hash algorithm.
  3127. * @param [in] em Encoded message.
  3128. * @param [in] saltLen Length of salt to generate.
  3129. * @return 1 on success.
  3130. * @return 0 on failure.
  3131. */
  3132. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3133. const WOLFSSL_EVP_MD *hashAlg,
  3134. const unsigned char *em, int saltLen)
  3135. {
  3136. int ret = 1;
  3137. int hashLen = 0;
  3138. int mgf = 0;
  3139. int emLen = 0;
  3140. int mPrimeLen = 0;
  3141. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3142. byte *mPrime = NULL;
  3143. byte *buf = NULL;
  3144. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3145. /* Validate parameters. */
  3146. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3147. ret = 0;
  3148. }
  3149. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3150. /* Set the external data from the wolfCrypt RSA key if not done. */
  3151. if ((ret == 1) && (!rsa->exSet)) {
  3152. ret = SetRsaExternal(rsa);
  3153. }
  3154. if (ret == 1) {
  3155. /* Get hash length for hash algorithm. */
  3156. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3157. if (hashLen < 0) {
  3158. ret = 0;
  3159. }
  3160. }
  3161. if (ret == 1) {
  3162. /* Get length of RSA key - encrypted message length. */
  3163. emLen = wolfSSL_RSA_size(rsa);
  3164. if (emLen <= 0) {
  3165. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3166. ret = 0;
  3167. }
  3168. }
  3169. if (ret == 1) {
  3170. /* Calculate the salt length to use for special cases. */
  3171. switch (saltLen) {
  3172. /* Negative saltLen values are treated differently */
  3173. case RSA_PSS_SALTLEN_DIGEST:
  3174. saltLen = hashLen;
  3175. break;
  3176. case RSA_PSS_SALTLEN_AUTO:
  3177. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3178. saltLen = RSA_PSS_SALT_LEN_DISCOVER;
  3179. break;
  3180. #endif
  3181. case RSA_PSS_SALTLEN_MAX:
  3182. #ifdef WOLFSSL_PSS_LONG_SALT
  3183. saltLen = emLen - hashLen - 2;
  3184. #else
  3185. saltLen = hashLen;
  3186. #endif
  3187. break;
  3188. default:
  3189. if (saltLen < 0) {
  3190. /* No other negative values implemented. */
  3191. WOLFSSL_ERROR_MSG("invalid saltLen");
  3192. ret = 0;
  3193. }
  3194. }
  3195. }
  3196. if (ret == 1) {
  3197. /* Get the wolfCrypt hash algorithm type. */
  3198. hashType = EvpMd2MacType(hashAlg);
  3199. if (hashType > WC_HASH_TYPE_MAX) {
  3200. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3201. ret = 0;
  3202. }
  3203. }
  3204. if (ret == 1) {
  3205. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3206. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3207. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3208. ret = 0;
  3209. }
  3210. }
  3211. if (ret == 1) {
  3212. /* Allocate buffer to unpad inline with. */
  3213. buf = (byte*)XMALLOC((size_t)emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3214. if (buf == NULL) {
  3215. WOLFSSL_ERROR_MSG("malloc error");
  3216. ret = 0;
  3217. }
  3218. }
  3219. if (ret == 1) {
  3220. /* Copy encrypted message to temp for inline unpadding. */
  3221. XMEMCPY(buf, em, (size_t)emLen);
  3222. /* Remove and verify the PSS padding. */
  3223. mPrimeLen = wc_RsaUnPad_ex(buf, (word32)emLen, &mPrime,
  3224. RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3225. wolfSSL_BN_num_bits(rsa->n), NULL);
  3226. if (mPrimeLen < 0) {
  3227. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3228. ret = 0;
  3229. }
  3230. }
  3231. if (ret == 1) {
  3232. /* Verify the hash is correct. */
  3233. if (wc_RsaPSS_CheckPadding_ex(mHash, (word32)hashLen, mPrime,
  3234. (word32)mPrimeLen, hashType, saltLen,
  3235. wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3236. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3237. ret = 0;
  3238. }
  3239. }
  3240. /* Dispose of any allocated buffer. */
  3241. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3242. return ret;
  3243. }
  3244. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3245. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3246. * WOLFSSL_NGINX) */
  3247. /*
  3248. * RSA sign/verify APIs
  3249. */
  3250. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3251. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3252. #else
  3253. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3254. #endif
  3255. #if defined(OPENSSL_EXTRA)
  3256. /* Encode the message hash.
  3257. *
  3258. * Used by signing and verification.
  3259. *
  3260. * @param [in] hashAlg Hash algorithm OID.
  3261. * @param [in] hash Hash of message to encode for signing.
  3262. * @param [in] hLen Length of hash of message.
  3263. * @param [out] enc Encoded message hash.
  3264. * @param [out] encLen Length of encoded message hash.
  3265. * @param [in] padding Which padding scheme is being used.
  3266. * @return 1 on success.
  3267. * @return 0 on failure.
  3268. */
  3269. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3270. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3271. {
  3272. int ret = 1;
  3273. int hType = WC_HASH_TYPE_NONE;
  3274. /* Validate parameters. */
  3275. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3276. ret = 0;
  3277. }
  3278. if ((ret == 1) && (hashAlg != NID_undef) &&
  3279. (padding == RSA_PKCS1_PADDING)) {
  3280. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3281. hType = (int)nid2oid(hashAlg, oidHashType);
  3282. if (hType == -1) {
  3283. ret = 0;
  3284. }
  3285. }
  3286. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3287. /* PKCS#1.5 encoding. */
  3288. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3289. if (encSz == 0) {
  3290. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3291. ret = 0;
  3292. }
  3293. else {
  3294. *encLen = (unsigned int)encSz;
  3295. }
  3296. }
  3297. /* Other padding schemes require the hash as is. */
  3298. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3299. XMEMCPY(enc, hash, hLen);
  3300. *encLen = hLen;
  3301. }
  3302. return ret;
  3303. }
  3304. /* Sign the message hash using hash algorithm and RSA key.
  3305. *
  3306. * @param [in] hashAlg Hash algorithm OID.
  3307. * @param [in] hash Hash of message to encode for signing.
  3308. * @param [in] hLen Length of hash of message.
  3309. * @param [out] enc Encoded message hash.
  3310. * @param [out] encLen Length of encoded message hash.
  3311. * @param [in] rsa RSA key.
  3312. * @return 1 on success.
  3313. * @return 0 on failure.
  3314. */
  3315. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3316. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3317. {
  3318. if (sigLen != NULL) {
  3319. /* No size checking in this API */
  3320. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3321. }
  3322. /* flag is 1: output complete signature. */
  3323. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3324. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3325. }
  3326. /* Sign the message hash using hash algorithm and RSA key.
  3327. *
  3328. * Not OpenSSL API.
  3329. *
  3330. * @param [in] hashAlg Hash algorithm NID.
  3331. * @param [in] hash Hash of message to encode for signing.
  3332. * @param [in] hLen Length of hash of message.
  3333. * @param [out] enc Encoded message hash.
  3334. * @param [out] encLen Length of encoded message hash.
  3335. * @param [in] rsa RSA key.
  3336. * @param [in] flag When 1: Output encrypted signature.
  3337. * When 0: Output encoded hash.
  3338. * @return 1 on success.
  3339. * @return 0 on failure.
  3340. */
  3341. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3342. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3343. WOLFSSL_RSA* rsa, int flag)
  3344. {
  3345. int ret = 0;
  3346. if ((flag == 0) || (flag == 1)) {
  3347. if (sigLen != NULL) {
  3348. /* No size checking in this API */
  3349. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3350. }
  3351. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3352. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3353. }
  3354. return ret;
  3355. }
  3356. /**
  3357. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3358. *
  3359. * Not OpenSSL API.
  3360. *
  3361. * @param [in] hashAlg Hash NID
  3362. * @param [in] hash Message hash to sign.
  3363. * @param [in] mLen Length of message hash to sign.
  3364. * @param [out] sigRet Output buffer.
  3365. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3366. * On Output: length of data written to sigRet.
  3367. * @param [in] rsa RSA key used to sign the input.
  3368. * @param [in] flag 1: Output the signature.
  3369. * 0: Output the value that the unpadded signature
  3370. * should be compared to.
  3371. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3372. * RSA_PKCS1_PADDING are currently supported for
  3373. * signing.
  3374. * @return 1 on success.
  3375. * @return 0 on failure.
  3376. */
  3377. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3378. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3379. WOLFSSL_RSA* rsa, int flag, int padding)
  3380. {
  3381. int ret = 1;
  3382. word32 outLen = 0;
  3383. int signSz = 0;
  3384. WC_RNG* rng = NULL;
  3385. int initTmpRng = 0;
  3386. #ifdef WOLFSSL_SMALL_STACK
  3387. WC_RNG* tmpRng = NULL;
  3388. byte* encodedSig = NULL;
  3389. #else
  3390. WC_RNG _tmpRng[1];
  3391. WC_RNG* tmpRng = _tmpRng;
  3392. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3393. #endif
  3394. unsigned int encSz = 0;
  3395. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3396. if (flag == 0) {
  3397. /* Only encode message. */
  3398. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3399. padding);
  3400. }
  3401. /* Validate parameters. */
  3402. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3403. WOLFSSL_ERROR_MSG("Bad function arguments");
  3404. ret = 0;
  3405. }
  3406. /* Set wolfCrypt RSA key data from external if not already done. */
  3407. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3408. ret = 0;
  3409. }
  3410. if (ret == 1) {
  3411. /* Get the maximum signature length. */
  3412. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3413. /* Check not an error return. */
  3414. if (outLen == 0) {
  3415. WOLFSSL_ERROR_MSG("Bad RSA size");
  3416. ret = 0;
  3417. }
  3418. /* Check signature buffer is big enough. */
  3419. else if (outLen > *sigLen) {
  3420. WOLFSSL_ERROR_MSG("Output buffer too small");
  3421. ret = 0;
  3422. }
  3423. }
  3424. #ifdef WOLFSSL_SMALL_STACK
  3425. if (ret == 1) {
  3426. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3427. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3428. DYNAMIC_TYPE_SIGNATURE);
  3429. if (encodedSig == NULL) {
  3430. ret = 0;
  3431. }
  3432. }
  3433. #endif
  3434. if (ret == 1) {
  3435. /* Get/create an RNG. */
  3436. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3437. if (rng == NULL) {
  3438. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3439. ret = 0;
  3440. }
  3441. }
  3442. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3443. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3444. &encSz, padding) == 0)) {
  3445. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3446. ret = 0;
  3447. }
  3448. if (ret == 1) {
  3449. switch (padding) {
  3450. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3451. case RSA_NO_PADDING:
  3452. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3453. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3454. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3455. ret = 0;
  3456. }
  3457. break;
  3458. #endif
  3459. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3460. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3461. case RSA_PKCS1_PSS_PADDING:
  3462. {
  3463. enum wc_HashType hType =
  3464. wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3465. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3466. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3467. "OpenSSL uses max length by default.");
  3468. #endif
  3469. /* Create RSA PSS signature. */
  3470. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3471. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3472. (RsaKey*)rsa->internal, rng)) <= 0) {
  3473. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3474. ret = 0;
  3475. }
  3476. break;
  3477. }
  3478. #endif
  3479. #ifndef WC_NO_RSA_OAEP
  3480. case RSA_PKCS1_OAEP_PADDING:
  3481. /* Not a signature padding scheme. */
  3482. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3483. "signing");
  3484. ret = 0;
  3485. break;
  3486. #endif
  3487. case RSA_PKCS1_PADDING:
  3488. {
  3489. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3490. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3491. (RsaKey*)rsa->internal, rng)) <= 0) {
  3492. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3493. ret = 0;
  3494. }
  3495. break;
  3496. }
  3497. default:
  3498. WOLFSSL_ERROR_MSG("Unsupported padding");
  3499. ret = 0;
  3500. break;
  3501. }
  3502. }
  3503. if (ret == 1) {
  3504. /* Return the size of signature generated. */
  3505. *sigLen = (unsigned int)signSz;
  3506. }
  3507. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3508. if (initTmpRng) {
  3509. wc_FreeRng(tmpRng);
  3510. }
  3511. #ifdef WOLFSSL_SMALL_STACK
  3512. /* Dispose of any allocated RNG and encoded signature. */
  3513. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3514. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3515. #endif
  3516. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3517. return ret;
  3518. }
  3519. /**
  3520. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3521. *
  3522. * @param [in] hashAlg Hash NID
  3523. * @param [in] hash Message hash.
  3524. * @param [in] mLen Length of message hash.
  3525. * @param [in] sigRet Signature data.
  3526. * @param [in] sigLen Length of signature data.
  3527. * @param [in] rsa RSA key used to sign the input
  3528. * @return 1 on success.
  3529. * @return 0 on failure.
  3530. */
  3531. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3532. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3533. WOLFSSL_RSA* rsa)
  3534. {
  3535. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3536. RSA_PKCS1_PADDING);
  3537. }
  3538. /**
  3539. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3540. *
  3541. * Not OpenSSL API.
  3542. *
  3543. * @param [in] hashAlg Hash NID
  3544. * @param [in] hash Message hash.
  3545. * @param [in] mLen Length of message hash.
  3546. * @param [in] sigRet Signature data.
  3547. * @param [in] sigLen Length of signature data.
  3548. * @param [in] rsa RSA key used to sign the input
  3549. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3550. * RSA_PKCS1_PADDING are currently supported for
  3551. * signing.
  3552. * @return 1 on success.
  3553. * @return 0 on failure.
  3554. */
  3555. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3556. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3557. WOLFSSL_RSA* rsa, int padding)
  3558. {
  3559. int ret = 1;
  3560. #ifdef WOLFSSL_SMALL_STACK
  3561. unsigned char* encodedSig = NULL;
  3562. #else
  3563. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3564. #endif
  3565. unsigned char* sigDec = NULL;
  3566. unsigned int len = MAX_ENCODED_SIG_SZ;
  3567. int verLen = 0;
  3568. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3569. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3570. #endif
  3571. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3572. /* Validate parameters. */
  3573. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3574. WOLFSSL_ERROR_MSG("Bad function arguments");
  3575. ret = 0;
  3576. }
  3577. if (ret == 1) {
  3578. /* Allocate memory for decrypted signature. */
  3579. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3580. DYNAMIC_TYPE_TMP_BUFFER);
  3581. if (sigDec == NULL) {
  3582. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3583. ret = 0;
  3584. }
  3585. }
  3586. #ifdef WOLFSSL_SMALL_STACK
  3587. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3588. /* Allocate memory for encoded signature. */
  3589. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3590. DYNAMIC_TYPE_TMP_BUFFER);
  3591. if (encodedSig == NULL) {
  3592. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3593. ret = 0;
  3594. }
  3595. }
  3596. #endif
  3597. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3598. /* Make encoded signature to compare with decrypted signature. */
  3599. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3600. padding) <= 0) {
  3601. WOLFSSL_ERROR_MSG("Message Digest Error");
  3602. ret = 0;
  3603. }
  3604. }
  3605. if (ret == 1) {
  3606. /* Decrypt signature */
  3607. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3608. !defined(HAVE_SELFTEST)
  3609. hType = wc_OidGetHash((int)nid2oid(hashAlg, oidHashType));
  3610. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3611. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3612. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3613. ret = 0;
  3614. }
  3615. #else
  3616. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3617. (RsaKey*)rsa->internal);
  3618. if (verLen < 0) {
  3619. ret = 0;
  3620. }
  3621. #endif
  3622. }
  3623. if (ret == 1) {
  3624. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3625. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3626. if (padding == RSA_PKCS1_PSS_PADDING) {
  3627. /* Check PSS padding is valid. */
  3628. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, (word32)verLen,
  3629. hType, DEF_PSS_SALT_LEN,
  3630. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3631. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3632. ret = 0;
  3633. }
  3634. }
  3635. else
  3636. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3637. * FIPS_VERSION >= 5.1) */
  3638. /* Compare decrypted signature to encoded signature. */
  3639. if (((int)len != verLen) ||
  3640. (XMEMCMP(encodedSig, sigDec, (size_t)verLen) != 0)) {
  3641. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3642. ret = 0;
  3643. }
  3644. }
  3645. /* Dispose of any allocated data. */
  3646. #ifdef WOLFSSL_SMALL_STACK
  3647. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3648. #endif
  3649. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3650. return ret;
  3651. }
  3652. /*
  3653. * RSA public/private encrypt/decrypt APIs
  3654. */
  3655. /* Encrypt with the RSA public key.
  3656. *
  3657. * Return compliant with OpenSSL.
  3658. *
  3659. * @param [in] len Length of data to encrypt.
  3660. * @param [in] from Data to encrypt.
  3661. * @param [out] to Encrypted data.
  3662. * @param [in] rsa RSA key.
  3663. * @param [in] padding Type of padding to place around plaintext.
  3664. * @return Size of encrypted data on success.
  3665. * @return -1 on failure.
  3666. */
  3667. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3668. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3669. {
  3670. int ret = 0;
  3671. int initTmpRng = 0;
  3672. WC_RNG *rng = NULL;
  3673. #ifdef WOLFSSL_SMALL_STACK
  3674. WC_RNG* tmpRng = NULL;
  3675. #else
  3676. WC_RNG _tmpRng[1];
  3677. WC_RNG* tmpRng = _tmpRng;
  3678. #endif
  3679. #if !defined(HAVE_FIPS)
  3680. int mgf = WC_MGF1NONE;
  3681. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3682. int pad_type = WC_RSA_NO_PAD;
  3683. #endif
  3684. int outLen = 0;
  3685. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3686. /* Validate parameters. */
  3687. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3688. (from == NULL)) {
  3689. WOLFSSL_ERROR_MSG("Bad function arguments");
  3690. ret = -1;
  3691. }
  3692. if (ret == 0) {
  3693. #if !defined(HAVE_FIPS)
  3694. /* Convert to wolfCrypt padding, hash and MGF. */
  3695. switch (padding) {
  3696. case RSA_PKCS1_PADDING:
  3697. pad_type = WC_RSA_PKCSV15_PAD;
  3698. break;
  3699. case RSA_PKCS1_OAEP_PADDING:
  3700. pad_type = WC_RSA_OAEP_PAD;
  3701. hash = WC_HASH_TYPE_SHA;
  3702. mgf = WC_MGF1SHA1;
  3703. break;
  3704. case RSA_NO_PADDING:
  3705. pad_type = WC_RSA_NO_PAD;
  3706. break;
  3707. default:
  3708. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3709. "scheme");
  3710. ret = -1;
  3711. }
  3712. #else
  3713. /* Check for supported padding schemes in FIPS. */
  3714. /* TODO: Do we support more schemes in later versions of FIPS? */
  3715. if (padding != RSA_PKCS1_PADDING) {
  3716. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3717. "FIPS");
  3718. ret = -1;
  3719. }
  3720. #endif
  3721. }
  3722. /* Set wolfCrypt RSA key data from external if not already done. */
  3723. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3724. ret = -1;
  3725. }
  3726. if (ret == 0) {
  3727. /* Calculate maximum length of encrypted data. */
  3728. outLen = wolfSSL_RSA_size(rsa);
  3729. if (outLen == 0) {
  3730. WOLFSSL_ERROR_MSG("Bad RSA size");
  3731. ret = -1;
  3732. }
  3733. }
  3734. if (ret == 0) {
  3735. /* Get an RNG. */
  3736. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3737. if (rng == NULL) {
  3738. ret = -1;
  3739. }
  3740. }
  3741. if (ret == 0) {
  3742. /* Use wolfCrypt to public-encrypt with RSA key. */
  3743. #if !defined(HAVE_FIPS)
  3744. ret = wc_RsaPublicEncrypt_ex(from, (word32)len, to, (word32)outLen,
  3745. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3746. #else
  3747. ret = wc_RsaPublicEncrypt(from, (word32)len, to, (word32)outLen,
  3748. (RsaKey*)rsa->internal, rng);
  3749. #endif
  3750. }
  3751. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3752. if (initTmpRng) {
  3753. wc_FreeRng(tmpRng);
  3754. }
  3755. #ifdef WOLFSSL_SMALL_STACK
  3756. /* Dispose of any allocated RNG. */
  3757. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3758. #endif
  3759. /* wolfCrypt error means return -1. */
  3760. if (ret <= 0) {
  3761. ret = -1;
  3762. }
  3763. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3764. return ret;
  3765. }
  3766. /* Decrypt with the RSA public key.
  3767. *
  3768. * Return compliant with OpenSSL.
  3769. *
  3770. * @param [in] len Length of encrypted data.
  3771. * @param [in] from Encrypted data.
  3772. * @param [out] to Decrypted data.
  3773. * @param [in] rsa RSA key.
  3774. * @param [in] padding Type of padding to around plaintext to remove.
  3775. * @return Size of decrypted data on success.
  3776. * @return -1 on failure.
  3777. */
  3778. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3779. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3780. {
  3781. int ret = 0;
  3782. #if !defined(HAVE_FIPS)
  3783. int mgf = WC_MGF1NONE;
  3784. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3785. int pad_type = WC_RSA_NO_PAD;
  3786. #endif
  3787. int outLen = 0;
  3788. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3789. /* Validate parameters. */
  3790. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3791. (from == NULL)) {
  3792. WOLFSSL_ERROR_MSG("Bad function arguments");
  3793. ret = -1;
  3794. }
  3795. if (ret == 0) {
  3796. #if !defined(HAVE_FIPS)
  3797. switch (padding) {
  3798. case RSA_PKCS1_PADDING:
  3799. pad_type = WC_RSA_PKCSV15_PAD;
  3800. break;
  3801. case RSA_PKCS1_OAEP_PADDING:
  3802. pad_type = WC_RSA_OAEP_PAD;
  3803. hash = WC_HASH_TYPE_SHA;
  3804. mgf = WC_MGF1SHA1;
  3805. break;
  3806. case RSA_NO_PADDING:
  3807. pad_type = WC_RSA_NO_PAD;
  3808. break;
  3809. default:
  3810. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3811. ret = -1;
  3812. }
  3813. #else
  3814. /* Check for supported padding schemes in FIPS. */
  3815. /* TODO: Do we support more schemes in later versions of FIPS? */
  3816. if (padding != RSA_PKCS1_PADDING) {
  3817. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3818. "FIPS");
  3819. ret = -1;
  3820. }
  3821. #endif
  3822. }
  3823. /* Set wolfCrypt RSA key data from external if not already done. */
  3824. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3825. ret = -1;
  3826. }
  3827. if (ret == 0) {
  3828. /* Calculate maximum length of decrypted data. */
  3829. outLen = wolfSSL_RSA_size(rsa);
  3830. if (outLen == 0) {
  3831. WOLFSSL_ERROR_MSG("Bad RSA size");
  3832. ret = -1;
  3833. }
  3834. }
  3835. if (ret == 0) {
  3836. /* Use wolfCrypt to private-decrypt with RSA key.
  3837. * Size of 'to' buffer must be size of RSA key */
  3838. #if !defined(HAVE_FIPS)
  3839. ret = wc_RsaPrivateDecrypt_ex(from, (word32)len, to, (word32)outLen,
  3840. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3841. #else
  3842. ret = wc_RsaPrivateDecrypt(from, (word32)len, to, (word32)outLen,
  3843. (RsaKey*)rsa->internal);
  3844. #endif
  3845. }
  3846. /* wolfCrypt error means return -1. */
  3847. if (ret <= 0) {
  3848. ret = -1;
  3849. }
  3850. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  3851. return ret;
  3852. }
  3853. /* Decrypt with the RSA public key.
  3854. *
  3855. * @param [in] len Length of encrypted data.
  3856. * @param [in] from Encrypted data.
  3857. * @param [out] to Decrypted data.
  3858. * @param [in] rsa RSA key.
  3859. * @param [in] padding Type of padding to around plaintext to remove.
  3860. * @return Size of decrypted data on success.
  3861. * @return -1 on failure.
  3862. */
  3863. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3864. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3865. {
  3866. int ret = 0;
  3867. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3868. int pad_type = WC_RSA_NO_PAD;
  3869. #endif
  3870. int outLen = 0;
  3871. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  3872. /* Validate parameters. */
  3873. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3874. (from == NULL)) {
  3875. WOLFSSL_ERROR_MSG("Bad function arguments");
  3876. ret = -1;
  3877. }
  3878. if (ret == 0) {
  3879. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3880. switch (padding) {
  3881. case RSA_PKCS1_PADDING:
  3882. pad_type = WC_RSA_PKCSV15_PAD;
  3883. break;
  3884. case RSA_NO_PADDING:
  3885. pad_type = WC_RSA_NO_PAD;
  3886. break;
  3887. /* TODO: RSA_X931_PADDING not supported */
  3888. default:
  3889. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  3890. ret = -1;
  3891. }
  3892. #else
  3893. if (padding != RSA_PKCS1_PADDING) {
  3894. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  3895. "FIPS");
  3896. ret = -1;
  3897. }
  3898. #endif
  3899. }
  3900. /* Set wolfCrypt RSA key data from external if not already done. */
  3901. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3902. ret = -1;
  3903. }
  3904. if (ret == 0) {
  3905. /* Calculate maximum length of encrypted data. */
  3906. outLen = wolfSSL_RSA_size(rsa);
  3907. if (outLen == 0) {
  3908. WOLFSSL_ERROR_MSG("Bad RSA size");
  3909. ret = -1;
  3910. }
  3911. }
  3912. if (ret == 0) {
  3913. /* Use wolfCrypt to public-decrypt with RSA key. */
  3914. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3915. /* Size of 'to' buffer must be size of RSA key. */
  3916. ret = wc_RsaSSL_Verify_ex(from, (word32)len, to, (word32)outLen,
  3917. (RsaKey*)rsa->internal, pad_type);
  3918. #else
  3919. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  3920. ret = wc_RsaSSL_Verify(from, (word32)len, to, (word32)outLen,
  3921. (RsaKey*)rsa->internal);
  3922. #endif
  3923. }
  3924. /* wolfCrypt error means return -1. */
  3925. if (ret <= 0) {
  3926. ret = -1;
  3927. }
  3928. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  3929. return ret;
  3930. }
  3931. /* Encrypt with the RSA private key.
  3932. *
  3933. * Calls wc_RsaSSL_Sign.
  3934. *
  3935. * @param [in] len Length of data to encrypt.
  3936. * @param [in] from Data to encrypt.
  3937. * @param [out] to Encrypted data.
  3938. * @param [in] rsa RSA key.
  3939. * @param [in] padding Type of padding to place around plaintext.
  3940. * @return Size of encrypted data on success.
  3941. * @return -1 on failure.
  3942. */
  3943. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  3944. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3945. {
  3946. int ret = 0;
  3947. int initTmpRng = 0;
  3948. WC_RNG *rng = NULL;
  3949. #ifdef WOLFSSL_SMALL_STACK
  3950. WC_RNG* tmpRng = NULL;
  3951. #else
  3952. WC_RNG _tmpRng[1];
  3953. WC_RNG* tmpRng = _tmpRng;
  3954. #endif
  3955. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  3956. /* Validate parameters. */
  3957. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3958. (from == NULL)) {
  3959. WOLFSSL_ERROR_MSG("Bad function arguments");
  3960. ret = -1;
  3961. }
  3962. if (ret == 0) {
  3963. switch (padding) {
  3964. case RSA_PKCS1_PADDING:
  3965. #ifdef WC_RSA_NO_PADDING
  3966. case RSA_NO_PADDING:
  3967. #endif
  3968. break;
  3969. /* TODO: RSA_X931_PADDING not supported */
  3970. default:
  3971. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  3972. ret = -1;
  3973. }
  3974. }
  3975. /* Set wolfCrypt RSA key data from external if not already done. */
  3976. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3977. ret = -1;
  3978. }
  3979. if (ret == 0) {
  3980. /* Get an RNG. */
  3981. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3982. if (rng == NULL) {
  3983. ret = -1;
  3984. }
  3985. }
  3986. if (ret == 0) {
  3987. /* Use wolfCrypt to private-encrypt with RSA key.
  3988. * Size of output buffer must be size of RSA key. */
  3989. if (padding == RSA_PKCS1_PADDING) {
  3990. ret = wc_RsaSSL_Sign(from, (word32)len, to,
  3991. (word32)wolfSSL_RSA_size(rsa), (RsaKey*)rsa->internal, rng);
  3992. }
  3993. #ifdef WC_RSA_NO_PADDING
  3994. else if (padding == RSA_NO_PADDING) {
  3995. word32 outLen = (word32)wolfSSL_RSA_size(rsa);
  3996. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  3997. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  3998. if (ret == 0)
  3999. ret = (int)outLen;
  4000. }
  4001. #endif
  4002. }
  4003. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  4004. if (initTmpRng) {
  4005. wc_FreeRng(tmpRng);
  4006. }
  4007. #ifdef WOLFSSL_SMALL_STACK
  4008. /* Dispose of any allocated RNG. */
  4009. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4010. #endif
  4011. /* wolfCrypt error means return -1. */
  4012. if (ret <= 0) {
  4013. ret = -1;
  4014. }
  4015. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4016. return ret;
  4017. }
  4018. /*
  4019. * RSA misc operation APIs
  4020. */
  4021. /* Calculate d mod p-1 and q-1 into BNs.
  4022. *
  4023. * Not OpenSSL API.
  4024. *
  4025. * @param [in, out] rsa RSA key.
  4026. * @return 1 on success.
  4027. * @return -1 on failure.
  4028. */
  4029. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4030. {
  4031. int ret = 1;
  4032. int err;
  4033. mp_int* t = NULL;
  4034. #ifdef WOLFSSL_SMALL_STACK
  4035. mp_int *tmp = NULL;
  4036. #else
  4037. mp_int tmp[1];
  4038. #endif
  4039. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4040. /* Validate parameters. */
  4041. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4042. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4043. WOLFSSL_ERROR_MSG("rsa no init error");
  4044. ret = -1;
  4045. }
  4046. #ifdef WOLFSSL_SMALL_STACK
  4047. if (ret == 1) {
  4048. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4049. DYNAMIC_TYPE_TMP_BUFFER);
  4050. if (tmp == NULL) {
  4051. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4052. ret = -1;
  4053. }
  4054. }
  4055. #endif
  4056. if (ret == 1) {
  4057. /* Initialize temp MP integer. */
  4058. if (mp_init(tmp) != MP_OKAY) {
  4059. WOLFSSL_ERROR_MSG("mp_init error");
  4060. ret = -1;
  4061. }
  4062. }
  4063. if (ret == 1) {
  4064. t = tmp;
  4065. /* Sub 1 from p into temp. */
  4066. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4067. if (err != MP_OKAY) {
  4068. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4069. ret = -1;
  4070. }
  4071. }
  4072. if (ret == 1) {
  4073. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4074. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4075. (mp_int*)rsa->dmp1->internal);
  4076. if (err != MP_OKAY) {
  4077. WOLFSSL_ERROR_MSG("mp_mod error");
  4078. ret = -1;
  4079. }
  4080. }
  4081. if (ret == 1) {
  4082. /* Sub 1 from q into temp. */
  4083. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4084. if (err != MP_OKAY) {
  4085. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4086. ret = -1;
  4087. }
  4088. }
  4089. if (ret == 1) {
  4090. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4091. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4092. (mp_int*)rsa->dmq1->internal);
  4093. if (err != MP_OKAY) {
  4094. WOLFSSL_ERROR_MSG("mp_mod error");
  4095. ret = -1;
  4096. }
  4097. }
  4098. mp_clear(t);
  4099. #ifdef WOLFSSL_SMALL_STACK
  4100. if (tmp != NULL)
  4101. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4102. #endif
  4103. return ret;
  4104. }
  4105. #ifndef NO_WOLFSSL_STUB
  4106. /* Enable blinding for RSA key operations.
  4107. *
  4108. * Blinding is a compile time option in wolfCrypt.
  4109. *
  4110. * @param [in] rsa RSA key. Unused.
  4111. * @param [in] bnCtx BN context to use for blinding. Unused.
  4112. * @return 1 always.
  4113. */
  4114. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4115. {
  4116. WOLFSSL_STUB("RSA_blinding_on");
  4117. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4118. (void)rsa;
  4119. (void)bnCtx;
  4120. return 1; /* on by default */
  4121. }
  4122. #endif
  4123. #endif /* OPENSSL_EXTRA */
  4124. #endif /* !NO_RSA */
  4125. /*******************************************************************************
  4126. * END OF RSA API
  4127. ******************************************************************************/
  4128. /*******************************************************************************
  4129. * START OF DSA API
  4130. ******************************************************************************/
  4131. #ifndef NO_DSA
  4132. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4133. !defined(NO_STDIO_FILESYSTEM)
  4134. /* return code compliant with OpenSSL :
  4135. * 1 if success, 0 if error
  4136. */
  4137. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4138. {
  4139. int ret = 1;
  4140. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4141. if (fp == XBADFILE || dsa == NULL) {
  4142. ret = 0;
  4143. }
  4144. if (ret == 1 && dsa->p != NULL) {
  4145. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4146. if (pBits == 0) {
  4147. ret = 0;
  4148. }
  4149. else {
  4150. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4151. ret = 0;
  4152. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4153. ret = 0;
  4154. }
  4155. }
  4156. if (ret == 1 && dsa->priv_key != NULL) {
  4157. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4158. }
  4159. if (ret == 1 && dsa->pub_key != NULL) {
  4160. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4161. }
  4162. if (ret == 1 && dsa->p != NULL) {
  4163. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4164. }
  4165. if (ret == 1 && dsa->q != NULL) {
  4166. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4167. }
  4168. if (ret == 1 && dsa->g != NULL) {
  4169. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4170. }
  4171. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4172. return ret;
  4173. }
  4174. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4175. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4176. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4177. {
  4178. if (dsa) {
  4179. dsa->p = NULL;
  4180. dsa->q = NULL;
  4181. dsa->g = NULL;
  4182. dsa->pub_key = NULL;
  4183. dsa->priv_key = NULL;
  4184. dsa->internal = NULL;
  4185. dsa->inSet = 0;
  4186. dsa->exSet = 0;
  4187. }
  4188. }
  4189. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4190. {
  4191. WOLFSSL_DSA* external;
  4192. DsaKey* key;
  4193. WOLFSSL_MSG("wolfSSL_DSA_new");
  4194. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4195. if (key == NULL) {
  4196. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4197. return NULL;
  4198. }
  4199. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4200. DYNAMIC_TYPE_DSA);
  4201. if (external == NULL) {
  4202. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4203. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4204. return NULL;
  4205. }
  4206. InitwolfSSL_DSA(external);
  4207. if (wc_InitDsaKey(key) != 0) {
  4208. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4209. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4210. wolfSSL_DSA_free(external);
  4211. return NULL;
  4212. }
  4213. external->internal = key;
  4214. return external;
  4215. }
  4216. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4217. {
  4218. WOLFSSL_MSG("wolfSSL_DSA_free");
  4219. if (dsa) {
  4220. if (dsa->internal) {
  4221. FreeDsaKey((DsaKey*)dsa->internal);
  4222. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4223. dsa->internal = NULL;
  4224. }
  4225. wolfSSL_BN_free(dsa->priv_key);
  4226. wolfSSL_BN_free(dsa->pub_key);
  4227. wolfSSL_BN_free(dsa->g);
  4228. wolfSSL_BN_free(dsa->q);
  4229. wolfSSL_BN_free(dsa->p);
  4230. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4231. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4232. /* dsa = NULL, don't try to access or double free it */
  4233. }
  4234. }
  4235. /* wolfSSL -> OpenSSL */
  4236. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4237. {
  4238. DsaKey* key;
  4239. WOLFSSL_MSG("Entering SetDsaExternal");
  4240. if (dsa == NULL || dsa->internal == NULL) {
  4241. WOLFSSL_MSG("dsa key NULL error");
  4242. return -1;
  4243. }
  4244. key = (DsaKey*)dsa->internal;
  4245. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4246. WOLFSSL_MSG("dsa p key error");
  4247. return -1;
  4248. }
  4249. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4250. WOLFSSL_MSG("dsa q key error");
  4251. return -1;
  4252. }
  4253. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4254. WOLFSSL_MSG("dsa g key error");
  4255. return -1;
  4256. }
  4257. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4258. WOLFSSL_MSG("dsa y key error");
  4259. return -1;
  4260. }
  4261. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4262. WOLFSSL_MSG("dsa x key error");
  4263. return -1;
  4264. }
  4265. dsa->exSet = 1;
  4266. return 1;
  4267. }
  4268. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4269. #ifdef OPENSSL_EXTRA
  4270. /* Openssl -> WolfSSL */
  4271. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4272. {
  4273. DsaKey* key;
  4274. WOLFSSL_MSG("Entering SetDsaInternal");
  4275. if (dsa == NULL || dsa->internal == NULL) {
  4276. WOLFSSL_MSG("dsa key NULL error");
  4277. return -1;
  4278. }
  4279. key = (DsaKey*)dsa->internal;
  4280. if (dsa->p != NULL &&
  4281. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4282. WOLFSSL_MSG("rsa p key error");
  4283. return -1;
  4284. }
  4285. if (dsa->q != NULL &&
  4286. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4287. WOLFSSL_MSG("rsa q key error");
  4288. return -1;
  4289. }
  4290. if (dsa->g != NULL &&
  4291. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4292. WOLFSSL_MSG("rsa g key error");
  4293. return -1;
  4294. }
  4295. if (dsa->pub_key != NULL) {
  4296. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4297. WOLFSSL_MSG("rsa pub_key error");
  4298. return -1;
  4299. }
  4300. /* public key */
  4301. key->type = DSA_PUBLIC;
  4302. }
  4303. if (dsa->priv_key != NULL) {
  4304. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4305. WOLFSSL_MSG("rsa priv_key error");
  4306. return -1;
  4307. }
  4308. /* private key */
  4309. key->type = DSA_PRIVATE;
  4310. }
  4311. dsa->inSet = 1;
  4312. return 1;
  4313. }
  4314. /* return code compliant with OpenSSL :
  4315. * 1 if success, 0 if error
  4316. */
  4317. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4318. {
  4319. int ret = 0;
  4320. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4321. if (dsa == NULL || dsa->internal == NULL) {
  4322. WOLFSSL_MSG("Bad arguments");
  4323. return 0;
  4324. }
  4325. if (dsa->inSet == 0) {
  4326. WOLFSSL_MSG("No DSA internal set, do it");
  4327. if (SetDsaInternal(dsa) != 1) {
  4328. WOLFSSL_MSG("SetDsaInternal failed");
  4329. return ret;
  4330. }
  4331. }
  4332. #ifdef WOLFSSL_KEY_GEN
  4333. {
  4334. int initTmpRng = 0;
  4335. WC_RNG *rng = NULL;
  4336. #ifdef WOLFSSL_SMALL_STACK
  4337. WC_RNG *tmpRng;
  4338. #else
  4339. WC_RNG tmpRng[1];
  4340. #endif
  4341. #ifdef WOLFSSL_SMALL_STACK
  4342. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4343. if (tmpRng == NULL)
  4344. return -1;
  4345. #endif
  4346. if (wc_InitRng(tmpRng) == 0) {
  4347. rng = tmpRng;
  4348. initTmpRng = 1;
  4349. }
  4350. else {
  4351. WOLFSSL_MSG("Bad RNG Init, trying global");
  4352. rng = wolfssl_get_global_rng();
  4353. }
  4354. if (rng) {
  4355. /* These were allocated above by SetDsaInternal(). They should
  4356. * be cleared before wc_MakeDsaKey() which reinitializes
  4357. * x and y. */
  4358. mp_clear(&((DsaKey*)dsa->internal)->x);
  4359. mp_clear(&((DsaKey*)dsa->internal)->y);
  4360. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4361. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4362. else if (SetDsaExternal(dsa) != 1)
  4363. WOLFSSL_MSG("SetDsaExternal failed");
  4364. else
  4365. ret = 1;
  4366. }
  4367. if (initTmpRng)
  4368. wc_FreeRng(tmpRng);
  4369. #ifdef WOLFSSL_SMALL_STACK
  4370. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4371. #endif
  4372. }
  4373. #else /* WOLFSSL_KEY_GEN */
  4374. WOLFSSL_MSG("No Key Gen built in");
  4375. #endif
  4376. return ret;
  4377. }
  4378. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4379. */
  4380. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4381. int seedLen, int* counterRet, unsigned long* hRet,
  4382. WOLFSSL_BN_CB cb, void* CBArg)
  4383. {
  4384. WOLFSSL_DSA* dsa;
  4385. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4386. (void)cb;
  4387. (void)CBArg;
  4388. dsa = wolfSSL_DSA_new();
  4389. if (dsa == NULL) {
  4390. return NULL;
  4391. }
  4392. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4393. counterRet, hRet, NULL) != 1) {
  4394. wolfSSL_DSA_free(dsa);
  4395. return NULL;
  4396. }
  4397. return dsa;
  4398. }
  4399. /* return code compliant with OpenSSL :
  4400. * 1 if success, 0 if error
  4401. */
  4402. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4403. unsigned char* seed, int seedLen,
  4404. int* counterRet,
  4405. unsigned long* hRet, void* cb)
  4406. {
  4407. int ret = 0;
  4408. (void)bits;
  4409. (void)seed;
  4410. (void)seedLen;
  4411. (void)counterRet;
  4412. (void)hRet;
  4413. (void)cb;
  4414. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4415. if (dsa == NULL || dsa->internal == NULL) {
  4416. WOLFSSL_MSG("Bad arguments");
  4417. return 0;
  4418. }
  4419. #ifdef WOLFSSL_KEY_GEN
  4420. {
  4421. int initTmpRng = 0;
  4422. WC_RNG *rng = NULL;
  4423. #ifdef WOLFSSL_SMALL_STACK
  4424. WC_RNG *tmpRng;
  4425. #else
  4426. WC_RNG tmpRng[1];
  4427. #endif
  4428. #ifdef WOLFSSL_SMALL_STACK
  4429. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4430. if (tmpRng == NULL)
  4431. return -1;
  4432. #endif
  4433. if (wc_InitRng(tmpRng) == 0) {
  4434. rng = tmpRng;
  4435. initTmpRng = 1;
  4436. }
  4437. else {
  4438. WOLFSSL_MSG("Bad RNG Init, trying global");
  4439. rng = wolfssl_get_global_rng();
  4440. }
  4441. if (rng) {
  4442. if (wc_MakeDsaParameters(rng, bits,
  4443. (DsaKey*)dsa->internal) != MP_OKAY)
  4444. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4445. else if (SetDsaExternal(dsa) != 1)
  4446. WOLFSSL_MSG("SetDsaExternal failed");
  4447. else
  4448. ret = 1;
  4449. }
  4450. if (initTmpRng)
  4451. wc_FreeRng(tmpRng);
  4452. #ifdef WOLFSSL_SMALL_STACK
  4453. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4454. #endif
  4455. }
  4456. #else /* WOLFSSL_KEY_GEN */
  4457. WOLFSSL_MSG("No Key Gen built in");
  4458. #endif
  4459. return ret;
  4460. }
  4461. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4462. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4463. {
  4464. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4465. if (d != NULL) {
  4466. if (p != NULL)
  4467. *p = d->p;
  4468. if (q != NULL)
  4469. *q = d->q;
  4470. if (g != NULL)
  4471. *g = d->g;
  4472. }
  4473. }
  4474. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4475. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4476. {
  4477. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4478. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4479. WOLFSSL_MSG("Bad parameter");
  4480. return 0;
  4481. }
  4482. wolfSSL_BN_free(d->p);
  4483. wolfSSL_BN_free(d->q);
  4484. wolfSSL_BN_free(d->g);
  4485. d->p = p;
  4486. d->q = q;
  4487. d->g = g;
  4488. return 1;
  4489. }
  4490. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4491. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4492. {
  4493. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4494. if (d != NULL) {
  4495. if (pub_key != NULL)
  4496. *pub_key = d->pub_key;
  4497. if (priv_key != NULL)
  4498. *priv_key = d->priv_key;
  4499. }
  4500. }
  4501. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4502. WOLFSSL_BIGNUM *priv_key)
  4503. {
  4504. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4505. /* The private key may be NULL */
  4506. if (d->pub_key == NULL && pub_key == NULL) {
  4507. WOLFSSL_MSG("Bad parameter");
  4508. return 0;
  4509. }
  4510. if (pub_key != NULL) {
  4511. wolfSSL_BN_free(d->pub_key);
  4512. d->pub_key = pub_key;
  4513. }
  4514. if (priv_key != NULL) {
  4515. wolfSSL_BN_free(d->priv_key);
  4516. d->priv_key = priv_key;
  4517. }
  4518. return 1;
  4519. }
  4520. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4521. {
  4522. WOLFSSL_DSA_SIG* sig;
  4523. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4524. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4525. DYNAMIC_TYPE_OPENSSL);
  4526. if (sig)
  4527. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4528. return sig;
  4529. }
  4530. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4531. {
  4532. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4533. if (sig) {
  4534. if (sig->r) {
  4535. wolfSSL_BN_free(sig->r);
  4536. }
  4537. if (sig->s) {
  4538. wolfSSL_BN_free(sig->s);
  4539. }
  4540. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4541. }
  4542. }
  4543. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4544. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4545. {
  4546. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4547. if (sig != NULL) {
  4548. *r = sig->r;
  4549. *s = sig->s;
  4550. }
  4551. }
  4552. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4553. WOLFSSL_BIGNUM *s)
  4554. {
  4555. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4556. if (r == NULL || s == NULL) {
  4557. WOLFSSL_MSG("Bad parameter");
  4558. return 0;
  4559. }
  4560. wolfSSL_BN_clear_free(sig->r);
  4561. wolfSSL_BN_clear_free(sig->s);
  4562. sig->r = r;
  4563. sig->s = s;
  4564. return 1;
  4565. }
  4566. #ifndef HAVE_SELFTEST
  4567. /**
  4568. *
  4569. * @param sig The input signature to encode
  4570. * @param out The output buffer. If *out is NULL then a new buffer is
  4571. * allocated. Otherwise the output is written to the buffer.
  4572. * @return length on success and -1 on error
  4573. */
  4574. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4575. {
  4576. /* Space for sequence + two asn ints */
  4577. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4578. word32 bufLen = sizeof(buf);
  4579. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4580. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4581. out == NULL) {
  4582. WOLFSSL_MSG("Bad function arguments");
  4583. return -1;
  4584. }
  4585. if (StoreECC_DSA_Sig(buf, &bufLen,
  4586. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4587. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4588. return -1;
  4589. }
  4590. if (*out == NULL) {
  4591. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4592. if (tmp == NULL) {
  4593. WOLFSSL_MSG("malloc error");
  4594. return -1;
  4595. }
  4596. *out = tmp;
  4597. }
  4598. XMEMCPY(*out, buf, bufLen);
  4599. return (int)bufLen;
  4600. }
  4601. /**
  4602. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4603. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4604. */
  4605. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4606. {
  4607. WOLFSSL_DSA_SIG* ret;
  4608. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4609. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4610. return NULL;
  4611. }
  4612. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4613. WOLFSSL_MSG("wolfSSL_BN_new error");
  4614. wolfSSL_DSA_SIG_free(ret);
  4615. return NULL;
  4616. }
  4617. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4618. WOLFSSL_MSG("wolfSSL_BN_new error");
  4619. wolfSSL_DSA_SIG_free(ret);
  4620. return NULL;
  4621. }
  4622. return ret;
  4623. }
  4624. /**
  4625. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4626. * ASN1_SEQUENCE
  4627. * ASN1_INTEGER (DSA r)
  4628. * ASN1_INTEGER (DSA s)
  4629. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4630. * length then this API interprets this as two unsigned binary numbers.
  4631. * @param sig If non-null then free'd first and then newly created
  4632. * WOLFSSL_DSA_SIG is assigned
  4633. * @param pp Input buffer that is moved forward on success
  4634. * @param length Length of input buffer
  4635. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4636. */
  4637. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4638. const unsigned char **pp, long length)
  4639. {
  4640. WOLFSSL_DSA_SIG* ret;
  4641. mp_int* r;
  4642. mp_int* s;
  4643. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4644. if (pp == NULL || *pp == NULL || length < 0) {
  4645. WOLFSSL_MSG("Bad function arguments");
  4646. return NULL;
  4647. }
  4648. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4649. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4650. return NULL;
  4651. }
  4652. r = (mp_int*)ret->r->internal;
  4653. s = (mp_int*)ret->s->internal;
  4654. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4655. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4656. /* Two raw numbers of length/2 size each */
  4657. if (mp_read_unsigned_bin(r, *pp, (word32)length/2) != 0) {
  4658. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4659. wolfSSL_DSA_SIG_free(ret);
  4660. return NULL;
  4661. }
  4662. if (mp_read_unsigned_bin(s, *pp + (length/2), (word32)length/2) !=
  4663. 0) {
  4664. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4665. wolfSSL_DSA_SIG_free(ret);
  4666. return NULL;
  4667. }
  4668. *pp += length;
  4669. }
  4670. else {
  4671. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4672. wolfSSL_DSA_SIG_free(ret);
  4673. return NULL;
  4674. }
  4675. }
  4676. else {
  4677. /* DecodeECC_DSA_Sig success move pointer forward */
  4678. #ifndef NO_STRICT_ECDSA_LEN
  4679. *pp += length;
  4680. #else
  4681. {
  4682. /* We need to figure out how much to move by ourselves */
  4683. word32 idx = 0;
  4684. int len = 0;
  4685. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4686. WOLFSSL_MSG("GetSequence error");
  4687. wolfSSL_DSA_SIG_free(ret);
  4688. return NULL;
  4689. }
  4690. *pp += len;
  4691. }
  4692. #endif
  4693. }
  4694. if (sig != NULL) {
  4695. if (*sig != NULL)
  4696. wolfSSL_DSA_SIG_free(*sig);
  4697. *sig = ret;
  4698. }
  4699. return ret;
  4700. }
  4701. #endif /* HAVE_SELFTEST */
  4702. /* return 1 on success, < 0 otherwise */
  4703. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4704. WOLFSSL_DSA* dsa)
  4705. {
  4706. int ret = -1;
  4707. int initTmpRng = 0;
  4708. WC_RNG* rng = NULL;
  4709. #ifdef WOLFSSL_SMALL_STACK
  4710. WC_RNG* tmpRng = NULL;
  4711. #else
  4712. WC_RNG tmpRng[1];
  4713. #endif
  4714. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4715. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4716. WOLFSSL_MSG("Bad function arguments");
  4717. return ret;
  4718. }
  4719. if (dsa->inSet == 0) {
  4720. WOLFSSL_MSG("No DSA internal set, do it");
  4721. if (SetDsaInternal(dsa) != 1) {
  4722. WOLFSSL_MSG("SetDsaInternal failed");
  4723. return ret;
  4724. }
  4725. }
  4726. #ifdef WOLFSSL_SMALL_STACK
  4727. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4728. if (tmpRng == NULL)
  4729. return -1;
  4730. #endif
  4731. if (wc_InitRng(tmpRng) == 0) {
  4732. rng = tmpRng;
  4733. initTmpRng = 1;
  4734. }
  4735. else {
  4736. WOLFSSL_MSG("Bad RNG Init, trying global");
  4737. rng = wolfssl_get_global_rng();
  4738. }
  4739. if (rng) {
  4740. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4741. WOLFSSL_MSG("DsaSign failed");
  4742. else
  4743. ret = 1;
  4744. }
  4745. if (initTmpRng)
  4746. wc_FreeRng(tmpRng);
  4747. #ifdef WOLFSSL_SMALL_STACK
  4748. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4749. #endif
  4750. return ret;
  4751. }
  4752. #ifndef HAVE_SELFTEST
  4753. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4754. int inLen, WOLFSSL_DSA* dsa)
  4755. {
  4756. byte sigBin[DSA_MAX_SIG_SIZE];
  4757. const byte *tmp = sigBin;
  4758. int sigLen;
  4759. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4760. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4761. WOLFSSL_MSG("Bad function arguments");
  4762. return NULL;
  4763. }
  4764. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4765. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4766. return NULL;
  4767. }
  4768. if (dsa->internal == NULL) {
  4769. WOLFSSL_MSG("dsa->internal is null");
  4770. return NULL;
  4771. }
  4772. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4773. if (sigLen <= 0) {
  4774. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4775. return NULL;
  4776. }
  4777. /* 2 * sigLen for the two points r and s */
  4778. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4779. }
  4780. #endif /* !HAVE_SELFTEST */
  4781. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4782. WOLFSSL_DSA* dsa, int *dsacheck)
  4783. {
  4784. int ret = -1;
  4785. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4786. if (d == NULL || sig == NULL || dsa == NULL) {
  4787. WOLFSSL_MSG("Bad function arguments");
  4788. return -1;
  4789. }
  4790. if (dsa->inSet == 0)
  4791. {
  4792. WOLFSSL_MSG("No DSA internal set, do it");
  4793. if (SetDsaInternal(dsa) != 1) {
  4794. WOLFSSL_MSG("SetDsaInternal failed");
  4795. return -1;
  4796. }
  4797. }
  4798. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4799. if (ret != 0 || *dsacheck != 1) {
  4800. WOLFSSL_MSG("DsaVerify failed");
  4801. return ret;
  4802. }
  4803. return 1;
  4804. }
  4805. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4806. {
  4807. if (!d)
  4808. return 0;
  4809. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4810. return 0;
  4811. return wolfSSL_BN_num_bits(d->p);
  4812. }
  4813. #ifndef HAVE_SELFTEST
  4814. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4815. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4816. {
  4817. int dsacheck, sz;
  4818. byte sigBin[DSA_MAX_SIG_SIZE];
  4819. byte* sigBinPtr = sigBin;
  4820. DsaKey* key;
  4821. int qSz;
  4822. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4823. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4824. WOLFSSL_MSG("Bad function arguments");
  4825. return 0;
  4826. }
  4827. if (!sig->r || !sig->s) {
  4828. WOLFSSL_MSG("No signature found in DSA_SIG");
  4829. return 0;
  4830. }
  4831. if (dsa->inSet == 0) {
  4832. WOLFSSL_MSG("No DSA internal set, do it");
  4833. if (SetDsaInternal(dsa) != 1) {
  4834. WOLFSSL_MSG("SetDsaInternal failed");
  4835. return 0;
  4836. }
  4837. }
  4838. key = (DsaKey*)dsa->internal;
  4839. if (key == NULL) {
  4840. WOLFSSL_MSG("dsa->internal is null");
  4841. return 0;
  4842. }
  4843. qSz = mp_unsigned_bin_size(&key->q);
  4844. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4845. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4846. return 0;
  4847. }
  4848. /* read r */
  4849. /* front pad with zeros */
  4850. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4851. return 0;
  4852. while (sz++ < qSz)
  4853. *sigBinPtr++ = 0;
  4854. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4855. return 0;
  4856. /* Move to s */
  4857. sigBinPtr = sigBin + qSz;
  4858. /* read s */
  4859. /* front pad with zeros */
  4860. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4861. return 0;
  4862. while (sz++ < qSz)
  4863. *sigBinPtr++ = 0;
  4864. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4865. return 0;
  4866. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4867. != 1) || dsacheck != 1) {
  4868. return 0;
  4869. }
  4870. return 1;
  4871. }
  4872. #endif /* !HAVE_SELFTEST */
  4873. WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  4874. unsigned char** out)
  4875. {
  4876. int ret = 0;
  4877. word32 derLen = 0;
  4878. int preAllocated = 1;
  4879. DsaKey* key = NULL;
  4880. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  4881. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  4882. ret = BAD_FUNC_ARG;
  4883. }
  4884. if (ret == 0) {
  4885. key = (DsaKey*)dsa->internal;
  4886. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  4887. if (ret == LENGTH_ONLY_E) {
  4888. ret = 0;
  4889. }
  4890. }
  4891. if (ret == 0 && *out == NULL) {
  4892. /* If we're allocating out for the caller, we don't increment out just
  4893. past the end of the DER buffer. If out is already allocated, we do.
  4894. (OpenSSL convention) */
  4895. preAllocated = 0;
  4896. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  4897. if (*out == NULL) {
  4898. ret = MEMORY_E;
  4899. }
  4900. }
  4901. if (ret == 0) {
  4902. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  4903. }
  4904. if (ret >= 0 && preAllocated == 1) {
  4905. *out += derLen;
  4906. }
  4907. if (ret < 0 && preAllocated == 0) {
  4908. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  4909. }
  4910. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  4911. return ret;
  4912. }
  4913. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  4914. long derLen)
  4915. {
  4916. WOLFSSL_DSA* ret = NULL;
  4917. int err = 0;
  4918. word32 idx = 0;
  4919. int asnLen;
  4920. DsaKey* internalKey = NULL;
  4921. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  4922. if (der == NULL || *der == NULL || derLen <= 0) {
  4923. err = 1;
  4924. }
  4925. if (err == 0) {
  4926. ret = wolfSSL_DSA_new();
  4927. err = ret == NULL;
  4928. }
  4929. if (err == 0) {
  4930. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  4931. }
  4932. if (err == 0) {
  4933. internalKey = (DsaKey*)ret->internal;
  4934. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  4935. }
  4936. if (err == 0) {
  4937. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  4938. }
  4939. if (err == 0) {
  4940. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  4941. }
  4942. if (err == 0) {
  4943. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  4944. != 1;
  4945. }
  4946. if (err == 0) {
  4947. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  4948. != 1;
  4949. }
  4950. if (err == 0) {
  4951. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  4952. != 1;
  4953. }
  4954. if (err == 0 && dsa != NULL) {
  4955. *dsa = ret;
  4956. }
  4957. if (err != 0 && ret != NULL) {
  4958. wolfSSL_DSA_free(ret);
  4959. ret = NULL;
  4960. }
  4961. return ret;
  4962. }
  4963. #if defined(WOLFSSL_KEY_GEN)
  4964. #ifndef NO_BIO
  4965. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  4966. * Returns 1 or 0
  4967. */
  4968. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  4969. const EVP_CIPHER* cipher,
  4970. unsigned char* passwd, int len,
  4971. wc_pem_password_cb* cb, void* arg)
  4972. {
  4973. int ret = 0, der_max_len = 0, derSz = 0;
  4974. byte *derBuf;
  4975. WOLFSSL_EVP_PKEY* pkey;
  4976. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  4977. if (bio == NULL || dsa == NULL) {
  4978. WOLFSSL_MSG("Bad Function Arguments");
  4979. return 0;
  4980. }
  4981. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  4982. if (pkey == NULL) {
  4983. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  4984. return 0;
  4985. }
  4986. pkey->type = EVP_PKEY_DSA;
  4987. pkey->dsa = dsa;
  4988. pkey->ownDsa = 0;
  4989. /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */
  4990. der_max_len = MAX_DSA_PRIVKEY_SZ;
  4991. derBuf = (byte*)XMALLOC((size_t)der_max_len, bio->heap,
  4992. DYNAMIC_TYPE_TMP_BUFFER);
  4993. if (derBuf == NULL) {
  4994. WOLFSSL_MSG("Malloc failed");
  4995. wolfSSL_EVP_PKEY_free(pkey);
  4996. return 0;
  4997. }
  4998. /* convert key to der format */
  4999. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5000. if (derSz < 0) {
  5001. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5002. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  5003. wolfSSL_EVP_PKEY_free(pkey);
  5004. return 0;
  5005. }
  5006. pkey->pkey.ptr = (char*)XMALLOC((size_t)derSz, bio->heap,
  5007. DYNAMIC_TYPE_TMP_BUFFER);
  5008. if (pkey->pkey.ptr == NULL) {
  5009. WOLFSSL_MSG("key malloc failed");
  5010. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5011. wolfSSL_EVP_PKEY_free(pkey);
  5012. return 0;
  5013. }
  5014. /* add der info to the evp key */
  5015. pkey->pkey_sz = derSz;
  5016. XMEMCPY(pkey->pkey.ptr, derBuf, (size_t)derSz);
  5017. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5018. ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len,
  5019. cb, arg);
  5020. wolfSSL_EVP_PKEY_free(pkey);
  5021. return ret;
  5022. }
  5023. #ifndef HAVE_SELFTEST
  5024. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5025. * Returns 1 or 0
  5026. */
  5027. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5028. {
  5029. int ret = 0;
  5030. WOLFSSL_EVP_PKEY* pkey;
  5031. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5032. if (bio == NULL || dsa == NULL) {
  5033. WOLFSSL_MSG("Bad function arguments");
  5034. return 0;
  5035. }
  5036. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  5037. if (pkey == NULL) {
  5038. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  5039. return 0;
  5040. }
  5041. pkey->type = EVP_PKEY_DSA;
  5042. pkey->dsa = dsa;
  5043. pkey->ownDsa = 0;
  5044. ret = pem_write_bio_pubkey(bio, pkey);
  5045. wolfSSL_EVP_PKEY_free(pkey);
  5046. return ret;
  5047. }
  5048. #endif /* HAVE_SELFTEST */
  5049. #endif /* !NO_BIO */
  5050. /* return code compliant with OpenSSL :
  5051. * 1 if success, 0 if error
  5052. */
  5053. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5054. const EVP_CIPHER* cipher,
  5055. unsigned char* passwd, int passwdSz,
  5056. unsigned char **pem, int *pLen)
  5057. {
  5058. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5059. byte *derBuf, *tmp, *cipherInfo = NULL;
  5060. int der_max_len = 0, derSz = 0;
  5061. const int type = DSA_PRIVATEKEY_TYPE;
  5062. const char* header = NULL;
  5063. const char* footer = NULL;
  5064. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5065. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5066. WOLFSSL_MSG("Bad function arguments");
  5067. return 0;
  5068. }
  5069. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5070. return 0;
  5071. if (dsa->inSet == 0) {
  5072. WOLFSSL_MSG("No DSA internal set, do it");
  5073. if (SetDsaInternal(dsa) != 1) {
  5074. WOLFSSL_MSG("SetDsaInternal failed");
  5075. return 0;
  5076. }
  5077. }
  5078. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5079. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL, DYNAMIC_TYPE_DER);
  5080. if (derBuf == NULL) {
  5081. WOLFSSL_MSG("malloc failed");
  5082. return 0;
  5083. }
  5084. /* Key to DER */
  5085. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, (word32)der_max_len);
  5086. if (derSz < 0) {
  5087. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5088. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5089. return 0;
  5090. }
  5091. /* encrypt DER buffer if required */
  5092. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5093. int ret;
  5094. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5095. passwd, passwdSz, &cipherInfo, der_max_len);
  5096. if (ret != 1) {
  5097. WOLFSSL_MSG("EncryptDerKey failed");
  5098. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5099. return ret;
  5100. }
  5101. /* tmp buffer with a max size */
  5102. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5103. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5104. }
  5105. else { /* tmp buffer with a max size */
  5106. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5107. (int)XSTRLEN(footer) + 1;
  5108. }
  5109. tmp = (byte*)XMALLOC((size_t)*pLen, NULL, DYNAMIC_TYPE_PEM);
  5110. if (tmp == NULL) {
  5111. WOLFSSL_MSG("malloc failed");
  5112. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5113. if (cipherInfo != NULL)
  5114. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5115. return 0;
  5116. }
  5117. /* DER to PEM */
  5118. *pLen = wc_DerToPemEx(derBuf, (word32)derSz, tmp, (word32)*pLen, cipherInfo,
  5119. 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((size_t)((*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, (size_t)((*pLen)+1));
  5138. if (XMEMCPY(*pem, tmp, (size_t)*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, (size_t)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,
  5283. (word32)derSz);
  5284. if (ret < 0) {
  5285. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5286. return -1;
  5287. }
  5288. if (SetDsaExternal(dsa) != 1) {
  5289. WOLFSSL_MSG("SetDsaExternal failed");
  5290. return -1;
  5291. }
  5292. dsa->inSet = 1;
  5293. return 1;
  5294. }
  5295. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5296. returns 1 on success, or 0 on failure. */
  5297. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5298. int derSz, int opt)
  5299. {
  5300. word32 idx = 0;
  5301. int ret;
  5302. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5303. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5304. WOLFSSL_MSG("Bad function arguments");
  5305. return -1;
  5306. }
  5307. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5308. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5309. (word32)derSz);
  5310. }
  5311. else {
  5312. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal,
  5313. (word32)derSz);
  5314. }
  5315. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5316. WOLFSSL_ERROR_VERBOSE(ret);
  5317. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5318. return -1;
  5319. }
  5320. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5321. WOLFSSL_ERROR_VERBOSE(ret);
  5322. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5323. return -1;
  5324. }
  5325. if (SetDsaExternal(dsa) != 1) {
  5326. WOLFSSL_MSG("SetDsaExternal failed");
  5327. return -1;
  5328. }
  5329. dsa->inSet = 1;
  5330. return 1;
  5331. }
  5332. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5333. #ifdef OPENSSL_EXTRA
  5334. #ifndef NO_BIO
  5335. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5336. wc_pem_password_cb *cb, void *u)
  5337. {
  5338. WOLFSSL_DSA* dsa;
  5339. DsaKey* key;
  5340. int length;
  5341. unsigned char* buf;
  5342. word32 bufSz;
  5343. int ret;
  5344. word32 idx = 0;
  5345. DerBuffer* pDer;
  5346. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5347. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5348. if (ret <= 0) {
  5349. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5350. return NULL;
  5351. }
  5352. bufSz = (word32)ret;
  5353. if (cb != NULL || u != NULL) {
  5354. /*
  5355. * cb is for a call back when encountering encrypted PEM files
  5356. * if cb == NULL and u != NULL then u = null terminated password string
  5357. */
  5358. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5359. }
  5360. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5361. NULL) < 0 ) {
  5362. WOLFSSL_MSG("Issue converting from PEM to DER");
  5363. return NULL;
  5364. }
  5365. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5366. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5367. FreeDer(&pDer);
  5368. return NULL;
  5369. }
  5370. dsa = wolfSSL_DSA_new();
  5371. if (dsa == NULL) {
  5372. FreeDer(&pDer);
  5373. WOLFSSL_MSG("Error creating DSA struct");
  5374. return NULL;
  5375. }
  5376. key = (DsaKey*)dsa->internal;
  5377. if (key == NULL) {
  5378. FreeDer(&pDer);
  5379. wolfSSL_DSA_free(dsa);
  5380. WOLFSSL_MSG("Error finding DSA key struct");
  5381. return NULL;
  5382. }
  5383. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5384. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5385. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5386. WOLFSSL_MSG("dsa key error");
  5387. FreeDer(&pDer);
  5388. wolfSSL_DSA_free(dsa);
  5389. return NULL;
  5390. }
  5391. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5392. WOLFSSL_MSG("dsa p key error");
  5393. FreeDer(&pDer);
  5394. wolfSSL_DSA_free(dsa);
  5395. return NULL;
  5396. }
  5397. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5398. WOLFSSL_MSG("dsa q key error");
  5399. FreeDer(&pDer);
  5400. wolfSSL_DSA_free(dsa);
  5401. return NULL;
  5402. }
  5403. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5404. WOLFSSL_MSG("dsa g key error");
  5405. FreeDer(&pDer);
  5406. wolfSSL_DSA_free(dsa);
  5407. return NULL;
  5408. }
  5409. if (x != NULL) {
  5410. *x = dsa;
  5411. }
  5412. FreeDer(&pDer);
  5413. return dsa;
  5414. }
  5415. #endif /* !NO_BIO */
  5416. #if !defined(NO_DH)
  5417. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5418. {
  5419. WOLFSSL_DH* dh;
  5420. DhKey* key;
  5421. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5422. if (dsa == NULL) {
  5423. return NULL;
  5424. }
  5425. dh = wolfSSL_DH_new();
  5426. if (dh == NULL) {
  5427. return NULL;
  5428. }
  5429. key = (DhKey*)dh->internal;
  5430. if (dsa->p != NULL &&
  5431. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5432. != 1) {
  5433. WOLFSSL_MSG("rsa p key error");
  5434. wolfSSL_DH_free(dh);
  5435. return NULL;
  5436. }
  5437. if (dsa->g != NULL &&
  5438. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5439. != 1) {
  5440. WOLFSSL_MSG("rsa g key error");
  5441. wolfSSL_DH_free(dh);
  5442. return NULL;
  5443. }
  5444. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5445. WOLFSSL_MSG("dsa p key error");
  5446. wolfSSL_DH_free(dh);
  5447. return NULL;
  5448. }
  5449. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5450. WOLFSSL_MSG("dsa g key error");
  5451. wolfSSL_DH_free(dh);
  5452. return NULL;
  5453. }
  5454. return dh;
  5455. }
  5456. #endif /* !NO_DH */
  5457. #endif /* OPENSSL_EXTRA */
  5458. #endif /* !NO_DSA */
  5459. /*******************************************************************************
  5460. * END OF DSA API
  5461. ******************************************************************************/
  5462. /*******************************************************************************
  5463. * START OF DH API
  5464. ******************************************************************************/
  5465. #ifndef NO_DH
  5466. #ifdef OPENSSL_EXTRA
  5467. /*
  5468. * DH constructor/deconstructor APIs
  5469. */
  5470. /* Allocate and initialize a new DH key.
  5471. *
  5472. * @return DH key on success.
  5473. * @return NULL on failure.
  5474. */
  5475. WOLFSSL_DH* wolfSSL_DH_new(void)
  5476. {
  5477. int err = 0;
  5478. WOLFSSL_DH* dh = NULL;
  5479. DhKey* key = NULL;
  5480. WOLFSSL_ENTER("wolfSSL_DH_new");
  5481. /* Allocate OpenSSL DH key. */
  5482. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5483. if (dh == NULL) {
  5484. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5485. err = 1;
  5486. }
  5487. if (!err) {
  5488. /* Clear key data. */
  5489. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5490. /* Initialize reference counting. */
  5491. wolfSSL_RefInit(&dh->ref, &err);
  5492. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5493. }
  5494. if (!err) {
  5495. #endif
  5496. /* Allocate wolfSSL DH key. */
  5497. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5498. if (key == NULL) {
  5499. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5500. err = 1;
  5501. }
  5502. }
  5503. if (!err) {
  5504. /* Set and initialize wolfSSL DH key. */
  5505. dh->internal = key;
  5506. if (wc_InitDhKey(key) != 0) {
  5507. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5508. err = 1;
  5509. }
  5510. }
  5511. if (err && (dh != NULL)) {
  5512. /* Dispose of the allocated memory. */
  5513. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5514. wolfSSL_RefFree(&dh->ref);
  5515. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5516. dh = NULL;
  5517. }
  5518. return dh;
  5519. }
  5520. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5521. /* Set the DH parameters based on the NID.
  5522. *
  5523. * @param [in, out] dh DH key to set.
  5524. * @param [in] nid Numeric ID of predefined DH parameters.
  5525. * @return 0 on success.
  5526. * @return 1 on failure.
  5527. */
  5528. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5529. {
  5530. int err = 0;
  5531. const DhParams* params = NULL;
  5532. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5533. * FIPS v2 module */
  5534. switch (nid) {
  5535. #ifdef HAVE_FFDHE_2048
  5536. case NID_ffdhe2048:
  5537. params = wc_Dh_ffdhe2048_Get();
  5538. break;
  5539. #endif /* HAVE_FFDHE_2048 */
  5540. #ifdef HAVE_FFDHE_3072
  5541. case NID_ffdhe3072:
  5542. params = wc_Dh_ffdhe3072_Get();
  5543. break;
  5544. #endif /* HAVE_FFDHE_3072 */
  5545. #ifdef HAVE_FFDHE_4096
  5546. case NID_ffdhe4096:
  5547. params = wc_Dh_ffdhe4096_Get();
  5548. break;
  5549. #endif /* HAVE_FFDHE_4096 */
  5550. default:
  5551. break;
  5552. }
  5553. if (params == NULL) {
  5554. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5555. err = 1;
  5556. }
  5557. if (!err) {
  5558. /* Set prime from data retrieved. */
  5559. dh->p = wolfSSL_BN_bin2bn(params->p, (int)params->p_len, NULL);
  5560. if (dh->p == NULL) {
  5561. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5562. err = 1;
  5563. }
  5564. }
  5565. if (!err) {
  5566. /* Set generator from data retrieved. */
  5567. dh->g = wolfSSL_BN_bin2bn(params->g, (int)params->g_len, NULL);
  5568. if (dh->g == NULL) {
  5569. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5570. err = 1;
  5571. }
  5572. }
  5573. #ifdef HAVE_FFDHE_Q
  5574. if (!err) {
  5575. /* Set order from data retrieved. */
  5576. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5577. if (dh->q == NULL) {
  5578. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5579. err = 1;
  5580. }
  5581. }
  5582. #endif
  5583. /* Synchronize the external into internal DH key's parameters. */
  5584. if ((!err) && (SetDhInternal(dh) != 1)) {
  5585. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5586. err = 1;
  5587. }
  5588. if (!err) {
  5589. /* External DH key parameters were set. */
  5590. dh->exSet = 1;
  5591. }
  5592. if (err == 1) {
  5593. /* Dispose of any external parameters. */
  5594. #ifdef HAVE_FFDHE_Q
  5595. wolfSSL_BN_free(dh->q);
  5596. dh->q = NULL;
  5597. #endif
  5598. wolfSSL_BN_free(dh->p);
  5599. dh->p = NULL;
  5600. wolfSSL_BN_free(dh->g);
  5601. dh->g = NULL;
  5602. }
  5603. return err;
  5604. }
  5605. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5606. FIPS_VERSION_GT(2,0))
  5607. /* Set the DH parameters based on the NID.
  5608. *
  5609. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5610. *
  5611. * @param [in, out] dh DH key to set.
  5612. * @param [in] nid Numeric ID of predefined DH parameters.
  5613. * @return 0 on success.
  5614. * @return 1 on failure.
  5615. */
  5616. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5617. {
  5618. int err = 0;
  5619. int name = 0;
  5620. #ifdef HAVE_FFDHE_Q
  5621. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5622. #else
  5623. int elements = ELEMENT_P | ELEMENT_G;
  5624. #endif /* HAVE_FFDHE_Q */
  5625. switch (nid) {
  5626. #ifdef HAVE_FFDHE_2048
  5627. case NID_ffdhe2048:
  5628. name = WC_FFDHE_2048;
  5629. break;
  5630. #endif /* HAVE_FFDHE_2048 */
  5631. #ifdef HAVE_FFDHE_3072
  5632. case NID_ffdhe3072:
  5633. name = WC_FFDHE_3072;
  5634. break;
  5635. #endif /* HAVE_FFDHE_3072 */
  5636. #ifdef HAVE_FFDHE_4096
  5637. case NID_ffdhe4096:
  5638. name = WC_FFDHE_4096;
  5639. break;
  5640. #endif /* HAVE_FFDHE_4096 */
  5641. default:
  5642. err = 1;
  5643. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5644. break;
  5645. }
  5646. /* Set the internal DH key's parameters based on name. */
  5647. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5648. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5649. err = 1;
  5650. }
  5651. /* Synchronize the internal into external DH key's parameters. */
  5652. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5653. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5654. err = 1;
  5655. }
  5656. return err;
  5657. }
  5658. #else
  5659. /* Set the DH parameters based on the NID.
  5660. *
  5661. * Pre-defined DH parameters not available.
  5662. *
  5663. * @param [in, out] dh DH key to set.
  5664. * @param [in] nid Numeric ID of predefined DH parameters.
  5665. * @return 1 for failure.
  5666. */
  5667. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5668. {
  5669. return 1;
  5670. }
  5671. #endif
  5672. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5673. *
  5674. * @param [in] nid Numeric ID of DH parameters.
  5675. *
  5676. * @return DH key on success.
  5677. * @return NULL on failure.
  5678. */
  5679. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5680. {
  5681. WOLFSSL_DH* dh = NULL;
  5682. int err = 0;
  5683. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5684. /* Allocate a new DH key. */
  5685. dh = wolfSSL_DH_new();
  5686. if (dh == NULL) {
  5687. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5688. err = 1;
  5689. }
  5690. if (!err) {
  5691. /* Set the parameters based on NID. */
  5692. err = wolfssl_dh_set_nid(dh, nid);
  5693. }
  5694. if (err && (dh != NULL)) {
  5695. /* Dispose of the key on failure to set. */
  5696. wolfSSL_DH_free(dh);
  5697. dh = NULL;
  5698. }
  5699. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5700. return dh;
  5701. }
  5702. /* Dispose of DH key and allocated data.
  5703. *
  5704. * Cannot use dh after this call.
  5705. *
  5706. * @param [in] dh DH key to free.
  5707. */
  5708. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5709. {
  5710. int doFree = 0;
  5711. WOLFSSL_ENTER("wolfSSL_DH_free");
  5712. if (dh != NULL) {
  5713. int err;
  5714. /* Only free if all references to it are done */
  5715. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5716. /* Ignore errors - doFree will be 0 on error. */
  5717. (void)err;
  5718. }
  5719. if (doFree) {
  5720. /* Dispose of allocated reference counting data. */
  5721. wolfSSL_RefFree(&dh->ref);
  5722. /* Dispose of wolfSSL DH key. */
  5723. if (dh->internal) {
  5724. wc_FreeDhKey((DhKey*)dh->internal);
  5725. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5726. dh->internal = NULL;
  5727. }
  5728. /* Dispose of any allocated BNs. */
  5729. wolfSSL_BN_free(dh->priv_key);
  5730. wolfSSL_BN_free(dh->pub_key);
  5731. wolfSSL_BN_free(dh->g);
  5732. wolfSSL_BN_free(dh->p);
  5733. wolfSSL_BN_free(dh->q);
  5734. /* Set back to NULLs for safety. */
  5735. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5736. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5737. }
  5738. }
  5739. /* Increments ref count of DH key.
  5740. *
  5741. * @param [in, out] dh DH key.
  5742. * @return 1 on success
  5743. * @return 0 on error
  5744. */
  5745. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5746. {
  5747. int err = 1;
  5748. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5749. if (dh != NULL) {
  5750. wolfSSL_RefInc(&dh->ref, &err);
  5751. }
  5752. return !err;
  5753. }
  5754. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5755. defined(OPENSSL_EXTRA)
  5756. #ifdef WOLFSSL_DH_EXTRA
  5757. /* Duplicate the DH key.
  5758. *
  5759. * Internal DH key in 'dh' is updated if necessary.
  5760. *
  5761. * @param [in, out] dh DH key to duplicate.
  5762. * @return NULL on failure.
  5763. * @return DH key on success.
  5764. */
  5765. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5766. {
  5767. WOLFSSL_DH* ret = NULL;
  5768. int err = 0;
  5769. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5770. /* Validate parameters. */
  5771. if (dh == NULL) {
  5772. WOLFSSL_ERROR_MSG("Bad parameter");
  5773. err = 1;
  5774. }
  5775. /* Ensure internal DH key is set. */
  5776. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5777. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5778. err = 1;
  5779. }
  5780. /* Create a new DH key object. */
  5781. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5782. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5783. err = 1;
  5784. }
  5785. /* Copy internal DH key from original to new. */
  5786. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5787. MP_OKAY)) {
  5788. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5789. err = 1;
  5790. }
  5791. if (!err) {
  5792. ret->inSet = 1;
  5793. /* Synchronize the internal into external DH key's parameters. */
  5794. if (SetDhExternal(ret) != 1) {
  5795. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5796. err = 1;
  5797. }
  5798. }
  5799. /* Dispose of any allocated DH key on error. */
  5800. if (err && (ret != NULL)) {
  5801. wolfSSL_DH_free(ret);
  5802. ret = NULL;
  5803. }
  5804. return ret;
  5805. }
  5806. #endif /* WOLFSSL_DH_EXTRA */
  5807. #endif
  5808. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5809. *
  5810. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5811. * Subgroup."
  5812. *
  5813. * @return NULL on failure.
  5814. * @return DH Key on success.
  5815. */
  5816. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5817. {
  5818. WOLFSSL_DH* dh;
  5819. int err = 0;
  5820. static const byte pHex[] = {
  5821. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5822. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5823. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5824. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5825. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5826. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5827. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5828. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5829. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5830. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5831. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5832. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5833. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5834. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5835. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5836. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5837. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5838. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5839. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5840. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5841. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5842. 0x1E, 0x1A, 0x15, 0x97
  5843. };
  5844. static const byte gHex[] = {
  5845. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5846. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5847. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5848. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5849. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5850. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5851. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5852. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5853. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5854. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5855. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5856. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5857. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  5858. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  5859. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  5860. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  5861. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  5862. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  5863. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  5864. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  5865. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  5866. 0x6C, 0xC4, 0x16, 0x59
  5867. };
  5868. static const byte qHex[] = {
  5869. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  5870. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  5871. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  5872. };
  5873. /* Create a new DH key to return. */
  5874. dh = wolfSSL_DH_new();
  5875. if (dh == NULL) {
  5876. err = 1;
  5877. }
  5878. if (!err) {
  5879. /* Set prime. */
  5880. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  5881. if (dh->p == NULL) {
  5882. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5883. err = 1;
  5884. }
  5885. }
  5886. if (!err) {
  5887. /* Set generator. */
  5888. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  5889. if (dh->g == NULL) {
  5890. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5891. err = 1;
  5892. }
  5893. }
  5894. if (!err) {
  5895. /* Set order. */
  5896. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  5897. if (dh->q == NULL) {
  5898. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5899. err = 1;
  5900. }
  5901. }
  5902. /* Set values into wolfSSL DH key. */
  5903. if ((!err) && (SetDhInternal(dh) != 1)) {
  5904. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  5905. err = 1;
  5906. }
  5907. if (!err) {
  5908. /* External DH key parameters were set. */
  5909. dh->exSet = 1;
  5910. }
  5911. /* Dispose of any allocated DH key on error. */
  5912. if (err && (dh != NULL)) {
  5913. wolfSSL_DH_free(dh);
  5914. dh = NULL;
  5915. }
  5916. return dh;
  5917. }
  5918. /* TODO: consider changing strings to byte arrays. */
  5919. /* Returns a big number with the 768-bit prime from RFC 2409.
  5920. *
  5921. * @param [in, out] bn If not NULL then this BN is set and returned.
  5922. * If NULL then a new BN is created, set and returned.
  5923. *
  5924. * @return NULL on failure.
  5925. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  5926. */
  5927. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  5928. {
  5929. #if WOLFSSL_MAX_BN_BITS >= 768
  5930. static const char prm[] = {
  5931. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5932. "C4C6628B80DC1CD129024E088A67CC74"
  5933. "020BBEA63B139B22514A08798E3404DD"
  5934. "EF9519B3CD3A431B302B0A6DF25F1437"
  5935. "4FE1356D6D51C245E485B576625E7EC6"
  5936. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  5937. };
  5938. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  5939. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5940. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5941. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  5942. bn = NULL;
  5943. }
  5944. return bn;
  5945. #else
  5946. (void)bn;
  5947. return NULL;
  5948. #endif
  5949. }
  5950. /* Returns a big number with the 1024-bit prime from RFC 2409.
  5951. *
  5952. * @param [in, out] bn If not NULL then this BN is set and returned.
  5953. * If NULL then a new BN is created, set and returned.
  5954. *
  5955. * @return NULL on failure.
  5956. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  5957. */
  5958. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  5959. {
  5960. #if WOLFSSL_MAX_BN_BITS >= 1024
  5961. static const char prm[] = {
  5962. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5963. "C4C6628B80DC1CD129024E088A67CC74"
  5964. "020BBEA63B139B22514A08798E3404DD"
  5965. "EF9519B3CD3A431B302B0A6DF25F1437"
  5966. "4FE1356D6D51C245E485B576625E7EC6"
  5967. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5968. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5969. "49286651ECE65381FFFFFFFFFFFFFFFF"
  5970. };
  5971. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  5972. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5973. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5974. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  5975. bn = NULL;
  5976. }
  5977. return bn;
  5978. #else
  5979. (void)bn;
  5980. return NULL;
  5981. #endif
  5982. }
  5983. /* Returns a big number with the 1536-bit prime from RFC 3526.
  5984. *
  5985. * @param [in, out] bn If not NULL then this BN is set and returned.
  5986. * If NULL then a new BN is created, set and returned.
  5987. *
  5988. * @return NULL on failure.
  5989. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  5990. */
  5991. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  5992. {
  5993. #if WOLFSSL_MAX_BN_BITS >= 1536
  5994. static const char prm[] = {
  5995. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5996. "C4C6628B80DC1CD129024E088A67CC74"
  5997. "020BBEA63B139B22514A08798E3404DD"
  5998. "EF9519B3CD3A431B302B0A6DF25F1437"
  5999. "4FE1356D6D51C245E485B576625E7EC6"
  6000. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6001. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6002. "49286651ECE45B3DC2007CB8A163BF05"
  6003. "98DA48361C55D39A69163FA8FD24CF5F"
  6004. "83655D23DCA3AD961C62F356208552BB"
  6005. "9ED529077096966D670C354E4ABC9804"
  6006. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  6007. };
  6008. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  6009. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6010. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6011. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  6012. bn = NULL;
  6013. }
  6014. return bn;
  6015. #else
  6016. (void)bn;
  6017. return NULL;
  6018. #endif
  6019. }
  6020. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6021. *
  6022. * @param [in, out] bn If not NULL then this BN is set and returned.
  6023. * If NULL then a new BN is created, set and returned.
  6024. *
  6025. * @return NULL on failure.
  6026. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6027. */
  6028. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6029. {
  6030. #if WOLFSSL_MAX_BN_BITS >= 2048
  6031. static const char prm[] = {
  6032. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6033. "C4C6628B80DC1CD129024E088A67CC74"
  6034. "020BBEA63B139B22514A08798E3404DD"
  6035. "EF9519B3CD3A431B302B0A6DF25F1437"
  6036. "4FE1356D6D51C245E485B576625E7EC6"
  6037. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6038. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6039. "49286651ECE45B3DC2007CB8A163BF05"
  6040. "98DA48361C55D39A69163FA8FD24CF5F"
  6041. "83655D23DCA3AD961C62F356208552BB"
  6042. "9ED529077096966D670C354E4ABC9804"
  6043. "F1746C08CA18217C32905E462E36CE3B"
  6044. "E39E772C180E86039B2783A2EC07A28F"
  6045. "B5C55DF06F4C52C9DE2BCBF695581718"
  6046. "3995497CEA956AE515D2261898FA0510"
  6047. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6048. };
  6049. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6050. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6051. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6052. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6053. bn = NULL;
  6054. }
  6055. return bn;
  6056. #else
  6057. (void)bn;
  6058. return NULL;
  6059. #endif
  6060. }
  6061. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6062. *
  6063. * @param [in, out] bn If not NULL then this BN is set and returned.
  6064. * If NULL then a new BN is created, set and returned.
  6065. *
  6066. * @return NULL on failure.
  6067. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6068. */
  6069. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6070. {
  6071. #if WOLFSSL_MAX_BN_BITS >= 3072
  6072. static const char prm[] = {
  6073. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6074. "C4C6628B80DC1CD129024E088A67CC74"
  6075. "020BBEA63B139B22514A08798E3404DD"
  6076. "EF9519B3CD3A431B302B0A6DF25F1437"
  6077. "4FE1356D6D51C245E485B576625E7EC6"
  6078. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6079. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6080. "49286651ECE45B3DC2007CB8A163BF05"
  6081. "98DA48361C55D39A69163FA8FD24CF5F"
  6082. "83655D23DCA3AD961C62F356208552BB"
  6083. "9ED529077096966D670C354E4ABC9804"
  6084. "F1746C08CA18217C32905E462E36CE3B"
  6085. "E39E772C180E86039B2783A2EC07A28F"
  6086. "B5C55DF06F4C52C9DE2BCBF695581718"
  6087. "3995497CEA956AE515D2261898FA0510"
  6088. "15728E5A8AAAC42DAD33170D04507A33"
  6089. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6090. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6091. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6092. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6093. "D87602733EC86A64521F2B18177B200C"
  6094. "BBE117577A615D6C770988C0BAD946E2"
  6095. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6096. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6097. };
  6098. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6099. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6100. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6101. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6102. bn = NULL;
  6103. }
  6104. return bn;
  6105. #else
  6106. (void)bn;
  6107. return NULL;
  6108. #endif
  6109. }
  6110. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6111. *
  6112. * @param [in, out] bn If not NULL then this BN is set and returned.
  6113. * If NULL then a new BN is created, set and returned.
  6114. *
  6115. * @return NULL on failure.
  6116. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6117. */
  6118. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6119. {
  6120. #if WOLFSSL_MAX_BN_BITS >= 4096
  6121. static const char prm[] = {
  6122. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6123. "C4C6628B80DC1CD129024E088A67CC74"
  6124. "020BBEA63B139B22514A08798E3404DD"
  6125. "EF9519B3CD3A431B302B0A6DF25F1437"
  6126. "4FE1356D6D51C245E485B576625E7EC6"
  6127. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6128. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6129. "49286651ECE45B3DC2007CB8A163BF05"
  6130. "98DA48361C55D39A69163FA8FD24CF5F"
  6131. "83655D23DCA3AD961C62F356208552BB"
  6132. "9ED529077096966D670C354E4ABC9804"
  6133. "F1746C08CA18217C32905E462E36CE3B"
  6134. "E39E772C180E86039B2783A2EC07A28F"
  6135. "B5C55DF06F4C52C9DE2BCBF695581718"
  6136. "3995497CEA956AE515D2261898FA0510"
  6137. "15728E5A8AAAC42DAD33170D04507A33"
  6138. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6139. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6140. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6141. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6142. "D87602733EC86A64521F2B18177B200C"
  6143. "BBE117577A615D6C770988C0BAD946E2"
  6144. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6145. "4B82D120A92108011A723C12A787E6D7"
  6146. "88719A10BDBA5B2699C327186AF4E23C"
  6147. "1A946834B6150BDA2583E9CA2AD44CE8"
  6148. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6149. "287C59474E6BC05D99B2964FA090C3A2"
  6150. "233BA186515BE7ED1F612970CEE2D7AF"
  6151. "B81BDD762170481CD0069127D5B05AA9"
  6152. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6153. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6154. };
  6155. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6156. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6157. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6158. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6159. bn = NULL;
  6160. }
  6161. return bn;
  6162. #else
  6163. (void)bn;
  6164. return NULL;
  6165. #endif
  6166. }
  6167. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6168. *
  6169. * @param [in, out] bn If not NULL then this BN is set and returned.
  6170. * If NULL then a new BN is created, set and returned.
  6171. *
  6172. * @return NULL on failure.
  6173. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6174. */
  6175. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6176. {
  6177. #if WOLFSSL_MAX_BN_BITS >= 6144
  6178. static const char prm[] = {
  6179. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6180. "C4C6628B80DC1CD129024E088A67CC74"
  6181. "020BBEA63B139B22514A08798E3404DD"
  6182. "EF9519B3CD3A431B302B0A6DF25F1437"
  6183. "4FE1356D6D51C245E485B576625E7EC6"
  6184. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6185. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6186. "49286651ECE45B3DC2007CB8A163BF05"
  6187. "98DA48361C55D39A69163FA8FD24CF5F"
  6188. "83655D23DCA3AD961C62F356208552BB"
  6189. "9ED529077096966D670C354E4ABC9804"
  6190. "F1746C08CA18217C32905E462E36CE3B"
  6191. "E39E772C180E86039B2783A2EC07A28F"
  6192. "B5C55DF06F4C52C9DE2BCBF695581718"
  6193. "3995497CEA956AE515D2261898FA0510"
  6194. "15728E5A8AAAC42DAD33170D04507A33"
  6195. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6196. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6197. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6198. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6199. "D87602733EC86A64521F2B18177B200C"
  6200. "BBE117577A615D6C770988C0BAD946E2"
  6201. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6202. "4B82D120A92108011A723C12A787E6D7"
  6203. "88719A10BDBA5B2699C327186AF4E23C"
  6204. "1A946834B6150BDA2583E9CA2AD44CE8"
  6205. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6206. "287C59474E6BC05D99B2964FA090C3A2"
  6207. "233BA186515BE7ED1F612970CEE2D7AF"
  6208. "B81BDD762170481CD0069127D5B05AA9"
  6209. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6210. "4DF435C93402849236C3FAB4D27C7026"
  6211. "C1D4DCB2602646DEC9751E763DBA37BD"
  6212. "F8FF9406AD9E530EE5DB382F413001AE"
  6213. "B06A53ED9027D831179727B0865A8918"
  6214. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6215. "DB7F1447E6CC254B332051512BD7AF42"
  6216. "6FB8F401378CD2BF5983CA01C64B92EC"
  6217. "F032EA15D1721D03F482D7CE6E74FEF6"
  6218. "D55E702F46980C82B5A84031900B1C9E"
  6219. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6220. "0F1D45B7FF585AC54BD407B22B4154AA"
  6221. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6222. "A79715EEF29BE32806A1D58BB7C5DA76"
  6223. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6224. "DA56C9EC2EF29632387FE8D76E3C0468"
  6225. "043E8F663F4860EE12BF2D5B0B7474D6"
  6226. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6227. };
  6228. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6229. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6230. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6231. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6232. bn = NULL;
  6233. }
  6234. return bn;
  6235. #else
  6236. (void)bn;
  6237. return NULL;
  6238. #endif
  6239. }
  6240. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6241. *
  6242. * @param [in, out] bn If not NULL then this BN is set and returned.
  6243. * If NULL then a new BN is created, set and returned.
  6244. *
  6245. * @return NULL on failure.
  6246. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6247. */
  6248. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6249. {
  6250. #if WOLFSSL_MAX_BN_BITS >= 8192
  6251. static const char prm[] = {
  6252. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6253. "C4C6628B80DC1CD129024E088A67CC74"
  6254. "020BBEA63B139B22514A08798E3404DD"
  6255. "EF9519B3CD3A431B302B0A6DF25F1437"
  6256. "4FE1356D6D51C245E485B576625E7EC6"
  6257. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6258. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6259. "49286651ECE45B3DC2007CB8A163BF05"
  6260. "98DA48361C55D39A69163FA8FD24CF5F"
  6261. "83655D23DCA3AD961C62F356208552BB"
  6262. "9ED529077096966D670C354E4ABC9804"
  6263. "F1746C08CA18217C32905E462E36CE3B"
  6264. "E39E772C180E86039B2783A2EC07A28F"
  6265. "B5C55DF06F4C52C9DE2BCBF695581718"
  6266. "3995497CEA956AE515D2261898FA0510"
  6267. "15728E5A8AAAC42DAD33170D04507A33"
  6268. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6269. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6270. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6271. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6272. "D87602733EC86A64521F2B18177B200C"
  6273. "BBE117577A615D6C770988C0BAD946E2"
  6274. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6275. "4B82D120A92108011A723C12A787E6D7"
  6276. "88719A10BDBA5B2699C327186AF4E23C"
  6277. "1A946834B6150BDA2583E9CA2AD44CE8"
  6278. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6279. "287C59474E6BC05D99B2964FA090C3A2"
  6280. "233BA186515BE7ED1F612970CEE2D7AF"
  6281. "B81BDD762170481CD0069127D5B05AA9"
  6282. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6283. "4DF435C93402849236C3FAB4D27C7026"
  6284. "C1D4DCB2602646DEC9751E763DBA37BD"
  6285. "F8FF9406AD9E530EE5DB382F413001AE"
  6286. "B06A53ED9027D831179727B0865A8918"
  6287. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6288. "DB7F1447E6CC254B332051512BD7AF42"
  6289. "6FB8F401378CD2BF5983CA01C64B92EC"
  6290. "F032EA15D1721D03F482D7CE6E74FEF6"
  6291. "D55E702F46980C82B5A84031900B1C9E"
  6292. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6293. "0F1D45B7FF585AC54BD407B22B4154AA"
  6294. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6295. "A79715EEF29BE32806A1D58BB7C5DA76"
  6296. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6297. "DA56C9EC2EF29632387FE8D76E3C0468"
  6298. "043E8F663F4860EE12BF2D5B0B7474D6"
  6299. "E694F91E6DBE115974A3926F12FEE5E4"
  6300. "38777CB6A932DF8CD8BEC4D073B931BA"
  6301. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6302. "2576F6936BA424663AAB639C5AE4F568"
  6303. "3423B4742BF1C978238F16CBE39D652D"
  6304. "E3FDB8BEFC848AD922222E04A4037C07"
  6305. "13EB57A81A23F0C73473FC646CEA306B"
  6306. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6307. "79683303ED5BDD3A062B3CF5B3A278A6"
  6308. "6D2A13F83F44F82DDF310EE074AB6A36"
  6309. "4597E899A0255DC164F31CC50846851D"
  6310. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6311. "FAF36BC31ECFA268359046F4EB879F92"
  6312. "4009438B481C6CD7889A002ED5EE382B"
  6313. "C9190DA6FC026E479558E4475677E9AA"
  6314. "9E3050E2765694DFC81F56E880B96E71"
  6315. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6316. };
  6317. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6318. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6319. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6320. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6321. bn = NULL;
  6322. }
  6323. return bn;
  6324. #else
  6325. (void)bn;
  6326. return NULL;
  6327. #endif
  6328. }
  6329. /*
  6330. * DH to/from bin APIs
  6331. */
  6332. #ifndef NO_CERTS
  6333. /* Load the DER encoded DH parameters/key into DH key.
  6334. *
  6335. * @param [in, out] dh DH key to load parameters into.
  6336. * @param [in] der Buffer holding DER encoded parameters data.
  6337. * @param [in, out] idx On in, index at which DH key DER data starts.
  6338. * On out, index after DH key DER data.
  6339. * @param [in] derSz Size of DER buffer in bytes.
  6340. *
  6341. * @return 0 on success.
  6342. * @return 1 when decoding DER or setting the external key fails.
  6343. */
  6344. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6345. word32* idx, word32 derSz)
  6346. {
  6347. int err = 0;
  6348. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6349. int ret;
  6350. /* Decode DH parameters/key from DER. */
  6351. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6352. if (ret != 0) {
  6353. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6354. err = 1;
  6355. }
  6356. if (!err) {
  6357. /* wolfSSL DH key set. */
  6358. dh->inSet = 1;
  6359. /* Set the external DH key based on wolfSSL DH key. */
  6360. if (SetDhExternal(dh) != 1) {
  6361. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6362. err = 1;
  6363. }
  6364. }
  6365. #else
  6366. byte* p;
  6367. byte* g;
  6368. word32 pSz = MAX_DH_SIZE;
  6369. word32 gSz = MAX_DH_SIZE;
  6370. /* Only DH parameters supported. */
  6371. /* Load external and set internal. */
  6372. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6373. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6374. if ((p == NULL) || (g == NULL)) {
  6375. err = 1;
  6376. }
  6377. /* Extract the p and g as data from the DER encoded DH parameters. */
  6378. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6379. &gSz) < 0)) {
  6380. err = 1;
  6381. }
  6382. if (!err) {
  6383. /* Put p and g in as big numbers - free existing BNs. */
  6384. if (dh->p != NULL) {
  6385. wolfSSL_BN_free(dh->p);
  6386. dh->p = NULL;
  6387. }
  6388. if (dh->g != NULL) {
  6389. wolfSSL_BN_free(dh->g);
  6390. dh->g = NULL;
  6391. }
  6392. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6393. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6394. if (dh->p == NULL || dh->g == NULL) {
  6395. err = 1;
  6396. }
  6397. else {
  6398. /* External DH key parameters were set. */
  6399. dh->exSet = 1;
  6400. }
  6401. }
  6402. /* Set internal as the outside has been updated. */
  6403. if ((!err) && (SetDhInternal(dh) != 1)) {
  6404. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6405. err = 1;
  6406. }
  6407. if (!err) {
  6408. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6409. }
  6410. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6411. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6412. #endif
  6413. return err;
  6414. }
  6415. #ifdef OPENSSL_ALL
  6416. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6417. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6418. *
  6419. * @param [out] dh DH key to put parameters into. May be NULL.
  6420. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6421. * Value updated to end of data when dh is not NULL.
  6422. * @param [in] length Length of data available in bytes.
  6423. *
  6424. * @return DH key on success.
  6425. * @return NULL on failure.
  6426. */
  6427. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6428. long length)
  6429. {
  6430. WOLFSSL_DH *newDh = NULL;
  6431. word32 idx = 0;
  6432. int err = 0;
  6433. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6434. /* Validate parameters. */
  6435. if ((pp == NULL) || (length <= 0)) {
  6436. WOLFSSL_ERROR_MSG("bad argument");
  6437. err = 1;
  6438. }
  6439. /* Create new DH key to return. */
  6440. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6441. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6442. err = 1;
  6443. }
  6444. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6445. (word32)length) != 0)) {
  6446. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6447. err = 1;
  6448. }
  6449. if ((!err) && (dh != NULL)) {
  6450. /* Return through parameter too. */
  6451. *dh = newDh;
  6452. /* Move buffer on by the used amount. */
  6453. *pp += idx;
  6454. }
  6455. if (err && (newDh != NULL)) {
  6456. /* Dispose of any created DH key. */
  6457. wolfSSL_DH_free(newDh);
  6458. newDh = NULL;
  6459. }
  6460. return newDh;
  6461. }
  6462. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6463. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6464. *
  6465. * @params [in] dh DH key with parameters to encode.
  6466. * @params [in, out] out Pointer to buffer to encode into.
  6467. * When NULL or pointer to NULL, only length returned.
  6468. * @return 0 on error.
  6469. * @return Size of DER encoding in bytes on success.
  6470. */
  6471. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6472. {
  6473. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6474. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6475. word32 len = (word32)-1;
  6476. int err = 0;
  6477. /* Validate parameters. */
  6478. if (dh == NULL) {
  6479. WOLFSSL_ERROR_MSG("Bad parameters");
  6480. err = 1;
  6481. }
  6482. /* Push external DH data into internal DH key if not set. */
  6483. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6484. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6485. err = 1;
  6486. }
  6487. if (!err) {
  6488. int ret;
  6489. unsigned char* der = NULL;
  6490. /* Use *out when available otherwise NULL. */
  6491. if (out != NULL) {
  6492. der = *out;
  6493. }
  6494. /* Get length and/or encode. */
  6495. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6496. /* Length of encoded data is returned on success. */
  6497. if (ret > 0) {
  6498. *out += len;
  6499. }
  6500. /* An error occurred unless only length returned. */
  6501. else if (ret != LENGTH_ONLY_E) {
  6502. err = 1;
  6503. }
  6504. }
  6505. /* Set return to 0 on error. */
  6506. if (err) {
  6507. len = 0;
  6508. }
  6509. return (int)len;
  6510. #else
  6511. word32 len;
  6512. int ret = 0;
  6513. int pSz;
  6514. int gSz;
  6515. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6516. /* Validate parameters. */
  6517. if (dh == NULL) {
  6518. WOLFSSL_ERROR_MSG("Bad parameters");
  6519. len = 0;
  6520. }
  6521. else {
  6522. /* SEQ <len>
  6523. * INT <len> [0x00] <prime>
  6524. * INT <len> [0x00] <generator>
  6525. * Integers have 0x00 prepended if the top bit of positive number is
  6526. * set.
  6527. */
  6528. /* Get total length of prime including any prepended zeros. */
  6529. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6530. mp_leading_bit((mp_int*)dh->p->internal);
  6531. /* Get total length of generator including any prepended zeros. */
  6532. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6533. mp_leading_bit((mp_int*)dh->g->internal);
  6534. /* Calculate length of data in sequence. */
  6535. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6536. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6537. /* Add in the length of the SEQUENCE. */
  6538. len += 1 + ASN_LEN_SIZE(len);
  6539. if ((out != NULL) && (*out != NULL)) {
  6540. /* Encode parameters. */
  6541. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6542. (mp_int*)dh->g->internal);
  6543. if (ret != MP_OKAY) {
  6544. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6545. len = 0;
  6546. }
  6547. else {
  6548. /* Move pointer on if encoded. */
  6549. *out += len;
  6550. }
  6551. }
  6552. }
  6553. return (int)len;
  6554. #endif
  6555. }
  6556. #endif /* OPENSSL_ALL */
  6557. #endif /* !NO_CERTS */
  6558. #endif /* OPENSSL_EXTRA */
  6559. #if defined(OPENSSL_EXTRA) || \
  6560. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6561. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6562. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6563. /* Load the DER encoded DH parameters into DH key.
  6564. *
  6565. * @param [in, out] dh DH key to load parameters into.
  6566. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6567. * @param [in] derSz Size of DER data in buffer in bytes.
  6568. *
  6569. * @return 1 on success.
  6570. * @return -1 when DH or derBuf is NULL,
  6571. * internal DH key in DH is NULL,
  6572. * derSz is 0 or less,
  6573. * error decoding DER data or
  6574. * setting external parameter values fails.
  6575. */
  6576. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6577. {
  6578. int ret = 1;
  6579. word32 idx = 0;
  6580. /* Validate parameters. */
  6581. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6582. (derSz <= 0)) {
  6583. WOLFSSL_ERROR_MSG("Bad function arguments");
  6584. ret = -1;
  6585. }
  6586. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6587. (word32)derSz) != 0)) {
  6588. WOLFSSL_ERROR_MSG("DH key decode failed");
  6589. ret = -1;
  6590. }
  6591. return ret;
  6592. }
  6593. #endif
  6594. /*
  6595. * DH PEM APIs
  6596. */
  6597. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6598. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6599. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6600. /* Create a DH key by reading the PEM encoded data from the BIO.
  6601. *
  6602. * @param [in] bio BIO object to read from.
  6603. * @param [in, out] dh DH key to use. May be NULL.
  6604. * @param [in] pem PEM data to decode.
  6605. * @param [in] pemSz Size of PEM data in bytes.
  6606. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6607. * freed after use.
  6608. * @return DH key on success.
  6609. * @return NULL on failure.
  6610. */
  6611. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6612. unsigned char* pem, int pemSz, int memAlloced)
  6613. {
  6614. WOLFSSL_DH* localDh = NULL;
  6615. DerBuffer *der = NULL;
  6616. int err = 0;
  6617. /* Convert PEM to DER assuming DH Parameter format. */
  6618. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6619. NULL) < 0)) {
  6620. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6621. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6622. != 0) {
  6623. err = 1;
  6624. }
  6625. /* If Success on X9.42 DH format, clear error from failed DH format */
  6626. else {
  6627. unsigned long error;
  6628. CLEAR_ASN_NO_PEM_HEADER_ERROR(error);
  6629. }
  6630. }
  6631. if (memAlloced) {
  6632. /* PEM data no longer needed. */
  6633. XFREE(pem, NULL, DYNAMIC_TYPE_PEM);
  6634. }
  6635. if (!err) {
  6636. /* Use the DH key passed in or allocate a new one. */
  6637. if (dh != NULL) {
  6638. localDh = *dh;
  6639. }
  6640. if (localDh == NULL) {
  6641. localDh = wolfSSL_DH_new();
  6642. if (localDh == NULL) {
  6643. err = 1;
  6644. }
  6645. }
  6646. }
  6647. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6648. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, (int)der->length)
  6649. != 1)) {
  6650. /* Free an allocated DH key. */
  6651. if ((dh == NULL) || (localDh != *dh)) {
  6652. wolfSSL_DH_free(localDh);
  6653. }
  6654. localDh = NULL;
  6655. err = 1;
  6656. }
  6657. /* Return the DH key on success. */
  6658. if ((!err) && (dh != NULL)) {
  6659. *dh = localDh;
  6660. }
  6661. /* Dispose of DER data. */
  6662. if (der != NULL) {
  6663. FreeDer(&der);
  6664. }
  6665. return localDh;
  6666. }
  6667. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6668. #ifndef NO_BIO
  6669. /* Create a DH key by reading the PEM encoded data from the BIO.
  6670. *
  6671. * DH parameters are public data and are not expected to be encrypted.
  6672. *
  6673. * @param [in] bio BIO object to read from.
  6674. * @param [in, out] dh DH key to When pointer to
  6675. * NULL, a new DH key is created.
  6676. * @param [in] cb Password callback when PEM encrypted. Not used.
  6677. * @param [in] pass NUL terminated string for passphrase when PEM
  6678. * encrypted. Not used.
  6679. * @return DH key on success.
  6680. * @return NULL on failure.
  6681. */
  6682. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6683. wc_pem_password_cb *cb, void *pass)
  6684. {
  6685. WOLFSSL_DH* localDh = NULL;
  6686. int err = 0;
  6687. unsigned char* mem = NULL;
  6688. int size = 0;
  6689. int memAlloced = 0;
  6690. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6691. (void)cb;
  6692. (void)pass;
  6693. /* Validate parameters. */
  6694. if (bio == NULL) {
  6695. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6696. err = 1;
  6697. }
  6698. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6699. */
  6700. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6701. != 0)) {
  6702. err = 1;
  6703. }
  6704. if (!err) {
  6705. /* Create a DH key from the PEM - try two different headers. */
  6706. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6707. }
  6708. return localDh;
  6709. }
  6710. #endif /* !NO_BIO */
  6711. #ifndef NO_FILESYSTEM
  6712. /* Read DH parameters from a file pointer into DH key.
  6713. *
  6714. * DH parameters are public data and are not expected to be encrypted.
  6715. *
  6716. * @param [in] fp File pointer to read DH parameter file from.
  6717. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6718. * NULL, a new DH key is created.
  6719. * @param [in] cb Password callback when PEM encrypted. Not used.
  6720. * @param [in] pass NUL terminated string for passphrase when PEM
  6721. * encrypted. Not used.
  6722. *
  6723. * @return NULL on failure.
  6724. * @return DH key with parameters set on success.
  6725. */
  6726. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6727. wc_pem_password_cb* cb, void* pass)
  6728. {
  6729. WOLFSSL_DH* localDh = NULL;
  6730. int err = 0;
  6731. unsigned char* mem = NULL;
  6732. int size = 0;
  6733. (void)cb;
  6734. (void)pass;
  6735. /* Read data from file pointer. */
  6736. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6737. err = 1;
  6738. }
  6739. if (!err) {
  6740. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6741. }
  6742. return localDh;
  6743. }
  6744. #endif /* !NO_FILESYSTEM */
  6745. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6746. /* Encoded parameter data in DH key as DER.
  6747. *
  6748. * @param [in, out] dh DH key object to encode.
  6749. * @param [out] out Buffer containing DER encoding.
  6750. * @param [in] heap Heap hint.
  6751. * @return <0 on error.
  6752. * @return Length of DER encoded DH parameters in bytes.
  6753. */
  6754. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6755. void* heap)
  6756. {
  6757. int ret = -1;
  6758. int err = 0;
  6759. byte* der = NULL;
  6760. word32 derSz;
  6761. DhKey* key = NULL;
  6762. (void)heap;
  6763. /* Set internal parameters based on external parameters. */
  6764. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6765. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6766. err = 1;
  6767. }
  6768. if (!err) {
  6769. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6770. key = (DhKey*)dh->internal;
  6771. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6772. if (ret != LENGTH_ONLY_E) {
  6773. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6774. err = 1;
  6775. }
  6776. }
  6777. if (!err) {
  6778. /* Allocate memory for DER encoding. */
  6779. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6780. if (der == NULL) {
  6781. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6782. err = 1;
  6783. }
  6784. }
  6785. if (!err) {
  6786. /* Encode DH parameters into DER buffer. */
  6787. ret = wc_DhParamsToDer(key, der, &derSz);
  6788. if (ret < 0) {
  6789. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6790. err = 1;
  6791. }
  6792. }
  6793. if (!err) {
  6794. *out = der;
  6795. der = NULL;
  6796. }
  6797. if (der != NULL) {
  6798. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6799. }
  6800. return ret;
  6801. }
  6802. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6803. * passed in.
  6804. *
  6805. * @param [in] fp File pointer to write to.
  6806. * @param [in] dh DH key to write.
  6807. * @return 1 on success.
  6808. * @return 0 on failure.
  6809. */
  6810. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6811. {
  6812. int ret = 1;
  6813. int derSz;
  6814. byte* derBuf = NULL;
  6815. void* heap = NULL;
  6816. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6817. /* Validate parameters. */
  6818. if ((fp == XBADFILE) || (dh == NULL)) {
  6819. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6820. ret = 0;
  6821. }
  6822. if (ret == 1) {
  6823. DhKey* key = (DhKey*)dh->internal;
  6824. if (key)
  6825. heap = key->heap;
  6826. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6827. WOLFSSL_ERROR_MSG("DER encoding failed");
  6828. ret = 0;
  6829. }
  6830. if (derBuf == NULL) {
  6831. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6832. ret = 0;
  6833. }
  6834. }
  6835. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6836. DH_PARAM_TYPE, NULL) != WOLFSSL_SUCCESS)) {
  6837. ret = 0;
  6838. }
  6839. /* Dispose of DER buffer. */
  6840. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6841. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6842. return ret;
  6843. }
  6844. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6845. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6846. * OPENSSL_EXTRA */
  6847. /*
  6848. * DH get/set APIs
  6849. */
  6850. #ifdef OPENSSL_EXTRA
  6851. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6852. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6853. /* Set the members of DhKey into WOLFSSL_DH
  6854. * Specify elements to set via the 2nd parameter
  6855. *
  6856. * @param [in, out] dh DH key to synchronize.
  6857. * @param [in] elm Elements to synchronize.
  6858. * @return 1 on success.
  6859. * @return -1 on failure.
  6860. */
  6861. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  6862. {
  6863. int ret = 1;
  6864. DhKey *key = NULL;
  6865. WOLFSSL_ENTER("SetDhExternal_ex");
  6866. /* Validate parameters. */
  6867. if ((dh == NULL) || (dh->internal == NULL)) {
  6868. WOLFSSL_ERROR_MSG("dh key NULL error");
  6869. ret = -1;
  6870. }
  6871. if (ret == 1) {
  6872. /* Get the wolfSSL DH key. */
  6873. key = (DhKey*)dh->internal;
  6874. }
  6875. if ((ret == 1) && (elm & ELEMENT_P)) {
  6876. /* Set the prime. */
  6877. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  6878. WOLFSSL_ERROR_MSG("dh param p error");
  6879. ret = -1;
  6880. }
  6881. }
  6882. if ((ret == 1) && (elm & ELEMENT_G)) {
  6883. /* Set the generator. */
  6884. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  6885. WOLFSSL_ERROR_MSG("dh param g error");
  6886. ret = -1;
  6887. }
  6888. }
  6889. if ((ret == 1) && (elm & ELEMENT_Q)) {
  6890. /* Set the order. */
  6891. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  6892. WOLFSSL_ERROR_MSG("dh param q error");
  6893. ret = -1;
  6894. }
  6895. }
  6896. #ifdef WOLFSSL_DH_EXTRA
  6897. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  6898. /* Set the private key. */
  6899. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  6900. WOLFSSL_ERROR_MSG("No DH Private Key");
  6901. ret = -1;
  6902. }
  6903. }
  6904. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  6905. /* Set the public key. */
  6906. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  6907. WOLFSSL_ERROR_MSG("No DH Public Key");
  6908. ret = -1;
  6909. }
  6910. }
  6911. #endif /* WOLFSSL_DH_EXTRA */
  6912. if (ret == 1) {
  6913. /* On success record that the external values have been set. */
  6914. dh->exSet = 1;
  6915. }
  6916. return ret;
  6917. }
  6918. /* Set the members of DhKey into WOLFSSL_DH
  6919. * DhKey was populated from wc_DhKeyDecode
  6920. * p, g, pub_key and priv_key are set.
  6921. *
  6922. * @param [in, out] dh DH key to synchronize.
  6923. * @return 1 on success.
  6924. * @return -1 on failure.
  6925. */
  6926. int SetDhExternal(WOLFSSL_DH *dh)
  6927. {
  6928. /* Assuming Q not required when using this API. */
  6929. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  6930. WOLFSSL_ENTER("SetDhExternal");
  6931. return SetDhExternal_ex(dh, elements);
  6932. }
  6933. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  6934. /* Set the internal/wolfSSL DH key with data from the external parts.
  6935. *
  6936. * @param [in, out] dh DH key to synchronize.
  6937. * @return 1 on success.
  6938. * @return -1 on failure.
  6939. */
  6940. int SetDhInternal(WOLFSSL_DH* dh)
  6941. {
  6942. int ret = 1;
  6943. DhKey *key = NULL;
  6944. WOLFSSL_ENTER("SetDhInternal");
  6945. /* Validate parameters. */
  6946. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  6947. WOLFSSL_ERROR_MSG("Bad function arguments");
  6948. ret = -1;
  6949. }
  6950. if (ret == 1) {
  6951. /* Get the wolfSSL DH key. */
  6952. key = (DhKey*)dh->internal;
  6953. /* Clear out key and initialize. */
  6954. wc_FreeDhKey(key);
  6955. if (wc_InitDhKey(key) != 0) {
  6956. ret = -1;
  6957. }
  6958. }
  6959. if (ret == 1) {
  6960. /* Transfer prime. */
  6961. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  6962. ret = -1;
  6963. }
  6964. }
  6965. if (ret == 1) {
  6966. /* Transfer generator. */
  6967. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  6968. ret = -1;
  6969. }
  6970. }
  6971. #ifdef HAVE_FFDHE_Q
  6972. /* Transfer order if available. */
  6973. if ((ret == 1) && (dh->q != NULL)) {
  6974. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  6975. ret = -1;
  6976. }
  6977. }
  6978. #endif
  6979. #ifdef WOLFSSL_DH_EXTRA
  6980. /* Transfer private key if available. */
  6981. if ((ret == 1) && (dh->priv_key != NULL) &&
  6982. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  6983. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  6984. ret = -1;
  6985. }
  6986. }
  6987. /* Transfer public key if available. */
  6988. if ((ret == 1) && (dh->pub_key != NULL) &&
  6989. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  6990. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  6991. ret = -1;
  6992. }
  6993. }
  6994. #endif /* WOLFSSL_DH_EXTRA */
  6995. if (ret == 1) {
  6996. /* On success record that the internal values have been set. */
  6997. dh->inSet = 1;
  6998. }
  6999. return ret;
  7000. }
  7001. /* Get the size, in bytes, of the DH key.
  7002. *
  7003. * Return code compliant with OpenSSL.
  7004. *
  7005. * @param [in] dh DH key.
  7006. * @return -1 on error.
  7007. * @return Size of DH key in bytes on success.
  7008. */
  7009. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  7010. {
  7011. int ret = -1;
  7012. WOLFSSL_ENTER("wolfSSL_DH_size");
  7013. /* Validate parameter. */
  7014. if (dh != NULL) {
  7015. /* Size of key is size of prime in bytes. */
  7016. ret = wolfSSL_BN_num_bytes(dh->p);
  7017. }
  7018. return ret;
  7019. }
  7020. /**
  7021. * Return parameters p, q and/or g of the DH key.
  7022. *
  7023. * @param [in] dh DH key to retrieve parameters from.
  7024. * @param [out] p Pointer to return prime in. May be NULL.
  7025. * @param [out] q Pointer to return order in. May be NULL.
  7026. * @param [out] g Pointer to return generator in. May be NULL.
  7027. */
  7028. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7029. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7030. {
  7031. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7032. if (dh != NULL) {
  7033. /* Return prime if required. */
  7034. if (p != NULL) {
  7035. *p = dh->p;
  7036. }
  7037. /* Return order if required. */
  7038. if (q != NULL) {
  7039. *q = dh->q;
  7040. }
  7041. /* Return generator if required. */
  7042. if (g != NULL) {
  7043. *g = dh->g;
  7044. }
  7045. }
  7046. }
  7047. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7048. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7049. #if defined(OPENSSL_ALL) || \
  7050. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7051. /* Sets the parameters p, g and optionally q into the DH key.
  7052. *
  7053. * Ownership of p, q and g get taken over by "dh" on success and should be
  7054. * free'd with a call to wolfSSL_DH_free -- not individually.
  7055. *
  7056. * @param [in, out] dh DH key to set.
  7057. * @param [in] p Prime value to set. May be NULL when value already
  7058. * present.
  7059. * @param [in] q Order value to set. May be NULL.
  7060. * @param [in] g Generator value to set. May be NULL when value already
  7061. * present.
  7062. * @return 1 on success.
  7063. * @return 0 on failure.
  7064. */
  7065. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7066. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7067. {
  7068. int ret = 1;
  7069. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7070. /* Validate parameters - q is optional. */
  7071. if (dh == NULL) {
  7072. WOLFSSL_ERROR_MSG("Bad function arguments");
  7073. ret = 0;
  7074. }
  7075. /* p can be NULL if we already have one set. */
  7076. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7077. WOLFSSL_ERROR_MSG("Bad function arguments");
  7078. ret = 0;
  7079. }
  7080. /* g can be NULL if we already have one set. */
  7081. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7082. WOLFSSL_ERROR_MSG("Bad function arguments");
  7083. ret = 0;
  7084. }
  7085. if (ret == 1) {
  7086. /* Invalidate internal key. */
  7087. dh->inSet = 0;
  7088. /* Free external representation of parameters and set with those passed
  7089. * in. */
  7090. if (p != NULL) {
  7091. wolfSSL_BN_free(dh->p);
  7092. dh->p = p;
  7093. }
  7094. if (q != NULL) {
  7095. wolfSSL_BN_free(dh->q);
  7096. dh->q = q;
  7097. }
  7098. if (g != NULL) {
  7099. wolfSSL_BN_free(dh->g);
  7100. dh->g = g;
  7101. }
  7102. /* External DH key parameters were set. */
  7103. dh->exSet = 1;
  7104. /* Set internal/wolfSSL DH key as well. */
  7105. if (SetDhInternal(dh) != 1) {
  7106. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7107. /* Don't keep parameters on failure. */
  7108. dh->p = NULL;
  7109. dh->q = NULL;
  7110. dh->g = NULL;
  7111. /* Internal and external DH key not set. */
  7112. dh->inSet = 0;
  7113. dh->exSet = 0;
  7114. ret = 0;
  7115. }
  7116. }
  7117. return ret;
  7118. }
  7119. /* Set the length of the DH private key in bits.
  7120. *
  7121. * Length field is checked at generation.
  7122. *
  7123. * @param [in, out] dh DH key to set.
  7124. * @param [in] len Length of DH private key in bytes.
  7125. * @return 0 on failure.
  7126. * @return 1 on success.
  7127. */
  7128. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7129. {
  7130. int ret = 1;
  7131. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7132. /* Validate parameter. */
  7133. if (dh == NULL) {
  7134. WOLFSSL_ERROR_MSG("Bad function arguments");
  7135. ret = 0;
  7136. }
  7137. else {
  7138. /* Store length. */
  7139. dh->length = (int)len;
  7140. }
  7141. return ret;
  7142. }
  7143. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7144. #endif
  7145. /* Get the public and private keys requested.
  7146. *
  7147. * @param [in] dh DH key to get keys from.
  7148. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7149. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7150. */
  7151. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7152. const WOLFSSL_BIGNUM **priv_key)
  7153. {
  7154. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7155. /* Get only when valid DH passed in. */
  7156. if (dh != NULL) {
  7157. /* Return public key if required and available. */
  7158. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7159. *pub_key = dh->pub_key;
  7160. }
  7161. /* Return private key if required and available. */
  7162. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7163. *priv_key = dh->priv_key;
  7164. }
  7165. }
  7166. }
  7167. /* Set the public and/or private key.
  7168. *
  7169. * @param [in, out] dh DH key to have keys set into.
  7170. * @param [in] pub_key Public key to set. May be NULL.
  7171. * @param [in] priv_key Private key to set. May be NULL.
  7172. * @return 0 on failure.
  7173. * @return 1 on success.
  7174. */
  7175. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7176. WOLFSSL_BIGNUM *priv_key)
  7177. {
  7178. int ret = 1;
  7179. #ifdef WOLFSSL_DH_EXTRA
  7180. DhKey *key = NULL;
  7181. #endif
  7182. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7183. /* Validate parameters. */
  7184. if (dh == NULL) {
  7185. ret = 0;
  7186. }
  7187. #ifdef WOLFSSL_DH_EXTRA
  7188. else {
  7189. key = (DhKey*)dh->internal;
  7190. }
  7191. #endif
  7192. /* Replace public key when one passed in. */
  7193. if ((ret == 1) && (pub_key != NULL)) {
  7194. wolfSSL_BN_free(dh->pub_key);
  7195. dh->pub_key = pub_key;
  7196. #ifdef WOLFSSL_DH_EXTRA
  7197. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7198. ret = 0;
  7199. }
  7200. #endif
  7201. }
  7202. /* Replace private key when one passed in. */
  7203. if ((ret == 1) && (priv_key != NULL)) {
  7204. wolfSSL_BN_clear_free(dh->priv_key);
  7205. dh->priv_key = priv_key;
  7206. #ifdef WOLFSSL_DH_EXTRA
  7207. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7208. ret = 0;
  7209. }
  7210. #endif
  7211. }
  7212. return ret;
  7213. }
  7214. #endif /* OPENSSL_EXTRA */
  7215. /*
  7216. * DH check APIs
  7217. */
  7218. #ifdef OPENSSL_EXTRA
  7219. #ifndef NO_CERTS
  7220. #ifdef OPENSSL_ALL
  7221. /* Check whether BN number is a prime.
  7222. *
  7223. * @param [in] n Number to check.
  7224. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7225. * @return 1 on success.
  7226. * @return 0 on error.
  7227. */
  7228. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7229. {
  7230. int ret = 1;
  7231. #ifdef WOLFSSL_SMALL_STACK
  7232. WC_RNG* tmpRng = NULL;
  7233. #else
  7234. WC_RNG tmpRng[1];
  7235. #endif
  7236. WC_RNG* rng;
  7237. int localRng;
  7238. /* Make an RNG with tmpRng or get global. */
  7239. rng = wolfssl_make_rng(tmpRng, &localRng);
  7240. if (rng == NULL) {
  7241. ret = 0;
  7242. }
  7243. if (ret == 1) {
  7244. mp_int* prime = (mp_int*)n->internal;
  7245. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7246. ret = 0;
  7247. }
  7248. /* Free local random number generator if created. */
  7249. if (localRng) {
  7250. wc_FreeRng(rng);
  7251. #ifdef WOLFSSL_SMALL_STACK
  7252. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7253. #endif
  7254. }
  7255. }
  7256. return ret;
  7257. }
  7258. /* Checks the Diffie-Hellman parameters.
  7259. *
  7260. * Checks that the generator and prime are available.
  7261. * Checks that the prime is prime.
  7262. * OpenSSL expects codes to be non-NULL.
  7263. *
  7264. * @param [in] dh DH key to check.
  7265. * @param [out] codes Codes of checks that failed.
  7266. * @return 1 on success.
  7267. * @return 0 when DH is NULL, there were errors or failed to create a random
  7268. * number generator.
  7269. */
  7270. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7271. {
  7272. int ret = 1;
  7273. int errors = 0;
  7274. WOLFSSL_ENTER("wolfSSL_DH_check");
  7275. /* Validate parameters. */
  7276. if (dh == NULL) {
  7277. ret = 0;
  7278. }
  7279. /* Check generator available. */
  7280. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7281. errors |= DH_NOT_SUITABLE_GENERATOR;
  7282. }
  7283. if (ret == 1) {
  7284. /* Check prime available. */
  7285. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7286. errors |= DH_CHECK_P_NOT_PRIME;
  7287. }
  7288. else {
  7289. /* Test if dh->p is prime. */
  7290. int isPrime = MP_NO;
  7291. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7292. /* Set error code if parameter p is not prime. */
  7293. if ((ret == 1) && (isPrime != MP_YES)) {
  7294. errors |= DH_CHECK_P_NOT_PRIME;
  7295. }
  7296. }
  7297. }
  7298. /* Return errors when user wants exact issues. */
  7299. if (codes != NULL) {
  7300. *codes = errors;
  7301. }
  7302. else if (errors) {
  7303. ret = 0;
  7304. }
  7305. return ret;
  7306. }
  7307. #endif /* OPENSSL_ALL */
  7308. #endif /* !NO_CERTS */
  7309. #endif /* OPENSSL_EXTRA */
  7310. /*
  7311. * DH generate APIs
  7312. */
  7313. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7314. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7315. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7316. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7317. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7318. /* Generate DH parameters.
  7319. *
  7320. * @param [in] prime_len Length of prime in bits.
  7321. * @param [in] generator Generator value to use.
  7322. * @param [in] callback Called with progress information. Unused.
  7323. * @param [in] cb_arg User callback argument. Unused.
  7324. * @return NULL on failure.
  7325. * @return DH key on success.
  7326. */
  7327. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7328. void (*callback) (int, int, void *), void *cb_arg)
  7329. {
  7330. WOLFSSL_DH* dh = NULL;
  7331. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7332. /* Not supported by wolfSSl APIs. */
  7333. (void)callback;
  7334. (void)cb_arg;
  7335. /* Create an empty DH key. */
  7336. if ((dh = wolfSSL_DH_new()) == NULL) {
  7337. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7338. }
  7339. /* Generate parameters into DH key. */
  7340. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7341. != 1) {
  7342. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7343. wolfSSL_DH_free(dh);
  7344. dh = NULL;
  7345. }
  7346. return dh;
  7347. }
  7348. /* Generate DH parameters.
  7349. *
  7350. * @param [in] dh DH key to generate parameters into.
  7351. * @param [in] prime_len Length of prime in bits.
  7352. * @param [in] generator Generator value to use.
  7353. * @param [in] callback Called with progress information. Unused.
  7354. * @param [in] cb_arg User callback argument. Unused.
  7355. * @return 0 on failure.
  7356. * @return 1 on success.
  7357. */
  7358. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7359. int generator, void (*callback) (int, int, void *))
  7360. {
  7361. int ret = 1;
  7362. DhKey* key = NULL;
  7363. #ifdef WOLFSSL_SMALL_STACK
  7364. WC_RNG* tmpRng = NULL;
  7365. #else
  7366. WC_RNG tmpRng[1];
  7367. #endif
  7368. WC_RNG* rng = NULL;
  7369. int localRng = 0;
  7370. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7371. /* Not supported by wolfSSL APIs. */
  7372. (void)callback;
  7373. (void)generator;
  7374. /* Validate parameters. */
  7375. if (dh == NULL) {
  7376. WOLFSSL_ERROR_MSG("Bad parameter");
  7377. ret = 0;
  7378. }
  7379. if (ret == 1) {
  7380. /* Make an RNG with tmpRng or get global. */
  7381. rng = wolfssl_make_rng(tmpRng, &localRng);
  7382. if (rng == NULL) {
  7383. WOLFSSL_ERROR_MSG("No RNG to use");
  7384. ret = 0;
  7385. }
  7386. }
  7387. if (ret == 1) {
  7388. /* Get internal/wolfSSL DH key. */
  7389. key = (DhKey*)dh->internal;
  7390. /* Clear out data from internal DH key. */
  7391. wc_FreeDhKey(key);
  7392. /* Re-initialize internal DH key. */
  7393. if (wc_InitDhKey(key) != 0) {
  7394. ret = 0;
  7395. }
  7396. }
  7397. if (ret == 1) {
  7398. /* Generate parameters into internal DH key. */
  7399. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7400. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7401. ret = 0;
  7402. }
  7403. }
  7404. /* Free local random number generator if created. */
  7405. if (localRng) {
  7406. wc_FreeRng(rng);
  7407. #ifdef WOLFSSL_SMALL_STACK
  7408. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7409. #endif
  7410. }
  7411. if (ret == 1) {
  7412. /* Internal parameters set by generation. */
  7413. dh->inSet = 1;
  7414. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7415. /* Synchronize the external to the internal parameters. */
  7416. if (SetDhExternal(dh) != 1) {
  7417. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7418. ret = 0;
  7419. }
  7420. }
  7421. return ret;
  7422. }
  7423. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7424. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7425. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7426. * HAVE_SBLIM_SFCB)) */
  7427. #ifdef OPENSSL_EXTRA
  7428. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7429. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7430. /* Generate a public/private key pair base on parameters.
  7431. *
  7432. * @param [in, out] dh DH key to generate keys into.
  7433. * @return 1 on success.
  7434. * @return 0 on error.
  7435. */
  7436. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7437. {
  7438. int ret = 1;
  7439. word32 pubSz = 0;
  7440. word32 privSz = 0;
  7441. int localRng = 0;
  7442. WC_RNG* rng = NULL;
  7443. #ifdef WOLFSSL_SMALL_STACK
  7444. WC_RNG* tmpRng = NULL;
  7445. #else
  7446. WC_RNG tmpRng[1];
  7447. #endif
  7448. unsigned char* pub = NULL;
  7449. unsigned char* priv = NULL;
  7450. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7451. /* Validate parameters. */
  7452. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7453. WOLFSSL_ERROR_MSG("Bad function arguments");
  7454. ret = 0;
  7455. }
  7456. /* Synchronize the external and internal parameters. */
  7457. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7458. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7459. ret = 0;
  7460. }
  7461. if (ret == 1) {
  7462. /* Make a new RNG or use global. */
  7463. rng = wolfssl_make_rng(tmpRng, &localRng);
  7464. /* Check we have a random number generator. */
  7465. if (rng == NULL) {
  7466. ret = 0;
  7467. }
  7468. }
  7469. if (ret == 1) {
  7470. /* Get the size of the prime in bytes. */
  7471. pubSz = (word32)wolfSSL_BN_num_bytes(dh->p);
  7472. if (pubSz == 0) {
  7473. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7474. ret = 0;
  7475. }
  7476. }
  7477. if (ret == 1) {
  7478. /* Private key size can be as much as the size of the prime. */
  7479. if (dh->length) {
  7480. privSz = (word32)(dh->length / 8); /* to bytes */
  7481. }
  7482. else {
  7483. privSz = pubSz;
  7484. }
  7485. /* Allocate public and private key arrays. */
  7486. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7487. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7488. if (pub == NULL || priv == NULL) {
  7489. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7490. ret = 0;
  7491. }
  7492. }
  7493. if (ret == 1) {
  7494. /* Dispose of old public and private keys. */
  7495. wolfSSL_BN_free(dh->pub_key);
  7496. wolfSSL_BN_free(dh->priv_key);
  7497. /* Allocate new public and private keys. */
  7498. dh->pub_key = wolfSSL_BN_new();
  7499. dh->priv_key = wolfSSL_BN_new();
  7500. if (dh->pub_key == NULL) {
  7501. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7502. ret = 0;
  7503. }
  7504. if (dh->priv_key == NULL) {
  7505. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7506. ret = 0;
  7507. }
  7508. }
  7509. PRIVATE_KEY_UNLOCK();
  7510. /* Generate public and private keys into arrays. */
  7511. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7512. &privSz, pub, &pubSz) < 0)) {
  7513. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7514. ret = 0;
  7515. }
  7516. /* Set public key from array. */
  7517. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, (int)pubSz, dh->pub_key) ==
  7518. NULL)) {
  7519. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7520. ret = 0;
  7521. }
  7522. /* Set private key from array. */
  7523. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, (int)privSz, dh->priv_key) ==
  7524. NULL)) {
  7525. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7526. ret = 0;
  7527. }
  7528. PRIVATE_KEY_LOCK();
  7529. if (localRng) {
  7530. /* Free an initialized local random number generator. */
  7531. wc_FreeRng(rng);
  7532. #ifdef WOLFSSL_SMALL_STACK
  7533. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7534. #endif
  7535. }
  7536. /* Dispose of allocated data. */
  7537. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7538. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7539. return ret;
  7540. }
  7541. /* Compute the shared key from the private key and peer's public key.
  7542. *
  7543. * Return code compliant with OpenSSL.
  7544. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7545. * supported.
  7546. *
  7547. * @param [out] key Buffer to place shared key.
  7548. * @param [in] otherPub Peer's public key.
  7549. * @param [in] dh DH key containing private key.
  7550. * @return -1 on error.
  7551. * @return Size of shared secret in bytes on success.
  7552. */
  7553. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7554. WOLFSSL_DH* dh)
  7555. {
  7556. int ret = 0;
  7557. word32 keySz = 0;
  7558. int pubSz = MAX_DHKEY_SZ;
  7559. int privSz = MAX_DHKEY_SZ;
  7560. int sz = 0;
  7561. #ifdef WOLFSSL_SMALL_STACK
  7562. unsigned char* pub = NULL;
  7563. unsigned char* priv = NULL;
  7564. #else
  7565. unsigned char pub [MAX_DHKEY_SZ];
  7566. unsigned char priv[MAX_DHKEY_SZ];
  7567. #endif
  7568. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7569. /* Validate parameters. */
  7570. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7571. WOLFSSL_ERROR_MSG("Bad function arguments");
  7572. ret = -1;
  7573. }
  7574. /* Get the maximum size of computed DH key. */
  7575. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7576. WOLFSSL_ERROR_MSG("Bad DH_size");
  7577. ret = -1;
  7578. }
  7579. if (ret == 0) {
  7580. /* Validate the size of the private key. */
  7581. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7582. if (sz > (int)privSz) {
  7583. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7584. ret = -1;
  7585. }
  7586. }
  7587. if (ret == 0) {
  7588. #ifdef WOLFSSL_SMALL_STACK
  7589. /* Keep real private key size to minimize amount allocated. */
  7590. privSz = sz;
  7591. #endif
  7592. /* Validate the size of the public key. */
  7593. sz = wolfSSL_BN_num_bytes(otherPub);
  7594. if (sz > pubSz) {
  7595. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7596. ret = -1;
  7597. }
  7598. }
  7599. if (ret == 0) {
  7600. #ifdef WOLFSSL_SMALL_STACK
  7601. /* Allocate memory for the public key array. */
  7602. pub = (unsigned char*)XMALLOC((size_t)sz, NULL,
  7603. DYNAMIC_TYPE_PUBLIC_KEY);
  7604. if (pub == NULL)
  7605. ret = -1;
  7606. }
  7607. if (ret == 0) {
  7608. /* Allocate memory for the private key array. */
  7609. priv = (unsigned char*)XMALLOC((size_t)privSz, NULL,
  7610. DYNAMIC_TYPE_PRIVATE_KEY);
  7611. if (priv == NULL) {
  7612. ret = -1;
  7613. }
  7614. }
  7615. if (ret == 0) {
  7616. #endif
  7617. /* Get the private key into the array. */
  7618. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7619. if (privSz <= 0) {
  7620. ret = -1;
  7621. }
  7622. }
  7623. if (ret == 0) {
  7624. /* Get the public key into the array. */
  7625. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7626. if (privSz <= 0) {
  7627. ret = -1;
  7628. }
  7629. }
  7630. /* Synchronize the external into the internal parameters. */
  7631. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7632. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7633. ret = -1;
  7634. }
  7635. PRIVATE_KEY_UNLOCK();
  7636. /* Calculate shared secret from private and public keys. */
  7637. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7638. (word32)privSz, pub, (word32)pubSz) < 0)) {
  7639. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7640. ret = -1;
  7641. }
  7642. if (ret == 0) {
  7643. /* Return actual length. */
  7644. ret = (int)keySz;
  7645. }
  7646. PRIVATE_KEY_LOCK();
  7647. #ifdef WOLFSSL_SMALL_STACK
  7648. if (priv != NULL)
  7649. #endif
  7650. {
  7651. /* Zeroize sensitive data. */
  7652. ForceZero(priv, (word32)privSz);
  7653. }
  7654. #ifdef WOLFSSL_SMALL_STACK
  7655. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7656. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7657. #endif
  7658. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7659. return ret;
  7660. }
  7661. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7662. * HAVE_FIPS_VERSION > 2 */
  7663. #endif /* OPENSSL_EXTRA */
  7664. #endif /* NO_DH */
  7665. /*******************************************************************************
  7666. * END OF DH API
  7667. ******************************************************************************/
  7668. /*******************************************************************************
  7669. * START OF EC API
  7670. ******************************************************************************/
  7671. #ifdef HAVE_ECC
  7672. #if defined(OPENSSL_EXTRA)
  7673. /* Start EC_curve */
  7674. /* Get the NIST name for the numeric ID.
  7675. *
  7676. * @param [in] nid Numeric ID of an EC curve.
  7677. * @return String representing NIST name of EC curve on success.
  7678. * @return NULL on error.
  7679. */
  7680. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7681. {
  7682. const char* name = NULL;
  7683. const WOLF_EC_NIST_NAME* nist_name;
  7684. /* Attempt to find the curve info matching the NID passed in. */
  7685. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7686. if (nist_name->nid == nid) {
  7687. /* NID found - return name. */
  7688. name = nist_name->name;
  7689. break;
  7690. }
  7691. }
  7692. return name;
  7693. }
  7694. /* Get the numeric ID for the NIST name.
  7695. *
  7696. * @param [in] name NIST name of EC curve.
  7697. * @return NID matching NIST name on success.
  7698. * @return 0 on error.
  7699. */
  7700. int wolfSSL_EC_curve_nist2nid(const char* name)
  7701. {
  7702. int nid = 0;
  7703. const WOLF_EC_NIST_NAME* nist_name;
  7704. /* Attempt to find the curve info matching the NIST name passed in. */
  7705. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7706. if (XSTRCMP(nist_name->name, name) == 0) {
  7707. /* Name found - return NID. */
  7708. nid = nist_name->nid;
  7709. break;
  7710. }
  7711. }
  7712. return nid;
  7713. }
  7714. #endif /* OPENSSL_EXTRA */
  7715. /* End EC_curve */
  7716. /* Start EC_METHOD */
  7717. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7718. /* Get the EC method of the EC group object.
  7719. *
  7720. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7721. * the NID.
  7722. *
  7723. * @param [in] group EC group object.
  7724. * @return EC method.
  7725. */
  7726. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7727. const WOLFSSL_EC_GROUP *group)
  7728. {
  7729. /* No method table used so just return the same object. */
  7730. return group;
  7731. }
  7732. /* Get field type for method.
  7733. *
  7734. * Only prime fields are supported.
  7735. *
  7736. * @param [in] meth EC method.
  7737. * @return X9.63 prime field NID on success.
  7738. * @return 0 on error.
  7739. */
  7740. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7741. {
  7742. int nid = 0;
  7743. if (meth != NULL) {
  7744. /* Only field type supported by code base. */
  7745. nid = NID_X9_62_prime_field;
  7746. }
  7747. return nid;
  7748. }
  7749. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7750. /* End EC_METHOD */
  7751. /* Start EC_GROUP */
  7752. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7753. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7754. * value.
  7755. *
  7756. * @param [in] n ECC curve id.
  7757. * @return ECC curve NID (OpenSSL compatible value).
  7758. */
  7759. int EccEnumToNID(int n)
  7760. {
  7761. WOLFSSL_ENTER("EccEnumToNID");
  7762. switch(n) {
  7763. case ECC_SECP192R1:
  7764. return NID_X9_62_prime192v1;
  7765. case ECC_PRIME192V2:
  7766. return NID_X9_62_prime192v2;
  7767. case ECC_PRIME192V3:
  7768. return NID_X9_62_prime192v3;
  7769. case ECC_PRIME239V1:
  7770. return NID_X9_62_prime239v1;
  7771. case ECC_PRIME239V2:
  7772. return NID_X9_62_prime239v2;
  7773. case ECC_PRIME239V3:
  7774. return NID_X9_62_prime239v3;
  7775. case ECC_SECP256R1:
  7776. return NID_X9_62_prime256v1;
  7777. case ECC_SECP112R1:
  7778. return NID_secp112r1;
  7779. case ECC_SECP112R2:
  7780. return NID_secp112r2;
  7781. case ECC_SECP128R1:
  7782. return NID_secp128r1;
  7783. case ECC_SECP128R2:
  7784. return NID_secp128r2;
  7785. case ECC_SECP160R1:
  7786. return NID_secp160r1;
  7787. case ECC_SECP160R2:
  7788. return NID_secp160r2;
  7789. case ECC_SECP224R1:
  7790. return NID_secp224r1;
  7791. case ECC_SECP384R1:
  7792. return NID_secp384r1;
  7793. case ECC_SECP521R1:
  7794. return NID_secp521r1;
  7795. case ECC_SECP160K1:
  7796. return NID_secp160k1;
  7797. case ECC_SECP192K1:
  7798. return NID_secp192k1;
  7799. case ECC_SECP224K1:
  7800. return NID_secp224k1;
  7801. case ECC_SECP256K1:
  7802. return NID_secp256k1;
  7803. case ECC_BRAINPOOLP160R1:
  7804. return NID_brainpoolP160r1;
  7805. case ECC_BRAINPOOLP192R1:
  7806. return NID_brainpoolP192r1;
  7807. case ECC_BRAINPOOLP224R1:
  7808. return NID_brainpoolP224r1;
  7809. case ECC_BRAINPOOLP256R1:
  7810. return NID_brainpoolP256r1;
  7811. case ECC_BRAINPOOLP320R1:
  7812. return NID_brainpoolP320r1;
  7813. case ECC_BRAINPOOLP384R1:
  7814. return NID_brainpoolP384r1;
  7815. case ECC_BRAINPOOLP512R1:
  7816. return NID_brainpoolP512r1;
  7817. #ifdef WOLFSSL_SM2
  7818. case ECC_SM2P256V1:
  7819. return NID_sm2;
  7820. #endif
  7821. default:
  7822. WOLFSSL_MSG("NID not found");
  7823. return -1;
  7824. }
  7825. }
  7826. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7827. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7828. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  7829. *
  7830. * Used by ecc_sets[].
  7831. *
  7832. * @param [in] n OpenSSL NID of EC curve.
  7833. * @return wolfCrypt EC curve id.
  7834. * @return -1 on error.
  7835. */
  7836. int NIDToEccEnum(int nid)
  7837. {
  7838. /* -1 on error. */
  7839. int id = -1;
  7840. WOLFSSL_ENTER("NIDToEccEnum");
  7841. switch (nid) {
  7842. case NID_X9_62_prime192v1:
  7843. id = ECC_SECP192R1;
  7844. break;
  7845. case NID_X9_62_prime192v2:
  7846. id = ECC_PRIME192V2;
  7847. break;
  7848. case NID_X9_62_prime192v3:
  7849. id = ECC_PRIME192V3;
  7850. break;
  7851. case NID_X9_62_prime239v1:
  7852. id = ECC_PRIME239V1;
  7853. break;
  7854. case NID_X9_62_prime239v2:
  7855. id = ECC_PRIME239V2;
  7856. break;
  7857. case NID_X9_62_prime239v3:
  7858. id = ECC_PRIME239V3;
  7859. break;
  7860. case NID_X9_62_prime256v1:
  7861. id = ECC_SECP256R1;
  7862. break;
  7863. case NID_secp112r1:
  7864. id = ECC_SECP112R1;
  7865. break;
  7866. case NID_secp112r2:
  7867. id = ECC_SECP112R2;
  7868. break;
  7869. case NID_secp128r1:
  7870. id = ECC_SECP128R1;
  7871. break;
  7872. case NID_secp128r2:
  7873. id = ECC_SECP128R2;
  7874. break;
  7875. case NID_secp160r1:
  7876. id = ECC_SECP160R1;
  7877. break;
  7878. case NID_secp160r2:
  7879. id = ECC_SECP160R2;
  7880. break;
  7881. case NID_secp224r1:
  7882. id = ECC_SECP224R1;
  7883. break;
  7884. case NID_secp384r1:
  7885. id = ECC_SECP384R1;
  7886. break;
  7887. case NID_secp521r1:
  7888. id = ECC_SECP521R1;
  7889. break;
  7890. case NID_secp160k1:
  7891. id = ECC_SECP160K1;
  7892. break;
  7893. case NID_secp192k1:
  7894. id = ECC_SECP192K1;
  7895. break;
  7896. case NID_secp224k1:
  7897. id = ECC_SECP224K1;
  7898. break;
  7899. case NID_secp256k1:
  7900. id = ECC_SECP256K1;
  7901. break;
  7902. case NID_brainpoolP160r1:
  7903. id = ECC_BRAINPOOLP160R1;
  7904. break;
  7905. case NID_brainpoolP192r1:
  7906. id = ECC_BRAINPOOLP192R1;
  7907. break;
  7908. case NID_brainpoolP224r1:
  7909. id = ECC_BRAINPOOLP224R1;
  7910. break;
  7911. case NID_brainpoolP256r1:
  7912. id = ECC_BRAINPOOLP256R1;
  7913. break;
  7914. case NID_brainpoolP320r1:
  7915. id = ECC_BRAINPOOLP320R1;
  7916. break;
  7917. case NID_brainpoolP384r1:
  7918. id = ECC_BRAINPOOLP384R1;
  7919. break;
  7920. case NID_brainpoolP512r1:
  7921. id = ECC_BRAINPOOLP512R1;
  7922. break;
  7923. default:
  7924. WOLFSSL_MSG("NID not found");
  7925. }
  7926. return id;
  7927. }
  7928. /* Set the fields of the EC group based on numeric ID.
  7929. *
  7930. * @param [in, out] group EC group.
  7931. * @param [in] nid Numeric ID of an EC curve.
  7932. */
  7933. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  7934. {
  7935. int eccEnum;
  7936. int realNid;
  7937. /* Convert ecc_curve_id enum to NID. */
  7938. if ((realNid = EccEnumToNID(nid)) != -1) {
  7939. /* ecc_curve_id enum passed in - have real NID value set. */
  7940. eccEnum = nid;
  7941. }
  7942. else {
  7943. /* NID passed in is OpenSSL type. */
  7944. realNid = nid;
  7945. /* Convert NID to ecc_curve_id enum. */
  7946. eccEnum = NIDToEccEnum(nid);
  7947. }
  7948. /* Set the numeric ID of the curve */
  7949. group->curve_nid = realNid;
  7950. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  7951. group->curve_idx = -1;
  7952. /* Find index and OID sum for curve if wolfCrypt supports it. */
  7953. if (eccEnum != -1) {
  7954. int i;
  7955. /* Find id and set the internal curve idx and OID sum. */
  7956. for (i = 0; ecc_sets[i].size != 0; i++) {
  7957. if (ecc_sets[i].id == eccEnum) {
  7958. /* Found id in wolfCrypt supported EC curves. */
  7959. group->curve_idx = i;
  7960. group->curve_oid = (int)ecc_sets[i].oidSum;
  7961. break;
  7962. }
  7963. }
  7964. }
  7965. }
  7966. /* Create a new EC group with the numeric ID for an EC curve.
  7967. *
  7968. * @param [in] nid Numeric ID of an EC curve.
  7969. * @return New, allocated EC group on success.
  7970. * @return NULL on error.
  7971. */
  7972. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  7973. {
  7974. int err = 0;
  7975. WOLFSSL_EC_GROUP* group;
  7976. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  7977. /* Allocate EC group. */
  7978. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  7979. DYNAMIC_TYPE_ECC);
  7980. if (group == NULL) {
  7981. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  7982. err = 1;
  7983. }
  7984. if (!err) {
  7985. /* Reset all fields. */
  7986. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  7987. /* Set the fields of group based on the numeric ID. */
  7988. ec_group_set_nid(group, nid);
  7989. }
  7990. return group;
  7991. }
  7992. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  7993. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7994. /* Dispose of the EC group.
  7995. *
  7996. * Cannot use group after this call.
  7997. *
  7998. * @param [in] group EC group to free.
  7999. */
  8000. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  8001. {
  8002. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  8003. /* Dispose of EC group. */
  8004. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  8005. }
  8006. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8007. #ifdef OPENSSL_EXTRA
  8008. #ifndef NO_BIO
  8009. /* Creates an EC group from the DER encoding.
  8010. *
  8011. * Only named curves supported.
  8012. *
  8013. * @param [out] group Reference to EC group object.
  8014. * @param [in] in Buffer holding DER encoding of curve.
  8015. * @param [in] inSz Length of data in buffer.
  8016. * @return EC group on success.
  8017. * @return NULL on error.
  8018. */
  8019. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  8020. const unsigned char* in, long inSz)
  8021. {
  8022. int err = 0;
  8023. WOLFSSL_EC_GROUP* ret = NULL;
  8024. word32 idx = 0;
  8025. word32 oid = 0;
  8026. int id = 0;
  8027. /* Use the group passed in. */
  8028. if ((group != NULL) && (*group != NULL)) {
  8029. ret = *group;
  8030. }
  8031. /* Only support named curves. */
  8032. if (in[0] != ASN_OBJECT_ID) {
  8033. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8034. err = 1;
  8035. }
  8036. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8037. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8038. 0)) {
  8039. err = 1;
  8040. }
  8041. if (!err) {
  8042. /* Get the internal ID for OID. */
  8043. id = wc_ecc_get_oid(oid, NULL, NULL);
  8044. if (id < 0) {
  8045. err = 1;
  8046. }
  8047. }
  8048. if (!err) {
  8049. /* Get the NID for the internal ID. */
  8050. int nid = EccEnumToNID(id);
  8051. if (ret == NULL) {
  8052. /* Create a new EC group with the numeric ID. */
  8053. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8054. if (ret == NULL) {
  8055. err = 1;
  8056. }
  8057. }
  8058. else {
  8059. ec_group_set_nid(ret, nid);
  8060. }
  8061. }
  8062. if ((!err) && (group != NULL)) {
  8063. /* Return the EC group through reference. */
  8064. *group = ret;
  8065. }
  8066. if (err) {
  8067. if ((ret != NULL) && (ret != *group)) {
  8068. wolfSSL_EC_GROUP_free(ret);
  8069. }
  8070. ret = NULL;
  8071. }
  8072. return ret;
  8073. }
  8074. /* Creates a new EC group from the PEM encoding in the BIO.
  8075. *
  8076. * @param [in] bio BIO to read PEM encoding from.
  8077. * @param [out] group Reference to EC group object.
  8078. * @param [in] cb Password callback when PEM encrypted.
  8079. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8080. * @return EC group on success.
  8081. * @return NULL on error.
  8082. */
  8083. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8084. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8085. {
  8086. int err = 0;
  8087. WOLFSSL_EC_GROUP* ret = NULL;
  8088. DerBuffer* der = NULL;
  8089. int keyFormat = 0;
  8090. if (bio == NULL) {
  8091. err = 1;
  8092. }
  8093. /* Read parameters from BIO and convert PEM to DER. */
  8094. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8095. &keyFormat, &der) < 0)) {
  8096. err = 1;
  8097. }
  8098. if (!err) {
  8099. /* Create EC group from DER encoding. */
  8100. ret = wolfssl_ec_group_d2i(group, der->buffer, der->length);
  8101. if (ret == NULL) {
  8102. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8103. }
  8104. }
  8105. /* Dispose of any allocated data. */
  8106. FreeDer(&der);
  8107. return ret;
  8108. }
  8109. #endif /* !NO_BIO */
  8110. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8111. /* Copy an EC group.
  8112. *
  8113. * Only used by wolfSSL_EC_KEY_dup at this time.
  8114. *
  8115. * @param [in, out] dst Destination EC group.
  8116. * @param [in] src Source EC group.
  8117. * @return 0 on success.
  8118. */
  8119. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8120. const WOLFSSL_EC_GROUP* src)
  8121. {
  8122. /* Copy the fields. */
  8123. dst->curve_idx = src->curve_idx;
  8124. dst->curve_nid = src->curve_nid;
  8125. dst->curve_oid = src->curve_oid;
  8126. return 0;
  8127. }
  8128. #endif /* OPENSSL_ALL && !NO_CERTS */
  8129. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8130. *
  8131. * @param [in] src EC group to duplicate.
  8132. *
  8133. * @return EC group on success.
  8134. * @return NULL on error.
  8135. */
  8136. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8137. {
  8138. WOLFSSL_EC_GROUP* newGroup = NULL;
  8139. if (src != NULL) {
  8140. /* Create new group base on NID in original EC group. */
  8141. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8142. }
  8143. return newGroup;
  8144. }
  8145. /* Compare two EC groups.
  8146. *
  8147. * Return code compliant with OpenSSL.
  8148. *
  8149. * @param [in] a First EC group.
  8150. * @param [in] b Second EC group.
  8151. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8152. *
  8153. * @return 0 if equal.
  8154. * @return 1 if not equal.
  8155. * @return -1 on error.
  8156. */
  8157. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8158. WOLFSSL_BN_CTX *ctx)
  8159. {
  8160. int ret;
  8161. /* No BN operations performed. */
  8162. (void)ctx;
  8163. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8164. /* Validate parameters. */
  8165. if ((a == NULL) || (b == NULL)) {
  8166. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8167. /* Return error value. */
  8168. ret = -1;
  8169. }
  8170. /* Compare NID and wolfSSL curve index. */
  8171. else {
  8172. /* 0 when same, 1 when not. */
  8173. ret = ((a->curve_nid == b->curve_nid) &&
  8174. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8175. }
  8176. return ret;
  8177. }
  8178. #ifndef NO_WOLFSSL_STUB
  8179. /* Set the ASN.1 flag that indicate encoding of curve.
  8180. *
  8181. * Stub function - flag not used elsewhere.
  8182. * Always encoded as named curve.
  8183. *
  8184. * @param [in] group EC group to modify.
  8185. * @param [in] flag ASN.1 flag to set. Valid values:
  8186. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8187. */
  8188. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8189. {
  8190. (void)group;
  8191. (void)flag;
  8192. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8193. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8194. }
  8195. #endif
  8196. /* Get the curve NID of the group.
  8197. *
  8198. * Return code compliant with OpenSSL.
  8199. *
  8200. * @param [in] group EC group.
  8201. * @return Curve NID on success.
  8202. * @return 0 on error.
  8203. */
  8204. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8205. {
  8206. int nid = 0;
  8207. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8208. if (group == NULL) {
  8209. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8210. }
  8211. else {
  8212. nid = group->curve_nid;
  8213. }
  8214. return nid;
  8215. }
  8216. /* Get the degree (curve size in bits) of the EC group.
  8217. *
  8218. * Return code compliant with OpenSSL.
  8219. *
  8220. * @return Degree of the curve on success.
  8221. * @return 0 on error.
  8222. */
  8223. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8224. {
  8225. int degree = 0;
  8226. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8227. if (group == NULL) {
  8228. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8229. }
  8230. else {
  8231. switch (group->curve_nid) {
  8232. case NID_secp112r1:
  8233. case NID_secp112r2:
  8234. degree = 112;
  8235. break;
  8236. case NID_secp128r1:
  8237. case NID_secp128r2:
  8238. degree = 128;
  8239. break;
  8240. case NID_secp160k1:
  8241. case NID_secp160r1:
  8242. case NID_secp160r2:
  8243. case NID_brainpoolP160r1:
  8244. degree = 160;
  8245. break;
  8246. case NID_secp192k1:
  8247. case NID_brainpoolP192r1:
  8248. case NID_X9_62_prime192v1:
  8249. case NID_X9_62_prime192v2:
  8250. case NID_X9_62_prime192v3:
  8251. degree = 192;
  8252. break;
  8253. case NID_secp224k1:
  8254. case NID_secp224r1:
  8255. case NID_brainpoolP224r1:
  8256. degree = 224;
  8257. break;
  8258. case NID_X9_62_prime239v1:
  8259. case NID_X9_62_prime239v2:
  8260. case NID_X9_62_prime239v3:
  8261. degree = 239;
  8262. break;
  8263. case NID_secp256k1:
  8264. case NID_brainpoolP256r1:
  8265. case NID_X9_62_prime256v1:
  8266. degree = 256;
  8267. break;
  8268. case NID_brainpoolP320r1:
  8269. degree = 320;
  8270. break;
  8271. case NID_secp384r1:
  8272. case NID_brainpoolP384r1:
  8273. degree = 384;
  8274. break;
  8275. case NID_brainpoolP512r1:
  8276. degree = 512;
  8277. break;
  8278. case NID_secp521r1:
  8279. degree = 521;
  8280. break;
  8281. }
  8282. }
  8283. return degree;
  8284. }
  8285. #endif /* OPENSSL_EXTRA */
  8286. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8287. /* Get the length of the order in bits of the EC group.
  8288. *
  8289. * TODO: consider switch statement or calculating directly from hex string
  8290. * array instead of using mp_int.
  8291. *
  8292. * @param [in] group EC group.
  8293. * @return Length of order in bits on success.
  8294. * @return 0 on error.
  8295. */
  8296. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8297. {
  8298. int ret = 0;
  8299. #ifdef WOLFSSL_SMALL_STACK
  8300. mp_int *order = NULL;
  8301. #else
  8302. mp_int order[1];
  8303. #endif
  8304. /* Validate parameter. */
  8305. if ((group == NULL) || (group->curve_idx < 0)) {
  8306. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8307. ret = -1;
  8308. }
  8309. #ifdef WOLFSSL_SMALL_STACK
  8310. if (ret == 0) {
  8311. /* Allocate memory for mp_int that will hold order value. */
  8312. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8313. DYNAMIC_TYPE_TMP_BUFFER);
  8314. if (order == NULL) {
  8315. ret = -1;
  8316. }
  8317. }
  8318. #endif
  8319. if (ret == 0) {
  8320. /* Initialize mp_int. */
  8321. ret = mp_init(order);
  8322. }
  8323. if (ret == 0) {
  8324. /* Read hex string of order from wolfCrypt array of curves. */
  8325. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8326. MP_RADIX_HEX);
  8327. if (ret == 0) {
  8328. /* Get bits of order. */
  8329. ret = mp_count_bits(order);
  8330. }
  8331. /* Clear and free mp_int. */
  8332. mp_clear(order);
  8333. }
  8334. #ifdef WOLFSSL_SMALL_STACK
  8335. /* Deallocate order. */
  8336. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8337. #endif
  8338. /* Convert error code to length of 0. */
  8339. if (ret < 0) {
  8340. ret = 0;
  8341. }
  8342. return ret;
  8343. }
  8344. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8345. #if defined(OPENSSL_EXTRA)
  8346. /* Get the order of the group as a BN.
  8347. *
  8348. * Return code compliant with OpenSSL.
  8349. *
  8350. * @param [in] group EC group.
  8351. * @param [in, out] order BN to hold order value.
  8352. * @param [in] ctx Context to use for BN operations. Unused.
  8353. * @return 1 on success.
  8354. * @return 0 on error.
  8355. */
  8356. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8357. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8358. {
  8359. int ret = 1;
  8360. mp_int* mp = NULL;
  8361. /* No BN operations performed - done with mp_int in BN. */
  8362. (void)ctx;
  8363. /* Validate parameters. */
  8364. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8365. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8366. ret = 0;
  8367. }
  8368. if (ret == 1) {
  8369. mp = (mp_int*)order->internal;
  8370. }
  8371. /* Initialize */
  8372. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8373. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8374. ret = 0;
  8375. }
  8376. /* Read hex string of order from wolfCrypt array of curves. */
  8377. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8378. MP_RADIX_HEX) != MP_OKAY)) {
  8379. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8380. /* Zero out any partial value but don't free. */
  8381. mp_zero(mp);
  8382. ret = 0;
  8383. }
  8384. return ret;
  8385. }
  8386. #endif /* OPENSSL_EXTRA */
  8387. /* End EC_GROUP */
  8388. /* Start EC_POINT */
  8389. #if defined(OPENSSL_EXTRA)
  8390. /* Set data of EC point into internal, wolfCrypt EC point object.
  8391. *
  8392. * EC_POINT Openssl -> WolfSSL
  8393. *
  8394. * @param [in, out] p EC point to update.
  8395. * @return 1 on success.
  8396. * @return -1 on failure.
  8397. */
  8398. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8399. {
  8400. int ret = 1;
  8401. WOLFSSL_ENTER("ec_point_internal_set");
  8402. /* Validate parameter. */
  8403. if ((p == NULL) || (p->internal == NULL)) {
  8404. WOLFSSL_MSG("ECPoint NULL error");
  8405. ret = -1;
  8406. }
  8407. else {
  8408. /* Get internal point as a wolfCrypt EC point. */
  8409. ecc_point* point = (ecc_point*)p->internal;
  8410. /* Set X ordinate if available. */
  8411. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8412. WOLFSSL_MSG("ecc point X error");
  8413. ret = -1;
  8414. }
  8415. /* Set Y ordinate if available. */
  8416. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8417. point->y) != 1)) {
  8418. WOLFSSL_MSG("ecc point Y error");
  8419. ret = -1;
  8420. }
  8421. /* Set Z ordinate if available. */
  8422. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8423. point->z) != 1)) {
  8424. WOLFSSL_MSG("ecc point Z error");
  8425. ret = -1;
  8426. }
  8427. /* Internal values set when operations succeeded. */
  8428. p->inSet = (ret == 1);
  8429. }
  8430. return ret;
  8431. }
  8432. /* Set data of internal, wolfCrypt EC point object into EC point.
  8433. *
  8434. * EC_POINT WolfSSL -> OpenSSL
  8435. *
  8436. * @param [in, out] p EC point to update.
  8437. * @return 1 on success.
  8438. * @return -1 on failure.
  8439. */
  8440. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8441. {
  8442. int ret = 1;
  8443. WOLFSSL_ENTER("ec_point_external_set");
  8444. /* Validate parameter. */
  8445. if ((p == NULL) || (p->internal == NULL)) {
  8446. WOLFSSL_MSG("ECPoint NULL error");
  8447. ret = -1;
  8448. }
  8449. else {
  8450. /* Get internal point as a wolfCrypt EC point. */
  8451. ecc_point* point = (ecc_point*)p->internal;
  8452. /* Set X ordinate. */
  8453. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8454. WOLFSSL_MSG("ecc point X error");
  8455. ret = -1;
  8456. }
  8457. /* Set Y ordinate. */
  8458. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8459. WOLFSSL_MSG("ecc point Y error");
  8460. ret = -1;
  8461. }
  8462. /* Set Z ordinate. */
  8463. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8464. WOLFSSL_MSG("ecc point Z error");
  8465. ret = -1;
  8466. }
  8467. /* External values set when operations succeeded. */
  8468. p->exSet = (ret == 1);
  8469. }
  8470. return ret;
  8471. }
  8472. /* Setup internals of EC point.
  8473. *
  8474. * Assumes point is not NULL.
  8475. *
  8476. * @param [in, out] point EC point to update.
  8477. * @return 1 on success.
  8478. * @return 0 on failure.
  8479. */
  8480. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8481. int ret = 1;
  8482. /* Check if internal values need setting. */
  8483. if (!point->inSet) {
  8484. WOLFSSL_MSG("No ECPoint internal set, do it");
  8485. /* Forcing to non-constant type to update internals. */
  8486. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8487. WOLFSSL_MSG("ec_point_internal_set failed");
  8488. ret = 0;
  8489. }
  8490. }
  8491. return ret;
  8492. }
  8493. /* Create a new EC point from the group.
  8494. *
  8495. * @param [in] group EC group.
  8496. * @return EC point on success.
  8497. * @return NULL on error.
  8498. */
  8499. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8500. {
  8501. int err = 0;
  8502. WOLFSSL_EC_POINT* point = NULL;
  8503. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8504. /* Validate parameter. */
  8505. if (group == NULL) {
  8506. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8507. err = 1;
  8508. }
  8509. if (!err) {
  8510. /* Allocate memory for new EC point. */
  8511. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8512. DYNAMIC_TYPE_ECC);
  8513. if (point == NULL) {
  8514. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8515. err = 1;
  8516. }
  8517. }
  8518. if (!err) {
  8519. /* Clear fields of EC point. */
  8520. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8521. /* Allocate internal EC point. */
  8522. point->internal = wc_ecc_new_point();
  8523. if (point->internal == NULL) {
  8524. WOLFSSL_MSG("ecc_new_point failure");
  8525. err = 1;
  8526. }
  8527. }
  8528. if (err) {
  8529. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8530. point = NULL;
  8531. }
  8532. return point;
  8533. }
  8534. #endif /* OPENSSL_EXTRA */
  8535. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8536. /* Dispose of the EC point.
  8537. *
  8538. * Cannot use point after this call.
  8539. *
  8540. * @param [in, out] point EC point to free.
  8541. */
  8542. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8543. {
  8544. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8545. if (point != NULL) {
  8546. if (point->internal != NULL) {
  8547. wc_ecc_del_point((ecc_point*)point->internal);
  8548. point->internal = NULL;
  8549. }
  8550. /* Free ordinates. */
  8551. wolfSSL_BN_free(point->X);
  8552. wolfSSL_BN_free(point->Y);
  8553. wolfSSL_BN_free(point->Z);
  8554. /* Clear fields. */
  8555. point->X = NULL;
  8556. point->Y = NULL;
  8557. point->Z = NULL;
  8558. point->inSet = 0;
  8559. point->exSet = 0;
  8560. /* Dispose of EC point. */
  8561. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8562. }
  8563. }
  8564. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8565. #ifdef OPENSSL_EXTRA
  8566. /* Clear and dispose of the EC point.
  8567. *
  8568. * Cannot use point after this call.
  8569. *
  8570. * @param [in, out] point EC point to free.
  8571. */
  8572. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8573. {
  8574. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8575. if (point != NULL) {
  8576. if (point->internal != NULL) {
  8577. /* Force internal point to be zeros. */
  8578. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8579. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8580. #else
  8581. ecc_point* p = (ecc_point*)point->internal;
  8582. mp_forcezero(p->x);
  8583. mp_forcezero(p->y);
  8584. mp_forcezero(p->z);
  8585. #endif
  8586. wc_ecc_del_point((ecc_point*)point->internal);
  8587. point->internal = NULL;
  8588. }
  8589. /* Clear the ordinates before freeing. */
  8590. wolfSSL_BN_clear_free(point->X);
  8591. wolfSSL_BN_clear_free(point->Y);
  8592. wolfSSL_BN_clear_free(point->Z);
  8593. /* Clear fields. */
  8594. point->X = NULL;
  8595. point->Y = NULL;
  8596. point->Z = NULL;
  8597. point->inSet = 0;
  8598. point->exSet = 0;
  8599. /* Dispose of EC point. */
  8600. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8601. }
  8602. }
  8603. /* Print out the internals of EC point in debug and when logging callback set.
  8604. *
  8605. * Not an OpenSSL API.
  8606. *
  8607. * TODO: Use WOLFSSL_MSG_EX()?
  8608. *
  8609. * @param [in] msg Message to prepend.
  8610. * @param [in] point EC point to print.
  8611. */
  8612. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8613. {
  8614. #if defined(DEBUG_WOLFSSL)
  8615. char *num;
  8616. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8617. /* Only print when debugging on. */
  8618. if (WOLFSSL_IS_DEBUG_ON()) {
  8619. if (point == NULL) {
  8620. /* No point passed in so just put out "NULL". */
  8621. WOLFSSL_MSG_EX("%s = NULL\n", msg);
  8622. }
  8623. else {
  8624. /* Put out message and status of internal/external data set. */
  8625. WOLFSSL_MSG_EX("%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8626. point->exSet);
  8627. /* Get x-ordinate as a hex string and print. */
  8628. num = wolfSSL_BN_bn2hex(point->X);
  8629. WOLFSSL_MSG_EX("\tX = %s\n", num);
  8630. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8631. /* Get x-ordinate as a hex string and print. */
  8632. num = wolfSSL_BN_bn2hex(point->Y);
  8633. WOLFSSL_MSG_EX("\tY = %s\n", num);
  8634. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8635. /* Get z-ordinate as a hex string and print. */
  8636. num = wolfSSL_BN_bn2hex(point->Z);
  8637. WOLFSSL_MSG_EX("\tZ = %s\n", num);
  8638. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8639. }
  8640. }
  8641. #else
  8642. (void)msg;
  8643. (void)point;
  8644. #endif
  8645. }
  8646. #ifndef HAVE_SELFTEST
  8647. /* Convert EC point to hex string that as either uncompressed or compressed.
  8648. *
  8649. * ECC point compression types were not included in selftest ecc.h
  8650. *
  8651. * @param [in] group EC group for point.
  8652. * @param [in] point EC point to encode.
  8653. * @param [in] form Format of encoding. Valid values:
  8654. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8655. * @param [in] ctx Context to use for BN operations. Unused.
  8656. * @return Allocated hex string on success.
  8657. * @return NULL on error.
  8658. */
  8659. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8660. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8661. {
  8662. static const char* hexDigit = "0123456789ABCDEF";
  8663. char* hex = NULL;
  8664. int i;
  8665. int sz = 0;
  8666. int len = 0;
  8667. int err = 0;
  8668. /* No BN operations performed. */
  8669. (void)ctx;
  8670. /* Validate parameters. */
  8671. if ((group == NULL) || (point == NULL)) {
  8672. err = 1;
  8673. }
  8674. /* Get curve id expects a positive index. */
  8675. if ((!err) && (group->curve_idx < 0)) {
  8676. err = 1;
  8677. }
  8678. if (!err) {
  8679. /* Get curve id to look up ordinate size. */
  8680. int id = wc_ecc_get_curve_id(group->curve_idx);
  8681. /* Get size of ordinate. */
  8682. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8683. err = 1;
  8684. }
  8685. }
  8686. if (!err) {
  8687. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8688. len = sz + 1;
  8689. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8690. /* Include y ordinate when uncompressed. */
  8691. len += sz;
  8692. }
  8693. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8694. */
  8695. hex = (char*)XMALLOC((size_t)(2 * len + 1), NULL, DYNAMIC_TYPE_ECC);
  8696. if (hex == NULL) {
  8697. err = 1;
  8698. }
  8699. }
  8700. if (!err) {
  8701. /* Make bytes all zeros to allow for ordinate values less than max size.
  8702. */
  8703. XMEMSET(hex, 0, (size_t)(2 * len + 1));
  8704. /* Calculate offset as leading zeros not encoded. */
  8705. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8706. /* Put in x-ordinate after format byte. */
  8707. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8708. 0) {
  8709. err = 1;
  8710. }
  8711. }
  8712. if (!err) {
  8713. if (form == POINT_CONVERSION_COMPRESSED) {
  8714. /* Compressed format byte value dependent on whether y-ordinate is
  8715. * odd.
  8716. */
  8717. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8718. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8719. /* No y-ordinate. */
  8720. }
  8721. else {
  8722. /* Put in uncompressed format byte. */
  8723. hex[0] = ECC_POINT_UNCOMP;
  8724. /* Calculate offset as leading zeros not encoded. */
  8725. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8726. /* Put in y-ordinate after x-ordinate. */
  8727. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8728. (byte*)(hex + i)) < 0) {
  8729. err = 1;
  8730. }
  8731. }
  8732. }
  8733. if (!err) {
  8734. /* Convert binary encoding to hex string. */
  8735. /* Start at end so as not to overwrite. */
  8736. for (i = len-1; i >= 0; i--) {
  8737. /* Get byte value and store has hex string. */
  8738. byte b = (byte)hex[i];
  8739. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8740. hex[i * 2 ] = hexDigit[b >> 4];
  8741. }
  8742. /* Memset put trailing zero or '\0' on end of string. */
  8743. }
  8744. if (err && (hex != NULL)) {
  8745. /* Dispose of allocated data not being returned. */
  8746. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8747. hex = NULL;
  8748. }
  8749. /* Return hex string encoding. */
  8750. return hex;
  8751. }
  8752. #endif /* HAVE_SELFTEST */
  8753. /* Encode the EC point as an uncompressed point in DER.
  8754. *
  8755. * Return code compliant with OpenSSL.
  8756. * Not OpenSSL API.
  8757. *
  8758. * @param [in] group EC group point belongs to.
  8759. * @param [in] point EC point to encode.
  8760. * @param [out] out Buffer to encode into. May be NULL.
  8761. * @param [in, out] len On in, length of buffer in bytes.
  8762. * On out, length of encoding in bytes.
  8763. * @return 1 on success.
  8764. * @return 0 on error.
  8765. */
  8766. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8767. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  8768. {
  8769. int res = 1;
  8770. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8771. /* Validate parameters. */
  8772. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  8773. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8774. res = 0;
  8775. }
  8776. /* Ensure points internals are set up. */
  8777. if ((res == 1) && (ec_point_setup(point) != 1)) {
  8778. res = 0;
  8779. }
  8780. /* Dump the point if encoding. */
  8781. if ((res == 1) && (out != NULL)) {
  8782. wolfSSL_EC_POINT_dump("i2d p", point);
  8783. }
  8784. if (res == 1) {
  8785. /* DER encode point in uncompressed format. */
  8786. int ret = wc_ecc_export_point_der(group->curve_idx,
  8787. (ecc_point*)point->internal, out, len);
  8788. /* Check return. When out is NULL, return will be length only error. */
  8789. if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) {
  8790. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8791. res = 0;
  8792. }
  8793. }
  8794. return res;
  8795. }
  8796. /* Decode the uncompressed point in DER into EC point.
  8797. *
  8798. * Return code compliant with OpenSSL.
  8799. * Not OpenSSL API.
  8800. *
  8801. * @param [in] in Buffer containing DER encoded point.
  8802. * @param [in] len Length of data in bytes.
  8803. * @param [in] group EC group associated with point.
  8804. * @param [in, out] point EC point to set data into.
  8805. * @return 1 on success.
  8806. * @return 0 on error.
  8807. */
  8808. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  8809. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  8810. {
  8811. int ret = 1;
  8812. WOLFSSL_BIGNUM* x = NULL;
  8813. WOLFSSL_BIGNUM* y = NULL;
  8814. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8815. /* Validate parameters. */
  8816. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  8817. (point->internal == NULL)) {
  8818. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8819. ret = 0;
  8820. }
  8821. if (ret == 1) {
  8822. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8823. /* Import point into internal EC point. */
  8824. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8825. (ecc_point*)point->internal, 0) != MP_OKAY) {
  8826. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8827. ret = 0;
  8828. }
  8829. #else
  8830. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8831. if (in[0] == 0x04) {
  8832. /* Import point into internal EC point. */
  8833. if (wc_ecc_import_point_der((unsigned char *)in, len,
  8834. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  8835. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8836. ret = 0;
  8837. }
  8838. }
  8839. else {
  8840. WOLFSSL_MSG("Only uncompressed points supported with "
  8841. "HAVE_SELFTEST");
  8842. ret = 0;
  8843. }
  8844. #endif
  8845. }
  8846. if (ret == 1)
  8847. point->inSet = 1;
  8848. /* Set new external point. */
  8849. if (ret == 1 && ec_point_external_set(point) != 1) {
  8850. WOLFSSL_MSG("ec_point_external_set failed");
  8851. ret = 0;
  8852. }
  8853. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  8854. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  8855. x = wolfSSL_BN_new();
  8856. y = wolfSSL_BN_new();
  8857. if (x == NULL || y == NULL)
  8858. ret = 0;
  8859. if (ret == 1 && wolfSSL_EC_POINT_get_affine_coordinates_GFp(group,
  8860. point, x, y, NULL) != 1) {
  8861. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp failed");
  8862. ret = 0;
  8863. }
  8864. /* wolfSSL_EC_POINT_set_affine_coordinates_GFp check that the point is
  8865. * on the curve. */
  8866. if (ret == 1 && wolfSSL_EC_POINT_set_affine_coordinates_GFp(group,
  8867. point, x, y, NULL) != 1) {
  8868. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp failed");
  8869. ret = 0;
  8870. }
  8871. #else
  8872. WOLFSSL_MSG("Importing non-affine point. This may cause issues in math "
  8873. "operations later on.");
  8874. #endif
  8875. }
  8876. if (ret == 1) {
  8877. /* Dump new point. */
  8878. wolfSSL_EC_POINT_dump("d2i p", point);
  8879. }
  8880. wolfSSL_BN_free(x);
  8881. wolfSSL_BN_free(y);
  8882. return ret;
  8883. }
  8884. /* Encode point as octet string.
  8885. *
  8886. * HYBRID not supported.
  8887. *
  8888. * @param [in] group EC group that point belongs to.
  8889. * @param [in] point EC point to encode.
  8890. * @param [in] form Format of encoding. Valid values:
  8891. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  8892. * @param [out] buf Buffer to write encoding into.
  8893. * @param [in] len Length of buffer.
  8894. * @param [in] ctx Context to use for BN operations. Unused.
  8895. * @return Length of encoded data on success.
  8896. * @return 0 on error.
  8897. */
  8898. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  8899. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  8900. WOLFSSL_BN_CTX *ctx)
  8901. {
  8902. int err = 0;
  8903. word32 enc_len = (word32)len;
  8904. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8905. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  8906. #endif /* !HAVE_SELFTEST */
  8907. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  8908. /* No BN operations performed. */
  8909. (void)ctx;
  8910. /* Validate parameters. */
  8911. if ((group == NULL) || (point == NULL)) {
  8912. err = 1;
  8913. }
  8914. /* Ensure points internals are set up. */
  8915. if ((!err) && (ec_point_setup(point) != 1)) {
  8916. err = 1;
  8917. }
  8918. /* Special case when point is infinity. */
  8919. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  8920. /* Encoding is a single octet: 0x00. */
  8921. enc_len = 1;
  8922. if (buf != NULL) {
  8923. /* Check whether buffer has space. */
  8924. if (len < 1) {
  8925. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  8926. err = 1;
  8927. }
  8928. else {
  8929. /* Put in encoding of infinity. */
  8930. buf[0] = 0x00;
  8931. }
  8932. }
  8933. }
  8934. /* Not infinity. */
  8935. else if (!err) {
  8936. /* Validate format. */
  8937. if (form != POINT_CONVERSION_UNCOMPRESSED
  8938. #ifndef HAVE_SELFTEST
  8939. && form != POINT_CONVERSION_COMPRESSED
  8940. #endif /* !HAVE_SELFTEST */
  8941. ) {
  8942. WOLFSSL_MSG("Unsupported point form");
  8943. err = 1;
  8944. }
  8945. if (!err) {
  8946. int ret;
  8947. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8948. /* Encode as compressed or uncompressed. */
  8949. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  8950. (ecc_point*)point->internal, buf, &enc_len, compressed);
  8951. #else
  8952. /* Encode uncompressed point in DER format. */
  8953. ret = wc_ecc_export_point_der(group->curve_idx,
  8954. (ecc_point*)point->internal, buf, &enc_len);
  8955. #endif /* !HAVE_SELFTEST */
  8956. /* Check return. When buf is NULL, return will be length only
  8957. * error.
  8958. */
  8959. if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) {
  8960. err = 1;
  8961. }
  8962. }
  8963. }
  8964. #if defined(DEBUG_WOLFSSL)
  8965. if (!err) {
  8966. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_point2oct point", point);
  8967. WOLFSSL_MSG("\twolfSSL_EC_POINT_point2oct output:");
  8968. WOLFSSL_BUFFER(buf, enc_len);
  8969. }
  8970. #endif
  8971. /* On error, return encoding length of 0. */
  8972. if (err) {
  8973. enc_len = 0;
  8974. }
  8975. return (size_t)enc_len;
  8976. }
  8977. /* Convert octet string to EC point.
  8978. *
  8979. * @param [in] group EC group.
  8980. * @param [in, out] point EC point to set data into.
  8981. * @param [in] buf Buffer holding octet string.
  8982. * @param [in] len Length of data in buffer in bytes.
  8983. * @param [in] ctx Context to use for BN operations. Unused.
  8984. */
  8985. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  8986. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  8987. WOLFSSL_BN_CTX *ctx)
  8988. {
  8989. int ret;
  8990. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  8991. /* No BN operations performed. */
  8992. (void)ctx;
  8993. /* Validate parameters. */
  8994. if ((group == NULL) || (point == NULL)) {
  8995. ret = 0;
  8996. }
  8997. else {
  8998. /* Decode DER encoding into EC point. */
  8999. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  9000. point);
  9001. }
  9002. return ret;
  9003. }
  9004. /* Convert an EC point to a single BN.
  9005. *
  9006. * @param [in] group EC group.
  9007. * @param [in] point EC point.
  9008. * @param [in] form Format of encoding. Valid values:
  9009. * POINT_CONVERSION_UNCOMPRESSED,
  9010. * POINT_CONVERSION_COMPRESSED.
  9011. * @param [in, out] bn BN to hold point value.
  9012. * When NULL a new BN is allocated otherwise this is
  9013. * returned on success.
  9014. * @param [in] ctx Context to use for BN operations. Unused.
  9015. * @return BN object with point as a value on success.
  9016. * @return NULL on error.
  9017. */
  9018. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  9019. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  9020. WOLFSSL_BN_CTX* ctx)
  9021. {
  9022. int err = 0;
  9023. size_t len = 0;
  9024. byte *buf = NULL;
  9025. WOLFSSL_BIGNUM *ret = NULL;
  9026. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  9027. /* Validate parameters. */
  9028. if ((group == NULL) || (point == NULL)) {
  9029. err = 1;
  9030. }
  9031. /* Calculate length of octet encoding. */
  9032. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  9033. 0, ctx)) == 0)) {
  9034. err = 1;
  9035. }
  9036. /* Allocate buffer to hold octet encoding. */
  9037. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  9038. NULL)) {
  9039. WOLFSSL_MSG("malloc failed");
  9040. err = 1;
  9041. }
  9042. /* Encode EC point as an octet string. */
  9043. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  9044. ctx) != len)) {
  9045. err = 1;
  9046. }
  9047. /* Load BN with octet string data. */
  9048. if (!err) {
  9049. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  9050. }
  9051. /* Dispose of any allocated data. */
  9052. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  9053. return ret;
  9054. }
  9055. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9056. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9057. /* Check if EC point is on the the curve defined by the EC group.
  9058. *
  9059. * @param [in] group EC group defining curve.
  9060. * @param [in] point EC point to check.
  9061. * @param [in] ctx Context to use for BN operations. Unused.
  9062. * @return 1 when point is on curve.
  9063. * @return 0 when point is not on curve or error.
  9064. */
  9065. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9066. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9067. {
  9068. int err = 0;
  9069. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9070. /* No BN operations performed. */
  9071. (void)ctx;
  9072. /* Validate parameters. */
  9073. if ((group == NULL) || (point == NULL)) {
  9074. WOLFSSL_MSG("Invalid arguments");
  9075. err = 1;
  9076. }
  9077. /* Ensure internal EC point set. */
  9078. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9079. (WOLFSSL_EC_POINT*)point) != 1) {
  9080. WOLFSSL_MSG("ec_point_internal_set error");
  9081. err = 1;
  9082. }
  9083. /* Check point is on curve from group. */
  9084. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9085. group->curve_idx) != MP_OKAY)) {
  9086. err = 1;
  9087. }
  9088. /* Return boolean of on curve. No error means on curve. */
  9089. return !err;
  9090. }
  9091. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9092. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9093. /* Convert Jacobian ordinates to affine.
  9094. *
  9095. * @param [in] group EC group.
  9096. * @param [in] point EC point to get coordinates from.
  9097. * @return 1 on success.
  9098. * @return 0 on error.
  9099. */
  9100. int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9101. WOLFSSL_EC_POINT *point)
  9102. {
  9103. int err = 0;
  9104. mp_digit mp = 0;
  9105. #ifdef WOLFSSL_SMALL_STACK
  9106. mp_int* modulus;
  9107. #else
  9108. mp_int modulus[1];
  9109. #endif
  9110. #ifdef WOLFSSL_SMALL_STACK
  9111. /* Allocate memory for curve's prime modulus. */
  9112. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9113. if (modulus == NULL) {
  9114. err = 1;
  9115. }
  9116. #endif
  9117. /* Initialize the MP integer. */
  9118. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9119. WOLFSSL_MSG("mp_init failed");
  9120. err = 1;
  9121. }
  9122. if (!err) {
  9123. /* Get the modulus from the hex string in the EC curve set. */
  9124. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9125. MP_RADIX_HEX) != MP_OKAY) {
  9126. WOLFSSL_MSG("mp_read_radix failed");
  9127. err = 1;
  9128. }
  9129. /* Get Montgomery multiplier for the modulus as ordinates in
  9130. * Montgomery form.
  9131. */
  9132. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9133. WOLFSSL_MSG("mp_montgomery_setup failed");
  9134. err = 1;
  9135. }
  9136. /* Map internal EC point from Jacobian to affine. */
  9137. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9138. MP_OKAY)) {
  9139. WOLFSSL_MSG("ecc_map failed");
  9140. err = 1;
  9141. }
  9142. /* Set new ordinates into external EC point. */
  9143. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9144. WOLFSSL_MSG("ec_point_external_set failed");
  9145. err = 1;
  9146. }
  9147. point->exSet = !err;
  9148. mp_clear(modulus);
  9149. }
  9150. #ifdef WOLFSSL_SMALL_STACK
  9151. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9152. #endif
  9153. return err;
  9154. }
  9155. /* Get the affine coordinates of the EC point on a Prime curve.
  9156. *
  9157. * When z-ordinate is not one then coordinates are Jacobian and need to be
  9158. * converted to affine before storing in BNs.
  9159. *
  9160. * Return code compliant with OpenSSL.
  9161. *
  9162. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9163. *
  9164. * @param [in] group EC group.
  9165. * @param [in] point EC point to get coordinates from.
  9166. * @param [in, out] x BN to hold x-ordinate.
  9167. * @param [in, out] y BN to hold y-ordinate.
  9168. * @param [in] ctx Context to use for BN operations. Unused.
  9169. * @return 1 on success.
  9170. * @return 0 on error.
  9171. */
  9172. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9173. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9174. WOLFSSL_BN_CTX* ctx)
  9175. {
  9176. int ret = 1;
  9177. /* BN operations don't need context. */
  9178. (void)ctx;
  9179. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9180. /* Validate parameters. */
  9181. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9182. (x == NULL) || (y == NULL)) {
  9183. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9184. ret = 0;
  9185. }
  9186. /* Don't return point at infinity. */
  9187. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9188. ret = 0;
  9189. }
  9190. /* Ensure internal EC point has values of external EC point. */
  9191. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9192. ret = 0;
  9193. }
  9194. /* Check whether ordinates are in Jacobian form. */
  9195. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9196. /* Convert from Jacobian to affine. */
  9197. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9198. ret = 0;
  9199. }
  9200. }
  9201. /* Copy the externally set x and y ordinates. */
  9202. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9203. ret = 0;
  9204. }
  9205. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9206. ret = 0;
  9207. }
  9208. return ret;
  9209. }
  9210. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9211. /* Sets the affine coordinates that belong on a prime curve.
  9212. *
  9213. * @param [in] group EC group.
  9214. * @param [in, out] point EC point to set coordinates into.
  9215. * @param [in] x BN holding x-ordinate.
  9216. * @param [in] y BN holding y-ordinate.
  9217. * @param [in] ctx Context to use for BN operations. Unused.
  9218. * @return 1 on success.
  9219. * @return 0 on error.
  9220. */
  9221. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9222. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9223. WOLFSSL_BN_CTX* ctx)
  9224. {
  9225. int ret = 1;
  9226. /* BN operations don't need context. */
  9227. (void)ctx;
  9228. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9229. /* Validate parameters. */
  9230. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9231. (x == NULL) || (y == NULL)) {
  9232. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9233. ret = 0;
  9234. }
  9235. /* Ensure we have a object for x-ordinate. */
  9236. if ((ret == 1) && (point->X == NULL) &&
  9237. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9238. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9239. ret = 0;
  9240. }
  9241. /* Ensure we have a object for y-ordinate. */
  9242. if ((ret == 1) && (point->Y == NULL) &&
  9243. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9244. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9245. ret = 0;
  9246. }
  9247. /* Ensure we have a object for z-ordinate. */
  9248. if ((ret == 1) && (point->Z == NULL) &&
  9249. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9250. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9251. ret = 0;
  9252. }
  9253. /* Copy the x-ordinate. */
  9254. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9255. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9256. ret = 0;
  9257. }
  9258. /* Copy the y-ordinate. */
  9259. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9260. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9261. ret = 0;
  9262. }
  9263. /* z-ordinate is one for affine coordinates. */
  9264. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9265. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9266. ret = 0;
  9267. }
  9268. /* Copy the new point data to internal object. */
  9269. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9270. WOLFSSL_MSG("ec_point_internal_set failed");
  9271. ret = 0;
  9272. }
  9273. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9274. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9275. /* Check that the point is valid. */
  9276. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9277. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9278. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9279. ret = 0;
  9280. }
  9281. #endif
  9282. return ret;
  9283. }
  9284. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9285. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9286. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9287. /* Add two points on the same together.
  9288. *
  9289. * @param [in] curveIdx Index of curve in ecc_set.
  9290. * @param [out] r Result point.
  9291. * @param [in] p1 First point to add.
  9292. * @param [in] p2 Second point to add.
  9293. * @return 1 on success.
  9294. * @return 0 on error.
  9295. */
  9296. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9297. ecc_point* p2)
  9298. {
  9299. int ret = 1;
  9300. #ifdef WOLFSSL_SMALL_STACK
  9301. mp_int* a = NULL;
  9302. mp_int* prime = NULL;
  9303. mp_int* mu = NULL;
  9304. #else
  9305. mp_int a[1];
  9306. mp_int prime[1];
  9307. mp_int mu[1];
  9308. #endif
  9309. mp_digit mp = 0;
  9310. ecc_point* montP1 = NULL;
  9311. ecc_point* montP2 = NULL;
  9312. #ifdef WOLFSSL_SMALL_STACK
  9313. if (ret == 1) {
  9314. /* Allocate memory for curve parameter: a. */
  9315. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9316. if (a == NULL) {
  9317. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9318. ret = 0;
  9319. }
  9320. }
  9321. if (ret == 1) {
  9322. /* Allocate memory for curve parameter: prime. */
  9323. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9324. if (prime == NULL) {
  9325. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9326. ret = 0;
  9327. }
  9328. }
  9329. if (ret == 1) {
  9330. /* Allocate memory for mu (Montgomery normalizer). */
  9331. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9332. if (mu == NULL) {
  9333. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9334. ret = 0;
  9335. }
  9336. }
  9337. if (ret == 1) {
  9338. /* Zero out all MP int data in case initialization fails. */
  9339. XMEMSET(a, 0, sizeof(mp_int));
  9340. XMEMSET(prime, 0, sizeof(mp_int));
  9341. XMEMSET(mu, 0, sizeof(mp_int));
  9342. }
  9343. #endif
  9344. /* Initialize the MP ints. */
  9345. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9346. MP_OKAY)) {
  9347. WOLFSSL_MSG("mp_init_multi error");
  9348. ret = 0;
  9349. }
  9350. /* Read the curve parameter: a. */
  9351. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9352. MP_OKAY)) {
  9353. WOLFSSL_MSG("mp_read_radix a error");
  9354. ret = 0;
  9355. }
  9356. /* Read the curve parameter: prime. */
  9357. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9358. MP_RADIX_HEX) != MP_OKAY)) {
  9359. WOLFSSL_MSG("mp_read_radix prime error");
  9360. ret = 0;
  9361. }
  9362. /* Calculate the Montgomery product. */
  9363. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9364. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9365. ret = 0;
  9366. }
  9367. /* TODO: use the heap filed of one of the points? */
  9368. /* Allocate new points to hold the Montgomery form values. */
  9369. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9370. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9371. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9372. ret = 0;
  9373. }
  9374. /* Calculate the Montgomery normalizer. */
  9375. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9376. MP_OKAY)) {
  9377. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9378. ret = 0;
  9379. }
  9380. /* Convert to Montgomery form. */
  9381. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9382. /* Copy the points if the normalizer is 1. */
  9383. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9384. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9385. WOLFSSL_MSG("wc_ecc_copy_point error");
  9386. ret = 0;
  9387. }
  9388. }
  9389. else if (ret == 1) {
  9390. /* Multiply each ordinate by the Montgomery normalizer. */
  9391. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9392. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9393. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9394. WOLFSSL_MSG("mp_mulmod error");
  9395. ret = 0;
  9396. }
  9397. /* Multiply each ordinate by the Montgomery normalizer. */
  9398. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9399. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9400. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9401. WOLFSSL_MSG("mp_mulmod error");
  9402. ret = 0;
  9403. }
  9404. }
  9405. /* Perform point addition with internal EC point objects - Jacobian form
  9406. * result.
  9407. */
  9408. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9409. mp) != MP_OKAY)) {
  9410. WOLFSSL_MSG("ecc_projective_add_point error");
  9411. ret = 0;
  9412. }
  9413. /* Map point back to affine coordinates. Converts from Montogomery form. */
  9414. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9415. WOLFSSL_MSG("ecc_map error");
  9416. ret = 0;
  9417. }
  9418. /* Dispose of allocated memory. */
  9419. mp_clear(a);
  9420. mp_clear(prime);
  9421. mp_clear(mu);
  9422. wc_ecc_del_point_h(montP1, NULL);
  9423. wc_ecc_del_point_h(montP2, NULL);
  9424. #ifdef WOLFSSL_SMALL_STACK
  9425. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9426. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9427. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9428. #endif
  9429. return ret;
  9430. }
  9431. /* Add two points on the same curve together.
  9432. *
  9433. * @param [in] group EC group.
  9434. * @param [out] r EC point that is result of point addition.
  9435. * @param [in] p1 First EC point to add.
  9436. * @param [in] p2 Second EC point to add.
  9437. * @param [in] ctx Context to use for BN operations. Unused.
  9438. * @return 1 on success.
  9439. * @return 0 on error.
  9440. */
  9441. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9442. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9443. {
  9444. int ret = 1;
  9445. /* No BN operations performed. */
  9446. (void)ctx;
  9447. /* Validate parameters. */
  9448. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9449. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9450. ret = 0;
  9451. }
  9452. /* Ensure the internal objects of the EC points are setup. */
  9453. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9454. (ec_point_setup(p2) != 1))) {
  9455. WOLFSSL_MSG("ec_point_setup error");
  9456. ret = 0;
  9457. }
  9458. #ifdef DEBUG_WOLFSSL
  9459. if (ret == 1) {
  9460. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9461. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9462. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9463. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p1", p1);
  9464. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add p2", p2);
  9465. if (curve != NULL)
  9466. WOLFSSL_MSG_EX("curve name: %s", curve);
  9467. if (nistName != NULL)
  9468. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9469. }
  9470. #endif
  9471. if (ret == 1) {
  9472. /* Add points using wolfCrypt objects. */
  9473. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9474. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9475. }
  9476. /* Copy internal EC point values out to external EC point. */
  9477. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9478. WOLFSSL_MSG("ec_point_external_set error");
  9479. ret = 0;
  9480. }
  9481. #ifdef DEBUG_WOLFSSL
  9482. if (ret == 1) {
  9483. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_add result", r);
  9484. }
  9485. #endif
  9486. return ret;
  9487. }
  9488. /* Sum the scalar multiplications of the base point and n, and q and m.
  9489. *
  9490. * r = base point * n + q * m
  9491. *
  9492. * @param [out] r EC point that is result of operation.
  9493. * @param [in] b Base point of curve.
  9494. * @param [in] n Scalar to multiply by base point.
  9495. * @param [in] q EC point to be scalar multiplied.
  9496. * @param [in] m Scalar to multiply q by.
  9497. * @param [in] a Parameter A of curve.
  9498. * @param [in] prime Prime (modulus) of curve.
  9499. * @return 1 on success.
  9500. * @return 0 on error.
  9501. */
  9502. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9503. mp_int* m, mp_int* a, mp_int* prime)
  9504. {
  9505. int ret = 1;
  9506. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9507. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9508. WOLFSSL_MSG("ecc_mul2add error");
  9509. ret = 0;
  9510. }
  9511. #else
  9512. ecc_point* tmp = NULL;
  9513. mp_digit mp = 0;
  9514. /* Calculate Montgomery product. */
  9515. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9516. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9517. ret = 0;
  9518. }
  9519. /* Create temporary point to hold: q * m */
  9520. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9521. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9522. ret = 0;
  9523. }
  9524. /* r = base point * n */
  9525. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9526. MP_OKAY)) {
  9527. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9528. ret = 0;
  9529. }
  9530. /* tmp = q * m */
  9531. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9532. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9533. ret = 0;
  9534. }
  9535. /* r = r + tmp */
  9536. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9537. MP_OKAY)) {
  9538. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9539. ret = 0;
  9540. }
  9541. /* Map point back to affine coordinates. Converts from Montogomery
  9542. * form. */
  9543. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9544. WOLFSSL_MSG("ecc_map nqm error");
  9545. ret = 0;
  9546. }
  9547. /* Dispose of allocated temporary point. */
  9548. wc_ecc_del_point(tmp);
  9549. #endif
  9550. return ret;
  9551. }
  9552. /* Sum the scalar multiplications of the base point and n, and q and m.
  9553. *
  9554. * r = base point * n + q * m
  9555. *
  9556. * @param [in] curveIdx Index of curve in ecc_set.
  9557. * @param [out] r EC point that is result of operation.
  9558. * @param [in] n Scalar to multiply by base point. May be NULL.
  9559. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9560. * @param [in] m Scalar to multiply q by. May be NULL.
  9561. * @return 1 on success.
  9562. * @return 0 on error.
  9563. */
  9564. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9565. ecc_point* q, mp_int* m)
  9566. {
  9567. int ret = 1;
  9568. #ifdef WOLFSSL_SMALL_STACK
  9569. mp_int* a = NULL;
  9570. mp_int* prime = NULL;
  9571. #else
  9572. mp_int a[1], prime[1];
  9573. #endif
  9574. #ifdef WOLFSSL_SMALL_STACK
  9575. /* Allocate MP integer for curve parameter: a. */
  9576. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9577. if (a == NULL) {
  9578. ret = 0;
  9579. }
  9580. if (ret == 1) {
  9581. /* Allocate MP integer for curve parameter: prime. */
  9582. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9583. if (prime == NULL) {
  9584. ret = 0;
  9585. }
  9586. }
  9587. #endif
  9588. /* Initialize the MP ints. */
  9589. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9590. MP_OKAY)) {
  9591. WOLFSSL_MSG("mp_init_multi error");
  9592. ret = 0;
  9593. }
  9594. /* Read the curve parameter: prime. */
  9595. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9596. MP_RADIX_HEX) != MP_OKAY)) {
  9597. WOLFSSL_MSG("mp_read_radix prime error");
  9598. ret = 0;
  9599. }
  9600. /* Read the curve parameter: a. */
  9601. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9602. MP_RADIX_HEX) != MP_OKAY)) {
  9603. WOLFSSL_MSG("mp_read_radix a error");
  9604. ret = 0;
  9605. }
  9606. if ((ret == 1) && (n != NULL)) {
  9607. /* Get generator - base point. */
  9608. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9609. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9610. WOLFSSL_MSG("wc_ecc_get_generator error");
  9611. ret = 0;
  9612. }
  9613. #else
  9614. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9615. /* Read generator (base point) x-ordinate. */
  9616. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9617. MP_RADIX_HEX) != MP_OKAY)) {
  9618. WOLFSSL_MSG("mp_read_radix Gx error");
  9619. ret = 0;
  9620. }
  9621. /* Read generator (base point) y-ordinate. */
  9622. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9623. MP_RADIX_HEX) != MP_OKAY)) {
  9624. WOLFSSL_MSG("mp_read_radix Gy error");
  9625. ret = 0;
  9626. }
  9627. /* z-ordinate is one as point is affine. */
  9628. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9629. WOLFSSL_MSG("mp_set Gz error");
  9630. ret = 0;
  9631. }
  9632. #endif /* NOPT_FIPS_VERSION == 2 */
  9633. }
  9634. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9635. /* r = base point * n + q * m */
  9636. ret = ec_mul2add(r, r, n, q, m, a, prime);
  9637. }
  9638. /* Not all values present, see if we are only doing base point * n. */
  9639. else if ((ret == 1) && (n != NULL)) {
  9640. /* r = base point * n */
  9641. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9642. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9643. ret = 0;
  9644. }
  9645. }
  9646. /* Not all values present, see if we are only doing q * m. */
  9647. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9648. /* r = q * m */
  9649. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9650. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9651. ret = 0;
  9652. }
  9653. }
  9654. /* No values to use. */
  9655. else if (ret == 1) {
  9656. /* Set result to infinity as no values passed in. */
  9657. mp_zero(r->x);
  9658. mp_zero(r->y);
  9659. mp_zero(r->z);
  9660. }
  9661. mp_clear(a);
  9662. mp_clear(prime);
  9663. #ifdef WOLFSSL_SMALL_STACK
  9664. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9665. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9666. #endif
  9667. return ret;
  9668. }
  9669. /* Sum the scalar multiplications of the base point and n, and q and m.
  9670. *
  9671. * r = base point * n + q * m
  9672. *
  9673. * Return code compliant with OpenSSL.
  9674. *
  9675. * @param [in] group EC group.
  9676. * @param [out] r EC point that is result of operation.
  9677. * @param [in] n Scalar to multiply by base point. May be NULL.
  9678. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9679. * @param [in] m Scalar to multiply q by. May be NULL.
  9680. * @param [in] ctx Context to use for BN operations. Unused.
  9681. * @return 1 on success.
  9682. * @return 0 on error.
  9683. */
  9684. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9685. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  9686. WOLFSSL_BN_CTX *ctx)
  9687. {
  9688. int ret = 1;
  9689. /* No BN operations performed. */
  9690. (void)ctx;
  9691. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9692. /* Validate parameters. */
  9693. if ((group == NULL) || (r == NULL)) {
  9694. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9695. ret = 0;
  9696. }
  9697. /* Ensure the internal representation of the EC point q is setup. */
  9698. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  9699. WOLFSSL_MSG("ec_point_setup error");
  9700. ret = 0;
  9701. }
  9702. #ifdef DEBUG_WOLFSSL
  9703. if (ret == 1) {
  9704. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9705. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9706. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9707. char* num;
  9708. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul input q", q);
  9709. num = wolfSSL_BN_bn2hex(n);
  9710. WOLFSSL_MSG_EX("\tn = %s", num);
  9711. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9712. num = wolfSSL_BN_bn2hex(m);
  9713. WOLFSSL_MSG_EX("\tm = %s", num);
  9714. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  9715. if (curve != NULL)
  9716. WOLFSSL_MSG_EX("curve name: %s", curve);
  9717. if (nistName != NULL)
  9718. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9719. }
  9720. #endif
  9721. if (ret == 1) {
  9722. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  9723. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  9724. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  9725. /* Perform multiplication with wolfCrypt objects. */
  9726. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  9727. ni, qi, mi);
  9728. }
  9729. /* Only on success is the internal point guaranteed to be set. */
  9730. if (r != NULL) {
  9731. r->inSet = (ret == 1);
  9732. }
  9733. /* Copy internal EC point values out to external EC point. */
  9734. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9735. WOLFSSL_MSG("ec_point_external_set error");
  9736. ret = 0;
  9737. }
  9738. #ifdef DEBUG_WOLFSSL
  9739. if (ret == 1) {
  9740. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_mul result", r);
  9741. }
  9742. #endif
  9743. return ret;
  9744. }
  9745. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9746. * !WOLFSSL_SP_MATH */
  9747. /* Invert the point on the curve.
  9748. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9749. *
  9750. * @param [in] curveIdx Index of curve in ecc_set.
  9751. * @param [in, out] point EC point to invert.
  9752. * @return 1 on success.
  9753. * @return 0 on error.
  9754. */
  9755. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  9756. {
  9757. int ret = 1;
  9758. #ifdef WOLFSSL_SMALL_STACK
  9759. mp_int* prime = NULL;
  9760. #else
  9761. mp_int prime[1];
  9762. #endif
  9763. #ifdef WOLFSSL_SMALL_STACK
  9764. /* Allocate memory for an MP int to hold the prime of the curve. */
  9765. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9766. if (prime == NULL) {
  9767. ret = 0;
  9768. }
  9769. #endif
  9770. /* Initialize MP int. */
  9771. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  9772. WOLFSSL_MSG("mp_init_multi error");
  9773. ret = 0;
  9774. }
  9775. /* Read the curve parameter: prime. */
  9776. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9777. MP_RADIX_HEX) != MP_OKAY)) {
  9778. WOLFSSL_MSG("mp_read_radix prime error");
  9779. ret = 0;
  9780. }
  9781. /* y = (prime - y) mod prime. */
  9782. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  9783. point->y) != MP_OKAY)) {
  9784. WOLFSSL_MSG("mp_sub error");
  9785. ret = 0;
  9786. }
  9787. /* Dispose of memory associated with MP. */
  9788. mp_free(prime);
  9789. #ifdef WOLFSSL_SMALL_STACK
  9790. /* Dispose of dynamically allocated temporaries. */
  9791. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9792. #endif
  9793. return ret;
  9794. }
  9795. /* Invert the point on the curve.
  9796. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9797. *
  9798. * @param [in] group EC group.
  9799. * @param [in, out] point EC point to invert.
  9800. * @param [in] ctx Context to use for BN operations. Unused.
  9801. * @return 1 on success.
  9802. * @return 0 on error.
  9803. */
  9804. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  9805. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9806. {
  9807. int ret = 1;
  9808. /* No BN operations performed. */
  9809. (void)ctx;
  9810. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9811. /* Validate parameters. */
  9812. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9813. ret = 0;
  9814. }
  9815. /* Ensure internal representation of point is setup. */
  9816. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9817. ret = 0;
  9818. }
  9819. #ifdef DEBUG_WOLFSSL
  9820. if (ret == 1) {
  9821. int nid = wolfSSL_EC_GROUP_get_curve_name(group);
  9822. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  9823. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  9824. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert input", point);
  9825. if (curve != NULL)
  9826. WOLFSSL_MSG_EX("curve name: %s", curve);
  9827. if (nistName != NULL)
  9828. WOLFSSL_MSG_EX("nist curve name: %s", nistName);
  9829. }
  9830. #endif
  9831. if (ret == 1 && !wolfSSL_BN_is_one(point->Z)) {
  9832. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9833. if (ec_point_convert_to_affine(group, point) != 0)
  9834. ret = 0;
  9835. #else
  9836. WOLFSSL_MSG("wolfSSL_EC_POINT_invert called on non-affine point");
  9837. ret = 0;
  9838. #endif
  9839. }
  9840. if (ret == 1) {
  9841. /* Perform inversion using wolfCrypt objects. */
  9842. ret = wolfssl_ec_point_invert(group->curve_idx,
  9843. (ecc_point*)point->internal);
  9844. }
  9845. /* Set the external EC point representation based on internal. */
  9846. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  9847. WOLFSSL_MSG("ec_point_external_set error");
  9848. ret = 0;
  9849. }
  9850. #ifdef DEBUG_WOLFSSL
  9851. if (ret == 1) {
  9852. wolfSSL_EC_POINT_dump("wolfSSL_EC_POINT_invert result", point);
  9853. }
  9854. #endif
  9855. return ret;
  9856. }
  9857. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  9858. /* Compare two points on a the same curve.
  9859. *
  9860. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  9861. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9862. * When equal:
  9863. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9864. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  9865. *
  9866. * @param [in] group EC group.
  9867. * @param [in] a EC point to compare.
  9868. * @param [in] b EC point to compare.
  9869. * @return 0 when equal.
  9870. * @return 1 when different.
  9871. * @return -1 on error.
  9872. */
  9873. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  9874. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  9875. {
  9876. int ret = 0;
  9877. BIGNUM* at = BN_new();
  9878. BIGNUM* bt = BN_new();
  9879. BIGNUM* az = BN_new();
  9880. BIGNUM* bz = BN_new();
  9881. BIGNUM* mod = BN_new();
  9882. /* Check that the big numbers were allocated. */
  9883. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  9884. (mod == NULL)) {
  9885. ret = -1;
  9886. }
  9887. /* Get the modulus for the curve. */
  9888. if ((ret == 0) &&
  9889. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  9890. ret = -1;
  9891. }
  9892. if (ret == 0) {
  9893. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  9894. if (BN_is_one(a->Z)) {
  9895. if (BN_copy(bt, b->X) == NULL) {
  9896. ret = -1;
  9897. }
  9898. }
  9899. /* az = Az ^ 2 */
  9900. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  9901. ret = -1;
  9902. }
  9903. /* bt = Bx * az = Bx * (Az ^ 2) */
  9904. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  9905. ret = -1;
  9906. }
  9907. }
  9908. if (ret == 0) {
  9909. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  9910. if (BN_is_one(b->Z)) {
  9911. if (BN_copy(at, a->X) == NULL) {
  9912. ret = -1;
  9913. }
  9914. }
  9915. /* bz = Bz ^ 2 */
  9916. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  9917. ret = -1;
  9918. }
  9919. /* at = Ax * bz = Ax * (Bz ^ 2) */
  9920. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  9921. ret = -1;
  9922. }
  9923. }
  9924. /* Compare x-ordinates. */
  9925. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9926. ret = 1;
  9927. }
  9928. if (ret == 0) {
  9929. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  9930. if (BN_is_one(a->Z)) {
  9931. if (BN_copy(bt, b->Y) == NULL) {
  9932. ret = -1;
  9933. }
  9934. }
  9935. /* az = az * Az = Az ^ 3 */
  9936. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  9937. ret = -1;
  9938. }
  9939. /* bt = By * az = By * (Az ^ 3) */
  9940. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  9941. ret = -1;
  9942. }
  9943. }
  9944. if (ret == 0) {
  9945. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  9946. if (BN_is_one(b->Z)) {
  9947. if (BN_copy(at, a->Y) == NULL) {
  9948. ret = -1;
  9949. }
  9950. }
  9951. /* bz = bz * Bz = Bz ^ 3 */
  9952. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  9953. ret = -1;
  9954. }
  9955. /* at = Ay * bz = Ay * (Bz ^ 3) */
  9956. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  9957. ret = -1;
  9958. }
  9959. }
  9960. /* Compare y-ordinates. */
  9961. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9962. ret = 1;
  9963. }
  9964. BN_free(mod);
  9965. BN_free(bz);
  9966. BN_free(az);
  9967. BN_free(bt);
  9968. BN_free(at);
  9969. return ret;
  9970. }
  9971. #endif
  9972. /* Compare two points on a the same curve.
  9973. *
  9974. * Return code compliant with OpenSSL.
  9975. *
  9976. * @param [in] group EC group.
  9977. * @param [in] a EC point to compare.
  9978. * @param [in] b EC point to compare.
  9979. * @param [in] ctx Context to use for BN operations. Unused.
  9980. * @return 0 when equal.
  9981. * @return 1 when different.
  9982. * @return -1 on error.
  9983. */
  9984. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  9985. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  9986. {
  9987. int ret = 0;
  9988. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  9989. /* Validate parameters. */
  9990. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  9991. (b == NULL) || (b->internal == NULL)) {
  9992. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  9993. ret = -1;
  9994. }
  9995. if (ret != -1) {
  9996. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  9997. /* If same Z ordinate then no need to convert to affine. */
  9998. if (BN_cmp(a->Z, b->Z) == 0) {
  9999. /* Compare */
  10000. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  10001. }
  10002. else {
  10003. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  10004. }
  10005. #else
  10006. /* No BN operations performed. */
  10007. (void)ctx;
  10008. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  10009. (ecc_point*)b->internal) != MP_EQ);
  10010. #endif
  10011. }
  10012. return ret;
  10013. }
  10014. /* Copy EC point.
  10015. *
  10016. * @param [out] dest EC point to copy into.
  10017. * @param [in] src EC point to copy.
  10018. * @return 1 on success.
  10019. * @return 0 on error.
  10020. */
  10021. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  10022. {
  10023. int ret = 1;
  10024. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  10025. /* Validate parameters. */
  10026. if ((dest == NULL) || (src == NULL)) {
  10027. ret = 0;
  10028. }
  10029. /* Ensure internal EC point of src is setup. */
  10030. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  10031. ret = 0;
  10032. }
  10033. /* Copy internal EC points. */
  10034. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  10035. (ecc_point*)dest->internal) != MP_OKAY)) {
  10036. ret = 0;
  10037. }
  10038. if (ret == 1) {
  10039. /* Destinatation internal point is set. */
  10040. dest->inSet = 1;
  10041. /* Set the external EC point of dest based on internal. */
  10042. if (ec_point_external_set(dest) != 1) {
  10043. ret = 0;
  10044. }
  10045. }
  10046. return ret;
  10047. }
  10048. /* Checks whether point is at infinity.
  10049. *
  10050. * Return code compliant with OpenSSL.
  10051. *
  10052. * @param [in] group EC group.
  10053. * @param [in] point EC point to check.
  10054. * @return 1 when at infinity.
  10055. * @return 0 when not at infinity.
  10056. */
  10057. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  10058. const WOLFSSL_EC_POINT *point)
  10059. {
  10060. int ret = 1;
  10061. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  10062. /* Validate parameters. */
  10063. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  10064. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  10065. ret = 0;
  10066. }
  10067. /* Ensure internal EC point is setup. */
  10068. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  10069. ret = 0;
  10070. }
  10071. if (ret == 1) {
  10072. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  10073. /* Check for infinity. */
  10074. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  10075. if (ret < 0) {
  10076. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  10077. /* Error return is 0 by OpenSSL. */
  10078. ret = 0;
  10079. }
  10080. #else
  10081. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  10082. ret = 0;
  10083. #endif
  10084. }
  10085. return ret;
  10086. }
  10087. #endif /* OPENSSL_EXTRA */
  10088. /* End EC_POINT */
  10089. /* Start EC_KEY */
  10090. #ifdef OPENSSL_EXTRA
  10091. /*
  10092. * EC key constructor/deconstructor APIs
  10093. */
  10094. /* Allocate a new EC key.
  10095. *
  10096. * Not OpenSSL API.
  10097. *
  10098. * @param [in] heap Heap hint for dynamic memory allocation.
  10099. * @param [in] devId Device identifier value.
  10100. * @return New, allocated EC key on success.
  10101. * @return NULL on error.
  10102. */
  10103. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  10104. {
  10105. WOLFSSL_EC_KEY *key = NULL;
  10106. int err = 0;
  10107. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  10108. /* Allocate memory for EC key. */
  10109. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  10110. DYNAMIC_TYPE_ECC);
  10111. if (key == NULL) {
  10112. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  10113. err = 1;
  10114. }
  10115. if (!err) {
  10116. /* Reset all fields to 0. */
  10117. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  10118. /* Cache heap hint. */
  10119. key->heap = heap;
  10120. /* Initialize fields to defaults. */
  10121. key->form = POINT_CONVERSION_UNCOMPRESSED;
  10122. /* Initialize reference count. */
  10123. wolfSSL_RefInit(&key->ref, &err);
  10124. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  10125. }
  10126. if (!err) {
  10127. #endif
  10128. /* Allocate memory for internal EC key representation. */
  10129. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  10130. DYNAMIC_TYPE_ECC);
  10131. if (key->internal == NULL) {
  10132. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10133. err = 1;
  10134. }
  10135. }
  10136. if (!err) {
  10137. /* Initialize wolfCrypt EC key. */
  10138. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10139. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10140. err = 1;
  10141. }
  10142. }
  10143. if (!err) {
  10144. /* Group unknown at creation */
  10145. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10146. if (key->group == NULL) {
  10147. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10148. err = 1;
  10149. }
  10150. }
  10151. if (!err) {
  10152. /* Allocate a point as public key. */
  10153. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10154. if (key->pub_key == NULL) {
  10155. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10156. err = 1;
  10157. }
  10158. }
  10159. if (!err) {
  10160. /* Allocate a BN as private key. */
  10161. key->priv_key = wolfSSL_BN_new();
  10162. if (key->priv_key == NULL) {
  10163. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10164. err = 1;
  10165. }
  10166. }
  10167. if (err) {
  10168. /* Dispose of EC key on error. */
  10169. wolfSSL_EC_KEY_free(key);
  10170. key = NULL;
  10171. }
  10172. /* Return new EC key object. */
  10173. return key;
  10174. }
  10175. /* Allocate a new EC key.
  10176. *
  10177. * @return New, allocated EC key on success.
  10178. * @return NULL on error.
  10179. */
  10180. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10181. {
  10182. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10183. }
  10184. /* Create new EC key with the group having the specified numeric ID.
  10185. *
  10186. * @param [in] nid Numeric ID.
  10187. * @return New, allocated EC key on success.
  10188. * @return NULL on error.
  10189. */
  10190. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10191. {
  10192. WOLFSSL_EC_KEY *key;
  10193. int err = 0;
  10194. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10195. /* Allocate empty, EC key. */
  10196. key = wolfSSL_EC_KEY_new();
  10197. if (key == NULL) {
  10198. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10199. err = 1;
  10200. }
  10201. if (!err) {
  10202. /* Set group to be nid. */
  10203. ec_group_set_nid(key->group, nid);
  10204. if (key->group->curve_idx == -1) {
  10205. wolfSSL_EC_KEY_free(key);
  10206. key = NULL;
  10207. }
  10208. }
  10209. /* Return the new EC key object. */
  10210. return key;
  10211. }
  10212. /* Dispose of the EC key and allocated data.
  10213. *
  10214. * Cannot use key after this call.
  10215. *
  10216. * @param [in] key EC key to free.
  10217. */
  10218. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10219. {
  10220. int doFree = 0;
  10221. int err;
  10222. (void)err;
  10223. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10224. if (key != NULL) {
  10225. void* heap = key->heap;
  10226. /* Decrement reference count. */
  10227. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10228. if (doFree) {
  10229. /* Dispose of allocated reference counting data. */
  10230. wolfSSL_RefFree(&key->ref);
  10231. /* Dispose of private key. */
  10232. wolfSSL_BN_free(key->priv_key);
  10233. wolfSSL_EC_POINT_free(key->pub_key);
  10234. wolfSSL_EC_GROUP_free(key->group);
  10235. if (key->internal != NULL) {
  10236. /* Dispose of wolfCrypt representation of EC key. */
  10237. wc_ecc_free((ecc_key*)key->internal);
  10238. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10239. }
  10240. /* Set back to NULLs for safety. */
  10241. ForceZero(key, sizeof(*key));
  10242. /* Dispose of the memory associated with the EC key. */
  10243. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10244. (void)heap;
  10245. }
  10246. }
  10247. }
  10248. /* Increments ref count of EC key.
  10249. *
  10250. * @param [in, out] key EC key.
  10251. * @return 1 on success
  10252. * @return 0 on error
  10253. */
  10254. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10255. {
  10256. int err = 1;
  10257. if (key != NULL) {
  10258. wolfSSL_RefInc(&key->ref, &err);
  10259. }
  10260. return !err;
  10261. }
  10262. #ifndef NO_CERTS
  10263. #if defined(OPENSSL_ALL)
  10264. /* Copy the internal, wolfCrypt EC key.
  10265. *
  10266. * @param [in, out] dst Destination wolfCrypt EC key.
  10267. * @param [in] src Source wolfCrypt EC key.
  10268. * @return 0 on success.
  10269. * @return Negative on error.
  10270. */
  10271. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10272. {
  10273. int ret;
  10274. /* Copy public key. */
  10275. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10276. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10277. #else
  10278. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10279. #endif
  10280. if (ret != MP_OKAY) {
  10281. WOLFSSL_MSG("wc_ecc_copy_point error");
  10282. }
  10283. if (ret == 0) {
  10284. /* Copy private key. */
  10285. ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst));
  10286. if (ret != MP_OKAY) {
  10287. WOLFSSL_MSG("mp_copy error");
  10288. }
  10289. }
  10290. if (ret == 0) {
  10291. /* Copy domain parameters. */
  10292. if (src->dp) {
  10293. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10294. if (ret != 0) {
  10295. WOLFSSL_MSG("wc_ecc_set_curve error");
  10296. }
  10297. }
  10298. }
  10299. if (ret == 0) {
  10300. /* Copy the other components. */
  10301. dst->type = src->type;
  10302. dst->idx = src->idx;
  10303. dst->state = src->state;
  10304. dst->flags = src->flags;
  10305. }
  10306. return ret;
  10307. }
  10308. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10309. *
  10310. * Copies the internal representation as well.
  10311. *
  10312. * @param [in] src EC key to duplicate.
  10313. *
  10314. * @return EC key on success.
  10315. * @return NULL on error.
  10316. */
  10317. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10318. {
  10319. int err = 0;
  10320. WOLFSSL_EC_KEY* newKey = NULL;
  10321. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10322. /* Validate EC key. */
  10323. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10324. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10325. WOLFSSL_MSG("src NULL error");
  10326. err = 1;
  10327. }
  10328. if (!err) {
  10329. /* Create a new, empty key. */
  10330. newKey = wolfSSL_EC_KEY_new();
  10331. if (newKey == NULL) {
  10332. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10333. err = 1;
  10334. }
  10335. }
  10336. if (!err) {
  10337. /* Copy internal EC key. */
  10338. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10339. (ecc_key*)src->internal) != 0) {
  10340. WOLFSSL_MSG("Copying internal EC key error");
  10341. err = 1;
  10342. }
  10343. }
  10344. if (!err) {
  10345. /* Internal key set. */
  10346. newKey->inSet = 1;
  10347. /* Copy group */
  10348. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10349. }
  10350. /* Copy public key. */
  10351. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10352. WOLFSSL_MSG("Copying EC public key error");
  10353. err = 1;
  10354. }
  10355. if (!err) {
  10356. /* Set header size of private key in PKCS#8 format.*/
  10357. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10358. /* Copy private key. */
  10359. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10360. WOLFSSL_MSG("Copying EC private key error");
  10361. err = 1;
  10362. }
  10363. }
  10364. if (err) {
  10365. /* Dispose of EC key on error. */
  10366. wolfSSL_EC_KEY_free(newKey);
  10367. newKey = NULL;
  10368. }
  10369. /* Return the new EC key. */
  10370. return newKey;
  10371. }
  10372. #endif /* OPENSSL_ALL */
  10373. #endif /* !NO_CERTS */
  10374. /*
  10375. * EC key to/from bin/octet APIs
  10376. */
  10377. /* Create an EC key from the octet encoded public key.
  10378. *
  10379. * Behaviour checked against OpenSSL.
  10380. *
  10381. * @param [out] key Reference to EC key. Must pass in a valid object with
  10382. * group set.
  10383. * @param [in, out] in On in, reference to buffer that contains data.
  10384. * On out, reference to buffer after public key data.
  10385. * @param [in] len Length of data in the buffer. Must be length of the
  10386. * encoded public key.
  10387. * @return Allocated EC key on success.
  10388. * @return NULL on error.
  10389. */
  10390. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10391. const unsigned char **in, long len)
  10392. {
  10393. int err = 0;
  10394. WOLFSSL_EC_KEY* ret = NULL;
  10395. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10396. /* Validate parameters: EC group needed to perform import. */
  10397. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10398. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10399. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10400. err = 1;
  10401. }
  10402. if (!err) {
  10403. /* Return the EC key object passed in. */
  10404. ret = *key;
  10405. /* Import point into public key field. */
  10406. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in,
  10407. (size_t)len, NULL) != 1) {
  10408. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10409. ret = NULL;
  10410. err = 1;
  10411. }
  10412. }
  10413. if (!err) {
  10414. /* Assumed length passed in is all the data. */
  10415. *in += len;
  10416. }
  10417. return ret;
  10418. }
  10419. /* Puts the encoded public key into out.
  10420. *
  10421. * Passing in NULL for out returns length only.
  10422. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10423. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10424. *
  10425. * @param [in] key EC key to encode.
  10426. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10427. * point to NULL.
  10428. * @return Length of encoding in bytes on success.
  10429. * @return 0 on error.
  10430. */
  10431. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10432. {
  10433. int ret = 1;
  10434. size_t len = 0;
  10435. int form = POINT_CONVERSION_UNCOMPRESSED;
  10436. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10437. /* Validate parameters. */
  10438. if (key == NULL) {
  10439. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10440. ret = 0;
  10441. }
  10442. /* Ensure the external key data is set from the internal EC key. */
  10443. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10444. key) != 1)) {
  10445. WOLFSSL_MSG("SetECKeyExternal failure");
  10446. ret = 0;
  10447. }
  10448. if (ret == 1) {
  10449. #ifdef HAVE_COMP_KEY
  10450. /* Default to compressed form if not set */
  10451. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10452. POINT_CONVERSION_UNCOMPRESSED :
  10453. POINT_CONVERSION_COMPRESSED;
  10454. #endif
  10455. /* Calculate length of point encoding. */
  10456. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10457. 0, NULL);
  10458. }
  10459. /* Encode if length calculated and pointer supplied to update. */
  10460. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10461. unsigned char *tmp = NULL;
  10462. /* Allocate buffer for encoding if no buffer supplied. */
  10463. if (*out == NULL) {
  10464. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10465. if (tmp == NULL) {
  10466. WOLFSSL_MSG("malloc failed");
  10467. ret = 0;
  10468. }
  10469. }
  10470. else {
  10471. /* Get buffer to encode into. */
  10472. tmp = *out;
  10473. }
  10474. /* Encode public key into buffer. */
  10475. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10476. form, tmp, len, NULL) == 0)) {
  10477. ret = 0;
  10478. }
  10479. if (ret == 1) {
  10480. /* Return buffer if allocated. */
  10481. if (*out == NULL) {
  10482. *out = tmp;
  10483. }
  10484. else {
  10485. /* Step over encoded data if not allocated. */
  10486. *out += len;
  10487. }
  10488. }
  10489. else if (*out == NULL) {
  10490. /* Dispose of allocated buffer. */
  10491. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10492. }
  10493. }
  10494. if (ret == 1) {
  10495. /* Return length on success. */
  10496. ret = (int)len;
  10497. }
  10498. return ret;
  10499. }
  10500. #ifdef HAVE_ECC_KEY_IMPORT
  10501. /* Create a EC key from the DER encoded private key.
  10502. *
  10503. * @param [out] key Reference to EC key.
  10504. * @param [in, out] in On in, reference to buffer that contains DER data.
  10505. * On out, reference to buffer after private key data.
  10506. * @param [in] long Length of data in the buffer. May be larger than the
  10507. * length of the encoded private key.
  10508. * @return Allocated EC key on success.
  10509. * @return NULL on error.
  10510. */
  10511. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10512. const unsigned char** in, long len)
  10513. {
  10514. int err = 0;
  10515. word32 idx = 0;
  10516. WOLFSSL_EC_KEY* ret = NULL;
  10517. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10518. /* Validate parameters. */
  10519. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10520. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10521. err = 1;
  10522. }
  10523. /* Create a new, empty EC key. */
  10524. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10525. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10526. err = 1;
  10527. }
  10528. /* Decode the private key DER data into internal EC key. */
  10529. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10530. (word32)len) != 0)) {
  10531. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10532. err = 1;
  10533. }
  10534. if (!err) {
  10535. /* Internal EC key setup. */
  10536. ret->inSet = 1;
  10537. /* Set the EC key from the internal values. */
  10538. if (SetECKeyExternal(ret) != 1) {
  10539. WOLFSSL_MSG("SetECKeyExternal error");
  10540. err = 1;
  10541. }
  10542. }
  10543. if (!err) {
  10544. /* Move buffer on to next byte after data used. */
  10545. *in += idx;
  10546. if (key) {
  10547. /* Return new EC key through reference. */
  10548. *key = ret;
  10549. }
  10550. }
  10551. if (err && (ret != NULL)) {
  10552. /* Dispose of allocated EC key. */
  10553. wolfSSL_EC_KEY_free(ret);
  10554. ret = NULL;
  10555. }
  10556. return ret;
  10557. }
  10558. #endif /* HAVE_ECC_KEY_IMPORT */
  10559. /* Enecode the private key of the EC key into the buffer as DER.
  10560. *
  10561. * @param [in] key EC key to encode.
  10562. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10563. * On out, reference to buffer adter the encoding.
  10564. * May be NULL.
  10565. * @return Length of DER encoding on success.
  10566. * @return 0 on error.
  10567. */
  10568. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10569. {
  10570. int err = 0;
  10571. word32 len = 0;
  10572. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10573. /* Validate parameters. */
  10574. if (key == NULL) {
  10575. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10576. err = 1;
  10577. }
  10578. /* Update the internal EC key if not set. */
  10579. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10580. 1)) {
  10581. WOLFSSL_MSG("SetECKeyInternal error");
  10582. err = 1;
  10583. }
  10584. /* Calculate the length of the private key DER encoding using internal EC
  10585. * key. */
  10586. if ((!err) && ((int)(len = (word32)wc_EccKeyDerSize((ecc_key*)key->internal,
  10587. 0)) <= 0)) {
  10588. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10589. err = 1;
  10590. }
  10591. /* Only return length when out is NULL. */
  10592. if ((!err) && (out != NULL)) {
  10593. unsigned char* buf = NULL;
  10594. /* Must have a buffer to encode into. */
  10595. if (*out == NULL) {
  10596. /* Allocate a new buffer of appropriate length. */
  10597. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10598. if (buf == NULL) {
  10599. /* Error and return 0. */
  10600. err = 1;
  10601. len = 0;
  10602. }
  10603. else {
  10604. /* Return the allocated buffer. */
  10605. *out = buf;
  10606. }
  10607. }
  10608. /* Encode the internal EC key as a private key in DER format. */
  10609. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10610. len) < 0) {
  10611. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10612. err = 1;
  10613. }
  10614. else if (buf != *out) {
  10615. /* Move the reference to byte past encoded private key. */
  10616. *out += len;
  10617. }
  10618. /* Dispose of any allocated buffer on error. */
  10619. if (err && (*out == buf)) {
  10620. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10621. *out = NULL;
  10622. }
  10623. }
  10624. return (int)len;
  10625. }
  10626. /* Load private key into EC key from DER encoding.
  10627. *
  10628. * Not an OpenSSL compatibility API.
  10629. *
  10630. * @param [in, out] key EC key to put private key values into.
  10631. * @param [in] derBuf Buffer holding DER encoding.
  10632. * @param [in] derSz Size of DER encoding in bytes.
  10633. * @return 1 on success.
  10634. * @return -1 on error.
  10635. */
  10636. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10637. int derSz)
  10638. {
  10639. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10640. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10641. }
  10642. /* Load private/public key into EC key from DER encoding.
  10643. *
  10644. * Not an OpenSSL compatibility API.
  10645. *
  10646. * @param [in, out] key EC key to put private/public key values into.
  10647. * @param [in] derBuf Buffer holding DER encoding.
  10648. * @param [in] derSz Size of DER encoding in bytes.
  10649. * @param [in] opt Key type option. Valid values:
  10650. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10651. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10652. * @return 1 on success.
  10653. * @return -1 on error.
  10654. */
  10655. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10656. int derSz, int opt)
  10657. {
  10658. int res = 1;
  10659. int ret;
  10660. word32 idx = 0;
  10661. word32 algId;
  10662. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10663. /* Validate parameters. */
  10664. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10665. (derSz <= 0)) {
  10666. WOLFSSL_MSG("Bad function arguments");
  10667. res = -1;
  10668. }
  10669. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10670. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10671. res = -1;
  10672. }
  10673. if (res == 1) {
  10674. /* Assume no PKCS#8 header. */
  10675. key->pkcs8HeaderSz = 0;
  10676. /* Check if input buffer has PKCS8 header. In the case that it does not
  10677. * have a PKCS8 header then do not error out.
  10678. */
  10679. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10680. (word32)derSz, &algId)) > 0) {
  10681. WOLFSSL_MSG("Found PKCS8 header");
  10682. key->pkcs8HeaderSz = (word16)idx;
  10683. res = 1;
  10684. }
  10685. /* Error out on parsing error. */
  10686. else if (ret != ASN_PARSE_E) {
  10687. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10688. res = -1;
  10689. }
  10690. }
  10691. if (res == 1) {
  10692. /* Load into internal EC key based on key type option. */
  10693. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10694. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10695. (word32)derSz);
  10696. }
  10697. else {
  10698. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10699. (word32)derSz);
  10700. if (ret < 0) {
  10701. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  10702. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  10703. if (tmp == NULL) {
  10704. ret = -1;
  10705. }
  10706. else {
  10707. /* We now try again as x.963 [point type][x][opt y]. */
  10708. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  10709. INVALID_DEVID);
  10710. if (ret == 0) {
  10711. ret = wc_ecc_import_x963(derBuf, (word32)derSz, tmp);
  10712. if (ret == 0) {
  10713. /* Take ownership of new key - set tmp to the old
  10714. * key which will then be freed below. */
  10715. ecc_key *old = (ecc_key *)key->internal;
  10716. key->internal = tmp;
  10717. tmp = old;
  10718. idx = (word32)derSz;
  10719. }
  10720. wc_ecc_free(tmp);
  10721. }
  10722. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  10723. DYNAMIC_TYPE_ECC);
  10724. }
  10725. }
  10726. }
  10727. if (ret < 0) {
  10728. /* Error returned from wolfSSL. */
  10729. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10730. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10731. }
  10732. else {
  10733. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10734. }
  10735. res = -1;
  10736. }
  10737. /* Internal key updated - update whether it is a valid key. */
  10738. key->inSet = (res == 1);
  10739. }
  10740. /* Set the external EC key based on value in internal. */
  10741. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  10742. WOLFSSL_MSG("SetECKeyExternal failed");
  10743. res = -1;
  10744. }
  10745. return res;
  10746. }
  10747. /*
  10748. * EC key PEM APIs
  10749. */
  10750. #if (defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM)) || \
  10751. (!defined(NO_BIO) && (defined(WOLFSSL_KEY_GEN) || \
  10752. defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)))
  10753. /* Encode the EC public key as DER.
  10754. *
  10755. * Also used by pem_write_pubkey().
  10756. *
  10757. * @param [in] key EC key to encode.
  10758. * @param [out] der Pointer through which buffer is returned.
  10759. * @param [in] heap Heap hint.
  10760. * @return Size of encoding on success.
  10761. * @return 0 on error.
  10762. */
  10763. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  10764. unsigned char** der, void* heap)
  10765. {
  10766. int sz;
  10767. unsigned char* buf = NULL;
  10768. (void)heap;
  10769. /* Calculate encoded size to allocate. */
  10770. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  10771. if (sz <= 0) {
  10772. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  10773. sz = 0;
  10774. }
  10775. if (sz > 0) {
  10776. /* Allocate memory to hold encoding. */
  10777. buf = (byte*)XMALLOC((size_t)sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10778. if (buf == NULL) {
  10779. WOLFSSL_MSG("malloc failed");
  10780. sz = 0;
  10781. }
  10782. }
  10783. if (sz > 0) {
  10784. /* Encode public key to DER using wolfSSL. */
  10785. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, (word32)sz, 1);
  10786. if (sz < 0) {
  10787. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  10788. sz = 0;
  10789. }
  10790. }
  10791. /* Return buffer on success. */
  10792. if (sz > 0) {
  10793. *der = buf;
  10794. }
  10795. else {
  10796. /* Dispose of any dynamically allocated data not returned. */
  10797. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10798. }
  10799. return sz;
  10800. }
  10801. #endif
  10802. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  10803. /*
  10804. * Return code compliant with OpenSSL.
  10805. *
  10806. * @param [in] fp File pointer to write PEM encoding to.
  10807. * @param [in] key EC key to encode and write.
  10808. * @return 1 on success.
  10809. * @return 0 on error.
  10810. */
  10811. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10812. {
  10813. int ret = 1;
  10814. unsigned char* derBuf = NULL;
  10815. int derSz = 0;
  10816. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10817. /* Validate parameters. */
  10818. if ((fp == XBADFILE) || (key == NULL)) {
  10819. WOLFSSL_MSG("Bad argument.");
  10820. return 0;
  10821. }
  10822. /* Encode public key in EC key as DER. */
  10823. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  10824. if (derSz == 0) {
  10825. ret = 0;
  10826. }
  10827. /* Write out to file the PEM encoding of the DER. */
  10828. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  10829. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  10830. ret = 0;
  10831. }
  10832. /* Dispose of any dynamically allocated data. */
  10833. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10834. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10835. return ret;
  10836. }
  10837. #endif
  10838. #ifndef NO_BIO
  10839. /* Read a PEM encoded EC public key from a BIO.
  10840. *
  10841. * @param [in] bio BIO to read EC public key from.
  10842. * @param [out] out Pointer to return EC key object through. May be NULL.
  10843. * @param [in] cb Password callback when PEM encrypted.
  10844. * @param [in] pass NUL terminated string for passphrase when PEM
  10845. * encrypted.
  10846. * @return New EC key object on success.
  10847. * @return NULL on error.
  10848. */
  10849. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10850. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10851. {
  10852. int err = 0;
  10853. WOLFSSL_EC_KEY* ec = NULL;
  10854. DerBuffer* der = NULL;
  10855. int keyFormat = 0;
  10856. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10857. /* Validate parameters. */
  10858. if (bio == NULL) {
  10859. err = 1;
  10860. }
  10861. if (!err) {
  10862. /* Create an empty EC key. */
  10863. ec = wolfSSL_EC_KEY_new();
  10864. if (ec == NULL) {
  10865. err = 1;
  10866. }
  10867. }
  10868. /* Read a PEM key in to a new DER buffer. */
  10869. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  10870. &keyFormat, &der) <= 0)) {
  10871. err = 1;
  10872. }
  10873. /* Load the EC key with the public key from the DER encoding. */
  10874. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  10875. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  10876. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10877. err = 1;
  10878. }
  10879. /* Dispose of dynamically allocated data not needed anymore. */
  10880. FreeDer(&der);
  10881. if (err) {
  10882. wolfSSL_EC_KEY_free(ec);
  10883. ec = NULL;
  10884. }
  10885. /* Return EC key through out if required. */
  10886. if ((out != NULL) && (ec != NULL)) {
  10887. *out = ec;
  10888. }
  10889. return ec;
  10890. }
  10891. /* Read a PEM encoded EC private key from a BIO.
  10892. *
  10893. * @param [in] bio BIO to read EC private key from.
  10894. * @param [out] out Pointer to return EC key object through. May be NULL.
  10895. * @param [in] cb Password callback when PEM encrypted.
  10896. * @param [in] pass NUL terminated string for passphrase when PEM
  10897. * encrypted.
  10898. * @return New EC key object on success.
  10899. * @return NULL on error.
  10900. */
  10901. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  10902. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10903. {
  10904. int err = 0;
  10905. WOLFSSL_EC_KEY* ec = NULL;
  10906. DerBuffer* der = NULL;
  10907. int keyFormat = 0;
  10908. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  10909. /* Validate parameters. */
  10910. if (bio == NULL) {
  10911. err = 1;
  10912. }
  10913. if (!err) {
  10914. /* Create an empty EC key. */
  10915. ec = wolfSSL_EC_KEY_new();
  10916. if (ec == NULL) {
  10917. err = 1;
  10918. }
  10919. }
  10920. /* Read a PEM key in to a new DER buffer.
  10921. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  10922. * pem_read_bio_key(), and then check key format if it is EC.
  10923. */
  10924. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  10925. &keyFormat, &der) <= 0)) {
  10926. err = 1;
  10927. }
  10928. if (keyFormat != ECDSAk) {
  10929. WOLFSSL_ERROR_MSG("Error not EC key format");
  10930. err = 1;
  10931. }
  10932. /* Load the EC key with the private key from the DER encoding. */
  10933. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, (int)der->length,
  10934. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  10935. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10936. err = 1;
  10937. }
  10938. /* Dispose of dynamically allocated data not needed anymore. */
  10939. FreeDer(&der);
  10940. if (err) {
  10941. wolfSSL_EC_KEY_free(ec);
  10942. ec = NULL;
  10943. }
  10944. /* Return EC key through out if required. */
  10945. if ((out != NULL) && (ec != NULL)) {
  10946. *out = ec;
  10947. }
  10948. return ec;
  10949. }
  10950. #endif /* !NO_BIO */
  10951. #if defined(WOLFSSL_KEY_GEN)
  10952. #ifndef NO_BIO
  10953. /* Write out the EC public key as PEM to the BIO.
  10954. *
  10955. * @param [in] bio BIO to write PEM encoding to.
  10956. * @param [in] ec EC public key to encode.
  10957. * @return 1 on success.
  10958. * @return 0 on error.
  10959. */
  10960. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  10961. {
  10962. int ret = 1;
  10963. unsigned char* derBuf = NULL;
  10964. int derSz = 0;
  10965. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  10966. /* Validate parameters. */
  10967. if ((bio == NULL) || (ec == NULL)) {
  10968. WOLFSSL_MSG("Bad Function Arguments");
  10969. return 0;
  10970. }
  10971. /* Encode public key in EC key as DER. */
  10972. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  10973. if (derSz == 0) {
  10974. ret = 0;
  10975. }
  10976. /* Write out to BIO the PEM encoding of the EC private key. */
  10977. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  10978. ECC_PUBLICKEY_TYPE) != 1)) {
  10979. ret = 0;
  10980. }
  10981. /* Dispose of any dynamically allocated data. */
  10982. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10983. return ret;
  10984. }
  10985. /* Write out the EC private key as PEM to the BIO.
  10986. *
  10987. * Return code compliant with OpenSSL.
  10988. *
  10989. * @param [in] bio BIO to write PEM encoding to.
  10990. * @param [in] ec EC private key to encode.
  10991. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  10992. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  10993. * @param [in] passwdSz Length of password string when PEM encrypted.
  10994. * @param [in] cb Password callback when PEM encrypted. Unused.
  10995. * @param [in] pass NUL terminated string for passphrase when PEM
  10996. * encrypted. Unused.
  10997. * @return 1 on success.
  10998. * @return 0 on error.
  10999. */
  11000. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  11001. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11002. wc_pem_password_cb* cb, void* arg)
  11003. {
  11004. int ret = 1;
  11005. unsigned char* pem = NULL;
  11006. int pLen = 0;
  11007. (void)cb;
  11008. (void)arg;
  11009. /* Validate parameters. */
  11010. if ((bio == NULL) || (ec == NULL)) {
  11011. ret = 0;
  11012. }
  11013. /* Write EC private key to PEM. */
  11014. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11015. passwdSz, &pem, &pLen) != 1)) {
  11016. ret = 0;
  11017. }
  11018. /* Write PEM to BIO. */
  11019. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  11020. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  11021. ret = 0;
  11022. }
  11023. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11024. return ret;
  11025. }
  11026. #endif /* !NO_BIO */
  11027. /* Encode the EC private key as PEM into buffer.
  11028. *
  11029. * Return code compliant with OpenSSL.
  11030. * Not an OpenSSL API.
  11031. *
  11032. * @param [in] ec EC private key to encode.
  11033. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11034. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11035. * @param [in] passwdSz Length of password string when PEM encrypted.
  11036. * @param [out] pem Newly allocated buffer holding PEM encoding.
  11037. * @param [out] pLen Length of PEM encoding in bytes.
  11038. * @return 1 on success.
  11039. * @return 0 on error.
  11040. */
  11041. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  11042. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  11043. unsigned char **pem, int *pLen)
  11044. {
  11045. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  11046. int ret = 1;
  11047. byte* derBuf = NULL;
  11048. word32 der_max_len = 0;
  11049. int derSz = 0;
  11050. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  11051. /* Validate parameters. */
  11052. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  11053. (ec->internal == NULL)) {
  11054. WOLFSSL_MSG("Bad function arguments");
  11055. ret = 0;
  11056. }
  11057. /* Ensure internal EC key is set from external. */
  11058. if ((ret == 1) && (ec->inSet == 0)) {
  11059. WOLFSSL_MSG("No ECC internal set, do it");
  11060. if (SetECKeyInternal(ec) != 1) {
  11061. WOLFSSL_MSG("SetECKeyInternal failed");
  11062. ret = 0;
  11063. }
  11064. }
  11065. if (ret == 1) {
  11066. /* Calculate maximum size of DER encoding.
  11067. * 4 > size of pub, priv + ASN.1 additional information */
  11068. der_max_len = 4 * (word32)wc_ecc_size((ecc_key*)ec->internal) +
  11069. AES_BLOCK_SIZE;
  11070. /* Allocate buffer big enough to hold encoding. */
  11071. derBuf = (byte*)XMALLOC((size_t)der_max_len, NULL,
  11072. DYNAMIC_TYPE_TMP_BUFFER);
  11073. if (derBuf == NULL) {
  11074. WOLFSSL_MSG("malloc failed");
  11075. ret = 0;
  11076. }
  11077. }
  11078. if (ret == 1) {
  11079. /* Encode EC private key as DER. */
  11080. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  11081. if (derSz < 0) {
  11082. WOLFSSL_MSG("wc_EccKeyToDer failed");
  11083. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  11084. ret = 0;
  11085. }
  11086. }
  11087. /* Convert DER to PEM - possibly encrypting. */
  11088. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  11089. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  11090. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  11091. ret = 0;
  11092. }
  11093. return ret;
  11094. #else
  11095. (void)ec;
  11096. (void)cipher;
  11097. (void)passwd;
  11098. (void)passwdSz;
  11099. (void)pem;
  11100. (void)pLen;
  11101. return 0;
  11102. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  11103. }
  11104. #ifndef NO_FILESYSTEM
  11105. /* Write out the EC private key as PEM to file.
  11106. *
  11107. * Return code compliant with OpenSSL.
  11108. *
  11109. * @param [in] fp File pointer to write PEM encoding to.
  11110. * @param [in] ec EC private key to encode.
  11111. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  11112. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  11113. * @param [in] passwdSz Length of password string when PEM encrypted.
  11114. * @param [in] cb Password callback when PEM encrypted. Unused.
  11115. * @param [in] pass NUL terminated string for passphrase when PEM
  11116. * encrypted. Unused.
  11117. * @return 1 on success.
  11118. * @return 0 on error.
  11119. */
  11120. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  11121. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  11122. wc_pem_password_cb *cb, void *pass)
  11123. {
  11124. int ret = 1;
  11125. byte *pem = NULL;
  11126. int pLen = 0;
  11127. (void)cb;
  11128. (void)pass;
  11129. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  11130. /* Validate parameters. */
  11131. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  11132. WOLFSSL_MSG("Bad function arguments");
  11133. ret = 0;
  11134. }
  11135. /* Write EC private key to PEM. */
  11136. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11137. passwdSz, &pem, &pLen) != 1)) {
  11138. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11139. ret = 0;
  11140. }
  11141. /* Write out to file the PEM encoding of the EC private key. */
  11142. if ((ret == 1) && ((int)XFWRITE(pem, 1, (size_t)pLen, fp) != pLen)) {
  11143. WOLFSSL_MSG("ECC private key file write failed");
  11144. ret = 0;
  11145. }
  11146. /* Dispose of any dynamically allocated data. */
  11147. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11148. return ret;
  11149. }
  11150. #endif /* NO_FILESYSTEM */
  11151. #endif /* defined(WOLFSSL_KEY_GEN) */
  11152. /*
  11153. * EC key print APIs
  11154. */
  11155. #ifndef NO_CERTS
  11156. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11157. !defined(NO_STDIO_FILESYSTEM)
  11158. /* Print the EC key to a file pointer as text.
  11159. *
  11160. * @param [in] fp File pointer.
  11161. * @param [in] key EC key to print.
  11162. * @param [in] indent Number of spaces to place before each line printed.
  11163. * @return 1 on success.
  11164. * @return 0 on failure.
  11165. */
  11166. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11167. {
  11168. int ret = 1;
  11169. int bits = 0;
  11170. int priv = 0;
  11171. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11172. /* Validate parameters. */
  11173. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11174. (indent < 0)) {
  11175. ret = 0;
  11176. }
  11177. if (ret == 1) {
  11178. /* Get EC groups order size in bits. */
  11179. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11180. if (bits <= 0) {
  11181. WOLFSSL_MSG("Failed to get group order bits.");
  11182. ret = 0;
  11183. }
  11184. }
  11185. if (ret == 1) {
  11186. const char* keyType;
  11187. /* Determine whether this is a private or public key. */
  11188. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11189. keyType = "Private-Key";
  11190. priv = 1;
  11191. }
  11192. else {
  11193. keyType = "Public-Key";
  11194. }
  11195. /* Print key header. */
  11196. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11197. ret = 0;
  11198. }
  11199. }
  11200. if ((ret == 1) && priv) {
  11201. /* Print the private key BN. */
  11202. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11203. }
  11204. /* Check for public key data in EC key. */
  11205. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11206. /* Get the public key point as one BN. */
  11207. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11208. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11209. if (pubBn == NULL) {
  11210. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11211. ret = 0;
  11212. }
  11213. else {
  11214. /* Print the public key in a BN. */
  11215. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11216. wolfSSL_BN_free(pubBn);
  11217. }
  11218. }
  11219. if (ret == 1) {
  11220. /* Get the NID of the group. */
  11221. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11222. if (nid > 0) {
  11223. /* Convert the NID into a long name and NIST name. */
  11224. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11225. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11226. /* Print OID name if known. */
  11227. if ((curve != NULL) &&
  11228. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11229. ret = 0;
  11230. }
  11231. /* Print NIST curve name if known. */
  11232. if ((nistName != NULL) &&
  11233. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11234. nistName) < 0)) {
  11235. ret = 0;
  11236. }
  11237. }
  11238. }
  11239. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11240. return ret;
  11241. }
  11242. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11243. #endif /* !NO_CERTS */
  11244. /*
  11245. * EC_KEY get/set/test APIs
  11246. */
  11247. /* Set data of internal, wolfCrypt EC key object into EC key.
  11248. *
  11249. * EC_KEY wolfSSL -> OpenSSL
  11250. *
  11251. * @param [in, out] p EC key to update.
  11252. * @return 1 on success.
  11253. * @return -1 on failure.
  11254. */
  11255. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11256. {
  11257. int ret = 1;
  11258. WOLFSSL_ENTER("SetECKeyExternal");
  11259. /* Validate parameter. */
  11260. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11261. WOLFSSL_MSG("ec key NULL error");
  11262. ret = -1;
  11263. }
  11264. else {
  11265. ecc_key* key = (ecc_key*)eckey->internal;
  11266. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11267. eckey->group->curve_oid = (int)key->dp->oidSum;
  11268. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11269. eckey->group->curve_idx = key->idx;
  11270. if (eckey->pub_key->internal != NULL) {
  11271. /* Copy internal public point from internal key's public point. */
  11272. if (wc_ecc_copy_point(&key->pubkey,
  11273. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11274. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11275. ret = -1;
  11276. }
  11277. /* Set external public key from internal wolfCrypt, public key. */
  11278. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11279. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11280. ret = -1;
  11281. }
  11282. }
  11283. /* set the external privkey */
  11284. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11285. (wolfssl_bn_set_value(&eckey->priv_key,
  11286. wc_ecc_key_get_priv(key)) != 1)) {
  11287. WOLFSSL_MSG("ec priv key error");
  11288. ret = -1;
  11289. }
  11290. /* External values set when operations succeeded. */
  11291. eckey->exSet = (ret == 1);
  11292. }
  11293. return ret;
  11294. }
  11295. /* Set data of EC key into internal, wolfCrypt EC key object.
  11296. *
  11297. * EC_KEY Openssl -> WolfSSL
  11298. *
  11299. * @param [in, out] p EC key to update.
  11300. * @return 1 on success.
  11301. * @return -1 on failure.
  11302. */
  11303. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11304. {
  11305. int ret = 1;
  11306. WOLFSSL_ENTER("SetECKeyInternal");
  11307. /* Validate parameter. */
  11308. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11309. (eckey->group == NULL)) {
  11310. WOLFSSL_MSG("ec key NULL error");
  11311. ret = -1;
  11312. }
  11313. else {
  11314. ecc_key* key = (ecc_key*)eckey->internal;
  11315. int pubSet = 0;
  11316. /* Validate group. */
  11317. if ((eckey->group->curve_idx < 0) ||
  11318. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11319. WOLFSSL_MSG("invalid curve idx");
  11320. ret = -1;
  11321. }
  11322. if (ret == 1) {
  11323. /* Set group (idx of curve and corresponding domain parameters). */
  11324. key->idx = eckey->group->curve_idx;
  11325. key->dp = &ecc_sets[key->idx];
  11326. pubSet = (eckey->pub_key != NULL);
  11327. }
  11328. /* Set public key (point). */
  11329. if ((ret == 1) && pubSet) {
  11330. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11331. WOLFSSL_MSG("ec key pub error");
  11332. ret = -1;
  11333. }
  11334. /* Copy public point to key. */
  11335. if ((ret == 1) && (wc_ecc_copy_point(
  11336. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11337. MP_OKAY)) {
  11338. WOLFSSL_MSG("wc_ecc_copy_point error");
  11339. ret = -1;
  11340. }
  11341. if (ret == 1) {
  11342. /* Set that the internal key is a public key */
  11343. key->type = ECC_PUBLICKEY;
  11344. }
  11345. }
  11346. /* set privkey */
  11347. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11348. if (wolfssl_bn_get_value(eckey->priv_key,
  11349. wc_ecc_key_get_priv(key)) != 1) {
  11350. WOLFSSL_MSG("ec key priv error");
  11351. ret = -1;
  11352. }
  11353. /* private key */
  11354. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11355. if (pubSet) {
  11356. key->type = ECC_PRIVATEKEY;
  11357. }
  11358. else {
  11359. key->type = ECC_PRIVATEKEY_ONLY;
  11360. }
  11361. }
  11362. }
  11363. /* Internal values set when operations succeeded. */
  11364. eckey->inSet = (ret == 1);
  11365. }
  11366. return ret;
  11367. }
  11368. /* Get point conversion format of EC key.
  11369. *
  11370. * @param [in] key EC key.
  11371. * @return Point conversion format on success.
  11372. * @return -1 on error.
  11373. */
  11374. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11375. {
  11376. int ret = -1;
  11377. if (key != NULL) {
  11378. ret = key->form;
  11379. }
  11380. return ret;
  11381. }
  11382. /* Set point conversion format into EC key.
  11383. *
  11384. * @param [in, out] key EC key to set format into.
  11385. * @param [in] form Point conversion format. Valid values:
  11386. * POINT_CONVERSION_UNCOMPRESSED,
  11387. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11388. */
  11389. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11390. {
  11391. if (key == NULL) {
  11392. WOLFSSL_MSG("Key passed in NULL");
  11393. }
  11394. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11395. #ifdef HAVE_COMP_KEY
  11396. || form == POINT_CONVERSION_COMPRESSED
  11397. #endif
  11398. ) {
  11399. key->form = (unsigned char)form;
  11400. }
  11401. else {
  11402. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11403. }
  11404. }
  11405. /* Get the EC group object that is in EC key.
  11406. *
  11407. * @param [in] key EC key.
  11408. * @return EC group object on success.
  11409. * @return NULL when key is NULL.
  11410. */
  11411. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11412. {
  11413. WOLFSSL_EC_GROUP* group = NULL;
  11414. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11415. if (key != NULL) {
  11416. group = key->group;
  11417. }
  11418. return group;
  11419. }
  11420. /* Set the group in WOLFSSL_EC_KEY
  11421. *
  11422. * @param [in, out] key EC key to update.
  11423. * @param [in] group EC group to copy.
  11424. * @return 1 on success
  11425. * @return 0 on failure.
  11426. */
  11427. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11428. {
  11429. int ret = 1;
  11430. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11431. /* Validate parameters. */
  11432. if ((key == NULL) || (group == NULL)) {
  11433. ret = 0;
  11434. }
  11435. if (ret == 1) {
  11436. /* Dispose of the current group. */
  11437. if (key->group != NULL) {
  11438. wolfSSL_EC_GROUP_free(key->group);
  11439. }
  11440. /* Duplicate the passed in group into EC key. */
  11441. key->group = wolfSSL_EC_GROUP_dup(group);
  11442. if (key->group == NULL) {
  11443. ret = 0;
  11444. }
  11445. }
  11446. return ret;
  11447. }
  11448. /* Get the BN object that is the private key in the EC key.
  11449. *
  11450. * @param [in] key EC key.
  11451. * @return BN object on success.
  11452. * @return NULL when key is NULL or private key is not set.
  11453. */
  11454. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11455. {
  11456. WOLFSSL_BIGNUM* priv_key = NULL;
  11457. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11458. /* Validate parameter. */
  11459. if (key == NULL) {
  11460. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11461. }
  11462. /* Only return private key if it is not 0. */
  11463. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11464. priv_key = key->priv_key;
  11465. }
  11466. return priv_key;
  11467. }
  11468. /* Sets the private key value into EC key.
  11469. *
  11470. * Return code compliant with OpenSSL.
  11471. *
  11472. * @param [in, out] key EC key to set.
  11473. * @param [in] priv_key Private key value in a BN.
  11474. * @return 1 on success
  11475. * @return 0 on failure.
  11476. */
  11477. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11478. const WOLFSSL_BIGNUM *priv_key)
  11479. {
  11480. int ret = 1;
  11481. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11482. /* Validate parameters. */
  11483. if ((key == NULL) || (priv_key == NULL)) {
  11484. WOLFSSL_MSG("Bad arguments");
  11485. ret = 0;
  11486. }
  11487. /* Check for obvious invalid values. */
  11488. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11489. wolfSSL_BN_is_one(priv_key)) {
  11490. WOLFSSL_MSG("Invalid private key value");
  11491. ret = 0;
  11492. }
  11493. if (ret == 1) {
  11494. /* Free key if previously set. */
  11495. if (key->priv_key != NULL) {
  11496. wolfSSL_BN_free(key->priv_key);
  11497. }
  11498. /* Duplicate the BN passed in. */
  11499. key->priv_key = wolfSSL_BN_dup(priv_key);
  11500. if (key->priv_key == NULL) {
  11501. WOLFSSL_MSG("key ecc priv key NULL");
  11502. ret = 0;
  11503. }
  11504. }
  11505. /* Set the external values into internal EC key. */
  11506. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11507. WOLFSSL_MSG("SetECKeyInternal failed");
  11508. /* Dispose of new private key on error. */
  11509. wolfSSL_BN_free(key->priv_key);
  11510. key->priv_key = NULL;
  11511. ret = 0;
  11512. }
  11513. return ret;
  11514. }
  11515. /* Get the public key EC point object that is in EC key.
  11516. *
  11517. * @param [in] key EC key.
  11518. * @return EC point object that is the public key on success.
  11519. * @return NULL when key is NULL.
  11520. */
  11521. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11522. {
  11523. WOLFSSL_EC_POINT* pub_key = NULL;
  11524. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11525. if (key != NULL) {
  11526. pub_key = key->pub_key;
  11527. }
  11528. return pub_key;
  11529. }
  11530. /*
  11531. * Return code compliant with OpenSSL.
  11532. *
  11533. * @param [in, out] key EC key.
  11534. * @param [in] pub Public key as an EC point.
  11535. * @return 1 on success
  11536. * @return 0 on failure.
  11537. */
  11538. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11539. const WOLFSSL_EC_POINT *pub)
  11540. {
  11541. int ret = 1;
  11542. ecc_point *pub_p = NULL;
  11543. ecc_point *key_p = NULL;
  11544. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11545. /* Validate parameters. */
  11546. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11547. (pub->internal == NULL)) {
  11548. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11549. ret = 0;
  11550. }
  11551. /* Ensure the internal EC key is set. */
  11552. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11553. WOLFSSL_MSG("SetECKeyInternal failed");
  11554. ret = 0;
  11555. }
  11556. /* Ensure the internal EC point of pub is setup. */
  11557. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11558. ret = 0;
  11559. }
  11560. if (ret == 1) {
  11561. /* Get the internal point of pub and the public key in key. */
  11562. pub_p = (ecc_point*)pub->internal;
  11563. key_p = (ecc_point*)key->pub_key->internal;
  11564. /* Create new point if required. */
  11565. if (key_p == NULL) {
  11566. key_p = wc_ecc_new_point();
  11567. key->pub_key->internal = (void*)key_p;
  11568. }
  11569. /* Check point available. */
  11570. if (key_p == NULL) {
  11571. WOLFSSL_MSG("key ecc point NULL");
  11572. ret = 0;
  11573. }
  11574. }
  11575. /* Copy the internal pub point into internal key point. */
  11576. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11577. WOLFSSL_MSG("ecc_copy_point failure");
  11578. ret = 0;
  11579. }
  11580. /* Copy the internal point data into external. */
  11581. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11582. WOLFSSL_MSG("SetECKeyInternal failed");
  11583. ret = 0;
  11584. }
  11585. /* Copy the internal key into external. */
  11586. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11587. WOLFSSL_MSG("SetECKeyInternal failed");
  11588. ret = 0;
  11589. }
  11590. if (ret == 1) {
  11591. /* Dump out the point and the key's public key for debug. */
  11592. wolfSSL_EC_POINT_dump("pub", pub);
  11593. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11594. }
  11595. return ret;
  11596. }
  11597. #ifndef NO_WOLFSSL_STUB
  11598. /* Set the ASN.1 encoding flag against the EC key.
  11599. *
  11600. * No implementation as only named curves supported for encoding.
  11601. *
  11602. * @param [in, out] key EC key.
  11603. * @param [in] flag ASN.1 flag to set. Valid values:
  11604. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11605. */
  11606. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11607. {
  11608. (void)key;
  11609. (void)asn1_flag;
  11610. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11611. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11612. }
  11613. #endif
  11614. /*
  11615. * EC key generate key APIs
  11616. */
  11617. /* Generate an EC key.
  11618. *
  11619. * Uses the internal curve index set in the EC key or the default.
  11620. *
  11621. * @param [in, out] key EC key.
  11622. * @return 1 on success
  11623. * @return 0 on failure.
  11624. */
  11625. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11626. {
  11627. int res = 1;
  11628. int initTmpRng = 0;
  11629. WC_RNG* rng = NULL;
  11630. #ifdef WOLFSSL_SMALL_STACK
  11631. WC_RNG* tmpRng = NULL;
  11632. #else
  11633. WC_RNG tmpRng[1];
  11634. #endif
  11635. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11636. /* Validate parameters. */
  11637. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11638. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11639. res = 0;
  11640. }
  11641. if (res == 1) {
  11642. /* Check if we know which internal curve index to use. */
  11643. if (key->group->curve_idx < 0) {
  11644. /* Generate key using the default curve. */
  11645. key->group->curve_idx = ECC_CURVE_DEF;
  11646. }
  11647. /* Create a random number generator. */
  11648. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  11649. if (rng == NULL) {
  11650. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to set RNG");
  11651. res = 0;
  11652. }
  11653. }
  11654. if (res == 1) {
  11655. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  11656. * is 0 then pass ECC_CURVE_DEF as arg */
  11657. int eccEnum = key->group->curve_nid ?
  11658. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  11659. /* Get the internal EC key. */
  11660. ecc_key* ecKey = (ecc_key*)key->internal;
  11661. /* Make the key using internal API. */
  11662. int ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  11663. #if defined(WOLFSSL_ASYNC_CRYPT)
  11664. /* Wait on asynchronouse operation. */
  11665. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  11666. #endif
  11667. if (ret != 0) {
  11668. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  11669. res = 0;
  11670. }
  11671. }
  11672. /* Dispose of local random number generator if initialized. */
  11673. if (initTmpRng) {
  11674. wc_FreeRng(rng);
  11675. #ifdef WOLFSSL_SMALL_STACK
  11676. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  11677. #endif
  11678. }
  11679. /* Set the external key from new internal key values. */
  11680. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11681. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  11682. res = 0;
  11683. }
  11684. return res;
  11685. }
  11686. /*
  11687. * EC key check key APIs
  11688. */
  11689. /* Check that the EC key is valid.
  11690. *
  11691. * @param [in] key EC key.
  11692. * @return 1 on valid.
  11693. * @return 0 on invalid or error.
  11694. */
  11695. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  11696. {
  11697. int ret = 1;
  11698. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  11699. /* Validate parameter. */
  11700. if ((key == NULL) || (key->internal == NULL)) {
  11701. WOLFSSL_MSG("Bad parameter");
  11702. ret = 0;
  11703. }
  11704. /* Set the external EC key values into internal if not already. */
  11705. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  11706. (WOLFSSL_EC_KEY*)key) != 1)) {
  11707. WOLFSSL_MSG("SetECKeyInternal failed");
  11708. ret = 0;
  11709. }
  11710. if (ret == 1) {
  11711. /* Have internal EC implementation check key. */
  11712. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  11713. }
  11714. return ret;
  11715. }
  11716. /* End EC_KEY */
  11717. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  11718. /* Get the supported, built-in EC curves
  11719. *
  11720. * @param [in, out] curves Pre-allocated list to put supported curves into.
  11721. * @param [in] len Maximum number of items to place in list.
  11722. * @return Number of built-in EC curves when curves is NULL or len is 0.
  11723. * @return Number of items placed in list otherwise.
  11724. */
  11725. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  11726. size_t len)
  11727. {
  11728. size_t i;
  11729. size_t cnt;
  11730. #ifdef HAVE_SELFTEST
  11731. /* Defined in ecc.h when available. */
  11732. size_t ecc_sets_count;
  11733. /* Count the pre-defined curves since global not available. */
  11734. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  11735. /* Do nothing. */
  11736. }
  11737. ecc_sets_count = i;
  11738. #endif
  11739. /* Assume we are going to return total count. */
  11740. cnt = ecc_sets_count;
  11741. /* Check we have a list that can hold data. */
  11742. if ((curves != NULL) && (len != 0)) {
  11743. /* Limit count to length of list. */
  11744. if (cnt > len) {
  11745. cnt = len;
  11746. }
  11747. /* Put in built-in EC curve nid and short name. */
  11748. for (i = 0; i < cnt; i++) {
  11749. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  11750. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  11751. }
  11752. }
  11753. return cnt;
  11754. }
  11755. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  11756. /* Start ECDSA_SIG */
  11757. /* Allocate a new ECDSA signature object.
  11758. *
  11759. * @return New, allocated ECDSA signature object on success.
  11760. * @return NULL on error.
  11761. */
  11762. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  11763. {
  11764. int err = 0;
  11765. WOLFSSL_ECDSA_SIG *sig;
  11766. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  11767. /* Allocate memory for ECDSA signature object. */
  11768. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  11769. DYNAMIC_TYPE_ECC);
  11770. if (sig == NULL) {
  11771. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  11772. err = 1;
  11773. }
  11774. if (!err) {
  11775. /* Set s to NULL in case of error. */
  11776. sig->s = NULL;
  11777. /* Allocate BN into r. */
  11778. sig->r = wolfSSL_BN_new();
  11779. if (sig->r == NULL) {
  11780. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  11781. err = 1;
  11782. }
  11783. }
  11784. if (!err) {
  11785. /* Allocate BN into s. */
  11786. sig->s = wolfSSL_BN_new();
  11787. if (sig->s == NULL) {
  11788. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  11789. err = 1;
  11790. }
  11791. }
  11792. if (err && (sig != NULL)) {
  11793. /* Dispose of allocated memory. */
  11794. wolfSSL_ECDSA_SIG_free(sig);
  11795. sig = NULL;
  11796. }
  11797. return sig;
  11798. }
  11799. /* Dispose of ECDSA signature object.
  11800. *
  11801. * Cannot use object after this call.
  11802. *
  11803. * @param [in] sig ECDSA signature object to free.
  11804. */
  11805. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  11806. {
  11807. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  11808. if (sig != NULL) {
  11809. /* Dispose of BNs allocated for r and s. */
  11810. wolfSSL_BN_free(sig->r);
  11811. wolfSSL_BN_free(sig->s);
  11812. /* Dispose of memory associated with ECDSA signature object. */
  11813. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  11814. }
  11815. }
  11816. /* Create an ECDSA signature from the DER encoding.
  11817. *
  11818. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  11819. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  11820. * On out, reference to buffer after signature data.
  11821. * @param [in] len Length of the data in the buffer. May be more than
  11822. * the length of the signature.
  11823. * @return ECDSA signature object on success.
  11824. * @return NULL on error.
  11825. */
  11826. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  11827. const unsigned char** pp, long len)
  11828. {
  11829. int err = 0;
  11830. /* ECDSA signature object to return. */
  11831. WOLFSSL_ECDSA_SIG *s = NULL;
  11832. /* Validate parameter. */
  11833. if (pp == NULL) {
  11834. err = 1;
  11835. }
  11836. if (!err) {
  11837. if (sig != NULL) {
  11838. /* Use the ECDSA signature object passed in. */
  11839. s = *sig;
  11840. }
  11841. if (s == NULL) {
  11842. /* No ECDSA signature object passed in - create a new one. */
  11843. s = wolfSSL_ECDSA_SIG_new();
  11844. if (s == NULL) {
  11845. err = 1;
  11846. }
  11847. }
  11848. }
  11849. if (!err) {
  11850. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  11851. mp_free((mp_int*)s->r->internal);
  11852. mp_free((mp_int*)s->s->internal);
  11853. /* Decode the signature into internal r and s fields. */
  11854. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  11855. (mp_int*)s->s->internal) != MP_OKAY) {
  11856. err = 1;
  11857. }
  11858. }
  11859. if (!err) {
  11860. /* Move pointer passed signature data successfully decoded. */
  11861. *pp += wolfssl_der_length(*pp, (int)len);
  11862. if (sig != NULL) {
  11863. /* Update reference to ECDSA signature object. */
  11864. *sig = s;
  11865. }
  11866. }
  11867. /* Dispose of newly allocated object on error. */
  11868. if (err) {
  11869. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  11870. wolfSSL_ECDSA_SIG_free(s);
  11871. }
  11872. /* Return NULL for object on error. */
  11873. s = NULL;
  11874. }
  11875. return s;
  11876. }
  11877. /* Encode the ECDSA signature as DER.
  11878. *
  11879. * @param [in] sig ECDSA signature object.
  11880. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  11881. * On out, reference to buffer after encoding.
  11882. * May be NULL or point to NULL in which case no encoding
  11883. * is done.
  11884. * @return Length of encoding on success.
  11885. * @return 0 on error.
  11886. */
  11887. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  11888. {
  11889. word32 len = 0;
  11890. /* Validate parameter. */
  11891. if (sig != NULL) {
  11892. /* ASN.1: SEQ + INT + INT
  11893. * ASN.1 Integer must be a positive value - prepend zero if number has
  11894. * top bit set.
  11895. */
  11896. /* Get total length of r including any prepended zero. */
  11897. word32 rLen = (word32)(mp_leading_bit((mp_int*)sig->r->internal) +
  11898. mp_unsigned_bin_size((mp_int*)sig->r->internal));
  11899. /* Get total length of s including any prepended zero. */
  11900. word32 sLen = (word32)(mp_leading_bit((mp_int*)sig->s->internal) +
  11901. mp_unsigned_bin_size((mp_int*)sig->s->internal));
  11902. /* Calculate length of data in sequence. */
  11903. len = (word32)1 + ASN_LEN_SIZE(rLen) + rLen +
  11904. (word32)1 + ASN_LEN_SIZE(sLen) + sLen;
  11905. /* Add in the length of the SEQUENCE. */
  11906. len += (word32)1 + ASN_LEN_SIZE(len);
  11907. /* Encode only if there is a buffer to encode into. */
  11908. if ((pp != NULL) && (*pp != NULL)) {
  11909. /* Encode using the internal representations of r and s. */
  11910. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  11911. (mp_int*)sig->s->internal) != MP_OKAY) {
  11912. /* No bytes encoded. */
  11913. len = 0;
  11914. }
  11915. else {
  11916. /* Update pointer to after encoding. */
  11917. *pp += len;
  11918. }
  11919. }
  11920. }
  11921. return (int)len;
  11922. }
  11923. /* Get the pointer to the fields of the ECDSA signature.
  11924. *
  11925. * r and s untouched when sig is NULL.
  11926. *
  11927. * @param [in] sig ECDSA signature object.
  11928. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  11929. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  11930. */
  11931. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  11932. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  11933. {
  11934. /* Validate parameter. */
  11935. if (sig != NULL) {
  11936. /* Return the r BN when pointer to return through. */
  11937. if (r != NULL) {
  11938. *r = sig->r;
  11939. }
  11940. /* Return the s BN when pointer to return through. */
  11941. if (s != NULL) {
  11942. *s = sig->s;
  11943. }
  11944. }
  11945. }
  11946. /* Set the pointers to the fields of the ECDSA signature.
  11947. *
  11948. * @param [in, out] sig ECDSA signature object to update.
  11949. * @param [in] r R field of ECDSA signature as a BN.
  11950. * @param [in] s S field of ECDSA signature as a BN.
  11951. * @return 1 on success.
  11952. * @return 0 on error.
  11953. */
  11954. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  11955. WOLFSSL_BIGNUM* s)
  11956. {
  11957. int ret = 1;
  11958. /* Validate parameters. */
  11959. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  11960. ret = 0;
  11961. }
  11962. if (ret == 1) {
  11963. /* Dispose of old BN objects. */
  11964. wolfSSL_BN_free(sig->r);
  11965. wolfSSL_BN_free(sig->s);
  11966. /* Assign new BN objects. */
  11967. sig->r = r;
  11968. sig->s = s;
  11969. }
  11970. return ret;
  11971. }
  11972. /* End ECDSA_SIG */
  11973. /* Start ECDSA */
  11974. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  11975. *
  11976. * @param [in] key EC key.
  11977. * @return Size of DER encoded signature on success.
  11978. * @return 0 on error.
  11979. */
  11980. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  11981. {
  11982. int err = 0;
  11983. int len = 0;
  11984. const EC_GROUP *group = NULL;
  11985. int bits = 0;
  11986. /* Validate parameter. */
  11987. if (key == NULL) {
  11988. err = 1;
  11989. }
  11990. /* Get group from key to get order bits. */
  11991. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  11992. err = 1;
  11993. }
  11994. /* Get order bits of group. */
  11995. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  11996. /* Group is not set. */
  11997. err = 1;
  11998. }
  11999. if (!err) {
  12000. /* r and s are mod order. */
  12001. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  12002. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  12003. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  12004. bytes + bytes; /* max r and s in bytes */
  12005. }
  12006. return len;
  12007. }
  12008. /* Create ECDSA signature by signing digest with key.
  12009. *
  12010. * @param [in] dgst Digest to sign.
  12011. * @param [in] dLen Length of digest in bytes.
  12012. * @param [in] key EC key to sign with.
  12013. * @return ECDSA signature object on success.
  12014. * @return NULL on error.
  12015. */
  12016. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  12017. WOLFSSL_EC_KEY *key)
  12018. {
  12019. int err = 0;
  12020. WOLFSSL_ECDSA_SIG *sig = NULL;
  12021. #ifdef WOLFSSL_SMALL_STACK
  12022. byte* out = NULL;
  12023. #else
  12024. byte out[ECC_BUFSIZE];
  12025. #endif
  12026. unsigned int outLen = ECC_BUFSIZE;
  12027. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  12028. /* Validate parameters. */
  12029. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  12030. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  12031. err = 1;
  12032. }
  12033. /* Ensure internal EC key is set from external. */
  12034. if ((!err) && (key->inSet == 0)) {
  12035. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  12036. if (SetECKeyInternal(key) != 1) {
  12037. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  12038. err = 1;
  12039. }
  12040. }
  12041. #ifdef WOLFSSL_SMALL_STACK
  12042. if (!err) {
  12043. /* Allocate buffer to hold encoded signature. */
  12044. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12045. if (out == NULL) {
  12046. err = 1;
  12047. }
  12048. }
  12049. #endif
  12050. /* Sign the digest with the key to create encoded ECDSA signature. */
  12051. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  12052. err = 1;
  12053. }
  12054. if (!err) {
  12055. const byte* p = out;
  12056. /* Decode the ECDSA signature into a new object. */
  12057. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  12058. }
  12059. #ifdef WOLFSSL_SMALL_STACK
  12060. /* Dispose of any temporary dynamically allocated data. */
  12061. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  12062. #endif
  12063. return sig;
  12064. }
  12065. /* Verify ECDSA signature in the object using digest and key.
  12066. *
  12067. * Return code compliant with OpenSSL.
  12068. *
  12069. * @param [in] dgst Digest to verify.
  12070. * @param [in] dLen Length of the digest in bytes.
  12071. * @param [in] sig ECDSA signature object.
  12072. * @param [in] key EC key containing public key.
  12073. * @return 1 when signature is valid.
  12074. * @return 0 when signature is invalid.
  12075. * @return -1 on error.
  12076. */
  12077. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  12078. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  12079. {
  12080. int ret = 1;
  12081. int verified = 0;
  12082. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  12083. byte signature[ECC_MAX_SIG_SIZE];
  12084. int signatureLen;
  12085. byte* p = signature;
  12086. #endif
  12087. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  12088. /* Validate parameters. */
  12089. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  12090. (key->internal == NULL)) {
  12091. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  12092. ret = -1;
  12093. }
  12094. /* Ensure internal EC key is set from external. */
  12095. if ((ret == 1) && (key->inSet == 0)) {
  12096. WOLFSSL_MSG("No EC key internal set, do it");
  12097. if (SetECKeyInternal(key) != 1) {
  12098. WOLFSSL_MSG("SetECKeyInternal failed");
  12099. ret = -1;
  12100. }
  12101. }
  12102. if (ret == 1) {
  12103. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12104. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  12105. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  12106. (mp_int*)sig->s->internal, dgst, (word32)dLen, &verified,
  12107. (ecc_key *)key->internal) != MP_OKAY) {
  12108. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12109. ret = -1;
  12110. }
  12111. else if (verified == 0) {
  12112. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12113. ret = 0;
  12114. }
  12115. #else
  12116. signatureLen = i2d_ECDSA_SIG(sig, &p);
  12117. if (signatureLen > 0) {
  12118. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  12119. ret = wc_ecc_verify_hash(signature, signatureLen, dgst,
  12120. (word32)dLen, &verified, (ecc_key*)key->internal);
  12121. if (ret != MP_OKAY) {
  12122. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  12123. ret = -1;
  12124. }
  12125. else if (verified == 0) {
  12126. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  12127. ret = 0;
  12128. }
  12129. }
  12130. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12131. }
  12132. return ret;
  12133. }
  12134. /* Sign the digest with the key to produce a DER encode signature.
  12135. *
  12136. * @param [in] type Digest algorithm used to create digest. Unused.
  12137. * @param [in] digest Digest of the message to sign.
  12138. * @param [in] digestSz Size of the digest in bytes.
  12139. * @param [out] sig Buffer to hold signature.
  12140. * @param [in, out] sigSz On in, size of buffer in bytes.
  12141. * On out, size of signatre in bytes.
  12142. * @param [in] key EC key containing private key.
  12143. * @return 1 on success.
  12144. * @return 0 on error.
  12145. */
  12146. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12147. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12148. {
  12149. int ret = 1;
  12150. WC_RNG* rng = NULL;
  12151. #ifdef WOLFSSL_SMALL_STACK
  12152. WC_RNG* tmpRng = NULL;
  12153. #else
  12154. WC_RNG tmpRng[1];
  12155. #endif
  12156. int initTmpRng = 0;
  12157. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12158. /* Digest algorithm not used in DER encoding. */
  12159. (void)type;
  12160. /* Validate parameters. */
  12161. if (key == NULL) {
  12162. ret = 0;
  12163. }
  12164. if (ret == 1) {
  12165. /* Make an RNG - create local or get global. */
  12166. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12167. if (rng == NULL) {
  12168. ret = 0;
  12169. }
  12170. }
  12171. /* Sign the digest with the key using the RNG and put signature into buffer
  12172. * update sigSz to be actual length.
  12173. */
  12174. if ((ret == 1) && (wc_ecc_sign_hash(digest, (word32)digestSz, sig, sigSz,
  12175. rng, (ecc_key*)key->internal) != 0)) {
  12176. ret = 0;
  12177. }
  12178. if (initTmpRng) {
  12179. wc_FreeRng(rng);
  12180. #ifdef WOLFSSL_SMALL_STACK
  12181. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12182. #endif
  12183. }
  12184. return ret;
  12185. }
  12186. /* Verify the signature with the digest and key.
  12187. *
  12188. * @param [in] type Digest algorithm used to create digest. Unused.
  12189. * @param [in] digest Digest of the message to verify.
  12190. * @param [in] digestSz Size of the digest in bytes.
  12191. * @param [in] sig Buffer holding signature.
  12192. * @param [in] sigSz Size of signature data in bytes.
  12193. * @param [in] key EC key containing public key.
  12194. * @return 1 when signature is valid.
  12195. * @return 0 when signature is invalid or error.
  12196. */
  12197. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12198. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12199. {
  12200. int ret = 1;
  12201. int verify = 0;
  12202. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12203. /* Digest algorithm not used in DER encoding. */
  12204. (void)type;
  12205. /* Validate parameters. */
  12206. if (key == NULL) {
  12207. ret = 0;
  12208. }
  12209. /* Verify signature using digest and key. */
  12210. if ((ret == 1) && (wc_ecc_verify_hash(sig, (word32)sigSz, digest,
  12211. (word32)digestSz, &verify, (ecc_key*)key->internal) != 0)) {
  12212. ret = 0;
  12213. }
  12214. /* When no error, verification may still have failed - check now. */
  12215. if ((ret == 1) && (verify != 1)) {
  12216. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12217. ret = 0;
  12218. }
  12219. return ret;
  12220. }
  12221. /* End ECDSA */
  12222. /* Start ECDH */
  12223. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12224. /* Compute the shared secret (key) using ECDH.
  12225. *
  12226. * KDF not supported.
  12227. *
  12228. * Return code compliant with OpenSSL.
  12229. *
  12230. * @param [out] out Buffer to hold key.
  12231. * @param [in] outLen Length of buffer in bytes.
  12232. * @param [in] pubKey Public key as an EC point.
  12233. * @param [in] privKey EC key holding a private key.
  12234. * @param [in] kdf Key derivation function to apply to secret.
  12235. * @return Length of computed key on success
  12236. * @return 0 on error.
  12237. */
  12238. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12239. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12240. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12241. {
  12242. int err = 0;
  12243. word32 len = 0;
  12244. ecc_key* key = NULL;
  12245. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12246. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12247. int setGlobalRNG = 0;
  12248. #endif
  12249. /* TODO: support using the KDF. */
  12250. (void)kdf;
  12251. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12252. /* Validate parameters. */
  12253. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12254. (privKey == NULL) || (privKey->internal == NULL)) {
  12255. WOLFSSL_MSG("Bad function arguments");
  12256. err = 1;
  12257. }
  12258. /* Ensure internal EC key is set from external. */
  12259. if ((!err) && (privKey->inSet == 0)) {
  12260. WOLFSSL_MSG("No EC key internal set, do it");
  12261. if (SetECKeyInternal(privKey) != 1) {
  12262. WOLFSSL_MSG("SetECKeyInternal failed");
  12263. err = 1;
  12264. }
  12265. }
  12266. if (!err) {
  12267. int ret;
  12268. /* Get the internal key. */
  12269. key = (ecc_key*)privKey->internal;
  12270. /* Set length into variable of type suitable for wolfSSL API. */
  12271. len = (word32)outLen;
  12272. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12273. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12274. /* An RNG is needed. */
  12275. if (key->rng == NULL) {
  12276. key->rng = wolfssl_make_global_rng();
  12277. /* RNG set and needs to be unset. */
  12278. setGlobalRNG = 1;
  12279. }
  12280. #endif
  12281. PRIVATE_KEY_UNLOCK();
  12282. /* Create secret using wolfSSL. */
  12283. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12284. (byte *)out, &len);
  12285. PRIVATE_KEY_LOCK();
  12286. if (ret != MP_OKAY) {
  12287. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12288. err = 1;
  12289. }
  12290. }
  12291. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12292. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12293. /* Remove global from key. */
  12294. if (setGlobalRNG) {
  12295. key->rng = NULL;
  12296. }
  12297. #endif
  12298. if (err) {
  12299. /* Make returned value zero. */
  12300. len = 0;
  12301. }
  12302. return (int)len;
  12303. }
  12304. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12305. /* End ECDH */
  12306. #endif /* OPENSSL_EXTRA */
  12307. #endif /* HAVE_ECC */
  12308. /*******************************************************************************
  12309. * END OF EC API
  12310. ******************************************************************************/
  12311. #endif /* !WOLFSSL_PK_INCLUDED */