pk.c 391 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730
  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_USER_RSA) || defined(HAVE_ECC) || \
  47. (!defined(NO_DSA) && !defined(HAVE_SELFTEST)))
  48. /* Forward declaration for wolfSSL_PEM_write_bio_DSA_PUBKEY.
  49. * Implementation in ssl.c.
  50. */
  51. static int pem_write_bio_pubkey(WOLFSSL_BIO* bio, WOLFSSL_EVP_PKEY* key);
  52. #endif
  53. /*******************************************************************************
  54. * COMMON FUNCTIONS
  55. ******************************************************************************/
  56. /* Calculate the number of bytes require to represent a length value in ASN.
  57. *
  58. * @param [in] l Length value to use.
  59. * @return Number of bytes required to represent length value.
  60. */
  61. #define ASN_LEN_SIZE(l) \
  62. (((l) < 128) ? 1 : (((l) < 256) ? 2 : 3))
  63. #if defined(OPENSSL_EXTRA)
  64. #ifndef NO_ASN
  65. #if (!defined(NO_FILESYSTEM) && (defined(OPENSSL_EXTRA) || \
  66. defined(OPENSSL_ALL))) || (!defined(NO_BIO) && defined(OPENSSL_EXTRA))
  67. /* Convert the PEM encoding in the buffer to DER.
  68. *
  69. * @param [in] pem Buffer containing PEM encoded data.
  70. * @param [in] pemSz Size of data in buffer in bytes.
  71. * @param [in] cb Password callback when PEM encrypted.
  72. * @param [in] pass NUL terminated string for passphrase when PEM
  73. * encrypted.
  74. * @param [in] keyType Type of key to match against PEM header/footer.
  75. * @param [out] keyFormat Format of key.
  76. * @param [out] der Buffer holding DER encoding.
  77. * @return Negative on failure.
  78. * @return Number of bytes consumed on success.
  79. */
  80. static int pem_mem_to_der(const char* pem, int pemSz, wc_pem_password_cb* cb,
  81. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  82. {
  83. #ifdef WOLFSSL_SMALL_STACK
  84. EncryptedInfo* info = NULL;
  85. #else
  86. EncryptedInfo info[1];
  87. #endif /* WOLFSSL_SMALL_STACK */
  88. wc_pem_password_cb* localCb = NULL;
  89. int ret = 0;
  90. if (cb != NULL) {
  91. localCb = cb;
  92. }
  93. else if (pass != NULL) {
  94. localCb = wolfSSL_PEM_def_callback;
  95. }
  96. #ifdef WOLFSSL_SMALL_STACK
  97. info = (EncryptedInfo*)XMALLOC(sizeof(EncryptedInfo), NULL,
  98. DYNAMIC_TYPE_ENCRYPTEDINFO);
  99. if (info == NULL) {
  100. WOLFSSL_ERROR_MSG("Error getting memory for EncryptedInfo structure");
  101. ret = MEMORY_E;
  102. }
  103. #endif /* WOLFSSL_SMALL_STACK */
  104. if (ret == 0) {
  105. XMEMSET(info, 0, sizeof(EncryptedInfo));
  106. info->passwd_cb = localCb;
  107. info->passwd_userdata = pass;
  108. /* Do not strip PKCS8 header */
  109. ret = PemToDer((const unsigned char *)pem, pemSz, keyType, der, NULL,
  110. info, keyFormat);
  111. if (ret < 0) {
  112. WOLFSSL_ERROR_MSG("Bad PEM To DER");
  113. }
  114. }
  115. if (ret >= 0) {
  116. ret = (int)info->consumed;
  117. }
  118. #ifdef WOLFSSL_SMALL_STACK
  119. XFREE(info, NULL, DYNAMIC_TYPE_ENCRYPTEDINFO);
  120. #endif
  121. return ret;
  122. }
  123. #endif
  124. #if !defined(NO_RSA) || !defined(WOLFCRYPT_ONLY)
  125. #ifndef NO_BIO
  126. /* Read PEM data from a BIO and decode to DER in a new buffer.
  127. *
  128. * @param [in, out] bio BIO object to read with.
  129. * @param [in] cb Password callback when PEM encrypted.
  130. * @param [in] pass NUL terminated string for passphrase when PEM
  131. * encrypted.
  132. * @param [in] keyType Type of key to match against PEM header/footer.
  133. * @param [out] keyFormat Format of key.
  134. * @param [out] der Buffer holding DER encoding.
  135. * @return Negative on failure.
  136. * @return Number of bytes consumed on success.
  137. */
  138. static int pem_read_bio_key(WOLFSSL_BIO* bio, wc_pem_password_cb* cb,
  139. void* pass, int keyType, int* keyFormat, DerBuffer** der)
  140. {
  141. int ret;
  142. char* mem = NULL;
  143. int memSz;
  144. int alloced = 0;
  145. ret = wolfssl_read_bio(bio, &mem, &memSz, &alloced);
  146. if (ret == 0) {
  147. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  148. /* Write left over data back to BIO if not a file BIO */
  149. if ((ret > 0) && ((memSz - ret) > 0) &&
  150. (bio->type != WOLFSSL_BIO_FILE)) {
  151. int res;
  152. res = wolfSSL_BIO_write(bio, mem + ret, memSz - ret);
  153. if (res != memSz - ret) {
  154. WOLFSSL_ERROR_MSG("Unable to write back excess data");
  155. if (res < 0) {
  156. ret = res;
  157. }
  158. else {
  159. ret = MEMORY_E;
  160. }
  161. }
  162. }
  163. if (alloced) {
  164. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  165. }
  166. }
  167. return ret;
  168. }
  169. #endif /* !NO_BIO */
  170. #if !defined(NO_FILESYSTEM)
  171. /* Read PEM data from a file and decode to DER in a new buffer.
  172. *
  173. * @param [in] fp File pointer to read with.
  174. * @param [in] cb Password callback when PEM encrypted.
  175. * @param [in] pass NUL terminated string for passphrase when PEM
  176. * encrypted.
  177. * @param [in] keyType Type of key to match against PEM header/footer.
  178. * @param [out] keyFormat Format of key.
  179. * @param [out] der Buffer holding DER encoding.
  180. * @return Negative on failure.
  181. * @return Number of bytes consumed on success.
  182. */
  183. static int pem_read_file_key(XFILE fp, wc_pem_password_cb* cb, void* pass,
  184. int keyType, int* keyFormat, DerBuffer** der)
  185. {
  186. int ret;
  187. char* mem = NULL;
  188. int memSz;
  189. ret = wolfssl_read_file(fp, &mem, &memSz);
  190. if (ret == 0) {
  191. ret = pem_mem_to_der(mem, memSz, cb, pass, keyType, keyFormat, der);
  192. XFREE(mem, NULL, DYNAMIC_TYPE_OPENSSL);
  193. }
  194. return ret;
  195. }
  196. #endif /* !NO_FILESYSTEM */
  197. #endif
  198. #if defined(OPENSSL_EXTRA) && ((!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) \
  199. && !defined(HAVE_USER_RSA)) || !defined(WOLFCRYPT_ONLY))
  200. /* Convert DER data to PEM in an allocated buffer.
  201. *
  202. * @param [in] der Buffer containing DER data.
  203. * @param [in] derSz Size of DER data in bytes.
  204. * @param [in] type Type of key being encoded.
  205. * @param [in] heap Heap hint for dynamic memory allocation.
  206. * @param [out] out Allocated buffer containing PEM.
  207. * @param [out] outSz Size of PEM encoding.
  208. * @return WOLFSSL_FAILURE on error.
  209. * @return WOLFSSL_SUCCESS on success.
  210. */
  211. static int der_to_pem_alloc(const unsigned char* der, int derSz, int type,
  212. void* heap, byte** out, int* outSz)
  213. {
  214. int ret = WOLFSSL_SUCCESS;
  215. int pemSz;
  216. byte* pem = NULL;
  217. (void)heap;
  218. pemSz = wc_DerToPem(der, derSz, NULL, 0, type);
  219. if (pemSz < 0) {
  220. ret = WOLFSSL_FAILURE;
  221. }
  222. if (ret == WOLFSSL_SUCCESS) {
  223. pem = (byte*)XMALLOC(pemSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  224. if (pem == NULL) {
  225. ret = WOLFSSL_FAILURE;
  226. }
  227. }
  228. if ((ret == WOLFSSL_SUCCESS) && (wc_DerToPem(der, derSz, pem, pemSz,
  229. type) < 0)) {
  230. ret = WOLFSSL_FAILURE;
  231. XFREE(pem, heap, DYNAMIC_TYPE_TMP_BUFFER);
  232. pem = NULL;
  233. }
  234. *out = pem;
  235. *outSz = pemSz;
  236. return ret;
  237. }
  238. #ifndef NO_BIO
  239. /* Write the DER data as PEM into BIO.
  240. *
  241. * @param [in] der Buffer containing DER data.
  242. * @param [in] derSz Size of DER data in bytes.
  243. * @param [in, out] bio BIO object to write with.
  244. * @param [in] type Type of key being encoded.
  245. * @return WOLFSSL_FAILURE on error.
  246. * @return WOLFSSL_SUCCESS on success.
  247. */
  248. static int der_write_to_bio_as_pem(const unsigned char* der, int derSz,
  249. WOLFSSL_BIO* bio, int type)
  250. {
  251. int ret;
  252. int pemSz;
  253. byte* pem = NULL;
  254. ret = der_to_pem_alloc(der, derSz, type, bio->heap, &pem, &pemSz);
  255. if (ret == WOLFSSL_SUCCESS) {
  256. int len = wolfSSL_BIO_write(bio, pem, pemSz);
  257. if (len != pemSz) {
  258. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  259. ret = WOLFSSL_FAILURE;
  260. }
  261. }
  262. XFREE(pem, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  263. return ret;
  264. }
  265. #endif
  266. #endif
  267. #if (!defined(NO_RSA) && defined(WOLFSSL_KEY_GEN) && \
  268. !defined(HAVE_USER_RSA)) || \
  269. (!defined(NO_DH) && defined(WOLFSSL_DH_EXTRA)) || \
  270. (defined(HAVE_ECC) && defined(WOLFSSL_KEY_GEN))
  271. #if !defined(NO_FILESYSTEM)
  272. /* Write the DER data as PEM into file pointer.
  273. *
  274. * @param [in] der Buffer containing DER data.
  275. * @param [in] derSz Size of DER data in bytes.
  276. * @param [in] fp File pointer to write with.
  277. * @param [in] type Type of key being encoded.
  278. * @param [in] heap Heap hint for dynamic memory allocation.
  279. * @return WOLFSSL_FAILURE on error.
  280. * @return WOLFSSL_SUCCESS on success.
  281. */
  282. static int der_write_to_file_as_pem(const unsigned char* der, int derSz,
  283. XFILE fp, int type, void* heap)
  284. {
  285. int ret;
  286. int pemSz;
  287. byte* pem = NULL;
  288. ret = der_to_pem_alloc(der, derSz, type, heap, &pem, &pemSz);
  289. if (ret == WOLFSSL_SUCCESS) {
  290. int len = (int)XFWRITE(pem, 1, pemSz, fp);
  291. if (len != pemSz) {
  292. WOLFSSL_ERROR_MSG("Unable to write full PEM to BIO");
  293. ret = WOLFSSL_FAILURE;
  294. }
  295. }
  296. XFREE(pem, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  297. return ret;
  298. }
  299. #endif
  300. #endif
  301. #if defined(WOLFSSL_KEY_GEN) && \
  302. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)) && \
  303. ((!defined(NO_RSA) && !defined(HAVE_USER_RSA)) || defined(HAVE_ECC))
  304. static int der_to_enc_pem_alloc(unsigned char* der, int derSz,
  305. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz, int type,
  306. void* heap, byte** out, int* outSz)
  307. {
  308. int ret = 1;
  309. byte* tmp = NULL;
  310. byte* cipherInfo = NULL;
  311. int pemSz = 0;
  312. /* Macro doesn't always use it. */
  313. (void)heap;
  314. /* Encrypt DER buffer if required. */
  315. if ((ret == 1) && (passwd != NULL) && (passwdSz > 0) && (cipher != NULL)) {
  316. int blockSz = wolfSSL_EVP_CIPHER_block_size(cipher);
  317. byte *tmpBuf;
  318. /* Add space for padding. */
  319. tmpBuf = (byte*)XREALLOC(der, derSz + blockSz, heap,
  320. DYNAMIC_TYPE_TMP_BUFFER);
  321. if (tmpBuf == NULL) {
  322. WOLFSSL_ERROR_MSG("Extending DER buffer failed");
  323. XFREE(der, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  324. ret = 0;
  325. }
  326. else {
  327. der = tmpBuf;
  328. /* Encrypt DER inline. */
  329. ret = EncryptDerKey(der, &derSz, cipher, passwd, passwdSz,
  330. &cipherInfo, derSz + blockSz);
  331. if (ret != 1) {
  332. WOLFSSL_ERROR_MSG("EncryptDerKey failed");
  333. }
  334. }
  335. }
  336. if (ret == 1) {
  337. /* Calculate PEM encoding size. */
  338. pemSz = wc_DerToPemEx(der, derSz, NULL, 0, cipherInfo, type);
  339. if (pemSz <= 0) {
  340. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  341. ret = 0;
  342. }
  343. }
  344. if (ret == 1) {
  345. /* Allocate space for PEM encoding plus a NUL terminator. */
  346. tmp = (byte*)XMALLOC(pemSz + 1, NULL, DYNAMIC_TYPE_KEY);
  347. if (tmp == NULL) {
  348. WOLFSSL_ERROR_MSG("malloc failed");
  349. ret = 0;
  350. }
  351. }
  352. if (ret == 1) {
  353. /* DER to PEM */
  354. pemSz = wc_DerToPemEx(der, derSz, tmp, pemSz, cipherInfo, type);
  355. if (pemSz <= 0) {
  356. WOLFSSL_ERROR_MSG("wc_DerToPemEx failed");
  357. ret = 0;
  358. }
  359. }
  360. if (ret == 1) {
  361. /* NUL terminate string - PEM. */
  362. tmp[pemSz] = 0x00;
  363. /* Return allocated buffer and size. */
  364. *out = tmp;
  365. *outSz = pemSz;
  366. /* Don't free returning buffer. */
  367. tmp = NULL;
  368. }
  369. XFREE(tmp, NULL, DYNAMIC_TYPE_KEY);
  370. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  371. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  372. return ret;
  373. }
  374. #endif
  375. #endif /* !NO_ASN */
  376. #if !defined(NO_CERTS) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  377. !defined(NO_STDIO_FILESYSTEM) && (!defined(NO_RSA) || !defined(NO_DSA) || \
  378. defined(HAVE_ECC)) && defined(OPENSSL_EXTRA)
  379. /* Print the number bn in hex with name field and indentation indent to file fp.
  380. *
  381. * Used by wolfSSL_DSA_print_fp, wolfSSL_RSA_print_fp and
  382. * wolfSSL_EC_KEY_print_fp to print DSA, RSA and ECC keys and parameters.
  383. *
  384. * @param [in] fp File pointer to write to.
  385. * @param [in] indent Number of spaces to prepend to each line.
  386. * @param [in] field Name of field.
  387. * @param [in] bn Big number to print.
  388. * @return 1 on success.
  389. * @return 0 on failure.
  390. * @return BAD_FUNC_ARG when fp is invalid, indent is less than 0, or field or
  391. * bn or NULL.
  392. */
  393. static int pk_bn_field_print_fp(XFILE fp, int indent, const char* field,
  394. const WOLFSSL_BIGNUM* bn)
  395. {
  396. static const int HEX_INDENT = 4;
  397. static const int MAX_DIGITS_PER_LINE = 30;
  398. int ret = 1;
  399. int i = 0;
  400. char* buf = NULL;
  401. /* Internal function - assume parameters are valid. */
  402. /* Convert BN to hexadecimal character array (allocates buffer). */
  403. buf = wolfSSL_BN_bn2hex(bn);
  404. if (buf == NULL) {
  405. ret = 0;
  406. }
  407. if (ret == 1) {
  408. /* Print leading spaces, name and spaces before data. */
  409. if (indent > 0) {
  410. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  411. ret = 0;
  412. }
  413. }
  414. if (ret == 1) {
  415. if (XFPRINTF(fp, "%s:\n", field) < 0)
  416. ret = 0;
  417. }
  418. if (ret == 1) {
  419. if (indent > 0) {
  420. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  421. ret = 0;
  422. }
  423. }
  424. if (ret == 1) {
  425. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0)
  426. ret = 0;
  427. }
  428. if (ret == 1) {
  429. /* Print first byte - should always exist. */
  430. if ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  431. if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  432. ret = 0;
  433. else if (XFPRINTF(fp, "%c", buf[i++]) < 0)
  434. ret = 0;
  435. }
  436. }
  437. if (ret == 1) {
  438. /* Print each hexadecimal character with byte separator. */
  439. while ((buf[i] != '\0') && (buf[i+1] != '\0')) {
  440. /* Byte separator every two nibbles - one byte. */
  441. if (XFPRINTF(fp, ":") < 0) {
  442. ret = 0;
  443. break;
  444. }
  445. /* New line after every 15 bytes - 30 nibbles. */
  446. if (i % MAX_DIGITS_PER_LINE == 0) {
  447. if (XFPRINTF(fp, "\n") < 0) {
  448. ret = 0;
  449. break;
  450. }
  451. if (indent > 0) {
  452. if (XFPRINTF(fp, "%*s", indent, "") < 0) {
  453. ret = 0;
  454. break;
  455. }
  456. }
  457. if (XFPRINTF(fp, "%*s", HEX_INDENT, "") < 0) {
  458. ret = 0;
  459. break;
  460. }
  461. }
  462. /* Print two nibbles - one byte. */
  463. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  464. ret = 0;
  465. break;
  466. }
  467. if (XFPRINTF(fp, "%c", buf[i++]) < 0) {
  468. ret = 0;
  469. break;
  470. }
  471. }
  472. /* Ensure on new line after data. */
  473. if (XFPRINTF(fp, "\n") < 0) {
  474. ret = 0;
  475. }
  476. }
  477. /* Dispose of any allocated character array. */
  478. XFREE(buf, NULL, DYNAMIC_TYPE_OPENSSL);
  479. return ret;
  480. }
  481. #endif /* !NO_CERTS && XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM &&
  482. * (!NO_DSA || !NO_RSA || HAVE_ECC) */
  483. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(NO_RSA) && \
  484. !defined(HAVE_FAST_RSA)
  485. /* snprintf() must be available */
  486. /* Maximum number of extra indent spaces on each line. */
  487. #define PRINT_NUM_MAX_INDENT 48
  488. /* Maximum size of a line containing a value. */
  489. #define PRINT_NUM_MAX_VALUE_LINE PRINT_NUM_MAX_INDENT
  490. /* Number of leading spaces on each line. */
  491. #define PRINT_NUM_INDENT_CNT 4
  492. /* Indent spaces for number lines. */
  493. #define PRINT_NUM_INDENT " "
  494. /* 4 leading spaces and 15 bytes with colons is a complete line. */
  495. #define PRINT_NUM_MAX_DIGIT_LINE (PRINT_NUM_INDENT_CNT + 3 * 15)
  496. /* Print indent to BIO.
  497. *
  498. * @param [in] bio BIO object to write to.
  499. * @param [in] line Buffer to put characters to before writing to BIO.
  500. * @param [in] lineLen Length of buffer.
  501. * @return 1 on success.
  502. * @return 0 on failure.
  503. */
  504. static int wolfssl_print_indent(WOLFSSL_BIO* bio, char* line, int lineLen,
  505. int indent)
  506. {
  507. int ret = 1;
  508. if (indent > 0) {
  509. /* Print indent spaces. */
  510. int len_wanted = XSNPRINTF(line, lineLen, "%*s", indent, " ");
  511. if (len_wanted >= lineLen) {
  512. WOLFSSL_ERROR_MSG("Buffer overflow formatting indentation");
  513. ret = 0;
  514. }
  515. else {
  516. /* Write indents string to BIO */
  517. if (wolfSSL_BIO_write(bio, line, len_wanted) <= 0) {
  518. ret = 0;
  519. }
  520. }
  521. }
  522. return ret;
  523. }
  524. /* Print out name, and value in decimal and hex to BIO.
  525. *
  526. * @param [in] bio BIO object to write to.
  527. * @param [in] value MP integer to write.
  528. * @param [in] name Name of value.
  529. * @param [in] indent Number of leading spaces before line.
  530. * @return 1 on success.
  531. * @return 0 on failure.
  532. */
  533. static int wolfssl_print_value(WOLFSSL_BIO* bio, mp_int* value,
  534. const char* name, int indent)
  535. {
  536. int ret = 1;
  537. int len;
  538. char line[PRINT_NUM_MAX_VALUE_LINE + 1];
  539. /* Get the length of hex encoded value. */
  540. len = mp_unsigned_bin_size(value);
  541. /* Value must no more than 32-bits - 4 bytes. */
  542. if ((len < 0) || (len > 4)) {
  543. WOLFSSL_ERROR_MSG("Error getting exponent size");
  544. ret = 0;
  545. }
  546. if (ret == 1) {
  547. /* Print any indent spaces. */
  548. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  549. }
  550. if (ret == 1) {
  551. /* Get 32-bits of value. */
  552. word32 v = (word32)value->dp[0];
  553. /* Print the line to the string. */
  554. len = (int)XSNPRINTF(line, sizeof(line), "%s %u (0x%x)\n", name, v,
  555. v);
  556. if (len >= (int)sizeof(line)) {
  557. WOLFSSL_ERROR_MSG("Buffer overflow while formatting value");
  558. ret = 0;
  559. } else {
  560. /* Write string to BIO */
  561. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  562. ret = 0;
  563. }
  564. }
  565. }
  566. return ret;
  567. }
  568. /* Print out name and multi-precision number to BIO.
  569. *
  570. * @param [in] bio BIO object to write to.
  571. * @param [in] num MP integer to write.
  572. * @param [in] name Name of value.
  573. * @param [in] indent Number of leading spaces before each line.
  574. * @return 1 on success.
  575. * @return 0 on failure.
  576. */
  577. static int wolfssl_print_number(WOLFSSL_BIO* bio, mp_int* num, const char* name,
  578. int indent)
  579. {
  580. int ret = 1;
  581. int rawLen = 0;
  582. byte* rawKey = NULL;
  583. char line[PRINT_NUM_MAX_DIGIT_LINE + 1];
  584. int li = 0; /* Line index. */
  585. int i;
  586. /* Allocate a buffer to hold binary encoded data. */
  587. rawLen = mp_unsigned_bin_size(num);
  588. if (rawLen == 0) {
  589. WOLFSSL_ERROR_MSG("Invalid number");
  590. ret = 0;
  591. }
  592. if (ret == 1) {
  593. rawKey = (byte*)XMALLOC(rawLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  594. if (rawKey == NULL) {
  595. WOLFSSL_ERROR_MSG("Memory allocation error");
  596. ret = 0;
  597. }
  598. }
  599. /* Encode number as big-endian byte array. */
  600. if ((ret == 1) && (mp_to_unsigned_bin(num, rawKey) < 0)) {
  601. ret = 0;
  602. }
  603. if (ret == 1) {
  604. /* Print any indent spaces. */
  605. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  606. }
  607. if (ret == 1) {
  608. /* Print header string line to string. */
  609. li = XSNPRINTF(line, sizeof(line), "%s\n", name);
  610. if (li >= (int)sizeof(line)) {
  611. WOLFSSL_ERROR_MSG("Buffer overflow formatting name");
  612. ret = 0;
  613. }
  614. else {
  615. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  616. ret = 0;
  617. }
  618. }
  619. }
  620. if (ret == 1) {
  621. /* Print any indent spaces. */
  622. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  623. }
  624. if (ret == 1) {
  625. /* Start first digit line with spaces.
  626. * Writing out zeros ensures number is a positive value. */
  627. li = XSNPRINTF(line, sizeof(line), PRINT_NUM_INDENT "%s",
  628. mp_leading_bit(num) ? "00:" : "");
  629. if (li >= (int)sizeof(line)) {
  630. WOLFSSL_ERROR_MSG("Buffer overflow formatting spaces");
  631. ret = 0;
  632. }
  633. }
  634. /* Put out each line of numbers. */
  635. for (i = 0; (ret == 1) && (i < rawLen); i++) {
  636. /* Encode another byte as 2 hex digits and append colon. */
  637. int len_wanted = XSNPRINTF(line + li, sizeof(line) - li, "%02x:",
  638. rawKey[i]);
  639. /* Check if there was room -- if not, print the current line, not
  640. * including the newest octet.
  641. */
  642. if (len_wanted >= (int)sizeof(line) - li) {
  643. /* bump current octet to the next line. */
  644. --i;
  645. /* More bytes coming so add a line break. */
  646. line[li++] = '\n';
  647. /* Write out the line. */
  648. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  649. ret = 0;
  650. }
  651. if (ret == 1) {
  652. /* Print any indent spaces. */
  653. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  654. }
  655. /* Put the leading spaces on new line. */
  656. XSTRNCPY(line, PRINT_NUM_INDENT, PRINT_NUM_INDENT_CNT + 1);
  657. li = PRINT_NUM_INDENT_CNT;
  658. }
  659. else {
  660. li += len_wanted;
  661. }
  662. }
  663. if (ret == 1) {
  664. /* Put out last line - replace last colon with carriage return. */
  665. line[li-1] = '\n';
  666. if (wolfSSL_BIO_write(bio, line, li) <= 0) {
  667. ret = 0;
  668. }
  669. }
  670. /* Dispose of any allocated data. */
  671. XFREE(rawKey, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  672. return ret;
  673. }
  674. #endif /* XSNPRINTF && !NO_BIO && !NO_RSA && !HAVE_FAST_RSA */
  675. #if !defined(NO_RSA) || (!defined(NO_DH) && !defined(NO_CERTS) && \
  676. defined(HAVE_FIPS) && !FIPS_VERSION_GT(2,0)) || defined(HAVE_ECC)
  677. /* Uses the DER SEQUENCE to determine size of DER data.
  678. *
  679. * Outer SEQUENCE encapsulates all the DER encoding.
  680. * Add the length of the SEQUENCE data to the length of the SEQUENCE header.
  681. *
  682. * @param [in] seq Buffer holding DER encoded sequence.
  683. * @param [in] len Length of data in buffer (may be larger than SEQ).
  684. * @return Size of complete DER encoding on success.
  685. * @return 0 on failure.
  686. */
  687. static int wolfssl_der_length(const unsigned char* seq, int len)
  688. {
  689. int ret = 0;
  690. word32 i = 0;
  691. /* Check it is a SEQUENCE and get the length of the underlying data.
  692. * i is updated to be after SEQUENCE header bytes.
  693. */
  694. if (GetSequence_ex(seq, &i, &ret, len, 0) >= 0) {
  695. /* Add SEQUENCE header length to underlying data length. */
  696. ret += (int)i;
  697. }
  698. return ret;
  699. }
  700. #endif /* !NO_RSA */
  701. #endif /* OPENSSL_EXTRA */
  702. /*******************************************************************************
  703. * START OF RSA API
  704. ******************************************************************************/
  705. #ifndef NO_RSA
  706. /*
  707. * RSA METHOD
  708. * Could be used to hold function pointers to implementations of RSA operations.
  709. */
  710. #if defined(OPENSSL_EXTRA)
  711. /* Return a blank RSA method and set the name and flags.
  712. *
  713. * Only one implementation of RSA operations.
  714. * name is duplicated.
  715. *
  716. * @param [in] name Name to use in method.
  717. * @param [in] flags Flags to set into method.
  718. * @return Newly allocated RSA method on success.
  719. * @return NULL on failure.
  720. */
  721. WOLFSSL_RSA_METHOD *wolfSSL_RSA_meth_new(const char *name, int flags)
  722. {
  723. WOLFSSL_RSA_METHOD* meth = NULL;
  724. int name_len = 0;
  725. int err;
  726. /* Validate name is not NULL. */
  727. err = (name == NULL);
  728. if (!err) {
  729. /* Allocate an RSA METHOD to return. */
  730. meth = (WOLFSSL_RSA_METHOD*)XMALLOC(sizeof(WOLFSSL_RSA_METHOD), NULL,
  731. DYNAMIC_TYPE_OPENSSL);
  732. err = (meth == NULL);
  733. }
  734. if (!err) {
  735. XMEMSET(meth, 0, sizeof(*meth));
  736. meth->flags = flags;
  737. meth->dynamic = 1;
  738. name_len = (int)XSTRLEN(name);
  739. meth->name = (char*)XMALLOC(name_len + 1, NULL, DYNAMIC_TYPE_OPENSSL);
  740. err = (meth->name == NULL);
  741. }
  742. if (!err) {
  743. XMEMCPY(meth->name, name, name_len+1);
  744. }
  745. if (err) {
  746. /* meth->name won't be allocated on error. */
  747. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  748. }
  749. return meth;
  750. }
  751. /* Default RSA method is one with wolfSSL name and no flags.
  752. *
  753. * @return Newly allocated wolfSSL RSA method on success.
  754. * @return NULL on failure.
  755. */
  756. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_default_method(void)
  757. {
  758. static const WOLFSSL_RSA_METHOD wolfssl_rsa_meth = {
  759. 0, /* No flags. */
  760. (char*)"wolfSSL RSA",
  761. 0 /* Static definition. */
  762. };
  763. return &wolfssl_rsa_meth;
  764. }
  765. /* Dispose of RSA method and allocated data.
  766. *
  767. * @param [in] meth RSA method to free.
  768. */
  769. void wolfSSL_RSA_meth_free(WOLFSSL_RSA_METHOD *meth)
  770. {
  771. /* Free method if available and dynamically allocated. */
  772. if ((meth != NULL) && meth->dynamic) {
  773. /* Name was duplicated and must be freed. */
  774. XFREE(meth->name, NULL, DYNAMIC_TYPE_OPENSSL);
  775. /* Dispose of RSA method. */
  776. XFREE(meth, NULL, DYNAMIC_TYPE_OPENSSL);
  777. }
  778. }
  779. #ifndef NO_WOLFSSL_STUB
  780. /* Stub function for any RSA method setting function.
  781. *
  782. * Nothing is stored - not even flags or name.
  783. *
  784. * @param [in] meth RSA method.
  785. * @param [in] p A pointer.
  786. * @return 1 to indicate success.
  787. */
  788. int wolfSSL_RSA_meth_set(WOLFSSL_RSA_METHOD *meth, void* p)
  789. {
  790. WOLFSSL_STUB("RSA_METHOD is not implemented.");
  791. (void)meth;
  792. (void)p;
  793. return 1;
  794. }
  795. #endif /* !NO_WOLFSSL_STUB */
  796. #endif /* OPENSSL_EXTRA */
  797. /*
  798. * RSA constructor/deconstructor APIs
  799. */
  800. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  801. /* Dispose of RSA key and allocated data.
  802. *
  803. * Cannot use rsa after this call.
  804. *
  805. * @param [in] rsa RSA key to free.
  806. */
  807. void wolfSSL_RSA_free(WOLFSSL_RSA* rsa)
  808. {
  809. int doFree = 1;
  810. WOLFSSL_ENTER("wolfSSL_RSA_free");
  811. /* Validate parameter. */
  812. if (rsa == NULL) {
  813. doFree = 0;
  814. }
  815. if (doFree) {
  816. int err;
  817. /* Decrement reference count. */
  818. wolfSSL_RefDec(&rsa->ref, &doFree, &err);
  819. #ifndef WOLFSSL_REFCNT_ERROR_RETURN
  820. (void)err;
  821. #endif
  822. }
  823. if (doFree) {
  824. void* heap = rsa->heap;
  825. /* Dispose of allocated reference counting data. */
  826. wolfSSL_RefFree(&rsa->ref);
  827. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  828. wolfSSL_CRYPTO_cleanup_ex_data(&rsa->ex_data);
  829. #endif
  830. if (rsa->internal != NULL) {
  831. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  832. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  833. /* Check if RNG is owned before freeing it. */
  834. if (rsa->ownRng) {
  835. WC_RNG* rng = ((RsaKey*)(rsa->internal))->rng;
  836. if ((rng != NULL) && (rng != wolfssl_get_global_rng())) {
  837. wc_FreeRng(rng);
  838. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  839. }
  840. /* RNG isn't freed by wolfCrypt RSA free. */
  841. }
  842. #endif
  843. /* Dispose of allocated data in wolfCrypt RSA key. */
  844. wc_FreeRsaKey((RsaKey*)rsa->internal);
  845. /* Dispose of memory for wolfCrypt RSA key. */
  846. XFREE(rsa->internal, heap, DYNAMIC_TYPE_RSA);
  847. }
  848. /* Dispose of external representation of RSA values. */
  849. wolfSSL_BN_clear_free(rsa->iqmp);
  850. wolfSSL_BN_clear_free(rsa->dmq1);
  851. wolfSSL_BN_clear_free(rsa->dmp1);
  852. wolfSSL_BN_clear_free(rsa->q);
  853. wolfSSL_BN_clear_free(rsa->p);
  854. wolfSSL_BN_clear_free(rsa->d);
  855. wolfSSL_BN_free(rsa->e);
  856. wolfSSL_BN_free(rsa->n);
  857. #if defined(OPENSSL_EXTRA)
  858. if (rsa->meth) {
  859. wolfSSL_RSA_meth_free((WOLFSSL_RSA_METHOD*)rsa->meth);
  860. }
  861. #endif
  862. /* Set back to NULLs for safety. */
  863. ForceZero(rsa, sizeof(*rsa));
  864. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  865. (void)heap;
  866. }
  867. }
  868. /* Allocate and initialize a new RSA key.
  869. *
  870. * Not OpenSSL API.
  871. *
  872. * @param [in] heap Heap hint for dynamic memory allocation.
  873. * @param [in] devId Device identifier value.
  874. * @return RSA key on success.
  875. * @return NULL on failure.
  876. */
  877. WOLFSSL_RSA* wolfSSL_RSA_new_ex(void* heap, int devId)
  878. {
  879. WOLFSSL_RSA* rsa = NULL;
  880. RsaKey* key = NULL;
  881. int err = 0;
  882. int rsaKeyInited = 0;
  883. WOLFSSL_ENTER("wolfSSL_RSA_new");
  884. /* Allocate memory for new wolfCrypt RSA key. */
  885. key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
  886. if (key == NULL) {
  887. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc RsaKey failure");
  888. err = 1;
  889. }
  890. if (!err) {
  891. /* Allocate memory for new RSA key. */
  892. rsa = (WOLFSSL_RSA*)XMALLOC(sizeof(WOLFSSL_RSA), heap,
  893. DYNAMIC_TYPE_RSA);
  894. if (rsa == NULL) {
  895. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new malloc WOLFSSL_RSA failure");
  896. err = 1;
  897. }
  898. }
  899. if (!err) {
  900. /* Clear all fields of RSA key. */
  901. XMEMSET(rsa, 0, sizeof(WOLFSSL_RSA));
  902. /* Cache heap to use for all allocations. */
  903. rsa->heap = heap;
  904. #ifdef OPENSSL_EXTRA
  905. /* Always have a method set. */
  906. rsa->meth = wolfSSL_RSA_get_default_method();
  907. #endif
  908. /* Initialize reference counting. */
  909. wolfSSL_RefInit(&rsa->ref, &err);
  910. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  911. }
  912. if (!err) {
  913. #endif
  914. /* Initialize wolfCrypt RSA key. */
  915. if (wc_InitRsaKey_ex(key, heap, devId) != 0) {
  916. WOLFSSL_ERROR_MSG("InitRsaKey WOLFSSL_RSA failure");
  917. err = 1;
  918. }
  919. else {
  920. rsaKeyInited = 1;
  921. }
  922. }
  923. #if !defined(HAVE_FIPS) && !defined(HAVE_USER_RSA) && \
  924. !defined(HAVE_FAST_RSA) && defined(WC_RSA_BLINDING)
  925. if (!err) {
  926. WC_RNG* rng;
  927. /* Create a local RNG. */
  928. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), heap, DYNAMIC_TYPE_RNG);
  929. if ((rng != NULL) && (wc_InitRng_ex(rng, heap, devId) != 0)) {
  930. WOLFSSL_MSG("InitRng failure, attempting to use global RNG");
  931. XFREE(rng, heap, DYNAMIC_TYPE_RNG);
  932. rng = NULL;
  933. }
  934. rsa->ownRng = 1;
  935. if (rng == NULL) {
  936. /* Get the wolfSSL global RNG - not thread safe. */
  937. rng = wolfssl_get_global_rng();
  938. rsa->ownRng = 0;
  939. }
  940. if (rng == NULL) {
  941. /* Couldn't create global either. */
  942. WOLFSSL_ERROR_MSG("wolfSSL_RSA_new no WC_RNG for blinding");
  943. err = 1;
  944. }
  945. else {
  946. /* Set the local or global RNG into the wolfCrypt RSA key. */
  947. (void)wc_RsaSetRNG(key, rng);
  948. /* Won't fail as key and rng are not NULL. */
  949. }
  950. }
  951. #endif /* !HAVE_FIPS && !HAVE_USER_RSA && !HAVE_FAST_RSA &&
  952. * WC_RSA_BLINDING */
  953. if (!err) {
  954. /* Set wolfCrypt RSA key into RSA key. */
  955. rsa->internal = key;
  956. /* Data from external RSA key has not been set into internal one. */
  957. rsa->inSet = 0;
  958. }
  959. if (err) {
  960. /* Dispose of any allocated data on error. */
  961. /* No failure after RNG allocation - no need to free RNG. */
  962. if (rsaKeyInited) {
  963. wc_FreeRsaKey(key);
  964. }
  965. XFREE(key, heap, DYNAMIC_TYPE_RSA);
  966. XFREE(rsa, heap, DYNAMIC_TYPE_RSA);
  967. /* Return NULL. */
  968. rsa = NULL;
  969. }
  970. return rsa;
  971. }
  972. /* Allocate and initialize a new RSA key.
  973. *
  974. * @return RSA key on success.
  975. * @return NULL on failure.
  976. */
  977. WOLFSSL_RSA* wolfSSL_RSA_new(void)
  978. {
  979. /* Call wolfSSL API to do work. */
  980. return wolfSSL_RSA_new_ex(NULL, INVALID_DEVID);
  981. }
  982. /* Increments ref count of RSA key.
  983. *
  984. * @param [in, out] rsa RSA key.
  985. * @return 1 on success
  986. * @return 0 on error
  987. */
  988. int wolfSSL_RSA_up_ref(WOLFSSL_RSA* rsa)
  989. {
  990. int err = 0;
  991. if (rsa != NULL) {
  992. wolfSSL_RefInc(&rsa->ref, &err);
  993. }
  994. return !err;
  995. }
  996. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  997. #ifdef OPENSSL_EXTRA
  998. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  999. /* Allocate a new RSA key and make it a copy.
  1000. *
  1001. * Encodes to and from DER to copy.
  1002. *
  1003. * @param [in] rsa RSA key to duplicate.
  1004. * @return RSA key on success.
  1005. * @return NULL on error.
  1006. */
  1007. WOLFSSL_RSA* wolfSSL_RSAPublicKey_dup(WOLFSSL_RSA *rsa)
  1008. {
  1009. WOLFSSL_RSA* ret = NULL;
  1010. int derSz = 0;
  1011. byte* derBuf = NULL;
  1012. int err;
  1013. WOLFSSL_ENTER("wolfSSL_RSAPublicKey_dup");
  1014. err = (rsa == NULL);
  1015. if (!err) {
  1016. /* Create a new RSA key to return. */
  1017. ret = wolfSSL_RSA_new();
  1018. if (ret == NULL) {
  1019. WOLFSSL_ERROR_MSG("Error creating a new WOLFSSL_RSA structure");
  1020. err = 1;
  1021. }
  1022. }
  1023. if (!err) {
  1024. /* Encode RSA public key to copy to DER - allocates DER buffer. */
  1025. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1026. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1027. err = 1;
  1028. }
  1029. }
  1030. if (!err) {
  1031. /* Decode DER of the RSA public key into new key. */
  1032. if (wolfSSL_RSA_LoadDer_ex(ret, derBuf, derSz,
  1033. WOLFSSL_RSA_LOAD_PUBLIC) != 1) {
  1034. WOLFSSL_ERROR_MSG("wolfSSL_RSA_LoadDer_ex failed");
  1035. err = 1;
  1036. }
  1037. }
  1038. /* Dispose of any allocated DER buffer. */
  1039. XFREE(derBuf, rsa ? rsa->heap : NULL, DYNAMIC_TYPE_ASN1);
  1040. if (err) {
  1041. /* Disposes of any created RSA key - on error. */
  1042. wolfSSL_RSA_free(ret);
  1043. ret = NULL;
  1044. }
  1045. return ret;
  1046. }
  1047. /* wolfSSL_RSAPrivateKey_dup not supported */
  1048. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1049. #ifndef HAVE_USER_RSA
  1050. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1051. void* heap);
  1052. #endif
  1053. /*
  1054. * RSA to/from bin APIs
  1055. */
  1056. /* Convert RSA public key data to internal.
  1057. *
  1058. * Creates new RSA key from the DER encoded RSA public key.
  1059. *
  1060. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1061. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1062. * @param [in] derSz Length of the data in the DER buffer.
  1063. * @return RSA key on success.
  1064. * @return NULL on failure.
  1065. */
  1066. WOLFSSL_RSA *wolfSSL_d2i_RSAPublicKey(WOLFSSL_RSA **out,
  1067. const unsigned char **derBuf, long derSz)
  1068. {
  1069. WOLFSSL_RSA *rsa = NULL;
  1070. int err = 0;
  1071. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1072. /* Validate parameters. */
  1073. if (derBuf == NULL) {
  1074. WOLFSSL_ERROR_MSG("Bad argument");
  1075. err = 1;
  1076. }
  1077. /* Create a new RSA key to return. */
  1078. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1079. WOLFSSL_ERROR_MSG("RSA_new failed");
  1080. err = 1;
  1081. }
  1082. /* Decode RSA key from DER. */
  1083. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1084. WOLFSSL_RSA_LOAD_PUBLIC) != 1)) {
  1085. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1086. err = 1;
  1087. }
  1088. if ((!err) && (out != NULL)) {
  1089. /* Return through parameter too. */
  1090. *out = rsa;
  1091. /* Move buffer on by the used amount. */
  1092. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1093. }
  1094. if (err) {
  1095. /* Dispose of any created RSA key. */
  1096. wolfSSL_RSA_free(rsa);
  1097. rsa = NULL;
  1098. }
  1099. return rsa;
  1100. }
  1101. /* Convert RSA private key data to internal.
  1102. *
  1103. * Create a new RSA key from the DER encoded RSA private key.
  1104. *
  1105. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1106. * @param [in, out] derBuf Pointer to start of DER encoded data.
  1107. * @param [in] derSz Length of the data in the DER buffer.
  1108. * @return RSA key on success.
  1109. * @return NULL on failure.
  1110. */
  1111. WOLFSSL_RSA *wolfSSL_d2i_RSAPrivateKey(WOLFSSL_RSA **out,
  1112. const unsigned char **derBuf, long derSz)
  1113. {
  1114. WOLFSSL_RSA *rsa = NULL;
  1115. int err = 0;
  1116. WOLFSSL_ENTER("wolfSSL_d2i_RSAPublicKey");
  1117. /* Validate parameters. */
  1118. if (derBuf == NULL) {
  1119. WOLFSSL_ERROR_MSG("Bad argument");
  1120. err = 1;
  1121. }
  1122. /* Create a new RSA key to return. */
  1123. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  1124. WOLFSSL_ERROR_MSG("RSA_new failed");
  1125. err = 1;
  1126. }
  1127. /* Decode RSA key from DER. */
  1128. if ((!err) && (wolfSSL_RSA_LoadDer_ex(rsa, *derBuf, (int)derSz,
  1129. WOLFSSL_RSA_LOAD_PRIVATE) != 1)) {
  1130. WOLFSSL_ERROR_MSG("RSA_LoadDer failed");
  1131. err = 1;
  1132. }
  1133. if ((!err) && (out != NULL)) {
  1134. /* Return through parameter too. */
  1135. *out = rsa;
  1136. /* Move buffer on by the used amount. */
  1137. *derBuf += wolfssl_der_length(*derBuf, (int)derSz);
  1138. }
  1139. if (err) {
  1140. /* Dispose of any created RSA key. */
  1141. wolfSSL_RSA_free(rsa);
  1142. rsa = NULL;
  1143. }
  1144. return rsa;
  1145. }
  1146. #if defined(OPENSSL_EXTRA) && !defined(HAVE_USER_RSA) && \
  1147. !defined(HAVE_FAST_RSA)
  1148. /* Converts an internal RSA structure to DER format for the private key.
  1149. *
  1150. * If "pp" is null then buffer size only is returned.
  1151. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1152. * responsible for free'ing it.
  1153. *
  1154. * @param [in] rsa RSA key.
  1155. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1156. * May be NULL.
  1157. * On out, newly allocated buffer or pointer to byte after
  1158. * encoding in passed in buffer.
  1159. *
  1160. * @return Size of DER encoding on success
  1161. * @return BAD_FUNC_ARG when rsa is NULL.
  1162. * @return 0 on failure.
  1163. */
  1164. int wolfSSL_i2d_RSAPrivateKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1165. {
  1166. int ret;
  1167. WOLFSSL_ENTER("wolfSSL_i2d_RSAPrivateKey");
  1168. /* Validate parameters. */
  1169. if (rsa == NULL) {
  1170. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1171. ret = BAD_FUNC_ARG;
  1172. }
  1173. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1174. * No heap hint as this gets returned to the user */
  1175. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 0, NULL)) < 0) {
  1176. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1177. ret = 0;
  1178. }
  1179. /* Size of DER encoding. */
  1180. return ret;
  1181. }
  1182. /* Converts an internal RSA structure to DER format for the public key.
  1183. *
  1184. * If "pp" is null then buffer size only is returned.
  1185. * If "*pp" is null then a created buffer is set in *pp and the caller is
  1186. * responsible for free'ing it.
  1187. *
  1188. * @param [in] rsa RSA key.
  1189. * @param [in, out] pp On in, pointer to allocated buffer or NULL.
  1190. * May be NULL.
  1191. * On out, newly allocated buffer or pointer to byte after
  1192. * encoding in passed in buffer.
  1193. * @return Size of DER encoding on success
  1194. * @return BAD_FUNC_ARG when rsa is NULL.
  1195. * @return 0 on failure.
  1196. */
  1197. int wolfSSL_i2d_RSAPublicKey(WOLFSSL_RSA *rsa, unsigned char **pp)
  1198. {
  1199. int ret;
  1200. WOLFSSL_ENTER("wolfSSL_i2d_RSAPublicKey");
  1201. /* check for bad functions arguments */
  1202. if (rsa == NULL) {
  1203. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1204. ret = BAD_FUNC_ARG;
  1205. }
  1206. /* Encode the RSA key as a DER. Call allocates buffer into pp.
  1207. * No heap hint as this gets returned to the user */
  1208. else if ((ret = wolfSSL_RSA_To_Der_ex(rsa, pp, 1, NULL)) < 0) {
  1209. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1210. ret = 0;
  1211. }
  1212. return ret;
  1213. }
  1214. #endif /* defined(OPENSSL_EXTRA) && !defined(HAVE_USER_RSA) &&
  1215. * !defined(HAVE_FAST_RSA) */
  1216. #endif /* OPENSSL_EXTRA */
  1217. /*
  1218. * RSA to/from BIO APIs
  1219. */
  1220. /* wolfSSL_d2i_RSAPublicKey_bio not supported */
  1221. #if defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || defined(WOLFSSL_HAPROXY) \
  1222. || defined(WOLFSSL_NGINX) || defined(WOLFSSL_QT)
  1223. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1224. !defined(HAVE_FAST_RSA) && !defined(NO_BIO)
  1225. /* Read DER data from a BIO.
  1226. *
  1227. * DER structures start with a constructed sequence. Use this to calculate the
  1228. * total length of the DER data.
  1229. *
  1230. * @param [in] bio BIO object to read from.
  1231. * @param [out] out Buffer holding DER encoding.
  1232. * @return Number of bytes to DER encoding on success.
  1233. * @return 0 on failure.
  1234. */
  1235. static int wolfssl_read_der_bio(WOLFSSL_BIO* bio, unsigned char** out)
  1236. {
  1237. int err = 0;
  1238. unsigned char seq[MAX_SEQ_SZ];
  1239. unsigned char* der = NULL;
  1240. int derLen = 0;
  1241. /* Read in a minimal amount to get a SEQUENCE header of any size. */
  1242. if (wolfSSL_BIO_read(bio, seq, sizeof(seq)) != sizeof(seq)) {
  1243. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() of sequence failure");
  1244. err = 1;
  1245. }
  1246. /* Calculate complete DER encoding length. */
  1247. if ((!err) && ((derLen = wolfssl_der_length(seq, sizeof(seq))) <= 0)) {
  1248. WOLFSSL_ERROR_MSG("DER SEQUENCE decode failed");
  1249. err = 1;
  1250. }
  1251. /* Allocate a buffer to read DER data into. */
  1252. if ((!err) && ((der = (unsigned char*)XMALLOC(derLen, bio->heap,
  1253. DYNAMIC_TYPE_TMP_BUFFER)) == NULL)) {
  1254. WOLFSSL_ERROR_MSG("Malloc failure");
  1255. err = 1;
  1256. }
  1257. if (!err) {
  1258. /* Calculate the unread amount. */
  1259. int len = derLen - sizeof(seq);
  1260. /* Copy the previously read data into the buffer. */
  1261. XMEMCPY(der, seq, sizeof(seq));
  1262. /* Read rest of DER data from BIO. */
  1263. if (wolfSSL_BIO_read(bio, der + sizeof(seq), len) != len) {
  1264. WOLFSSL_ERROR_MSG("wolfSSL_BIO_read() failure");
  1265. err = 1;
  1266. }
  1267. }
  1268. if (!err) {
  1269. /* Return buffer through parameter. */
  1270. *out = der;
  1271. }
  1272. if (err) {
  1273. /* Dispose of any allocated buffer on error. */
  1274. XFREE(der, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1275. derLen = 0;
  1276. }
  1277. return derLen;
  1278. }
  1279. /* Reads the RSA private key data from a BIO to the internal form.
  1280. *
  1281. * Creates new RSA key from the DER encoded RSA private key read from the BIO.
  1282. *
  1283. * @param [in] bio BIO object to read from.
  1284. * @param [out] out Pointer to RSA key to return through. May be NULL.
  1285. * @return RSA key on success.
  1286. * @return NULL on failure.
  1287. */
  1288. WOLFSSL_RSA* wolfSSL_d2i_RSAPrivateKey_bio(WOLFSSL_BIO *bio, WOLFSSL_RSA **out)
  1289. {
  1290. WOLFSSL_RSA* key = NULL;
  1291. unsigned char* der = NULL;
  1292. int derLen = 0;
  1293. int err;
  1294. WOLFSSL_ENTER("wolfSSL_d2i_RSAPrivateKey_bio");
  1295. /* Validate parameters. */
  1296. err = (bio == NULL);
  1297. /* Read just DER encoding from BIO - buffer allocated in call. */
  1298. if ((!err) && ((derLen = wolfssl_read_der_bio(bio, &der)) == 0)) {
  1299. err = 1;
  1300. }
  1301. if (!err) {
  1302. /* Keep der for call to deallocate. */
  1303. const unsigned char* cder = der;
  1304. /* Create an RSA key from the data from the BIO. */
  1305. key = wolfSSL_d2i_RSAPrivateKey(NULL, &cder, derLen);
  1306. err = (key == NULL);
  1307. }
  1308. if ((!err) && (out != NULL)) {
  1309. /* Return the created RSA key through the parameter. */
  1310. *out = key;
  1311. }
  1312. if (err) {
  1313. /* Dispose of created key on error. */
  1314. wolfSSL_RSA_free(key);
  1315. key = NULL;
  1316. }
  1317. /* Dispose of allocated data. */
  1318. XFREE(der, bio ? bio->heap : NULL, DYNAMIC_TYPE_TMP_BUFFER);
  1319. return key;
  1320. }
  1321. #endif /* defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) &&
  1322. * !defined(HAVE_FAST_RSA) && !NO_BIO */
  1323. #endif /* OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY || WOLFSSL_QT */
  1324. /*
  1325. * RSA DER APIs
  1326. */
  1327. #ifdef OPENSSL_EXTRA
  1328. #ifndef HAVE_USER_RSA
  1329. /* Create a DER encoding of key.
  1330. *
  1331. * Not OpenSSL API.
  1332. *
  1333. * @param [in] rsa RSA key.
  1334. * @param [out] outBuf Allocated buffer containing DER encoding.
  1335. * May be NULL.
  1336. * @param [in] publicKey Whether to encode as public key.
  1337. * @param [in] heap Heap hint.
  1338. * @return Encoding size on success.
  1339. * @return Negative on failure.
  1340. */
  1341. int wolfSSL_RSA_To_Der(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1342. void* heap)
  1343. {
  1344. byte* p = NULL;
  1345. int ret;
  1346. if (outBuf != NULL) {
  1347. p = *outBuf;
  1348. }
  1349. ret = wolfSSL_RSA_To_Der_ex(rsa, outBuf, publicKey, heap);
  1350. if ((ret > 0) && (p != NULL)) {
  1351. *outBuf = p;
  1352. }
  1353. return ret;
  1354. }
  1355. /* Create a DER encoding of key.
  1356. *
  1357. * Buffer allocated with heap and DYNAMIC_TYPE_TMP_BUFFER.
  1358. *
  1359. * @param [in] rsa RSA key.
  1360. * @param [in, out] outBuf On in, pointer to allocated buffer or NULL.
  1361. * May be NULL.
  1362. * On out, newly allocated buffer or pointer to byte
  1363. * after encoding in passed in buffer.
  1364. * @param [in] publicKey Whether to encode as public key.
  1365. * @return Encoding size on success.
  1366. * @return Negative on failure.
  1367. */
  1368. static int wolfSSL_RSA_To_Der_ex(WOLFSSL_RSA* rsa, byte** outBuf, int publicKey,
  1369. void* heap)
  1370. {
  1371. int ret = 1;
  1372. int derSz = 0;
  1373. byte* derBuf = NULL;
  1374. WOLFSSL_ENTER("wolfSSL_RSA_To_Der");
  1375. /* Unused if memory is disabled. */
  1376. (void)heap;
  1377. /* Validate parameters. */
  1378. if ((rsa == NULL) || ((publicKey != 0) && (publicKey != 1))) {
  1379. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", BAD_FUNC_ARG);
  1380. ret = BAD_FUNC_ARG;
  1381. }
  1382. /* Push external RSA data into internal RSA key if not set. */
  1383. if ((ret == 1) && (!rsa->inSet)) {
  1384. ret = SetRsaInternal(rsa);
  1385. }
  1386. /* wc_RsaKeyToPublicDer encode regardless of values. */
  1387. if ((ret == 1) && publicKey && (mp_iszero(&((RsaKey*)rsa->internal)->n) ||
  1388. mp_iszero(&((RsaKey*)rsa->internal)->e))) {
  1389. ret = BAD_FUNC_ARG;
  1390. }
  1391. if (ret == 1) {
  1392. if (publicKey) {
  1393. /* Calculate length of DER encoded RSA public key. */
  1394. derSz = wc_RsaPublicKeyDerSize((RsaKey*)rsa->internal, 1);
  1395. if (derSz < 0) {
  1396. WOLFSSL_ERROR_MSG("wc_RsaPublicKeyDerSize failed");
  1397. ret = derSz;
  1398. }
  1399. }
  1400. else {
  1401. /* Calculate length of DER encoded RSA private key. */
  1402. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, NULL, 0);
  1403. if (derSz < 0) {
  1404. WOLFSSL_ERROR_MSG("wc_RsaKeyToDer failed");
  1405. ret = derSz;
  1406. }
  1407. }
  1408. }
  1409. if ((ret == 1) && (outBuf != NULL)) {
  1410. derBuf = *outBuf;
  1411. if (derBuf == NULL) {
  1412. /* Allocate buffer to hold DER encoded RSA key. */
  1413. derBuf = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1414. if (derBuf == NULL) {
  1415. WOLFSSL_ERROR_MSG("Memory allocation failed");
  1416. ret = MEMORY_ERROR;
  1417. }
  1418. }
  1419. }
  1420. if ((ret == 1) && (outBuf != NULL)) {
  1421. if (publicKey) {
  1422. /* RSA public key to DER. */
  1423. derSz = wc_RsaKeyToPublicDer((RsaKey*)rsa->internal, derBuf, derSz);
  1424. }
  1425. else {
  1426. /* RSA private key to DER. */
  1427. derSz = wc_RsaKeyToDer((RsaKey*)rsa->internal, derBuf, derSz);
  1428. }
  1429. if (derSz < 0) {
  1430. WOLFSSL_ERROR_MSG("RSA key encoding failed");
  1431. ret = derSz;
  1432. }
  1433. else if ((*outBuf) != NULL) {
  1434. derBuf = NULL;
  1435. *outBuf += derSz;
  1436. }
  1437. else {
  1438. /* Return allocated buffer. */
  1439. *outBuf = derBuf;
  1440. }
  1441. }
  1442. if (ret == 1) {
  1443. /* Success - return DER encoding size. */
  1444. ret = derSz;
  1445. }
  1446. if ((outBuf != NULL) && (*outBuf != derBuf)) {
  1447. /* Not returning buffer, needs to be disposed of. */
  1448. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  1449. }
  1450. WOLFSSL_LEAVE("wolfSSL_RSA_To_Der", ret);
  1451. return ret;
  1452. }
  1453. #endif /* !HAVE_USER_RSA */
  1454. #endif /* OPENSSL_EXTRA */
  1455. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  1456. /* Load the DER encoded private RSA key.
  1457. *
  1458. * Not OpenSSL API.
  1459. *
  1460. * @param [in] rsa RSA key.
  1461. * @param [in] derBuf Buffer holding DER encoding.
  1462. * @param [in] derSz Length of DER encoding.
  1463. * @return 1 on success.
  1464. * @return -1 on failure.
  1465. */
  1466. int wolfSSL_RSA_LoadDer(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1467. int derSz)
  1468. {
  1469. /* Call implementation that handles both private and public keys. */
  1470. return wolfSSL_RSA_LoadDer_ex(rsa, derBuf, derSz, WOLFSSL_RSA_LOAD_PRIVATE);
  1471. }
  1472. /* Load the DER encoded public or private RSA key.
  1473. *
  1474. * Not OpenSSL API.
  1475. *
  1476. * @param [in] rsa RSA key.
  1477. * @param [in] derBuf Buffer holding DER encoding.
  1478. * @param [in] derSz Length of DER encoding.
  1479. * @param [in] opt Indicates public or private key.
  1480. * (WOLFSSL_RSA_LOAD_PUBLIC or WOLFSSL_RSA_LOAD_PRIVATE)
  1481. * @return 1 on success.
  1482. * @return -1 on failure.
  1483. */
  1484. int wolfSSL_RSA_LoadDer_ex(WOLFSSL_RSA* rsa, const unsigned char* derBuf,
  1485. int derSz, int opt)
  1486. {
  1487. int ret = 1;
  1488. int res;
  1489. word32 idx = 0;
  1490. word32 algId;
  1491. WOLFSSL_ENTER("wolfSSL_RSA_LoadDer");
  1492. /* Validate parameters. */
  1493. if ((rsa == NULL) || (rsa->internal == NULL) || (derBuf == NULL) ||
  1494. (derSz <= 0)) {
  1495. WOLFSSL_ERROR_MSG("Bad function arguments");
  1496. ret = -1;
  1497. }
  1498. if (ret == 1) {
  1499. rsa->pkcs8HeaderSz = 0;
  1500. /* Check if input buffer has PKCS8 header. In the case that it does not
  1501. * have a PKCS8 header then do not error out. */
  1502. res = ToTraditionalInline_ex((const byte*)derBuf, &idx, (word32)derSz,
  1503. &algId);
  1504. if (res > 0) {
  1505. /* Store size of PKCS#8 header for encoding. */
  1506. WOLFSSL_MSG("Found PKCS8 header");
  1507. rsa->pkcs8HeaderSz = (word16)idx;
  1508. }
  1509. /* When decoding and not PKCS#8, return will be ASN_PARSE_E. */
  1510. else if (res != ASN_PARSE_E) {
  1511. /* Something went wrong while decoding. */
  1512. WOLFSSL_ERROR_MSG("Unexpected error with trying to remove PKCS#8 "
  1513. "header");
  1514. ret = -1;
  1515. }
  1516. }
  1517. if (ret == 1) {
  1518. /* Decode private or public key data. */
  1519. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1520. res = wc_RsaPrivateKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1521. derSz);
  1522. }
  1523. else {
  1524. res = wc_RsaPublicKeyDecode(derBuf, &idx, (RsaKey*)rsa->internal,
  1525. derSz);
  1526. }
  1527. /* Check for error. */
  1528. if (res < 0) {
  1529. if (opt == WOLFSSL_RSA_LOAD_PRIVATE) {
  1530. WOLFSSL_ERROR_MSG("RsaPrivateKeyDecode failed");
  1531. }
  1532. else {
  1533. WOLFSSL_ERROR_MSG("RsaPublicKeyDecode failed");
  1534. }
  1535. WOLFSSL_ERROR_VERBOSE(res);
  1536. ret = -1;
  1537. }
  1538. }
  1539. if (ret == 1) {
  1540. /* Set external RSA key data from wolfCrypt key. */
  1541. if (SetRsaExternal(rsa) != 1) {
  1542. ret = -1;
  1543. }
  1544. else {
  1545. rsa->inSet = 1;
  1546. }
  1547. }
  1548. return ret;
  1549. }
  1550. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  1551. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  1552. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  1553. /* Load DER encoded data into WOLFSSL_RSA object.
  1554. *
  1555. * Creates a new WOLFSSL_RSA object if one is not passed in.
  1556. *
  1557. * @param [in, out] rsa WOLFSSL_RSA object to load into.
  1558. * When rsa or *rsa is NULL a new object is created.
  1559. * When not NULL and *rsa is NULL then new object
  1560. * returned through pointer.
  1561. * @param [in] in DER encoded RSA key data.
  1562. * @param [in] inSz Size of DER encoded data in bytes.
  1563. * @param [in] opt Public or private key encoded in data. Valid values:
  1564. * WOLFSSL_RSA_LOAD_PRIVATE, WOLFSSL_RSA_LOAD_PUBLIC.
  1565. * @return NULL on failure.
  1566. * @return WOLFSSL_RSA object on success.
  1567. */
  1568. static WOLFSSL_RSA* wolfssl_rsa_d2i(WOLFSSL_RSA** rsa, const unsigned char* in,
  1569. long inSz, int opt)
  1570. {
  1571. WOLFSSL_RSA* ret = NULL;
  1572. if ((rsa != NULL) && (*rsa != NULL)) {
  1573. ret = *rsa;
  1574. }
  1575. else {
  1576. ret = wolfSSL_RSA_new();
  1577. }
  1578. if ((ret != NULL) && (wolfSSL_RSA_LoadDer_ex(ret, in, (int)inSz, opt)
  1579. != 1)) {
  1580. if ((rsa == NULL) || (ret != *rsa)) {
  1581. wolfSSL_RSA_free(ret);
  1582. }
  1583. ret = NULL;
  1584. }
  1585. if ((rsa != NULL) && (*rsa == NULL)) {
  1586. *rsa = ret;
  1587. }
  1588. return ret;
  1589. }
  1590. #endif
  1591. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  1592. /*
  1593. * RSA PEM APIs
  1594. */
  1595. #ifdef OPENSSL_EXTRA
  1596. #ifndef NO_BIO
  1597. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1598. /* Writes PEM encoding of an RSA public key to a BIO.
  1599. *
  1600. * @param [in] bio BIO object to write to.
  1601. * @param [in] rsa RSA key to write.
  1602. * @return 1 on success.
  1603. * @return 0 on failure.
  1604. */
  1605. int wolfSSL_PEM_write_bio_RSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa)
  1606. {
  1607. int ret = 1;
  1608. int derSz = 0;
  1609. byte* derBuf = NULL;
  1610. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSA_PUBKEY");
  1611. /* Validate parameters. */
  1612. if ((bio == NULL) || (rsa == NULL)) {
  1613. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1614. return 0;
  1615. }
  1616. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, bio->heap)) < 0) {
  1617. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1618. ret = 0;
  1619. }
  1620. if (derBuf == NULL) {
  1621. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1622. ret = 0;
  1623. }
  1624. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  1625. PUBLICKEY_TYPE) != WOLFSSL_SUCCESS)) {
  1626. ret = 0;
  1627. }
  1628. /* Dispose of DER buffer. */
  1629. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1630. return ret;
  1631. }
  1632. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1633. #endif /* !NO_BIO */
  1634. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA)
  1635. #ifndef NO_FILESYSTEM
  1636. /* Writes PEM encoding of an RSA public key to a file pointer.
  1637. *
  1638. * @param [in] fp File pointer to write to.
  1639. * @param [in] rsa RSA key to write.
  1640. * @param [in] type PEM type to write out.
  1641. * @return 1 on success.
  1642. * @return 0 on failure.
  1643. */
  1644. static int wolfssl_pem_write_rsa_public_key(XFILE fp, WOLFSSL_RSA* rsa,
  1645. int type)
  1646. {
  1647. int ret = 1;
  1648. int derSz;
  1649. byte* derBuf = NULL;
  1650. /* Validate parameters. */
  1651. if ((fp == XBADFILE) || (rsa == NULL)) {
  1652. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  1653. return 0;
  1654. }
  1655. if ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 1, rsa->heap)) < 0) {
  1656. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1657. ret = 0;
  1658. }
  1659. if (derBuf == NULL) {
  1660. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed to get buffer");
  1661. ret = 0;
  1662. }
  1663. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp, type,
  1664. rsa->heap) != WOLFSSL_SUCCESS)) {
  1665. ret = 0;
  1666. }
  1667. /* Dispose of DER buffer. */
  1668. XFREE(derBuf, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  1669. return ret;
  1670. }
  1671. /* Writes PEM encoding of an RSA public key to a file pointer.
  1672. *
  1673. * Header/footer will contain: PUBLIC KEY
  1674. *
  1675. * @param [in] fp File pointer to write to.
  1676. * @param [in] rsa RSA key to write.
  1677. * @return 1 on success.
  1678. * @return 0 on failure.
  1679. */
  1680. int wolfSSL_PEM_write_RSA_PUBKEY(XFILE fp, WOLFSSL_RSA* rsa)
  1681. {
  1682. return wolfssl_pem_write_rsa_public_key(fp, rsa, PUBLICKEY_TYPE);
  1683. }
  1684. /* Writes PEM encoding of an RSA public key to a file pointer.
  1685. *
  1686. * Header/footer will contain: RSA PUBLIC KEY
  1687. *
  1688. * @param [in] fp File pointer to write to.
  1689. * @param [in] rsa RSA key to write.
  1690. * @return 1 on success.
  1691. * @return 0 on failure.
  1692. */
  1693. int wolfSSL_PEM_write_RSAPublicKey(XFILE fp, WOLFSSL_RSA* rsa)
  1694. {
  1695. return wolfssl_pem_write_rsa_public_key(fp, rsa, RSA_PUBLICKEY_TYPE);
  1696. }
  1697. #endif /* !NO_FILESYSTEM */
  1698. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA */
  1699. #ifndef NO_BIO
  1700. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1701. *
  1702. * @param [in] bio BIO object to read from.
  1703. * @param [out] out RSA key created.
  1704. * @param [in] cb Password callback when PEM encrypted.
  1705. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1706. * @return RSA key on success.
  1707. * @return NULL on failure.
  1708. */
  1709. WOLFSSL_RSA *wolfSSL_PEM_read_bio_RSA_PUBKEY(WOLFSSL_BIO* bio,
  1710. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1711. {
  1712. WOLFSSL_RSA* rsa = NULL;
  1713. DerBuffer* der = NULL;
  1714. int keyFormat = 0;
  1715. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSA_PUBKEY");
  1716. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PUBLICKEY_TYPE,
  1717. &keyFormat, &der) >= 0)) {
  1718. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1719. WOLFSSL_RSA_LOAD_PUBLIC);
  1720. if (rsa == NULL) {
  1721. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1722. }
  1723. }
  1724. FreeDer(&der);
  1725. if ((out != NULL) && (rsa != NULL)) {
  1726. *out = rsa;
  1727. }
  1728. return rsa;
  1729. }
  1730. #endif /* !NO_BIO */
  1731. #ifndef NO_FILESYSTEM
  1732. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1733. *
  1734. * Header/footer should contain: PUBLIC KEY
  1735. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1736. *
  1737. * @param [in] fp File pointer to read from.
  1738. * @param [out] out RSA key created.
  1739. * @param [in] cb Password callback when PEM encrypted.
  1740. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1741. * @return RSA key on success.
  1742. * @return NULL on failure.
  1743. */
  1744. WOLFSSL_RSA *wolfSSL_PEM_read_RSA_PUBKEY(XFILE fp,
  1745. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void *pass)
  1746. {
  1747. WOLFSSL_RSA* rsa = NULL;
  1748. DerBuffer* der = NULL;
  1749. int keyFormat = 0;
  1750. WOLFSSL_ENTER("wolfSSL_PEM_read_RSA_PUBKEY");
  1751. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PUBLICKEY_TYPE,
  1752. &keyFormat, &der) >= 0)) {
  1753. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1754. WOLFSSL_RSA_LOAD_PUBLIC);
  1755. if (rsa == NULL) {
  1756. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1757. }
  1758. }
  1759. FreeDer(&der);
  1760. if ((out != NULL) && (rsa != NULL)) {
  1761. *out = rsa;
  1762. }
  1763. return rsa;
  1764. }
  1765. /* Create an RSA public key by reading the PEM encoded data from the BIO.
  1766. *
  1767. * Header/footer should contain: RSA PUBLIC KEY
  1768. * PEM decoder supports either 'RSA PUBLIC KEY' or 'PUBLIC KEY'.
  1769. *
  1770. * @param [in] fp File pointer to read from.
  1771. * @param [out] rsa RSA key created.
  1772. * @param [in] cb Password callback when PEM encrypted. May be NULL.
  1773. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1774. * May be NULL.
  1775. * @return RSA key on success.
  1776. * @return NULL on failure.
  1777. */
  1778. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPublicKey(XFILE fp, WOLFSSL_RSA** rsa,
  1779. wc_pem_password_cb* cb, void* pass)
  1780. {
  1781. return wolfSSL_PEM_read_RSA_PUBKEY(fp, rsa, cb, pass);
  1782. }
  1783. #endif /* NO_FILESYSTEM */
  1784. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_USER_RSA) && \
  1785. (defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM))
  1786. /* Writes PEM encoding of an RSA private key to newly allocated buffer.
  1787. *
  1788. * Buffer returned was allocated with: DYNAMIC_TYPE_KEY.
  1789. *
  1790. * @param [in] rsa RSA key to write.
  1791. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1792. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1793. * @param [in] passwdSz Length of password string when PEM encrypted.
  1794. * @param [out] pem Allocated buffer with PEM encoding.
  1795. * @param [out] pLen Length of PEM encoding.
  1796. * @return 1 on success.
  1797. * @return 0 on failure.
  1798. */
  1799. int wolfSSL_PEM_write_mem_RSAPrivateKey(RSA* rsa, const EVP_CIPHER* cipher,
  1800. unsigned char* passwd, int passwdSz, unsigned char **pem, int *pLen)
  1801. {
  1802. int ret = 1;
  1803. byte* derBuf = NULL;
  1804. int derSz = 0;
  1805. WOLFSSL_ENTER("wolfSSL_PEM_write_mem_RSAPrivateKey");
  1806. /* Validate parameters. */
  1807. if ((pem == NULL) || (pLen == NULL) || (rsa == NULL) ||
  1808. (rsa->internal == NULL)) {
  1809. WOLFSSL_ERROR_MSG("Bad function arguments");
  1810. ret = 0;
  1811. }
  1812. /* Set the RSA key data into the wolfCrypt RSA key if not done so. */
  1813. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  1814. ret = 0;
  1815. }
  1816. /* Encode wolfCrypt RSA key to DER - derBuf allocated in call. */
  1817. if ((ret == 1) && ((derSz = wolfSSL_RSA_To_Der(rsa, &derBuf, 0,
  1818. rsa->heap)) < 0)) {
  1819. WOLFSSL_ERROR_MSG("wolfSSL_RSA_To_Der failed");
  1820. ret = 0;
  1821. }
  1822. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  1823. passwdSz, PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  1824. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  1825. ret = 0;
  1826. }
  1827. return ret;
  1828. }
  1829. #ifndef NO_BIO
  1830. /* Writes PEM encoding of an RSA private key to a BIO.
  1831. *
  1832. * @param [in] bio BIO object to write to.
  1833. * @param [in] rsa RSA key to write.
  1834. * @param [in] cipher Cipher to use when PEM encrypted.
  1835. * @param [in] passwd Password string when PEM encrypted.
  1836. * @param [in] len Length of password string when PEM encrypted.
  1837. * @param [in] cb Password callback to use when PEM encrypted.
  1838. * @param [in] arg NUL terminated string for passphrase when PEM encrypted.
  1839. * @return 1 on success.
  1840. * @return 0 on failure.
  1841. */
  1842. int wolfSSL_PEM_write_bio_RSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa,
  1843. const WOLFSSL_EVP_CIPHER* cipher, unsigned char* passwd, int len,
  1844. wc_pem_password_cb* cb, void* arg)
  1845. {
  1846. int ret = 1;
  1847. byte* pem = NULL;
  1848. int pLen = 0;
  1849. (void)cb;
  1850. (void)arg;
  1851. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_RSAPrivateKey");
  1852. /* Validate parameters. */
  1853. if ((bio == NULL) || (rsa == NULL) || (rsa->internal == NULL)) {
  1854. WOLFSSL_ERROR_MSG("Bad function arguments");
  1855. ret = 0;
  1856. }
  1857. if (ret == 1) {
  1858. /* Write PEM to buffer that is allocated in the call. */
  1859. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, len,
  1860. &pem, &pLen);
  1861. if (ret != 1) {
  1862. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1863. }
  1864. }
  1865. /* Write PEM to BIO. */
  1866. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) <= 0)) {
  1867. WOLFSSL_ERROR_MSG("RSA private key BIO write failed");
  1868. ret = 0;
  1869. }
  1870. /* Dispose of any allocated PEM buffer. */
  1871. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1872. return ret;
  1873. }
  1874. #endif /* !NO_BIO */
  1875. #ifndef NO_FILESYSTEM
  1876. /* Writes PEM encoding of an RSA private key to a file pointer.
  1877. *
  1878. * TODO: Support use of the password callback and callback context.
  1879. *
  1880. * @param [in] fp File pointer to write to.
  1881. * @param [in] rsa RSA key to write.
  1882. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  1883. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  1884. * @param [in] passwdSz Length of password string when PEM encrypted.
  1885. * @param [in] cb Password callback to use when PEM encrypted. Unused.
  1886. * @param [in] arg NUL terminated string for passphrase when PEM
  1887. * encrypted. Unused.
  1888. * @return 1 on success.
  1889. * @return 0 on failure.
  1890. */
  1891. int wolfSSL_PEM_write_RSAPrivateKey(XFILE fp, WOLFSSL_RSA *rsa,
  1892. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  1893. wc_pem_password_cb *cb, void *arg)
  1894. {
  1895. int ret = 1;
  1896. byte* pem = NULL;
  1897. int pLen;
  1898. (void)cb;
  1899. (void)arg;
  1900. WOLFSSL_ENTER("wolfSSL_PEM_write_RSAPrivateKey");
  1901. /* Validate parameters. */
  1902. if ((fp == XBADFILE) || (rsa == NULL) || (rsa->internal == NULL)) {
  1903. WOLFSSL_ERROR_MSG("Bad function arguments");
  1904. ret = 0;
  1905. }
  1906. if (ret == 1) {
  1907. /* Write PEM to buffer that is allocated in the call. */
  1908. ret = wolfSSL_PEM_write_mem_RSAPrivateKey(rsa, cipher, passwd, passwdSz,
  1909. &pem, &pLen);
  1910. if (ret != 1) {
  1911. WOLFSSL_ERROR_MSG("wolfSSL_PEM_write_mem_RSAPrivateKey failed");
  1912. }
  1913. }
  1914. /* Write PEM to file pointer. */
  1915. if ((ret == 1) && ((int)XFWRITE(pem, pLen, 1, fp) != 1)) {
  1916. WOLFSSL_ERROR_MSG("RSA private key file write failed");
  1917. ret = 0;
  1918. }
  1919. /* Dispose of any allocated PEM buffer. */
  1920. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  1921. return ret;
  1922. }
  1923. #endif /* NO_FILESYSTEM */
  1924. #endif /* WOLFSSL_KEY_GEN && !HAVE_USER_RSA && WOLFSSL_PEM_TO_DER */
  1925. #ifndef NO_BIO
  1926. /* Create an RSA private key by reading the PEM encoded data from the BIO.
  1927. *
  1928. * @param [in] bio BIO object to read from.
  1929. * @param [out] out RSA key created.
  1930. * @param [in] cb Password callback when PEM encrypted.
  1931. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1932. * @return RSA key on success.
  1933. * @return NULL on failure.
  1934. */
  1935. WOLFSSL_RSA* wolfSSL_PEM_read_bio_RSAPrivateKey(WOLFSSL_BIO* bio,
  1936. WOLFSSL_RSA** out, wc_pem_password_cb* cb, void* pass)
  1937. {
  1938. WOLFSSL_RSA* rsa = NULL;
  1939. DerBuffer* der = NULL;
  1940. int keyFormat = 0;
  1941. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_RSAPrivateKey");
  1942. if ((bio != NULL) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  1943. &keyFormat, &der) >= 0)) {
  1944. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1945. WOLFSSL_RSA_LOAD_PRIVATE);
  1946. if (rsa == NULL) {
  1947. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1948. }
  1949. }
  1950. FreeDer(&der);
  1951. if ((out != NULL) && (rsa != NULL)) {
  1952. *out = rsa;
  1953. }
  1954. return rsa;
  1955. }
  1956. #endif /* !NO_BIO */
  1957. /* Create an RSA private key by reading the PEM encoded data from the file
  1958. * pointer.
  1959. *
  1960. * @param [in] fp File pointer to read from.
  1961. * @param [out] out RSA key created.
  1962. * @param [in] cb Password callback when PEM encrypted.
  1963. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  1964. * @return RSA key on success.
  1965. * @return NULL on failure.
  1966. */
  1967. #ifndef NO_FILESYSTEM
  1968. WOLFSSL_RSA* wolfSSL_PEM_read_RSAPrivateKey(XFILE fp, WOLFSSL_RSA** out,
  1969. wc_pem_password_cb* cb, void* pass)
  1970. {
  1971. WOLFSSL_RSA* rsa = NULL;
  1972. DerBuffer* der = NULL;
  1973. int keyFormat = 0;
  1974. WOLFSSL_ENTER("wolfSSL_PEM_read_RSAPrivateKey");
  1975. if ((fp != XBADFILE) && (pem_read_file_key(fp, cb, pass, PRIVATEKEY_TYPE,
  1976. &keyFormat, &der) >= 0)) {
  1977. rsa = wolfssl_rsa_d2i(out, der->buffer, der->length,
  1978. WOLFSSL_RSA_LOAD_PRIVATE);
  1979. if (rsa == NULL) {
  1980. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_RSA");
  1981. }
  1982. }
  1983. FreeDer(&der);
  1984. if ((out != NULL) && (rsa != NULL)) {
  1985. *out = rsa;
  1986. }
  1987. return rsa;
  1988. }
  1989. #endif /* !NO_FILESYSTEM */
  1990. /*
  1991. * RSA print APIs
  1992. */
  1993. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  1994. !defined(NO_STDIO_FILESYSTEM)
  1995. /* Print an RSA key to a file pointer.
  1996. *
  1997. * @param [in] fp File pointer to write to.
  1998. * @param [in] rsa RSA key to write.
  1999. * @param [in] indent Number of spaces to prepend to each line.
  2000. * @return 1 on success.
  2001. * @return 0 on failure.
  2002. */
  2003. int wolfSSL_RSA_print_fp(XFILE fp, WOLFSSL_RSA* rsa, int indent)
  2004. {
  2005. int ret = 1;
  2006. WOLFSSL_ENTER("wolfSSL_RSA_print_fp");
  2007. /* Validate parameters. */
  2008. if ((fp == XBADFILE) || (rsa == NULL)) {
  2009. ret = 0;
  2010. }
  2011. /* Set the external data from the wolfCrypt RSA key if not done. */
  2012. if ((ret == 1) && (!rsa->exSet)) {
  2013. ret = SetRsaExternal(rsa);
  2014. }
  2015. /* Get the key size from modulus if available. */
  2016. if ((ret == 1) && (rsa->n != NULL)) {
  2017. int keySize = wolfSSL_BN_num_bits(rsa->n);
  2018. if (keySize == 0) {
  2019. ret = 0;
  2020. }
  2021. else {
  2022. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  2023. ret = 0;
  2024. else if (XFPRINTF(fp, "RSA Private-Key: (%d bit, 2 primes)\n",
  2025. keySize) < 0)
  2026. ret = 0;
  2027. }
  2028. }
  2029. /* Print out any components available. */
  2030. if ((ret == 1) && (rsa->n != NULL)) {
  2031. ret = pk_bn_field_print_fp(fp, indent, "modulus", rsa->n);
  2032. }
  2033. if ((ret == 1) && (rsa->d != NULL)) {
  2034. ret = pk_bn_field_print_fp(fp, indent, "privateExponent", rsa->d);
  2035. }
  2036. if ((ret == 1) && (rsa->p != NULL)) {
  2037. ret = pk_bn_field_print_fp(fp, indent, "prime1", rsa->p);
  2038. }
  2039. if ((ret == 1) && (rsa->q != NULL)) {
  2040. ret = pk_bn_field_print_fp(fp, indent, "prime2", rsa->q);
  2041. }
  2042. if ((ret == 1) && (rsa->dmp1 != NULL)) {
  2043. ret = pk_bn_field_print_fp(fp, indent, "exponent1", rsa->dmp1);
  2044. }
  2045. if ((ret == 1) && (rsa->dmq1 != NULL)) {
  2046. ret = pk_bn_field_print_fp(fp, indent, "exponent2", rsa->dmq1);
  2047. }
  2048. if ((ret == 1) && (rsa->iqmp != NULL)) {
  2049. ret = pk_bn_field_print_fp(fp, indent, "coefficient", rsa->iqmp);
  2050. }
  2051. WOLFSSL_LEAVE("wolfSSL_RSA_print_fp", ret);
  2052. return ret;
  2053. }
  2054. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  2055. #if defined(XSNPRINTF) && !defined(NO_BIO) && !defined(HAVE_FAST_RSA)
  2056. /* snprintf() must be available */
  2057. /* Maximum size of a header line. */
  2058. #define RSA_PRINT_MAX_HEADER_LINE PRINT_NUM_MAX_INDENT
  2059. /* Writes the human readable form of RSA to a BIO.
  2060. *
  2061. * @param [in] bio BIO object to write to.
  2062. * @param [in] rsa RSA key to write.
  2063. * @param [in] indent Number of spaces before each line.
  2064. * @return 1 on success.
  2065. * @return 0 on failure.
  2066. */
  2067. int wolfSSL_RSA_print(WOLFSSL_BIO* bio, WOLFSSL_RSA* rsa, int indent)
  2068. {
  2069. int ret = 1;
  2070. int sz = 0;
  2071. RsaKey* key = NULL;
  2072. char line[RSA_PRINT_MAX_HEADER_LINE];
  2073. int i = 0;
  2074. mp_int *num = NULL;
  2075. /* Header strings. */
  2076. const char *name[] = {
  2077. "Modulus:", "Exponent:", "PrivateExponent:", "Prime1:", "Prime2:",
  2078. "Exponent1:", "Exponent2:", "Coefficient:"
  2079. };
  2080. WOLFSSL_ENTER("wolfSSL_RSA_print");
  2081. /* Validate parameters. */
  2082. if ((bio == NULL) || (rsa == NULL) || (indent > PRINT_NUM_MAX_INDENT)) {
  2083. ret = -1;
  2084. }
  2085. if (ret == 1) {
  2086. key = (RsaKey*)rsa->internal;
  2087. /* Get size in bits of key for printing out. */
  2088. sz = wolfSSL_RSA_bits(rsa);
  2089. if (sz <= 0) {
  2090. WOLFSSL_ERROR_MSG("Error getting RSA key size");
  2091. ret = 0;
  2092. }
  2093. }
  2094. if (ret == 1) {
  2095. /* Print any indent spaces. */
  2096. ret = wolfssl_print_indent(bio, line, sizeof(line), indent);
  2097. }
  2098. if (ret == 1) {
  2099. /* Print header line. */
  2100. int len = XSNPRINTF(line, sizeof(line), "\nRSA %s: (%d bit)\n",
  2101. (!mp_iszero(&key->d)) ? "Private-Key" : "Public-Key", sz);
  2102. if (len >= (int)sizeof(line)) {
  2103. WOLFSSL_ERROR_MSG("Buffer overflow while formatting key preamble");
  2104. ret = 0;
  2105. }
  2106. else {
  2107. if (wolfSSL_BIO_write(bio, line, len) <= 0) {
  2108. ret = 0;
  2109. }
  2110. }
  2111. }
  2112. for (i = 0; (ret == 1) && (i < RSA_INTS); i++) {
  2113. /* Get mp_int for index. */
  2114. switch (i) {
  2115. case 0:
  2116. /* Print out modulus */
  2117. num = &key->n;
  2118. break;
  2119. case 1:
  2120. num = &key->e;
  2121. break;
  2122. case 2:
  2123. num = &key->d;
  2124. break;
  2125. case 3:
  2126. num = &key->p;
  2127. break;
  2128. case 4:
  2129. num = &key->q;
  2130. break;
  2131. case 5:
  2132. num = &key->dP;
  2133. break;
  2134. case 6:
  2135. num = &key->dQ;
  2136. break;
  2137. case 7:
  2138. num = &key->u;
  2139. break;
  2140. default:
  2141. WOLFSSL_ERROR_MSG("Bad index value");
  2142. }
  2143. if (i == 1) {
  2144. /* Print exponent as a 32-bit value. */
  2145. ret = wolfssl_print_value(bio, num, name[i], indent);
  2146. }
  2147. else if (!mp_iszero(num)) {
  2148. /* Print name and MP integer. */
  2149. ret = wolfssl_print_number(bio, num, name[i], indent);
  2150. }
  2151. }
  2152. return ret;
  2153. }
  2154. #endif /* XSNPRINTF && !NO_BIO && !HAVE_FAST_RSA */
  2155. #endif /* OPENSSL_EXTRA */
  2156. /*
  2157. * RSA get/set/test APIs
  2158. */
  2159. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  2160. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2161. /* Set RSA key data (external) from wolfCrypt RSA key (internal).
  2162. *
  2163. * @param [in, out] rsa RSA key.
  2164. * @return 1 on success.
  2165. * @return 0 on failure.
  2166. */
  2167. int SetRsaExternal(WOLFSSL_RSA* rsa)
  2168. {
  2169. int ret = 1;
  2170. WOLFSSL_ENTER("SetRsaExternal");
  2171. /* Validate parameters. */
  2172. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2173. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2174. ret = -1;
  2175. }
  2176. if (ret == 1) {
  2177. RsaKey* key = (RsaKey*)rsa->internal;
  2178. /* Copy modulus. */
  2179. ret = wolfssl_bn_set_value(&rsa->n, &key->n);
  2180. if (ret != 1) {
  2181. WOLFSSL_ERROR_MSG("rsa n error");
  2182. }
  2183. if (ret == 1) {
  2184. /* Copy public exponent. */
  2185. ret = wolfssl_bn_set_value(&rsa->e, &key->e);
  2186. if (ret != 1) {
  2187. WOLFSSL_ERROR_MSG("rsa e error");
  2188. }
  2189. }
  2190. if (key->type == RSA_PRIVATE) {
  2191. if (ret == 1) {
  2192. /* Copy private exponent. */
  2193. ret = wolfssl_bn_set_value(&rsa->d, &key->d);
  2194. if (ret != 1) {
  2195. WOLFSSL_ERROR_MSG("rsa d error");
  2196. }
  2197. }
  2198. if (ret == 1) {
  2199. /* Copy first prime. */
  2200. ret = wolfssl_bn_set_value(&rsa->p, &key->p);
  2201. if (ret != 1) {
  2202. WOLFSSL_ERROR_MSG("rsa p error");
  2203. }
  2204. }
  2205. if (ret == 1) {
  2206. /* Copy second prime. */
  2207. ret = wolfssl_bn_set_value(&rsa->q, &key->q);
  2208. if (ret != 1) {
  2209. WOLFSSL_ERROR_MSG("rsa q error");
  2210. }
  2211. }
  2212. #ifndef RSA_LOW_MEM
  2213. if (ret == 1) {
  2214. /* Copy d mod p-1. */
  2215. ret = wolfssl_bn_set_value(&rsa->dmp1, &key->dP);
  2216. if (ret != 1) {
  2217. WOLFSSL_ERROR_MSG("rsa dP error");
  2218. }
  2219. }
  2220. if (ret == 1) {
  2221. /* Copy d mod q-1. */
  2222. ret = wolfssl_bn_set_value(&rsa->dmq1, &key->dQ);
  2223. if (ret != 1) {
  2224. WOLFSSL_ERROR_MSG("rsa dq error");
  2225. }
  2226. }
  2227. if (ret == 1) {
  2228. /* Copy 1/q mod p. */
  2229. ret = wolfssl_bn_set_value(&rsa->iqmp, &key->u);
  2230. if (ret != 1) {
  2231. WOLFSSL_ERROR_MSG("rsa u error");
  2232. }
  2233. }
  2234. #endif /* !RSA_LOW_MEM */
  2235. }
  2236. }
  2237. if (ret == 1) {
  2238. /* External values set. */
  2239. rsa->exSet = 1;
  2240. }
  2241. else {
  2242. /* Return 0 on failure. */
  2243. ret = 0;
  2244. }
  2245. return ret;
  2246. }
  2247. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  2248. #endif /* (OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL) */
  2249. #ifdef OPENSSL_EXTRA
  2250. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2251. /* Set wolfCrypt RSA key data (internal) from RSA key (external).
  2252. *
  2253. * @param [in, out] rsa RSA key.
  2254. * @return 1 on success.
  2255. * @return 0 on failure.
  2256. */
  2257. int SetRsaInternal(WOLFSSL_RSA* rsa)
  2258. {
  2259. int ret = 1;
  2260. WOLFSSL_ENTER("SetRsaInternal");
  2261. /* Validate parameters. */
  2262. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2263. WOLFSSL_ERROR_MSG("rsa key NULL error");
  2264. ret = -1;
  2265. }
  2266. if (ret == 1) {
  2267. RsaKey* key = (RsaKey*)rsa->internal;
  2268. /* Copy down modulus if available. */
  2269. if ((rsa->n != NULL) && (wolfssl_bn_get_value(rsa->n, &key->n) != 1)) {
  2270. WOLFSSL_ERROR_MSG("rsa n key error");
  2271. ret = -1;
  2272. }
  2273. /* Copy down public exponent if available. */
  2274. if ((ret == 1) && (rsa->e != NULL) &&
  2275. (wolfssl_bn_get_value(rsa->e, &key->e) != 1)) {
  2276. WOLFSSL_ERROR_MSG("rsa e key error");
  2277. ret = -1;
  2278. }
  2279. /* Enough numbers for public key */
  2280. key->type = RSA_PUBLIC;
  2281. /* Copy down private exponent if available. */
  2282. if ((ret == 1) && (rsa->d != NULL)) {
  2283. if (wolfssl_bn_get_value(rsa->d, &key->d) != 1) {
  2284. WOLFSSL_ERROR_MSG("rsa d key error");
  2285. ret = -1;
  2286. }
  2287. else {
  2288. /* Enough numbers for private key */
  2289. key->type = RSA_PRIVATE;
  2290. }
  2291. }
  2292. /* Copy down first prime if available. */
  2293. if ((ret == 1) && (rsa->p != NULL) &&
  2294. (wolfssl_bn_get_value(rsa->p, &key->p) != 1)) {
  2295. WOLFSSL_ERROR_MSG("rsa p key error");
  2296. ret = -1;
  2297. }
  2298. /* Copy down second prime if available. */
  2299. if ((ret == 1) && (rsa->q != NULL) &&
  2300. (wolfssl_bn_get_value(rsa->q, &key->q) != 1)) {
  2301. WOLFSSL_ERROR_MSG("rsa q key error");
  2302. ret = -1;
  2303. }
  2304. #ifndef RSA_LOW_MEM
  2305. /* Copy down d mod p-1 if available. */
  2306. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2307. (wolfssl_bn_get_value(rsa->dmp1, &key->dP) != 1)) {
  2308. WOLFSSL_ERROR_MSG("rsa dP key error");
  2309. ret = -1;
  2310. }
  2311. /* Copy down d mod q-1 if available. */
  2312. if ((ret == 1) && (rsa->dmp1 != NULL) &&
  2313. (wolfssl_bn_get_value(rsa->dmq1, &key->dQ) != 1)) {
  2314. WOLFSSL_ERROR_MSG("rsa dQ key error");
  2315. ret = -1;
  2316. }
  2317. /* Copy down 1/q mod p if available. */
  2318. if ((ret == 1) && (rsa->iqmp != NULL) &&
  2319. (wolfssl_bn_get_value(rsa->iqmp, &key->u) != 1)) {
  2320. WOLFSSL_ERROR_MSG("rsa u key error");
  2321. ret = -1;
  2322. }
  2323. #endif /* !RSA_LOW_MEM */
  2324. if (ret == 1) {
  2325. /* All available numbers have been set down. */
  2326. rsa->inSet = 1;
  2327. }
  2328. }
  2329. return ret;
  2330. }
  2331. #endif /* HAVE_USER_RSA */
  2332. /* Set the RSA method into object.
  2333. *
  2334. * @param [in, out] rsa RSA key.
  2335. * @param [in] meth RSA method.
  2336. * @return 1 always.
  2337. */
  2338. int wolfSSL_RSA_set_method(WOLFSSL_RSA *rsa, WOLFSSL_RSA_METHOD *meth)
  2339. {
  2340. if (rsa != NULL) {
  2341. /* Store the method into object. */
  2342. rsa->meth = meth;
  2343. /* Copy over flags. */
  2344. rsa->flags = meth->flags;
  2345. }
  2346. /* OpenSSL always assumes it will work. */
  2347. return 1;
  2348. }
  2349. /* Get the RSA method from the RSA object.
  2350. *
  2351. * @param [in] rsa RSA key.
  2352. * @return RSA method on success.
  2353. * @return NULL when RSA is NULL or no method set.
  2354. */
  2355. const WOLFSSL_RSA_METHOD* wolfSSL_RSA_get_method(const WOLFSSL_RSA *rsa)
  2356. {
  2357. return (rsa != NULL) ? rsa->meth : NULL;
  2358. }
  2359. /* Get the size in bytes of the RSA key.
  2360. *
  2361. * Return compliant with OpenSSL
  2362. *
  2363. * @param [in] rsa RSA key.
  2364. * @return RSA modulus size in bytes.
  2365. * @return 0 on error.
  2366. */
  2367. int wolfSSL_RSA_size(const WOLFSSL_RSA* rsa)
  2368. {
  2369. int ret = 0;
  2370. WOLFSSL_ENTER("wolfSSL_RSA_size");
  2371. if (rsa != NULL) {
  2372. /* Make sure we have set the RSA values into wolfCrypt RSA key. */
  2373. if (rsa->inSet || (SetRsaInternal((WOLFSSL_RSA*)rsa) == 1)) {
  2374. /* Get key size in bytes using wolfCrypt RSA key. */
  2375. ret = wc_RsaEncryptSize((RsaKey*)rsa->internal);
  2376. }
  2377. }
  2378. return ret;
  2379. }
  2380. /* Get the size in bits of the RSA key.
  2381. *
  2382. * Uses external modulus field.
  2383. *
  2384. * @param [in] rsa RSA key.
  2385. * @return RSA modulus size in bits.
  2386. * @return 0 on error.
  2387. */
  2388. int wolfSSL_RSA_bits(const WOLFSSL_RSA* rsa)
  2389. {
  2390. int ret = 0;
  2391. WOLFSSL_ENTER("wolfSSL_RSA_bits");
  2392. if (rsa != NULL) {
  2393. /* Get number of bits in external modulus. */
  2394. ret = wolfSSL_BN_num_bits(rsa->n);
  2395. }
  2396. return ret;
  2397. }
  2398. #ifndef HAVE_USER_RSA
  2399. /* Get the BN objects that are the Chinese-Remainder Theorem (CRT) parameters.
  2400. *
  2401. * Only for those that are not NULL parameters.
  2402. *
  2403. * @param [in] rsa RSA key.
  2404. * @param [out] dmp1 BN that is d mod (p - 1). May be NULL.
  2405. * @param [out] dmq1 BN that is d mod (q - 1). May be NULL.
  2406. * @param [out] iqmp BN that is 1/q mod p. May be NULL.
  2407. */
  2408. void wolfSSL_RSA_get0_crt_params(const WOLFSSL_RSA *rsa,
  2409. const WOLFSSL_BIGNUM **dmp1, const WOLFSSL_BIGNUM **dmq1,
  2410. const WOLFSSL_BIGNUM **iqmp)
  2411. {
  2412. WOLFSSL_ENTER("wolfSSL_RSA_get0_crt_params");
  2413. /* For any parameters not NULL, return the BN from the key or NULL. */
  2414. if (dmp1 != NULL) {
  2415. *dmp1 = (rsa != NULL) ? rsa->dmp1 : NULL;
  2416. }
  2417. if (dmq1 != NULL) {
  2418. *dmq1 = (rsa != NULL) ? rsa->dmq1 : NULL;
  2419. }
  2420. if (iqmp != NULL) {
  2421. *iqmp = (rsa != NULL) ? rsa->iqmp : NULL;
  2422. }
  2423. }
  2424. /* Set the BN objects that are the Chinese-Remainder Theorem (CRT) parameters
  2425. * into RSA key.
  2426. *
  2427. * If CRT parameter is NULL then there must be one in the RSA key already.
  2428. *
  2429. * @param [in, out] rsa RSA key.
  2430. * @param [in] dmp1 BN that is d mod (p - 1). May be NULL.
  2431. * @param [in] dmq1 BN that is d mod (q - 1). May be NULL.
  2432. * @param [in] iqmp BN that is 1/q mod p. May be NULL.
  2433. * @return 1 on success.
  2434. * @return 0 on failure.
  2435. */
  2436. int wolfSSL_RSA_set0_crt_params(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *dmp1,
  2437. WOLFSSL_BIGNUM *dmq1, WOLFSSL_BIGNUM *iqmp)
  2438. {
  2439. int ret = 1;
  2440. WOLFSSL_ENTER("wolfSSL_RSA_set0_crt_params");
  2441. /* If a param is NULL in rsa then it must be non-NULL in the
  2442. * corresponding user input. */
  2443. if ((rsa == NULL) || ((rsa->dmp1 == NULL) && (dmp1 == NULL)) ||
  2444. ((rsa->dmq1 == NULL) && (dmq1 == NULL)) ||
  2445. ((rsa->iqmp == NULL) && (iqmp == NULL))) {
  2446. WOLFSSL_ERROR_MSG("Bad parameters");
  2447. ret = 0;
  2448. }
  2449. if (ret == 1) {
  2450. /* Replace the BNs. */
  2451. if (dmp1 != NULL) {
  2452. wolfSSL_BN_clear_free(rsa->dmp1);
  2453. rsa->dmp1 = dmp1;
  2454. }
  2455. if (dmq1 != NULL) {
  2456. wolfSSL_BN_clear_free(rsa->dmq1);
  2457. rsa->dmq1 = dmq1;
  2458. }
  2459. if (iqmp != NULL) {
  2460. wolfSSL_BN_clear_free(rsa->iqmp);
  2461. rsa->iqmp = iqmp;
  2462. }
  2463. /* Set the values into the wolfCrypt RSA key. */
  2464. if (SetRsaInternal(rsa) != 1) {
  2465. ret = 0;
  2466. }
  2467. }
  2468. return ret;
  2469. }
  2470. /* Get the BN objects that are the factors of the RSA key (two primes p and q).
  2471. *
  2472. * @param [in] rsa RSA key.
  2473. * @param [out] p BN that is first prime. May be NULL.
  2474. * @param [out] q BN that is second prime. May be NULL.
  2475. */
  2476. void wolfSSL_RSA_get0_factors(const WOLFSSL_RSA *rsa, const WOLFSSL_BIGNUM **p,
  2477. const WOLFSSL_BIGNUM **q)
  2478. {
  2479. WOLFSSL_ENTER("wolfSSL_RSA_get0_factors");
  2480. /* For any primes not NULL, return the BN from the key or NULL. */
  2481. if (p != NULL) {
  2482. *p = (rsa != NULL) ? rsa->p : NULL;
  2483. }
  2484. if (q != NULL) {
  2485. *q = (rsa != NULL) ? rsa->q : NULL;
  2486. }
  2487. }
  2488. /* Set the BN objects that are the factors of the RSA key (two primes p and q).
  2489. *
  2490. * If factor parameter is NULL then there must be one in the RSA key already.
  2491. *
  2492. * @param [in, out] rsa RSA key.
  2493. * @param [in] p BN that is first prime. May be NULL.
  2494. * @param [in] q BN that is second prime. May be NULL.
  2495. * @return 1 on success.
  2496. * @return 0 on failure.
  2497. */
  2498. int wolfSSL_RSA_set0_factors(WOLFSSL_RSA *rsa, WOLFSSL_BIGNUM *p,
  2499. WOLFSSL_BIGNUM *q)
  2500. {
  2501. int ret = 1;
  2502. WOLFSSL_ENTER("wolfSSL_RSA_set0_factors");
  2503. /* If a param is null in r then it must be non-null in the
  2504. * corresponding user input. */
  2505. if (rsa == NULL || ((rsa->p == NULL) && (p == NULL)) ||
  2506. ((rsa->q == NULL) && (q == NULL))) {
  2507. WOLFSSL_ERROR_MSG("Bad parameters");
  2508. ret = 0;
  2509. }
  2510. if (ret == 1) {
  2511. /* Replace the BNs. */
  2512. if (p != NULL) {
  2513. wolfSSL_BN_clear_free(rsa->p);
  2514. rsa->p = p;
  2515. }
  2516. if (q != NULL) {
  2517. wolfSSL_BN_clear_free(rsa->q);
  2518. rsa->q = q;
  2519. }
  2520. /* Set the values into the wolfCrypt RSA key. */
  2521. if (SetRsaInternal(rsa) != 1) {
  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. ret = 0;
  2592. }
  2593. }
  2594. return ret;
  2595. }
  2596. #endif /* !HAVE_USER_RSA */
  2597. /* Get the flags of the RSA key.
  2598. *
  2599. * @param [in] rsa RSA key.
  2600. * @return Flags set in RSA key on success.
  2601. * @return 0 when RSA key is NULL.
  2602. */
  2603. int wolfSSL_RSA_flags(const WOLFSSL_RSA *rsa)
  2604. {
  2605. int ret = 0;
  2606. /* Get flags from the RSA key if available. */
  2607. if (rsa != NULL) {
  2608. ret = rsa->flags;
  2609. }
  2610. return ret;
  2611. }
  2612. /* Set the flags into the RSA key.
  2613. *
  2614. * @param [in, out] rsa RSA key.
  2615. * @param [in] flags Flags to set.
  2616. */
  2617. void wolfSSL_RSA_set_flags(WOLFSSL_RSA *rsa, int flags)
  2618. {
  2619. /* Add the flags into RSA key if available. */
  2620. if (rsa != NULL) {
  2621. rsa->flags |= flags;
  2622. }
  2623. }
  2624. /* Clear the flags in the RSA key.
  2625. *
  2626. * @param [in, out] rsa RSA key.
  2627. * @param [in] flags Flags to clear.
  2628. */
  2629. void wolfSSL_RSA_clear_flags(WOLFSSL_RSA *rsa, int flags)
  2630. {
  2631. /* Clear the flags passed in that are on the RSA key if available. */
  2632. if (rsa != NULL) {
  2633. rsa->flags &= ~flags;
  2634. }
  2635. }
  2636. /* Test the flags in the RSA key.
  2637. *
  2638. * @param [in] rsa RSA key.
  2639. * @return Matching flags of RSA key on success.
  2640. * @return 0 when RSA key is NULL.
  2641. */
  2642. int wolfSSL_RSA_test_flags(const WOLFSSL_RSA *rsa, int flags)
  2643. {
  2644. /* Return the flags passed in that are set on the RSA key if available. */
  2645. return (rsa != NULL) ? (rsa->flags & flags) : 0;
  2646. }
  2647. /* Get the extra data, by index, associated with the RSA key.
  2648. *
  2649. * @param [in] rsa RSA key.
  2650. * @param [in] idx Index of extra data.
  2651. * @return Extra data (anonymous type) on success.
  2652. * @return NULL on failure.
  2653. */
  2654. void* wolfSSL_RSA_get_ex_data(const WOLFSSL_RSA *rsa, int idx)
  2655. {
  2656. WOLFSSL_ENTER("wolfSSL_RSA_get_ex_data");
  2657. #ifdef HAVE_EX_DATA
  2658. return (rsa == NULL) ? NULL :
  2659. wolfSSL_CRYPTO_get_ex_data(&rsa->ex_data, idx);
  2660. #else
  2661. (void)rsa;
  2662. (void)idx;
  2663. return NULL;
  2664. #endif
  2665. }
  2666. /* Set extra data against the RSA key at an index.
  2667. *
  2668. * @param [in, out] rsa RSA key.
  2669. * @param [in] idx Index set set extra data at.
  2670. * @param [in] data Extra data of anonymous type.
  2671. * @return 1 on success.
  2672. * @return 0 on failure.
  2673. */
  2674. int wolfSSL_RSA_set_ex_data(WOLFSSL_RSA *rsa, int idx, void *data)
  2675. {
  2676. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data");
  2677. #ifdef HAVE_EX_DATA
  2678. return (rsa == NULL) ? 0 :
  2679. wolfSSL_CRYPTO_set_ex_data(&rsa->ex_data, idx, data);
  2680. #else
  2681. (void)rsa;
  2682. (void)idx;
  2683. (void)data;
  2684. return 0;
  2685. #endif
  2686. }
  2687. #ifdef HAVE_EX_DATA_CLEANUP_HOOKS
  2688. /* Set the extra data and cleanup callback against the RSA key at an index.
  2689. *
  2690. * Not OpenSSL API.
  2691. *
  2692. * @param [in, out] rsa RSA key.
  2693. * @param [in] idx Index set set extra data at.
  2694. * @param [in] data Extra data of anonymous type.
  2695. * @param [in] freeCb Callback function to free extra data.
  2696. * @return 1 on success.
  2697. * @return 0 on failure.
  2698. */
  2699. int wolfSSL_RSA_set_ex_data_with_cleanup(WOLFSSL_RSA *rsa, int idx, void *data,
  2700. wolfSSL_ex_data_cleanup_routine_t freeCb)
  2701. {
  2702. WOLFSSL_ENTER("wolfSSL_RSA_set_ex_data_with_cleanup");
  2703. return (rsa == NULL) ? 0 :
  2704. wolfSSL_CRYPTO_set_ex_data_with_cleanup(&rsa->ex_data, idx, data,
  2705. freeCb);
  2706. }
  2707. #endif /* HAVE_EX_DATA_CLEANUP_HOOKS */
  2708. /*
  2709. * RSA check key APIs
  2710. */
  2711. #ifdef WOLFSSL_RSA_KEY_CHECK
  2712. /* Check that the RSA key is valid using wolfCrypt.
  2713. *
  2714. * @param [in] rsa RSA key.
  2715. * @return 1 on success.
  2716. * @return 0 on failure.
  2717. */
  2718. int wolfSSL_RSA_check_key(const WOLFSSL_RSA* rsa)
  2719. {
  2720. int ret = 1;
  2721. WOLFSSL_ENTER("wolfSSL_RSA_check_key");
  2722. /* Validate parameters. */
  2723. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2724. ret = 0;
  2725. }
  2726. /* Constant RSA - assume internal data has been set. */
  2727. /* Check wolfCrypt RSA key. */
  2728. if ((ret == 1) && (wc_CheckRsaKey((RsaKey*)rsa->internal) != 0)) {
  2729. ret = 0;
  2730. }
  2731. WOLFSSL_LEAVE("wolfSSL_RSA_check_key", ret);
  2732. return ret;
  2733. }
  2734. #endif /* WOLFSSL_RSA_KEY_CHECK */
  2735. /*
  2736. * RSA generate APIs
  2737. */
  2738. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  2739. /* Get a random number generator associated with the RSA key.
  2740. *
  2741. * If not able, then get the global if possible.
  2742. * *tmpRng must not be an initialized RNG.
  2743. * *tmpRng is allocated when WOLFSSL_SMALL_STACK is defined and an RNG isn't
  2744. * associated with the wolfCrypt RSA key.
  2745. *
  2746. * @param [in] rsa RSA key.
  2747. * @param [out] tmpRng Temporary random number generator.
  2748. * @param [out] initTmpRng Temporary random number generator was initialized.
  2749. *
  2750. * @return A wolfCrypt RNG to use on success.
  2751. * @return NULL on error.
  2752. */
  2753. WC_RNG* WOLFSSL_RSA_GetRNG(WOLFSSL_RSA* rsa, WC_RNG** tmpRng, int* initTmpRng)
  2754. {
  2755. WC_RNG* rng = NULL;
  2756. int err = 0;
  2757. /* Check validity of parameters. */
  2758. if ((rsa == NULL) || (initTmpRng == NULL)) {
  2759. err = 1;
  2760. }
  2761. if (!err) {
  2762. /* Haven't initialized any RNG passed through tmpRng. */
  2763. *initTmpRng = 0;
  2764. #if !defined(HAVE_FIPS) && defined(WC_RSA_BLINDING)
  2765. /* Use wolfCrypt RSA key's RNG if available/set. */
  2766. rng = ((RsaKey*)rsa->internal)->rng;
  2767. #endif
  2768. }
  2769. if ((!err) && (rng == NULL) && (tmpRng != NULL)) {
  2770. /* Make an RNG with tmpRng or get global. */
  2771. rng = wolfssl_make_rng(*tmpRng, initTmpRng);
  2772. if ((rng != NULL) && *initTmpRng) {
  2773. *tmpRng = rng;
  2774. }
  2775. }
  2776. return rng;
  2777. }
  2778. #endif
  2779. /* Use the wolfCrypt RSA APIs to generate a new RSA key.
  2780. *
  2781. * @param [in, out] rsa RSA key.
  2782. * @param [in] bits Number of bits that the modulus must have.
  2783. * @param [in] e A BN object holding the public exponent to use.
  2784. * @param [in] cb Status callback. Unused.
  2785. * @return 0 on success.
  2786. * @return wolfSSL native error code on error.
  2787. */
  2788. static int wolfssl_rsa_generate_key_native(WOLFSSL_RSA* rsa, int bits,
  2789. WOLFSSL_BIGNUM* e, void* cb)
  2790. {
  2791. #ifdef WOLFSSL_KEY_GEN
  2792. int ret = 0;
  2793. #ifdef WOLFSSL_SMALL_STACK
  2794. WC_RNG* tmpRng = NULL;
  2795. #else
  2796. WC_RNG _tmpRng[1];
  2797. WC_RNG* tmpRng = _tmpRng;
  2798. #endif
  2799. int initTmpRng = 0;
  2800. WC_RNG* rng = NULL;
  2801. #endif
  2802. (void)cb;
  2803. WOLFSSL_ENTER("wolfssl_rsa_generate_key_native");
  2804. #ifdef WOLFSSL_KEY_GEN
  2805. /* Get RNG in wolfCrypt RSA key or initialize a new one (or global). */
  2806. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  2807. if (rng == NULL) {
  2808. /* Something went wrong so return memory error. */
  2809. ret = MEMORY_E;
  2810. }
  2811. if (ret == 0) {
  2812. /* Generate an RSA key. */
  2813. ret = wc_MakeRsaKey((RsaKey*)rsa->internal, bits,
  2814. (long)wolfSSL_BN_get_word(e), rng);
  2815. if (ret != MP_OKAY) {
  2816. WOLFSSL_ERROR_MSG("wc_MakeRsaKey failed");
  2817. }
  2818. }
  2819. if (ret == 0) {
  2820. /* Get the values from wolfCrypt RSA key into external RSA key. */
  2821. ret = SetRsaExternal(rsa);
  2822. if (ret == 1) {
  2823. /* Internal matches external. */
  2824. rsa->inSet = 1;
  2825. /* Return success. */
  2826. ret = 0;
  2827. }
  2828. else {
  2829. /* Something went wrong so return memory error. */
  2830. ret = MEMORY_E;
  2831. }
  2832. }
  2833. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  2834. if (initTmpRng) {
  2835. wc_FreeRng(tmpRng);
  2836. }
  2837. #ifdef WOLFSSL_SMALL_STACK
  2838. /* Dispose of any allocated RNG. */
  2839. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  2840. #endif
  2841. return ret;
  2842. #else
  2843. WOLFSSL_ERROR_MSG("No Key Gen built in");
  2844. (void)rsa;
  2845. (void)e;
  2846. (void)bits;
  2847. return NOT_COMPILED_IN;
  2848. #endif
  2849. }
  2850. /* Generate an RSA key that has the specified modulus size and public exponent.
  2851. *
  2852. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2853. * down to nearest multiple of 8. For example generating a key of size
  2854. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2855. *
  2856. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2857. * @param [in] e Public exponent to use i.e. 65537.
  2858. * @param [in] cb Status callback. Unused.
  2859. * @param [in] data Data to pass to status callback. Unused.
  2860. * @return A new RSA key on success.
  2861. * @return NULL on failure.
  2862. */
  2863. WOLFSSL_RSA* wolfSSL_RSA_generate_key(int bits, unsigned long e,
  2864. void(*cb)(int, int, void*), void* data)
  2865. {
  2866. WOLFSSL_RSA* rsa = NULL;
  2867. WOLFSSL_BIGNUM* bn = NULL;
  2868. int err = 0;
  2869. WOLFSSL_ENTER("wolfSSL_RSA_generate_key");
  2870. (void)cb;
  2871. (void)data;
  2872. /* Validate bits. */
  2873. if (bits < 0) {
  2874. WOLFSSL_ERROR_MSG("Bad argument: bits was less than 0");
  2875. err = 1;
  2876. }
  2877. /* Create a new BN to hold public exponent - for when wolfCrypt supports
  2878. * longer values. */
  2879. if ((!err) && ((bn = wolfSSL_BN_new()) == NULL)) {
  2880. WOLFSSL_ERROR_MSG("Error creating big number");
  2881. err = 1;
  2882. }
  2883. /* Set public exponent. */
  2884. if ((!err) && (wolfSSL_BN_set_word(bn, e) != 1)) {
  2885. WOLFSSL_ERROR_MSG("Error using e value");
  2886. err = 1;
  2887. }
  2888. /* Create an RSA key object to hold generated key. */
  2889. if ((!err) && ((rsa = wolfSSL_RSA_new()) == NULL)) {
  2890. WOLFSSL_ERROR_MSG("memory error");
  2891. err = 1;
  2892. }
  2893. while (!err) {
  2894. int ret;
  2895. /* Use wolfCrypt to generate RSA key. */
  2896. ret = wolfssl_rsa_generate_key_native(rsa, bits, bn, NULL);
  2897. #ifdef HAVE_FIPS
  2898. /* Keep trying if failed to find a prime. */
  2899. if (ret == PRIME_GEN_E) {
  2900. continue;
  2901. }
  2902. #endif
  2903. if (ret != WOLFSSL_ERROR_NONE) {
  2904. /* Unrecoverable error in generation. */
  2905. err = 1;
  2906. }
  2907. /* Done generating - unrecoverable error or success. */
  2908. break;
  2909. }
  2910. if (err) {
  2911. /* Dispose of RSA key object if generation didn't work. */
  2912. wolfSSL_RSA_free(rsa);
  2913. /* Returning NULL on error. */
  2914. rsa = NULL;
  2915. }
  2916. /* Dispose of the temporary BN used for the public exponent. */
  2917. wolfSSL_BN_free(bn);
  2918. return rsa;
  2919. }
  2920. /* Generate an RSA key that has the specified modulus size and public exponent.
  2921. *
  2922. * Note: Because of wc_MakeRsaKey an RSA key size generated can be rounded
  2923. * down to nearest multiple of 8. For example generating a key of size
  2924. * 2999 bits will make a key of size 374 bytes instead of 375 bytes.
  2925. *
  2926. * @param [in] bits Number of bits that the modulus must have i.e. 2048.
  2927. * @param [in] e Public exponent to use, i.e. 65537, as a BN.
  2928. * @param [in] cb Status callback. Unused.
  2929. * @return 1 on success.
  2930. * @return 0 on failure.
  2931. */
  2932. int wolfSSL_RSA_generate_key_ex(WOLFSSL_RSA* rsa, int bits, WOLFSSL_BIGNUM* e,
  2933. void* cb)
  2934. {
  2935. int ret = 1;
  2936. /* Validate parameters. */
  2937. if ((rsa == NULL) || (rsa->internal == NULL)) {
  2938. WOLFSSL_ERROR_MSG("bad arguments");
  2939. ret = 0;
  2940. }
  2941. else {
  2942. for (;;) {
  2943. /* Use wolfCrypt to generate RSA key. */
  2944. int gen_ret = wolfssl_rsa_generate_key_native(rsa, bits, e, cb);
  2945. #ifdef HAVE_FIPS
  2946. /* Keep trying again if public key value didn't work. */
  2947. if (gen_ret == PRIME_GEN_E) {
  2948. continue;
  2949. }
  2950. #endif
  2951. if (gen_ret != WOLFSSL_ERROR_NONE) {
  2952. /* Unrecoverable error in generation. */
  2953. ret = 0;
  2954. }
  2955. /* Done generating - unrecoverable error or success. */
  2956. break;
  2957. }
  2958. }
  2959. return ret;
  2960. }
  2961. #endif /* OPENSSL_EXTRA */
  2962. /*
  2963. * RSA padding APIs
  2964. */
  2965. #if defined(WC_RSA_PSS) && (defined(OPENSSL_ALL) || defined(WOLFSSL_ASIO) || \
  2966. defined(WOLFSSL_HAPROXY) || defined(WOLFSSL_NGINX))
  2967. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  2968. /* Add PKCS#1 PSS padding to hash.
  2969. *
  2970. *
  2971. * +-----------+
  2972. * | M |
  2973. * +-----------+
  2974. * |
  2975. * V
  2976. * Hash
  2977. * |
  2978. * V
  2979. * +--------+----------+----------+
  2980. * M' = |Padding1| mHash | salt |
  2981. * +--------+----------+----------+
  2982. * |
  2983. * +--------+----------+ V
  2984. * DB = |Padding2|maskedseed| Hash
  2985. * +--------+----------+ |
  2986. * | |
  2987. * V | +--+
  2988. * xor <--- MGF <---| |bc|
  2989. * | | +--+
  2990. * | | |
  2991. * V V V
  2992. * +-------------------+----------+--+
  2993. * EM = | maskedDB |maskedseed|bc|
  2994. * +-------------------+----------+--+
  2995. * Diagram taken from https://tools.ietf.org/html/rfc3447#section-9.1
  2996. *
  2997. * @param [in] rsa RSA key.
  2998. * @param [out] em Encoded message.
  2999. * @param [in[ mHash Message hash.
  3000. * @param [in] hashAlg Hash algorithm.
  3001. * @param [in] saltLen Length of salt to generate.
  3002. * @return 1 on success.
  3003. * @return 0 on failure.
  3004. */
  3005. int wolfSSL_RSA_padding_add_PKCS1_PSS(WOLFSSL_RSA *rsa, unsigned char *em,
  3006. const unsigned char *mHash, const WOLFSSL_EVP_MD *hashAlg, int saltLen)
  3007. {
  3008. int ret = 1;
  3009. enum wc_HashType hashType;
  3010. int hashLen = 0;
  3011. int emLen = 0;
  3012. int mgf = 0;
  3013. int initTmpRng = 0;
  3014. WC_RNG *rng = NULL;
  3015. #ifdef WOLFSSL_SMALL_STACK
  3016. WC_RNG* tmpRng = NULL;
  3017. #else
  3018. WC_RNG _tmpRng[1];
  3019. WC_RNG* tmpRng = _tmpRng;
  3020. #endif
  3021. WOLFSSL_ENTER("wolfSSL_RSA_padding_add_PKCS1_PSS");
  3022. /* Validate parameters. */
  3023. if ((rsa == NULL) || (em == NULL) || (mHash == NULL) || (hashAlg == NULL)) {
  3024. ret = 0;
  3025. }
  3026. if (ret == 1) {
  3027. /* Get/create an RNG. */
  3028. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3029. if (rng == NULL) {
  3030. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3031. ret = 0;
  3032. }
  3033. }
  3034. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3035. /* Set the external data from the wolfCrypt RSA key if not done. */
  3036. if ((ret == 1) && (!rsa->exSet)) {
  3037. ret = SetRsaExternal(rsa);
  3038. }
  3039. if (ret == 1) {
  3040. /* Get the wolfCrypt hash algorithm type. */
  3041. hashType = EvpMd2MacType(hashAlg);
  3042. if (hashType > WC_HASH_TYPE_MAX) {
  3043. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3044. ret = 0;
  3045. }
  3046. }
  3047. if (ret == 1) {
  3048. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3049. mgf = wc_hash2mgf(hashType);
  3050. if (mgf == WC_MGF1NONE) {
  3051. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3052. ret = 0;
  3053. }
  3054. }
  3055. if (ret == 1) {
  3056. /* Get the length of the hash output. */
  3057. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3058. if (hashLen < 0) {
  3059. WOLFSSL_ERROR_MSG("wolfSSL_EVP_MD_size error");
  3060. ret = 0;
  3061. }
  3062. }
  3063. if (ret == 1) {
  3064. /* Get length of RSA key - encrypted message length. */
  3065. emLen = wolfSSL_RSA_size(rsa);
  3066. if (ret <= 0) {
  3067. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3068. ret = 0;
  3069. }
  3070. }
  3071. if (ret == 1) {
  3072. /* Calculate the salt length to use for special cases. */
  3073. /* TODO: use special case wolfCrypt values? */
  3074. switch (saltLen) {
  3075. /* Negative saltLen values are treated differently. */
  3076. case RSA_PSS_SALTLEN_DIGEST:
  3077. saltLen = hashLen;
  3078. break;
  3079. case RSA_PSS_SALTLEN_MAX_SIGN:
  3080. case RSA_PSS_SALTLEN_MAX:
  3081. #ifdef WOLFSSL_PSS_LONG_SALT
  3082. saltLen = emLen - hashLen - 2;
  3083. #else
  3084. saltLen = hashLen;
  3085. #endif
  3086. break;
  3087. default:
  3088. if (saltLen < 0) {
  3089. /* No other negative values implemented. */
  3090. WOLFSSL_ERROR_MSG("invalid saltLen");
  3091. ret = 0;
  3092. }
  3093. }
  3094. }
  3095. if (ret == 1) {
  3096. /* Generate RSA PKCS#1 PSS padding for hash using wolfCrypt. */
  3097. if (wc_RsaPad_ex(mHash, hashLen, em, emLen, RSA_BLOCK_TYPE_1, rng,
  3098. WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3099. wolfSSL_BN_num_bits(rsa->n), NULL) != MP_OKAY) {
  3100. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3101. ret = 0;
  3102. }
  3103. }
  3104. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3105. if (initTmpRng) {
  3106. wc_FreeRng(tmpRng);
  3107. }
  3108. #ifdef WOLFSSL_SMALL_STACK
  3109. /* Dispose of any allocated RNG. */
  3110. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3111. #endif
  3112. return ret;
  3113. }
  3114. /* Checks that the hash is valid for the RSA PKCS#1 PSS encoded message.
  3115. *
  3116. * Refer to wolfSSL_RSA_padding_add_PKCS1_PSS for a diagram.
  3117. *
  3118. * @param [in] rsa RSA key.
  3119. * @param [in[ mHash Message hash.
  3120. * @param [in] hashAlg Hash algorithm.
  3121. * @param [in] em Encoded message.
  3122. * @param [in] saltLen Length of salt to generate.
  3123. * @return 1 on success.
  3124. * @return 0 on failure.
  3125. */
  3126. int wolfSSL_RSA_verify_PKCS1_PSS(WOLFSSL_RSA *rsa, const unsigned char *mHash,
  3127. const WOLFSSL_EVP_MD *hashAlg,
  3128. const unsigned char *em, int saltLen)
  3129. {
  3130. int ret = 1;
  3131. int hashLen = 0;
  3132. int mgf = 0;
  3133. int emLen = 0;
  3134. int mPrimeLen = 0;
  3135. enum wc_HashType hashType = WC_HASH_TYPE_NONE;
  3136. byte *mPrime = NULL;
  3137. byte *buf = NULL;
  3138. WOLFSSL_ENTER("wolfSSL_RSA_verify_PKCS1_PSS");
  3139. /* Validate parameters. */
  3140. if ((rsa == NULL) || (mHash == NULL) || (hashAlg == NULL) || (em == NULL)) {
  3141. ret = 0;
  3142. }
  3143. /* TODO: use wolfCrypt RSA key to get emLen and bits? */
  3144. /* Set the external data from the wolfCrypt RSA key if not done. */
  3145. if ((ret == 1) && (!rsa->exSet)) {
  3146. ret = SetRsaExternal(rsa);
  3147. }
  3148. if (ret == 1) {
  3149. /* Get hash length for hash algorithm. */
  3150. hashLen = wolfSSL_EVP_MD_size(hashAlg);
  3151. if (hashLen < 0) {
  3152. ret = 0;
  3153. }
  3154. }
  3155. if (ret == 1) {
  3156. /* Get length of RSA key - encrypted message length. */
  3157. emLen = wolfSSL_RSA_size(rsa);
  3158. if (emLen <= 0) {
  3159. WOLFSSL_ERROR_MSG("wolfSSL_RSA_size error");
  3160. ret = 0;
  3161. }
  3162. }
  3163. if (ret == 1) {
  3164. /* Calculate the salt length to use for special cases. */
  3165. /* TODO: use special case wolfCrypt values. */
  3166. switch (saltLen) {
  3167. /* Negative saltLen values are treated differently */
  3168. case RSA_PSS_SALTLEN_DIGEST:
  3169. saltLen = hashLen;
  3170. break;
  3171. case RSA_PSS_SALTLEN_MAX_SIGN:
  3172. case RSA_PSS_SALTLEN_MAX:
  3173. #ifdef WOLFSSL_PSS_LONG_SALT
  3174. saltLen = emLen - hashLen - 2;
  3175. #else
  3176. saltLen = hashLen;
  3177. #endif
  3178. break;
  3179. default:
  3180. if (saltLen < 0) {
  3181. /* No other negative values implemented. */
  3182. WOLFSSL_ERROR_MSG("invalid saltLen");
  3183. ret = 0;
  3184. }
  3185. }
  3186. }
  3187. if (ret == 1) {
  3188. /* Get the wolfCrypt hash algorithm type. */
  3189. hashType = EvpMd2MacType(hashAlg);
  3190. if (hashType > WC_HASH_TYPE_MAX) {
  3191. WOLFSSL_ERROR_MSG("EvpMd2MacType error");
  3192. ret = 0;
  3193. }
  3194. }
  3195. if (ret == 1) {
  3196. /* Get the wolfCrypt MGF algorithm from hash algorithm. */
  3197. if ((mgf = wc_hash2mgf(hashType)) == WC_MGF1NONE) {
  3198. WOLFSSL_ERROR_MSG("wc_hash2mgf error");
  3199. ret = 0;
  3200. }
  3201. }
  3202. if (ret == 1) {
  3203. /* Allocate buffer to unpad inline with. */
  3204. buf = (byte*)XMALLOC(emLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3205. if (buf == NULL) {
  3206. WOLFSSL_ERROR_MSG("malloc error");
  3207. ret = 0;
  3208. }
  3209. }
  3210. if (ret == 1) {
  3211. /* Copy encrypted message to temp for inline unpadding. */
  3212. XMEMCPY(buf, em, emLen);
  3213. /* Remove and verify the PSS padding. */
  3214. mPrimeLen = wc_RsaUnPad_ex(buf, emLen, &mPrime, RSA_BLOCK_TYPE_1,
  3215. WC_RSA_PSS_PAD, hashType, mgf, NULL, 0, saltLen,
  3216. wolfSSL_BN_num_bits(rsa->n), NULL);
  3217. if (mPrimeLen < 0) {
  3218. WOLFSSL_ERROR_MSG("wc_RsaPad_ex error");
  3219. ret = 0;
  3220. }
  3221. }
  3222. if (ret == 1) {
  3223. /* Verify the hash is correct. */
  3224. if (wc_RsaPSS_CheckPadding_ex(mHash, hashLen, mPrime, mPrimeLen,
  3225. hashType, saltLen, wolfSSL_BN_num_bits(rsa->n)) != MP_OKAY) {
  3226. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3227. ret = 0;
  3228. }
  3229. }
  3230. /* Dispose of any allocated buffer. */
  3231. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3232. return ret;
  3233. }
  3234. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  3235. #endif /* WC_RSA_PSS && (OPENSSL_ALL || WOLFSSL_ASIO || WOLFSSL_HAPROXY ||
  3236. * WOLFSSL_NGINX) */
  3237. /*
  3238. * RSA sign/verify APIs
  3239. */
  3240. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3241. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DEFAULT
  3242. #else
  3243. #define DEF_PSS_SALT_LEN RSA_PSS_SALT_LEN_DISCOVER
  3244. #endif
  3245. #if defined(OPENSSL_EXTRA)
  3246. #if !defined(HAVE_USER_RSA)
  3247. /* Encode the message hash.
  3248. *
  3249. * Used by signing and verification.
  3250. *
  3251. * @param [in] hashAlg Hash algorithm OID.
  3252. * @param [in] hash Hash of message to encode for signing.
  3253. * @param [in] hLen Length of hash of message.
  3254. * @param [out] enc Encoded message hash.
  3255. * @param [out] encLen Length of encoded message hash.
  3256. * @param [in] padding Which padding scheme is being used.
  3257. * @return 1 on success.
  3258. * @return 0 on failure.
  3259. */
  3260. static int wolfssl_rsa_sig_encode(int hashAlg, const unsigned char* hash,
  3261. unsigned int hLen, unsigned char* enc, unsigned int* encLen, int padding)
  3262. {
  3263. int ret = 1;
  3264. int hType = WC_HASH_TYPE_NONE;
  3265. /* Validate parameters. */
  3266. if ((hash == NULL) || (enc == NULL) || (encLen == NULL)) {
  3267. ret = 0;
  3268. }
  3269. if ((ret == 1) && (hashAlg != NID_undef) &&
  3270. (padding == RSA_PKCS1_PADDING)) {
  3271. /* Convert hash algorithm to hash type for PKCS#1.5 padding. */
  3272. hType = nid2oid(hashAlg, oidHashType);
  3273. if (hType == -1) {
  3274. ret = 0;
  3275. }
  3276. }
  3277. if ((ret == 1) && (padding == RSA_PKCS1_PADDING)) {
  3278. /* PKCS#1.5 encoding. */
  3279. word32 encSz = wc_EncodeSignature(enc, hash, hLen, hType);
  3280. if (encSz == 0) {
  3281. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3282. ret = 0;
  3283. }
  3284. else {
  3285. *encLen = (unsigned int)encSz;
  3286. }
  3287. }
  3288. /* Other padding schemes require the hash as is. */
  3289. if ((ret == 1) && (padding != RSA_PKCS1_PADDING)) {
  3290. XMEMCPY(enc, hash, hLen);
  3291. *encLen = hLen;
  3292. }
  3293. return ret;
  3294. }
  3295. /* Sign the message hash using hash algorithm and RSA key.
  3296. *
  3297. * @param [in] hashAlg Hash algorithm OID.
  3298. * @param [in] hash Hash of message to encode for signing.
  3299. * @param [in] hLen Length of hash of message.
  3300. * @param [out] enc Encoded message hash.
  3301. * @param [out] encLen Length of encoded message hash.
  3302. * @param [in] rsa RSA key.
  3303. * @return 1 on success.
  3304. * @return 0 on failure.
  3305. */
  3306. int wolfSSL_RSA_sign(int hashAlg, const unsigned char* hash, unsigned int hLen,
  3307. unsigned char* sigRet, unsigned int* sigLen, WOLFSSL_RSA* rsa)
  3308. {
  3309. if (sigLen != NULL) {
  3310. /* No size checking in this API */
  3311. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3312. }
  3313. /* flag is 1: output complete signature. */
  3314. return wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3315. sigLen, rsa, 1, RSA_PKCS1_PADDING);
  3316. }
  3317. /* Sign the message hash using hash algorithm and RSA key.
  3318. *
  3319. * Not OpenSSL API.
  3320. *
  3321. * @param [in] hashAlg Hash algorithm NID.
  3322. * @param [in] hash Hash of message to encode for signing.
  3323. * @param [in] hLen Length of hash of message.
  3324. * @param [out] enc Encoded message hash.
  3325. * @param [out] encLen Length of encoded message hash.
  3326. * @param [in] rsa RSA key.
  3327. * @param [in] flag When 1: Output encrypted signature.
  3328. * When 0: Output encoded hash.
  3329. * @return 1 on success.
  3330. * @return 0 on failure.
  3331. */
  3332. int wolfSSL_RSA_sign_ex(int hashAlg, const unsigned char* hash,
  3333. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3334. WOLFSSL_RSA* rsa, int flag)
  3335. {
  3336. int ret = 0;
  3337. if ((flag == 0) || (flag == 1)) {
  3338. if (sigLen != NULL) {
  3339. /* No size checking in this API */
  3340. *sigLen = RSA_MAX_SIZE / CHAR_BIT;
  3341. }
  3342. ret = wolfSSL_RSA_sign_generic_padding(hashAlg, hash, hLen, sigRet,
  3343. sigLen, rsa, flag, RSA_PKCS1_PADDING);
  3344. }
  3345. return ret;
  3346. }
  3347. /**
  3348. * Sign a message hash with the chosen message digest, padding, and RSA key.
  3349. *
  3350. * Not OpenSSL API.
  3351. *
  3352. * @param [in] hashAlg Hash NID
  3353. * @param [in] hash Message hash to sign.
  3354. * @param [in] mLen Length of message hash to sign.
  3355. * @param [out] sigRet Output buffer.
  3356. * @param [in, out] sigLen On Input: length of sigRet buffer.
  3357. * On Output: length of data written to sigRet.
  3358. * @param [in] rsa RSA key used to sign the input.
  3359. * @param [in] flag 1: Output the signature.
  3360. * 0: Output the value that the unpadded signature
  3361. * should be compared to.
  3362. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3363. * RSA_PKCS1_PADDING are currently supported for
  3364. * signing.
  3365. * @return 1 on success.
  3366. * @return 0 on failure.
  3367. */
  3368. int wolfSSL_RSA_sign_generic_padding(int hashAlg, const unsigned char* hash,
  3369. unsigned int hLen, unsigned char* sigRet, unsigned int* sigLen,
  3370. WOLFSSL_RSA* rsa, int flag, int padding)
  3371. {
  3372. int ret = 1;
  3373. word32 outLen = 0;
  3374. int signSz = 0;
  3375. WC_RNG* rng = NULL;
  3376. int initTmpRng = 0;
  3377. #ifdef WOLFSSL_SMALL_STACK
  3378. WC_RNG* tmpRng = NULL;
  3379. byte* encodedSig = NULL;
  3380. #else
  3381. WC_RNG _tmpRng[1];
  3382. WC_RNG* tmpRng = _tmpRng;
  3383. byte encodedSig[MAX_ENCODED_SIG_SZ];
  3384. #endif
  3385. unsigned int encSz = 0;
  3386. WOLFSSL_ENTER("wolfSSL_RSA_sign_generic_padding");
  3387. if (flag == 0) {
  3388. /* Only encode message. */
  3389. return wolfssl_rsa_sig_encode(hashAlg, hash, hLen, sigRet, sigLen,
  3390. padding);
  3391. }
  3392. /* Validate parameters. */
  3393. if ((hash == NULL) || (sigRet == NULL) || sigLen == NULL || rsa == NULL) {
  3394. WOLFSSL_ERROR_MSG("Bad function arguments");
  3395. ret = 0;
  3396. }
  3397. /* Set wolfCrypt RSA key data from external if not already done. */
  3398. if ((ret == 1) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3399. ret = 0;
  3400. }
  3401. if (ret == 1) {
  3402. /* Get the maximum signature length. */
  3403. outLen = (word32)wolfSSL_BN_num_bytes(rsa->n);
  3404. /* Check not an error return. */
  3405. if (outLen == 0) {
  3406. WOLFSSL_ERROR_MSG("Bad RSA size");
  3407. ret = 0;
  3408. }
  3409. /* Check signature buffer is big enough. */
  3410. else if (outLen > *sigLen) {
  3411. WOLFSSL_ERROR_MSG("Output buffer too small");
  3412. ret = 0;
  3413. }
  3414. }
  3415. #ifdef WOLFSSL_SMALL_STACK
  3416. if (ret == 1) {
  3417. /* Allocate encoded signature buffer if doing PKCS#1 padding. */
  3418. encodedSig = (byte*)XMALLOC(MAX_ENCODED_SIG_SZ, NULL,
  3419. DYNAMIC_TYPE_SIGNATURE);
  3420. if (encodedSig == NULL) {
  3421. ret = 0;
  3422. }
  3423. }
  3424. #endif
  3425. if (ret == 1) {
  3426. /* Get/create an RNG. */
  3427. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3428. if (rng == NULL) {
  3429. WOLFSSL_ERROR_MSG("WOLFSSL_RSA_GetRNG error");
  3430. ret = 0;
  3431. }
  3432. }
  3433. /* Either encodes with PKCS#1.5 or copies hash into encodedSig. */
  3434. if ((ret == 1) && (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig,
  3435. &encSz, padding) == 0)) {
  3436. WOLFSSL_ERROR_MSG("Bad Encode Signature");
  3437. ret = 0;
  3438. }
  3439. if (ret == 1) {
  3440. switch (padding) {
  3441. #if defined(WC_RSA_NO_PADDING) || defined(WC_RSA_DIRECT)
  3442. case RSA_NO_PADDING:
  3443. if ((signSz = wc_RsaDirect(encodedSig, encSz, sigRet, &outLen,
  3444. (RsaKey*)rsa->internal, RSA_PRIVATE_ENCRYPT, rng)) <= 0) {
  3445. WOLFSSL_ERROR_MSG("Bad Rsa Sign no pad");
  3446. ret = 0;
  3447. }
  3448. break;
  3449. #endif
  3450. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3451. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,1))
  3452. case RSA_PKCS1_PSS_PADDING:
  3453. {
  3454. enum wc_HashType hType =
  3455. wc_OidGetHash(nid2oid(hashAlg, oidHashType));
  3456. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3457. WOLFSSL_MSG("Using RSA-PSS with hash length salt. "
  3458. "OpenSSL uses max length by default.");
  3459. #endif
  3460. /* Create RSA PSS signature. */
  3461. if ((signSz = wc_RsaPSS_Sign_ex(encodedSig, encSz, sigRet, outLen,
  3462. hType, wc_hash2mgf(hType), DEF_PSS_SALT_LEN,
  3463. (RsaKey*)rsa->internal, rng)) <= 0) {
  3464. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3465. ret = 0;
  3466. }
  3467. break;
  3468. }
  3469. #endif
  3470. #ifndef WC_NO_RSA_OAEP
  3471. case RSA_PKCS1_OAEP_PADDING:
  3472. /* Not a signature padding scheme. */
  3473. WOLFSSL_ERROR_MSG("RSA_PKCS1_OAEP_PADDING not supported for "
  3474. "signing");
  3475. ret = 0;
  3476. break;
  3477. #endif
  3478. case RSA_PKCS1_PADDING:
  3479. {
  3480. /* Sign (private encrypt) PKCS#1 encoded signature. */
  3481. if ((signSz = wc_RsaSSL_Sign(encodedSig, encSz, sigRet, outLen,
  3482. (RsaKey*)rsa->internal, rng)) <= 0) {
  3483. WOLFSSL_ERROR_MSG("Bad Rsa Sign");
  3484. ret = 0;
  3485. }
  3486. break;
  3487. }
  3488. default:
  3489. WOLFSSL_ERROR_MSG("Unsupported padding");
  3490. ret = 0;
  3491. break;
  3492. }
  3493. }
  3494. if (ret == 1) {
  3495. /* Return the size of signature generated. */
  3496. *sigLen = (unsigned int)signSz;
  3497. }
  3498. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3499. if (initTmpRng) {
  3500. wc_FreeRng(tmpRng);
  3501. }
  3502. #ifdef WOLFSSL_SMALL_STACK
  3503. /* Dispose of any allocated RNG and encoded signature. */
  3504. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3505. XFREE(encodedSig, NULL, DYNAMIC_TYPE_SIGNATURE);
  3506. #endif
  3507. WOLFSSL_LEAVE("wolfSSL_RSA_sign_generic_padding", ret);
  3508. return ret;
  3509. }
  3510. /**
  3511. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3512. *
  3513. * @param [in] hashAlg Hash NID
  3514. * @param [in] hash Message hash.
  3515. * @param [in] mLen Length of message hash.
  3516. * @param [in] sigRet Signature data.
  3517. * @param [in] sigLen Length of signature data.
  3518. * @param [in] rsa RSA key used to sign the input
  3519. * @return 1 on success.
  3520. * @return 0 on failure.
  3521. */
  3522. int wolfSSL_RSA_verify(int hashAlg, const unsigned char* hash,
  3523. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3524. WOLFSSL_RSA* rsa)
  3525. {
  3526. return wolfSSL_RSA_verify_ex(hashAlg, hash, hLen, sig, sigLen, rsa,
  3527. RSA_PKCS1_PADDING);
  3528. }
  3529. /**
  3530. * Verify a message hash with the chosen message digest, padding, and RSA key.
  3531. *
  3532. * Not OpenSSL API.
  3533. *
  3534. * @param [in] hashAlg Hash NID
  3535. * @param [in] hash Message hash.
  3536. * @param [in] mLen Length of message hash.
  3537. * @param [in] sigRet Signature data.
  3538. * @param [in] sigLen Length of signature data.
  3539. * @param [in] rsa RSA key used to sign the input
  3540. * @param [in] padding Padding to use. Only RSA_PKCS1_PSS_PADDING and
  3541. * RSA_PKCS1_PADDING are currently supported for
  3542. * signing.
  3543. * @return 1 on success.
  3544. * @return 0 on failure.
  3545. */
  3546. int wolfSSL_RSA_verify_ex(int hashAlg, const unsigned char* hash,
  3547. unsigned int hLen, const unsigned char* sig, unsigned int sigLen,
  3548. WOLFSSL_RSA* rsa, int padding)
  3549. {
  3550. int ret = 1;
  3551. #ifdef WOLFSSL_SMALL_STACK
  3552. unsigned char* encodedSig = NULL;
  3553. #else
  3554. unsigned char encodedSig[MAX_ENCODED_SIG_SZ];
  3555. #endif
  3556. unsigned char* sigDec = NULL;
  3557. unsigned int len = MAX_ENCODED_SIG_SZ;
  3558. int verLen = 0;
  3559. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && !defined(HAVE_SELFTEST)
  3560. enum wc_HashType hType = WC_HASH_TYPE_NONE;
  3561. #endif
  3562. WOLFSSL_ENTER("wolfSSL_RSA_verify");
  3563. /* Validate parameters. */
  3564. if ((hash == NULL) || (sig == NULL) || (rsa == NULL)) {
  3565. WOLFSSL_ERROR_MSG("Bad function arguments");
  3566. ret = 0;
  3567. }
  3568. if (ret == 1) {
  3569. /* Allocate memory for decrypted signature. */
  3570. sigDec = (unsigned char *)XMALLOC(sigLen, NULL,
  3571. DYNAMIC_TYPE_TMP_BUFFER);
  3572. if (sigDec == NULL) {
  3573. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3574. ret = 0;
  3575. }
  3576. }
  3577. #ifdef WOLFSSL_SMALL_STACK
  3578. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3579. /* Allocate memory for encoded signature. */
  3580. encodedSig = (unsigned char *)XMALLOC(len, NULL,
  3581. DYNAMIC_TYPE_TMP_BUFFER);
  3582. if (encodedSig == NULL) {
  3583. WOLFSSL_ERROR_MSG("Memory allocation failure");
  3584. ret = 0;
  3585. }
  3586. }
  3587. #endif
  3588. if ((ret == 1) && (padding != RSA_PKCS1_PSS_PADDING)) {
  3589. /* Make encoded signature to compare with decrypted signature. */
  3590. if (wolfssl_rsa_sig_encode(hashAlg, hash, hLen, encodedSig, &len,
  3591. padding) <= 0) {
  3592. WOLFSSL_ERROR_MSG("Message Digest Error");
  3593. ret = 0;
  3594. }
  3595. }
  3596. if (ret == 1) {
  3597. /* Decrypt signature */
  3598. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1)) && \
  3599. !defined(HAVE_SELFTEST)
  3600. hType = wc_OidGetHash(nid2oid(hashAlg, oidHashType));
  3601. if ((verLen = wc_RsaSSL_Verify_ex2(sig, sigLen, (unsigned char *)sigDec,
  3602. sigLen, (RsaKey*)rsa->internal, padding, hType)) <= 0) {
  3603. WOLFSSL_ERROR_MSG("RSA Decrypt error");
  3604. ret = 0;
  3605. }
  3606. #else
  3607. verLen = wc_RsaSSL_Verify(sig, sigLen, (unsigned char *)sigDec, sigLen,
  3608. (RsaKey*)rsa->internal);
  3609. if (verLen < 0) {
  3610. ret = 0;
  3611. }
  3612. #endif
  3613. }
  3614. if (ret == 1) {
  3615. #if defined(WC_RSA_PSS) && !defined(HAVE_SELFTEST) && \
  3616. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 1))
  3617. if (padding == RSA_PKCS1_PSS_PADDING) {
  3618. /* Check PSS padding is valid. */
  3619. if (wc_RsaPSS_CheckPadding_ex(hash, hLen, sigDec, verLen,
  3620. hType, DEF_PSS_SALT_LEN,
  3621. mp_count_bits(&((RsaKey*)rsa->internal)->n)) != 0) {
  3622. WOLFSSL_ERROR_MSG("wc_RsaPSS_CheckPadding_ex error");
  3623. ret = 0;
  3624. }
  3625. }
  3626. else
  3627. #endif /* WC_RSA_PSS && !HAVE_SELFTEST && (!HAVE_FIPS ||
  3628. * FIPS_VERSION >= 5.1) */
  3629. /* Compare decrypted signature to encoded signature. */
  3630. if ((int)len != verLen || XMEMCMP(encodedSig, sigDec, verLen) != 0) {
  3631. WOLFSSL_ERROR_MSG("wolfSSL_RSA_verify_ex failed");
  3632. ret = 0;
  3633. }
  3634. }
  3635. /* Dispose of any allocated data. */
  3636. #ifdef WOLFSSL_SMALL_STACK
  3637. XFREE(encodedSig, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3638. #endif
  3639. XFREE(sigDec, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  3640. return ret;
  3641. }
  3642. /*
  3643. * RSA public/private encrypt/decrypt APIs
  3644. */
  3645. #if !defined(HAVE_USER_RSA) && !defined(HAVE_FAST_RSA)
  3646. /* Encrypt with the RSA public key.
  3647. *
  3648. * Return compliant with OpenSSL.
  3649. *
  3650. * @param [in] len Length of data to encrypt.
  3651. * @param [in] from Data to encrypt.
  3652. * @param [out] to Encrypted data.
  3653. * @param [in] rsa RSA key.
  3654. * @param [in] padding Type of padding to place around plaintext.
  3655. * @return Size of encrypted data on success.
  3656. * @return -1 on failure.
  3657. */
  3658. int wolfSSL_RSA_public_encrypt(int len, const unsigned char* from,
  3659. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3660. {
  3661. int ret = 0;
  3662. int initTmpRng = 0;
  3663. WC_RNG *rng = NULL;
  3664. #ifdef WOLFSSL_SMALL_STACK
  3665. WC_RNG* tmpRng = NULL;
  3666. #else
  3667. WC_RNG _tmpRng[1];
  3668. WC_RNG* tmpRng = _tmpRng;
  3669. #endif
  3670. #if !defined(HAVE_FIPS)
  3671. int mgf = WC_MGF1NONE;
  3672. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3673. int pad_type = WC_RSA_NO_PAD;
  3674. #endif
  3675. int outLen = 0;
  3676. WOLFSSL_ENTER("wolfSSL_RSA_public_encrypt");
  3677. /* Validate parameters. */
  3678. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3679. (from == NULL)) {
  3680. WOLFSSL_ERROR_MSG("Bad function arguments");
  3681. ret = -1;
  3682. }
  3683. if (ret == 0) {
  3684. #if !defined(HAVE_FIPS)
  3685. /* Convert to wolfCrypt padding, hash and MGF. */
  3686. switch (padding) {
  3687. case RSA_PKCS1_PADDING:
  3688. pad_type = WC_RSA_PKCSV15_PAD;
  3689. break;
  3690. case RSA_PKCS1_OAEP_PADDING:
  3691. pad_type = WC_RSA_OAEP_PAD;
  3692. hash = WC_HASH_TYPE_SHA;
  3693. mgf = WC_MGF1SHA1;
  3694. break;
  3695. case RSA_NO_PADDING:
  3696. pad_type = WC_RSA_NO_PAD;
  3697. break;
  3698. default:
  3699. WOLFSSL_ERROR_MSG("RSA_public_encrypt doesn't support padding "
  3700. "scheme");
  3701. ret = -1;
  3702. }
  3703. #else
  3704. /* Check for supported padding schemes in FIPS. */
  3705. /* TODO: Do we support more schemes in later versions of FIPS? */
  3706. if (padding != RSA_PKCS1_PADDING) {
  3707. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3708. "FIPS");
  3709. ret = -1;
  3710. }
  3711. #endif
  3712. }
  3713. /* Set wolfCrypt RSA key data from external if not already done. */
  3714. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3715. ret = -1;
  3716. }
  3717. if (ret == 0) {
  3718. /* Calculate maximum length of encrypted data. */
  3719. outLen = wolfSSL_RSA_size(rsa);
  3720. if (outLen == 0) {
  3721. WOLFSSL_ERROR_MSG("Bad RSA size");
  3722. ret = -1;
  3723. }
  3724. }
  3725. if (ret == 0) {
  3726. /* Get an RNG. */
  3727. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3728. if (rng == NULL) {
  3729. ret = -1;
  3730. }
  3731. }
  3732. if (ret == 0) {
  3733. /* Use wolfCrypt to public-encrypt with RSA key. */
  3734. #if !defined(HAVE_FIPS)
  3735. ret = wc_RsaPublicEncrypt_ex(from, len, to, outLen,
  3736. (RsaKey*)rsa->internal, rng, pad_type, hash, mgf, NULL, 0);
  3737. #else
  3738. ret = wc_RsaPublicEncrypt(from, len, to, outLen, (RsaKey*)rsa->internal,
  3739. rng);
  3740. #endif
  3741. }
  3742. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3743. if (initTmpRng) {
  3744. wc_FreeRng(tmpRng);
  3745. }
  3746. #ifdef WOLFSSL_SMALL_STACK
  3747. /* Dispose of any allocated RNG. */
  3748. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  3749. #endif
  3750. /* wolfCrypt error means return -1. */
  3751. if (ret <= 0) {
  3752. ret = -1;
  3753. }
  3754. WOLFSSL_LEAVE("wolfSSL_RSA_public_encrypt", ret);
  3755. return ret;
  3756. }
  3757. /* Decrypt with the RSA public key.
  3758. *
  3759. * Return compliant with OpenSSL.
  3760. *
  3761. * @param [in] len Length of encrypted data.
  3762. * @param [in] from Encrypted data.
  3763. * @param [out] to Decrypted data.
  3764. * @param [in] rsa RSA key.
  3765. * @param [in] padding Type of padding to around plaintext to remove.
  3766. * @return Size of decrypted data on success.
  3767. * @return -1 on failure.
  3768. */
  3769. int wolfSSL_RSA_private_decrypt(int len, const unsigned char* from,
  3770. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3771. {
  3772. int ret = 0;
  3773. #if !defined(HAVE_FIPS)
  3774. int mgf = WC_MGF1NONE;
  3775. enum wc_HashType hash = WC_HASH_TYPE_NONE;
  3776. int pad_type = WC_RSA_NO_PAD;
  3777. #endif
  3778. int outLen = 0;
  3779. WOLFSSL_ENTER("wolfSSL_RSA_private_decrypt");
  3780. /* Validate parameters. */
  3781. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3782. (from == NULL)) {
  3783. WOLFSSL_ERROR_MSG("Bad function arguments");
  3784. ret = -1;
  3785. }
  3786. if (ret == 0) {
  3787. #if !defined(HAVE_FIPS)
  3788. switch (padding) {
  3789. case RSA_PKCS1_PADDING:
  3790. pad_type = WC_RSA_PKCSV15_PAD;
  3791. break;
  3792. case RSA_PKCS1_OAEP_PADDING:
  3793. pad_type = WC_RSA_OAEP_PAD;
  3794. hash = WC_HASH_TYPE_SHA;
  3795. mgf = WC_MGF1SHA1;
  3796. break;
  3797. case RSA_NO_PADDING:
  3798. pad_type = WC_RSA_NO_PAD;
  3799. break;
  3800. default:
  3801. WOLFSSL_ERROR_MSG("RSA_private_decrypt unsupported padding");
  3802. ret = -1;
  3803. }
  3804. #else
  3805. /* Check for supported padding schemes in FIPS. */
  3806. /* TODO: Do we support more schemes in later versions of FIPS? */
  3807. if (padding != RSA_PKCS1_PADDING) {
  3808. WOLFSSL_ERROR_MSG("RSA_public_encrypt pad type not supported in "
  3809. "FIPS");
  3810. ret = -1;
  3811. }
  3812. #endif
  3813. }
  3814. /* Set wolfCrypt RSA key data from external if not already done. */
  3815. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3816. ret = -1;
  3817. }
  3818. if (ret == 0) {
  3819. /* Calculate maximum length of decrypted data. */
  3820. outLen = wolfSSL_RSA_size(rsa);
  3821. if (outLen == 0) {
  3822. WOLFSSL_ERROR_MSG("Bad RSA size");
  3823. ret = -1;
  3824. }
  3825. }
  3826. if (ret == 0) {
  3827. /* Use wolfCrypt to private-decrypt with RSA key.
  3828. * Size of 'to' buffer must be size of RSA key */
  3829. #if !defined(HAVE_FIPS)
  3830. ret = wc_RsaPrivateDecrypt_ex(from, len, to, outLen,
  3831. (RsaKey*)rsa->internal, pad_type, hash, mgf, NULL, 0);
  3832. #else
  3833. ret = wc_RsaPrivateDecrypt(from, len, to, outLen,
  3834. (RsaKey*)rsa->internal);
  3835. #endif
  3836. }
  3837. /* wolfCrypt error means return -1. */
  3838. if (ret <= 0) {
  3839. ret = -1;
  3840. }
  3841. WOLFSSL_LEAVE("wolfSSL_RSA_private_decrypt", ret);
  3842. return ret;
  3843. }
  3844. /* Decrypt with the RSA public key.
  3845. *
  3846. * @param [in] len Length of encrypted data.
  3847. * @param [in] from Encrypted data.
  3848. * @param [out] to Decrypted data.
  3849. * @param [in] rsa RSA key.
  3850. * @param [in] padding Type of padding to around plaintext to remove.
  3851. * @return Size of decrypted data on success.
  3852. * @return -1 on failure.
  3853. */
  3854. int wolfSSL_RSA_public_decrypt(int len, const unsigned char* from,
  3855. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3856. {
  3857. int ret = 0;
  3858. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3859. int pad_type = WC_RSA_NO_PAD;
  3860. #endif
  3861. int outLen = 0;
  3862. WOLFSSL_ENTER("wolfSSL_RSA_public_decrypt");
  3863. /* Validate parameters. */
  3864. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3865. (from == NULL)) {
  3866. WOLFSSL_ERROR_MSG("Bad function arguments");
  3867. ret = -1;
  3868. }
  3869. if (ret == 0) {
  3870. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3871. switch (padding) {
  3872. case RSA_PKCS1_PADDING:
  3873. pad_type = WC_RSA_PKCSV15_PAD;
  3874. break;
  3875. case RSA_NO_PADDING:
  3876. pad_type = WC_RSA_NO_PAD;
  3877. break;
  3878. /* TODO: RSA_X931_PADDING not supported */
  3879. default:
  3880. WOLFSSL_ERROR_MSG("RSA_public_decrypt unsupported padding");
  3881. ret = -1;
  3882. }
  3883. #else
  3884. if (padding != RSA_PKCS1_PADDING) {
  3885. WOLFSSL_ERROR_MSG("RSA_public_decrypt pad type not supported in "
  3886. "FIPS");
  3887. ret = -1;
  3888. }
  3889. #endif
  3890. }
  3891. /* Set wolfCrypt RSA key data from external if not already done. */
  3892. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3893. ret = -1;
  3894. }
  3895. if (ret == 0) {
  3896. /* Calculate maximum length of encrypted data. */
  3897. outLen = wolfSSL_RSA_size(rsa);
  3898. if (outLen == 0) {
  3899. WOLFSSL_ERROR_MSG("Bad RSA size");
  3900. ret = -1;
  3901. }
  3902. }
  3903. if (ret == 0) {
  3904. /* Use wolfCrypt to public-decrypt with RSA key. */
  3905. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  3906. /* Size of 'to' buffer must be size of RSA key. */
  3907. ret = wc_RsaSSL_Verify_ex(from, len, to, outLen,
  3908. (RsaKey*)rsa->internal, pad_type);
  3909. #else
  3910. /* For FIPS v1/v2 only PKCSV15 padding is supported */
  3911. ret = wc_RsaSSL_Verify(from, len, to, outLen, (RsaKey*)rsa->internal);
  3912. #endif
  3913. }
  3914. /* wolfCrypt error means return -1. */
  3915. if (ret <= 0) {
  3916. ret = -1;
  3917. }
  3918. WOLFSSL_LEAVE("wolfSSL_RSA_public_decrypt", ret);
  3919. return ret;
  3920. }
  3921. /* Encrypt with the RSA private key.
  3922. *
  3923. * Calls wc_RsaSSL_Sign.
  3924. *
  3925. * @param [in] len Length of data to encrypt.
  3926. * @param [in] from Data to encrypt.
  3927. * @param [out] to Encrypted data.
  3928. * @param [in] rsa RSA key.
  3929. * @param [in] padding Type of padding to place around plaintext.
  3930. * @return Size of encrypted data on success.
  3931. * @return -1 on failure.
  3932. */
  3933. int wolfSSL_RSA_private_encrypt(int len, const unsigned char* from,
  3934. unsigned char* to, WOLFSSL_RSA* rsa, int padding)
  3935. {
  3936. int ret = 0;
  3937. int initTmpRng = 0;
  3938. WC_RNG *rng = NULL;
  3939. #ifdef WOLFSSL_SMALL_STACK
  3940. WC_RNG* tmpRng = NULL;
  3941. #else
  3942. WC_RNG _tmpRng[1];
  3943. WC_RNG* tmpRng = _tmpRng;
  3944. #endif
  3945. WOLFSSL_ENTER("wolfSSL_RSA_private_encrypt");
  3946. /* Validate parameters. */
  3947. if ((len < 0) || (rsa == NULL) || (rsa->internal == NULL) ||
  3948. (from == NULL)) {
  3949. WOLFSSL_ERROR_MSG("Bad function arguments");
  3950. ret = -1;
  3951. }
  3952. if (ret == 0) {
  3953. switch (padding) {
  3954. case RSA_PKCS1_PADDING:
  3955. #ifdef WC_RSA_NO_PADDING
  3956. case RSA_NO_PADDING:
  3957. #endif
  3958. break;
  3959. /* TODO: RSA_X931_PADDING not supported */
  3960. default:
  3961. WOLFSSL_ERROR_MSG("RSA_private_encrypt unsupported padding");
  3962. ret = -1;
  3963. }
  3964. }
  3965. /* Set wolfCrypt RSA key data from external if not already done. */
  3966. if ((ret == 0) && (!rsa->inSet) && (SetRsaInternal(rsa) != 1)) {
  3967. ret = -1;
  3968. }
  3969. if (ret == 0) {
  3970. /* Get an RNG. */
  3971. rng = WOLFSSL_RSA_GetRNG(rsa, (WC_RNG**)&tmpRng, &initTmpRng);
  3972. if (rng == NULL) {
  3973. ret = -1;
  3974. }
  3975. }
  3976. if (ret == 0) {
  3977. /* Use wolfCrypt to private-encrypt with RSA key.
  3978. * Size of output buffer must be size of RSA key. */
  3979. if (padding == RSA_PKCS1_PADDING) {
  3980. ret = wc_RsaSSL_Sign(from, (word32)len, to, wolfSSL_RSA_size(rsa),
  3981. (RsaKey*)rsa->internal, rng);
  3982. }
  3983. #ifdef WC_RSA_NO_PADDING
  3984. else if (padding == RSA_NO_PADDING) {
  3985. word32 outLen = wolfSSL_RSA_size(rsa);
  3986. ret = wc_RsaFunction(from, (word32)len, to, &outLen,
  3987. RSA_PRIVATE_ENCRYPT, (RsaKey*)rsa->internal, rng);
  3988. if (ret == 0)
  3989. ret = (int)outLen;
  3990. }
  3991. #endif
  3992. }
  3993. /* Finalize RNG if initialized in WOLFSSL_RSA_GetRNG(). */
  3994. if (initTmpRng) {
  3995. wc_FreeRng(tmpRng);
  3996. }
  3997. #ifdef WOLFSSL_SMALL_STACK
  3998. /* Dispose of any allocated RNG. */
  3999. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4000. #endif
  4001. /* wolfCrypt error means return -1. */
  4002. if (ret <= 0) {
  4003. ret = -1;
  4004. }
  4005. WOLFSSL_LEAVE("wolfSSL_RSA_private_encrypt", ret);
  4006. return ret;
  4007. }
  4008. #endif /* !HAVE_USER_RSA && !HAVE_FAST_RSA */
  4009. /*
  4010. * RSA misc operation APIs
  4011. */
  4012. /* Calculate d mod p-1 and q-1 into BNs.
  4013. *
  4014. * Not OpenSSL API.
  4015. *
  4016. * @param [in, out] rsa RSA key.
  4017. * @return 1 on success.
  4018. * @return -1 on failure.
  4019. */
  4020. int wolfSSL_RSA_GenAdd(WOLFSSL_RSA* rsa)
  4021. {
  4022. int ret = 1;
  4023. int err;
  4024. mp_int* t = NULL;
  4025. #ifdef WOLFSSL_SMALL_STACK
  4026. mp_int *tmp = NULL;
  4027. #else
  4028. mp_int tmp[1];
  4029. #endif
  4030. WOLFSSL_ENTER("wolfSSL_RsaGenAdd");
  4031. /* Validate parameters. */
  4032. if ((rsa == NULL) || (rsa->p == NULL) || (rsa->q == NULL) ||
  4033. (rsa->d == NULL) || (rsa->dmp1 == NULL) || (rsa->dmq1 == NULL)) {
  4034. WOLFSSL_ERROR_MSG("rsa no init error");
  4035. ret = -1;
  4036. }
  4037. #ifdef WOLFSSL_SMALL_STACK
  4038. if (ret == 1) {
  4039. tmp = (mp_int *)XMALLOC(sizeof(*tmp), rsa->heap,
  4040. DYNAMIC_TYPE_TMP_BUFFER);
  4041. if (tmp == NULL) {
  4042. WOLFSSL_ERROR_MSG("Memory allocation failure");
  4043. ret = -1;
  4044. }
  4045. }
  4046. #endif
  4047. if (ret == 1) {
  4048. /* Initialize temp MP integer. */
  4049. if (mp_init(tmp) != MP_OKAY) {
  4050. WOLFSSL_ERROR_MSG("mp_init error");
  4051. ret = -1;
  4052. }
  4053. }
  4054. if (ret == 1) {
  4055. t = tmp;
  4056. /* Sub 1 from p into temp. */
  4057. err = mp_sub_d((mp_int*)rsa->p->internal, 1, tmp);
  4058. if (err != MP_OKAY) {
  4059. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4060. ret = -1;
  4061. }
  4062. }
  4063. if (ret == 1) {
  4064. /* Calculate d mod (p - 1) into dmp1 MP integer of BN. */
  4065. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4066. (mp_int*)rsa->dmp1->internal);
  4067. if (err != MP_OKAY) {
  4068. WOLFSSL_ERROR_MSG("mp_mod error");
  4069. ret = -1;
  4070. }
  4071. }
  4072. if (ret == 1) {
  4073. /* Sub 1 from q into temp. */
  4074. err = mp_sub_d((mp_int*)rsa->q->internal, 1, tmp);
  4075. if (err != MP_OKAY) {
  4076. WOLFSSL_ERROR_MSG("mp_sub_d error");
  4077. ret = -1;
  4078. }
  4079. }
  4080. if (ret == 1) {
  4081. /* Calculate d mod (q - 1) into dmq1 MP integer of BN. */
  4082. err = mp_mod((mp_int*)rsa->d->internal, tmp,
  4083. (mp_int*)rsa->dmq1->internal);
  4084. if (err != MP_OKAY) {
  4085. WOLFSSL_ERROR_MSG("mp_mod error");
  4086. ret = -1;
  4087. }
  4088. }
  4089. mp_clear(t);
  4090. #ifdef WOLFSSL_SMALL_STACK
  4091. if (tmp != NULL)
  4092. XFREE(tmp, rsa->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4093. #endif
  4094. return ret;
  4095. }
  4096. #endif /* !HAVE_USER_RSA */
  4097. #ifndef NO_WOLFSSL_STUB
  4098. /* Enable blinding for RSA key operations.
  4099. *
  4100. * Blinding is a compile time option in wolfCrypt.
  4101. *
  4102. * @param [in] rsa RSA key. Unused.
  4103. * @param [in] bnCtx BN context to use for blinding. Unused.
  4104. * @return 1 always.
  4105. */
  4106. int wolfSSL_RSA_blinding_on(WOLFSSL_RSA* rsa, WOLFSSL_BN_CTX* bnCtx)
  4107. {
  4108. WOLFSSL_STUB("RSA_blinding_on");
  4109. WOLFSSL_ENTER("wolfSSL_RSA_blinding_on");
  4110. (void)rsa;
  4111. (void)bnCtx;
  4112. return 1; /* on by default */
  4113. }
  4114. #endif
  4115. #endif /* OPENSSL_EXTRA */
  4116. #endif /* !NO_RSA */
  4117. /*******************************************************************************
  4118. * END OF RSA API
  4119. ******************************************************************************/
  4120. /*******************************************************************************
  4121. * START OF DSA API
  4122. ******************************************************************************/
  4123. #ifndef NO_DSA
  4124. #if defined(OPENSSL_EXTRA) && defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  4125. !defined(NO_STDIO_FILESYSTEM)
  4126. /* return code compliant with OpenSSL :
  4127. * 1 if success, 0 if error
  4128. */
  4129. int wolfSSL_DSA_print_fp(XFILE fp, WOLFSSL_DSA* dsa, int indent)
  4130. {
  4131. int ret = 1;
  4132. WOLFSSL_ENTER("wolfSSL_DSA_print_fp");
  4133. if (fp == XBADFILE || dsa == NULL) {
  4134. ret = 0;
  4135. }
  4136. if (ret == 1 && dsa->p != NULL) {
  4137. int pBits = wolfSSL_BN_num_bits(dsa->p);
  4138. if (pBits == 0) {
  4139. ret = 0;
  4140. }
  4141. else {
  4142. if (XFPRINTF(fp, "%*s", indent, "") < 0)
  4143. ret = 0;
  4144. else if (XFPRINTF(fp, "Private-Key: (%d bit)\n", pBits) < 0)
  4145. ret = 0;
  4146. }
  4147. }
  4148. if (ret == 1 && dsa->priv_key != NULL) {
  4149. ret = pk_bn_field_print_fp(fp, indent, "priv", dsa->priv_key);
  4150. }
  4151. if (ret == 1 && dsa->pub_key != NULL) {
  4152. ret = pk_bn_field_print_fp(fp, indent, "pub", dsa->pub_key);
  4153. }
  4154. if (ret == 1 && dsa->p != NULL) {
  4155. ret = pk_bn_field_print_fp(fp, indent, "P", dsa->p);
  4156. }
  4157. if (ret == 1 && dsa->q != NULL) {
  4158. ret = pk_bn_field_print_fp(fp, indent, "Q", dsa->q);
  4159. }
  4160. if (ret == 1 && dsa->g != NULL) {
  4161. ret = pk_bn_field_print_fp(fp, indent, "G", dsa->g);
  4162. }
  4163. WOLFSSL_LEAVE("wolfSSL_DSA_print_fp", ret);
  4164. return ret;
  4165. }
  4166. #endif /* OPENSSL_EXTRA && XSNPRINTF && !NO_FILESYSTEM && NO_STDIO_FILESYSTEM */
  4167. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  4168. static void InitwolfSSL_DSA(WOLFSSL_DSA* dsa)
  4169. {
  4170. if (dsa) {
  4171. dsa->p = NULL;
  4172. dsa->q = NULL;
  4173. dsa->g = NULL;
  4174. dsa->pub_key = NULL;
  4175. dsa->priv_key = NULL;
  4176. dsa->internal = NULL;
  4177. dsa->inSet = 0;
  4178. dsa->exSet = 0;
  4179. }
  4180. }
  4181. WOLFSSL_DSA* wolfSSL_DSA_new(void)
  4182. {
  4183. WOLFSSL_DSA* external;
  4184. DsaKey* key;
  4185. WOLFSSL_MSG("wolfSSL_DSA_new");
  4186. key = (DsaKey*) XMALLOC(sizeof(DsaKey), NULL, DYNAMIC_TYPE_DSA);
  4187. if (key == NULL) {
  4188. WOLFSSL_MSG("wolfSSL_DSA_new malloc DsaKey failure");
  4189. return NULL;
  4190. }
  4191. external = (WOLFSSL_DSA*) XMALLOC(sizeof(WOLFSSL_DSA), NULL,
  4192. DYNAMIC_TYPE_DSA);
  4193. if (external == NULL) {
  4194. WOLFSSL_MSG("wolfSSL_DSA_new malloc WOLFSSL_DSA failure");
  4195. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4196. return NULL;
  4197. }
  4198. InitwolfSSL_DSA(external);
  4199. if (wc_InitDsaKey(key) != 0) {
  4200. WOLFSSL_MSG("wolfSSL_DSA_new InitDsaKey failure");
  4201. XFREE(key, NULL, DYNAMIC_TYPE_DSA);
  4202. wolfSSL_DSA_free(external);
  4203. return NULL;
  4204. }
  4205. external->internal = key;
  4206. return external;
  4207. }
  4208. void wolfSSL_DSA_free(WOLFSSL_DSA* dsa)
  4209. {
  4210. WOLFSSL_MSG("wolfSSL_DSA_free");
  4211. if (dsa) {
  4212. if (dsa->internal) {
  4213. FreeDsaKey((DsaKey*)dsa->internal);
  4214. XFREE(dsa->internal, NULL, DYNAMIC_TYPE_DSA);
  4215. dsa->internal = NULL;
  4216. }
  4217. wolfSSL_BN_free(dsa->priv_key);
  4218. wolfSSL_BN_free(dsa->pub_key);
  4219. wolfSSL_BN_free(dsa->g);
  4220. wolfSSL_BN_free(dsa->q);
  4221. wolfSSL_BN_free(dsa->p);
  4222. InitwolfSSL_DSA(dsa); /* set back to NULLs for safety */
  4223. XFREE(dsa, NULL, DYNAMIC_TYPE_DSA);
  4224. /* dsa = NULL, don't try to access or double free it */
  4225. }
  4226. }
  4227. /* wolfSSL -> OpenSSL */
  4228. int SetDsaExternal(WOLFSSL_DSA* dsa)
  4229. {
  4230. DsaKey* key;
  4231. WOLFSSL_MSG("Entering SetDsaExternal");
  4232. if (dsa == NULL || dsa->internal == NULL) {
  4233. WOLFSSL_MSG("dsa key NULL error");
  4234. return -1;
  4235. }
  4236. key = (DsaKey*)dsa->internal;
  4237. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  4238. WOLFSSL_MSG("dsa p key error");
  4239. return -1;
  4240. }
  4241. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  4242. WOLFSSL_MSG("dsa q key error");
  4243. return -1;
  4244. }
  4245. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  4246. WOLFSSL_MSG("dsa g key error");
  4247. return -1;
  4248. }
  4249. if (wolfssl_bn_set_value(&dsa->pub_key, &key->y) != 1) {
  4250. WOLFSSL_MSG("dsa y key error");
  4251. return -1;
  4252. }
  4253. if (wolfssl_bn_set_value(&dsa->priv_key, &key->x) != 1) {
  4254. WOLFSSL_MSG("dsa x key error");
  4255. return -1;
  4256. }
  4257. dsa->exSet = 1;
  4258. return 1;
  4259. }
  4260. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  4261. #ifdef OPENSSL_EXTRA
  4262. /* Openssl -> WolfSSL */
  4263. int SetDsaInternal(WOLFSSL_DSA* dsa)
  4264. {
  4265. DsaKey* key;
  4266. WOLFSSL_MSG("Entering SetDsaInternal");
  4267. if (dsa == NULL || dsa->internal == NULL) {
  4268. WOLFSSL_MSG("dsa key NULL error");
  4269. return -1;
  4270. }
  4271. key = (DsaKey*)dsa->internal;
  4272. if (dsa->p != NULL &&
  4273. wolfssl_bn_get_value(dsa->p, &key->p) != 1) {
  4274. WOLFSSL_MSG("rsa p key error");
  4275. return -1;
  4276. }
  4277. if (dsa->q != NULL &&
  4278. wolfssl_bn_get_value(dsa->q, &key->q) != 1) {
  4279. WOLFSSL_MSG("rsa q key error");
  4280. return -1;
  4281. }
  4282. if (dsa->g != NULL &&
  4283. wolfssl_bn_get_value(dsa->g, &key->g) != 1) {
  4284. WOLFSSL_MSG("rsa g key error");
  4285. return -1;
  4286. }
  4287. if (dsa->pub_key != NULL) {
  4288. if (wolfssl_bn_get_value(dsa->pub_key, &key->y) != 1) {
  4289. WOLFSSL_MSG("rsa pub_key error");
  4290. return -1;
  4291. }
  4292. /* public key */
  4293. key->type = DSA_PUBLIC;
  4294. }
  4295. if (dsa->priv_key != NULL) {
  4296. if (wolfssl_bn_get_value(dsa->priv_key, &key->x) != 1) {
  4297. WOLFSSL_MSG("rsa priv_key error");
  4298. return -1;
  4299. }
  4300. /* private key */
  4301. key->type = DSA_PRIVATE;
  4302. }
  4303. dsa->inSet = 1;
  4304. return 1;
  4305. }
  4306. /* return code compliant with OpenSSL :
  4307. * 1 if success, 0 if error
  4308. */
  4309. int wolfSSL_DSA_generate_key(WOLFSSL_DSA* dsa)
  4310. {
  4311. int ret = 0;
  4312. WOLFSSL_ENTER("wolfSSL_DSA_generate_key");
  4313. if (dsa == NULL || dsa->internal == NULL) {
  4314. WOLFSSL_MSG("Bad arguments");
  4315. return 0;
  4316. }
  4317. if (dsa->inSet == 0) {
  4318. WOLFSSL_MSG("No DSA internal set, do it");
  4319. if (SetDsaInternal(dsa) != 1) {
  4320. WOLFSSL_MSG("SetDsaInternal failed");
  4321. return ret;
  4322. }
  4323. }
  4324. #ifdef WOLFSSL_KEY_GEN
  4325. {
  4326. int initTmpRng = 0;
  4327. WC_RNG *rng = NULL;
  4328. #ifdef WOLFSSL_SMALL_STACK
  4329. WC_RNG *tmpRng;
  4330. #else
  4331. WC_RNG tmpRng[1];
  4332. #endif
  4333. #ifdef WOLFSSL_SMALL_STACK
  4334. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4335. if (tmpRng == NULL)
  4336. return -1;
  4337. #endif
  4338. if (wc_InitRng(tmpRng) == 0) {
  4339. rng = tmpRng;
  4340. initTmpRng = 1;
  4341. }
  4342. else {
  4343. WOLFSSL_MSG("Bad RNG Init, trying global");
  4344. rng = wolfssl_get_global_rng();
  4345. }
  4346. if (rng) {
  4347. /* These were allocated above by SetDsaInternal(). They should
  4348. * be cleared before wc_MakeDsaKey() which reinitializes
  4349. * x and y. */
  4350. mp_clear(&((DsaKey*)dsa->internal)->x);
  4351. mp_clear(&((DsaKey*)dsa->internal)->y);
  4352. if (wc_MakeDsaKey(rng, (DsaKey*)dsa->internal) != MP_OKAY)
  4353. WOLFSSL_MSG("wc_MakeDsaKey failed");
  4354. else if (SetDsaExternal(dsa) != 1)
  4355. WOLFSSL_MSG("SetDsaExternal failed");
  4356. else
  4357. ret = 1;
  4358. }
  4359. if (initTmpRng)
  4360. wc_FreeRng(tmpRng);
  4361. #ifdef WOLFSSL_SMALL_STACK
  4362. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4363. #endif
  4364. }
  4365. #else /* WOLFSSL_KEY_GEN */
  4366. WOLFSSL_MSG("No Key Gen built in");
  4367. #endif
  4368. return ret;
  4369. }
  4370. /* Returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  4371. */
  4372. WOLFSSL_DSA* wolfSSL_DSA_generate_parameters(int bits, unsigned char* seed,
  4373. int seedLen, int* counterRet, unsigned long* hRet,
  4374. WOLFSSL_BN_CB cb, void* CBArg)
  4375. {
  4376. WOLFSSL_DSA* dsa;
  4377. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters");
  4378. (void)cb;
  4379. (void)CBArg;
  4380. dsa = wolfSSL_DSA_new();
  4381. if (dsa == NULL) {
  4382. return NULL;
  4383. }
  4384. if (wolfSSL_DSA_generate_parameters_ex(dsa, bits, seed, seedLen,
  4385. counterRet, hRet, NULL) != 1) {
  4386. wolfSSL_DSA_free(dsa);
  4387. return NULL;
  4388. }
  4389. return dsa;
  4390. }
  4391. /* return code compliant with OpenSSL :
  4392. * 1 if success, 0 if error
  4393. */
  4394. int wolfSSL_DSA_generate_parameters_ex(WOLFSSL_DSA* dsa, int bits,
  4395. unsigned char* seed, int seedLen,
  4396. int* counterRet,
  4397. unsigned long* hRet, void* cb)
  4398. {
  4399. int ret = 0;
  4400. (void)bits;
  4401. (void)seed;
  4402. (void)seedLen;
  4403. (void)counterRet;
  4404. (void)hRet;
  4405. (void)cb;
  4406. WOLFSSL_ENTER("wolfSSL_DSA_generate_parameters_ex");
  4407. if (dsa == NULL || dsa->internal == NULL) {
  4408. WOLFSSL_MSG("Bad arguments");
  4409. return 0;
  4410. }
  4411. #ifdef WOLFSSL_KEY_GEN
  4412. {
  4413. int initTmpRng = 0;
  4414. WC_RNG *rng = NULL;
  4415. #ifdef WOLFSSL_SMALL_STACK
  4416. WC_RNG *tmpRng;
  4417. #else
  4418. WC_RNG tmpRng[1];
  4419. #endif
  4420. #ifdef WOLFSSL_SMALL_STACK
  4421. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4422. if (tmpRng == NULL)
  4423. return -1;
  4424. #endif
  4425. if (wc_InitRng(tmpRng) == 0) {
  4426. rng = tmpRng;
  4427. initTmpRng = 1;
  4428. }
  4429. else {
  4430. WOLFSSL_MSG("Bad RNG Init, trying global");
  4431. rng = wolfssl_get_global_rng();
  4432. }
  4433. if (rng) {
  4434. if (wc_MakeDsaParameters(rng, bits,
  4435. (DsaKey*)dsa->internal) != MP_OKAY)
  4436. WOLFSSL_MSG("wc_MakeDsaParameters failed");
  4437. else if (SetDsaExternal(dsa) != 1)
  4438. WOLFSSL_MSG("SetDsaExternal failed");
  4439. else
  4440. ret = 1;
  4441. }
  4442. if (initTmpRng)
  4443. wc_FreeRng(tmpRng);
  4444. #ifdef WOLFSSL_SMALL_STACK
  4445. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4446. #endif
  4447. }
  4448. #else /* WOLFSSL_KEY_GEN */
  4449. WOLFSSL_MSG("No Key Gen built in");
  4450. #endif
  4451. return ret;
  4452. }
  4453. void wolfSSL_DSA_get0_pqg(const WOLFSSL_DSA *d, const WOLFSSL_BIGNUM **p,
  4454. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  4455. {
  4456. WOLFSSL_ENTER("wolfSSL_DSA_get0_pqg");
  4457. if (d != NULL) {
  4458. if (p != NULL)
  4459. *p = d->p;
  4460. if (q != NULL)
  4461. *q = d->q;
  4462. if (g != NULL)
  4463. *g = d->g;
  4464. }
  4465. }
  4466. int wolfSSL_DSA_set0_pqg(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *p,
  4467. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  4468. {
  4469. WOLFSSL_ENTER("wolfSSL_DSA_set0_pqg");
  4470. if (d == NULL || p == NULL || q == NULL || g == NULL) {
  4471. WOLFSSL_MSG("Bad parameter");
  4472. return 0;
  4473. }
  4474. wolfSSL_BN_free(d->p);
  4475. wolfSSL_BN_free(d->q);
  4476. wolfSSL_BN_free(d->g);
  4477. d->p = p;
  4478. d->q = q;
  4479. d->g = g;
  4480. return 1;
  4481. }
  4482. void wolfSSL_DSA_get0_key(const WOLFSSL_DSA *d,
  4483. const WOLFSSL_BIGNUM **pub_key, const WOLFSSL_BIGNUM **priv_key)
  4484. {
  4485. WOLFSSL_ENTER("wolfSSL_DSA_get0_key");
  4486. if (d != NULL) {
  4487. if (pub_key != NULL)
  4488. *pub_key = d->pub_key;
  4489. if (priv_key != NULL)
  4490. *priv_key = d->priv_key;
  4491. }
  4492. }
  4493. int wolfSSL_DSA_set0_key(WOLFSSL_DSA *d, WOLFSSL_BIGNUM *pub_key,
  4494. WOLFSSL_BIGNUM *priv_key)
  4495. {
  4496. WOLFSSL_ENTER("wolfSSL_DSA_set0_key");
  4497. /* The private key may be NULL */
  4498. if (pub_key == NULL) {
  4499. WOLFSSL_MSG("Bad parameter");
  4500. return 0;
  4501. }
  4502. wolfSSL_BN_free(d->pub_key);
  4503. wolfSSL_BN_free(d->priv_key);
  4504. d->pub_key = pub_key;
  4505. d->priv_key = priv_key;
  4506. return 1;
  4507. }
  4508. WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new(void)
  4509. {
  4510. WOLFSSL_DSA_SIG* sig;
  4511. WOLFSSL_ENTER("wolfSSL_DSA_SIG_new");
  4512. sig = (WOLFSSL_DSA_SIG*)XMALLOC(sizeof(WOLFSSL_DSA_SIG), NULL,
  4513. DYNAMIC_TYPE_OPENSSL);
  4514. if (sig)
  4515. XMEMSET(sig, 0, sizeof(WOLFSSL_DSA_SIG));
  4516. return sig;
  4517. }
  4518. void wolfSSL_DSA_SIG_free(WOLFSSL_DSA_SIG *sig)
  4519. {
  4520. WOLFSSL_ENTER("wolfSSL_DSA_SIG_free");
  4521. if (sig) {
  4522. if (sig->r) {
  4523. wolfSSL_BN_free(sig->r);
  4524. }
  4525. if (sig->s) {
  4526. wolfSSL_BN_free(sig->s);
  4527. }
  4528. XFREE(sig, NULL, DYNAMIC_TYPE_OPENSSL);
  4529. }
  4530. }
  4531. void wolfSSL_DSA_SIG_get0(const WOLFSSL_DSA_SIG *sig,
  4532. const WOLFSSL_BIGNUM **r, const WOLFSSL_BIGNUM **s)
  4533. {
  4534. WOLFSSL_ENTER("wolfSSL_DSA_SIG_get0");
  4535. if (sig != NULL) {
  4536. *r = sig->r;
  4537. *s = sig->s;
  4538. }
  4539. }
  4540. int wolfSSL_DSA_SIG_set0(WOLFSSL_DSA_SIG *sig, WOLFSSL_BIGNUM *r,
  4541. WOLFSSL_BIGNUM *s)
  4542. {
  4543. WOLFSSL_ENTER("wolfSSL_DSA_SIG_set0");
  4544. if (r == NULL || s == NULL) {
  4545. WOLFSSL_MSG("Bad parameter");
  4546. return 0;
  4547. }
  4548. wolfSSL_BN_clear_free(sig->r);
  4549. wolfSSL_BN_clear_free(sig->s);
  4550. sig->r = r;
  4551. sig->s = s;
  4552. return 1;
  4553. }
  4554. #ifndef HAVE_SELFTEST
  4555. /**
  4556. *
  4557. * @param sig The input signature to encode
  4558. * @param out The output buffer. If *out is NULL then a new buffer is
  4559. * allocated. Otherwise the output is written to the buffer.
  4560. * @return length on success and -1 on error
  4561. */
  4562. int wolfSSL_i2d_DSA_SIG(const WOLFSSL_DSA_SIG *sig, byte **out)
  4563. {
  4564. /* Space for sequence + two asn ints */
  4565. byte buf[MAX_SEQ_SZ + 2*(ASN_TAG_SZ + MAX_LENGTH_SZ + DSA_MAX_HALF_SIZE)];
  4566. word32 bufLen = sizeof(buf);
  4567. WOLFSSL_ENTER("wolfSSL_i2d_DSA_SIG");
  4568. if (sig == NULL || sig->r == NULL || sig->s == NULL ||
  4569. out == NULL) {
  4570. WOLFSSL_MSG("Bad function arguments");
  4571. return -1;
  4572. }
  4573. if (StoreECC_DSA_Sig(buf, &bufLen,
  4574. (mp_int*)sig->r->internal, (mp_int*)sig->s->internal) != 0) {
  4575. WOLFSSL_MSG("StoreECC_DSA_Sig error");
  4576. return -1;
  4577. }
  4578. if (*out == NULL) {
  4579. byte* tmp = (byte*)XMALLOC(bufLen, NULL, DYNAMIC_TYPE_ASN1);
  4580. if (tmp == NULL) {
  4581. WOLFSSL_MSG("malloc error");
  4582. return -1;
  4583. }
  4584. *out = tmp;
  4585. }
  4586. XMEMCPY(*out, buf, bufLen);
  4587. return (int)bufLen;
  4588. }
  4589. /**
  4590. * Same as wolfSSL_DSA_SIG_new but also initializes the internal bignums as well.
  4591. * @return New WOLFSSL_DSA_SIG with r and s created as well
  4592. */
  4593. static WOLFSSL_DSA_SIG* wolfSSL_DSA_SIG_new_bn(void)
  4594. {
  4595. WOLFSSL_DSA_SIG* ret;
  4596. if ((ret = wolfSSL_DSA_SIG_new()) == NULL) {
  4597. WOLFSSL_MSG("wolfSSL_DSA_SIG_new error");
  4598. return NULL;
  4599. }
  4600. if ((ret->r = wolfSSL_BN_new()) == NULL) {
  4601. WOLFSSL_MSG("wolfSSL_BN_new error");
  4602. wolfSSL_DSA_SIG_free(ret);
  4603. return NULL;
  4604. }
  4605. if ((ret->s = wolfSSL_BN_new()) == NULL) {
  4606. WOLFSSL_MSG("wolfSSL_BN_new error");
  4607. wolfSSL_DSA_SIG_free(ret);
  4608. return NULL;
  4609. }
  4610. return ret;
  4611. }
  4612. /**
  4613. * This parses a DER encoded ASN.1 structure. The ASN.1 encoding is:
  4614. * ASN1_SEQUENCE
  4615. * ASN1_INTEGER (DSA r)
  4616. * ASN1_INTEGER (DSA s)
  4617. * Alternatively, if the input is DSA_160_SIG_SIZE or DSA_256_SIG_SIZE in
  4618. * length then this API interprets this as two unsigned binary numbers.
  4619. * @param sig If non-null then free'd first and then newly created
  4620. * WOLFSSL_DSA_SIG is assigned
  4621. * @param pp Input buffer that is moved forward on success
  4622. * @param length Length of input buffer
  4623. * @return Newly created WOLFSSL_DSA_SIG on success or NULL on failure
  4624. */
  4625. WOLFSSL_DSA_SIG* wolfSSL_d2i_DSA_SIG(WOLFSSL_DSA_SIG **sig,
  4626. const unsigned char **pp, long length)
  4627. {
  4628. WOLFSSL_DSA_SIG* ret;
  4629. mp_int* r;
  4630. mp_int* s;
  4631. WOLFSSL_ENTER("wolfSSL_d2i_DSA_SIG");
  4632. if (pp == NULL || *pp == NULL || length < 0) {
  4633. WOLFSSL_MSG("Bad function arguments");
  4634. return NULL;
  4635. }
  4636. if ((ret = wolfSSL_DSA_SIG_new_bn()) == NULL) {
  4637. WOLFSSL_MSG("wolfSSL_DSA_SIG_new_bn error");
  4638. return NULL;
  4639. }
  4640. r = (mp_int*)ret->r->internal;
  4641. s = (mp_int*)ret->s->internal;
  4642. if (DecodeECC_DSA_Sig(*pp, (word32)length, r, s) != 0) {
  4643. if (length == DSA_160_SIG_SIZE || length == DSA_256_SIG_SIZE) {
  4644. /* Two raw numbers of length/2 size each */
  4645. if (mp_read_unsigned_bin(r, *pp, (int)length/2) != 0) {
  4646. WOLFSSL_MSG("r mp_read_unsigned_bin error");
  4647. wolfSSL_DSA_SIG_free(ret);
  4648. return NULL;
  4649. }
  4650. if (mp_read_unsigned_bin(s, *pp + (length/2), (int)length/2) != 0) {
  4651. WOLFSSL_MSG("s mp_read_unsigned_bin error");
  4652. wolfSSL_DSA_SIG_free(ret);
  4653. return NULL;
  4654. }
  4655. *pp += length;
  4656. }
  4657. else {
  4658. WOLFSSL_MSG("DecodeECC_DSA_Sig error");
  4659. wolfSSL_DSA_SIG_free(ret);
  4660. return NULL;
  4661. }
  4662. }
  4663. else {
  4664. /* DecodeECC_DSA_Sig success move pointer forward */
  4665. #ifndef NO_STRICT_ECDSA_LEN
  4666. *pp += length;
  4667. #else
  4668. {
  4669. /* We need to figure out how much to move by ourselves */
  4670. word32 idx = 0;
  4671. int len = 0;
  4672. if (GetSequence(*pp, &idx, &len, (word32)length) < 0) {
  4673. WOLFSSL_MSG("GetSequence error");
  4674. wolfSSL_DSA_SIG_free(ret);
  4675. return NULL;
  4676. }
  4677. *pp += len;
  4678. }
  4679. #endif
  4680. }
  4681. if (sig != NULL) {
  4682. if (*sig != NULL)
  4683. wolfSSL_DSA_SIG_free(*sig);
  4684. *sig = ret;
  4685. }
  4686. return ret;
  4687. }
  4688. #endif /* HAVE_SELFTEST */
  4689. /* return 1 on success, < 0 otherwise */
  4690. int wolfSSL_DSA_do_sign(const unsigned char* d, unsigned char* sigRet,
  4691. WOLFSSL_DSA* dsa)
  4692. {
  4693. int ret = -1;
  4694. int initTmpRng = 0;
  4695. WC_RNG* rng = NULL;
  4696. #ifdef WOLFSSL_SMALL_STACK
  4697. WC_RNG* tmpRng = NULL;
  4698. #else
  4699. WC_RNG tmpRng[1];
  4700. #endif
  4701. WOLFSSL_ENTER("wolfSSL_DSA_do_sign");
  4702. if (d == NULL || sigRet == NULL || dsa == NULL) {
  4703. WOLFSSL_MSG("Bad function arguments");
  4704. return ret;
  4705. }
  4706. if (dsa->inSet == 0) {
  4707. WOLFSSL_MSG("No DSA internal set, do it");
  4708. if (SetDsaInternal(dsa) != 1) {
  4709. WOLFSSL_MSG("SetDsaInternal failed");
  4710. return ret;
  4711. }
  4712. }
  4713. #ifdef WOLFSSL_SMALL_STACK
  4714. tmpRng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  4715. if (tmpRng == NULL)
  4716. return -1;
  4717. #endif
  4718. if (wc_InitRng(tmpRng) == 0) {
  4719. rng = tmpRng;
  4720. initTmpRng = 1;
  4721. }
  4722. else {
  4723. WOLFSSL_MSG("Bad RNG Init, trying global");
  4724. rng = wolfssl_get_global_rng();
  4725. }
  4726. if (rng) {
  4727. if (wc_DsaSign(d, sigRet, (DsaKey*)dsa->internal, rng) < 0)
  4728. WOLFSSL_MSG("DsaSign failed");
  4729. else
  4730. ret = 1;
  4731. }
  4732. if (initTmpRng)
  4733. wc_FreeRng(tmpRng);
  4734. #ifdef WOLFSSL_SMALL_STACK
  4735. XFREE(tmpRng, NULL, DYNAMIC_TYPE_RNG);
  4736. #endif
  4737. return ret;
  4738. }
  4739. #ifndef HAVE_SELFTEST
  4740. WOLFSSL_DSA_SIG* wolfSSL_DSA_do_sign_ex(const unsigned char* digest,
  4741. int inLen, WOLFSSL_DSA* dsa)
  4742. {
  4743. byte sigBin[DSA_MAX_SIG_SIZE];
  4744. const byte *tmp = sigBin;
  4745. int sigLen;
  4746. WOLFSSL_ENTER("wolfSSL_DSA_do_sign_ex");
  4747. if (!digest || !dsa || inLen != WC_SHA_DIGEST_SIZE) {
  4748. WOLFSSL_MSG("Bad function arguments");
  4749. return NULL;
  4750. }
  4751. if (wolfSSL_DSA_do_sign(digest, sigBin, dsa) != 1) {
  4752. WOLFSSL_MSG("wolfSSL_DSA_do_sign error");
  4753. return NULL;
  4754. }
  4755. if (dsa->internal == NULL) {
  4756. WOLFSSL_MSG("dsa->internal is null");
  4757. return NULL;
  4758. }
  4759. sigLen = mp_unsigned_bin_size(&((DsaKey*)dsa->internal)->q);
  4760. if (sigLen <= 0) {
  4761. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4762. return NULL;
  4763. }
  4764. /* 2 * sigLen for the two points r and s */
  4765. return wolfSSL_d2i_DSA_SIG(NULL, &tmp, 2 * sigLen);
  4766. }
  4767. #endif /* !HAVE_SELFTEST */
  4768. int wolfSSL_DSA_do_verify(const unsigned char* d, unsigned char* sig,
  4769. WOLFSSL_DSA* dsa, int *dsacheck)
  4770. {
  4771. int ret = -1;
  4772. WOLFSSL_ENTER("wolfSSL_DSA_do_verify");
  4773. if (d == NULL || sig == NULL || dsa == NULL) {
  4774. WOLFSSL_MSG("Bad function arguments");
  4775. return -1;
  4776. }
  4777. if (dsa->inSet == 0)
  4778. {
  4779. WOLFSSL_MSG("No DSA internal set, do it");
  4780. if (SetDsaInternal(dsa) != 1) {
  4781. WOLFSSL_MSG("SetDsaInternal failed");
  4782. return -1;
  4783. }
  4784. }
  4785. ret = DsaVerify(d, sig, (DsaKey*)dsa->internal, dsacheck);
  4786. if (ret != 0 || *dsacheck != 1) {
  4787. WOLFSSL_MSG("DsaVerify failed");
  4788. return ret;
  4789. }
  4790. return 1;
  4791. }
  4792. int wolfSSL_DSA_bits(const WOLFSSL_DSA *d)
  4793. {
  4794. if (!d)
  4795. return 0;
  4796. if (!d->exSet && SetDsaExternal((WOLFSSL_DSA*)d) != 1)
  4797. return 0;
  4798. return wolfSSL_BN_num_bits(d->p);
  4799. }
  4800. #ifndef HAVE_SELFTEST
  4801. int wolfSSL_DSA_do_verify_ex(const unsigned char* digest, int digest_len,
  4802. WOLFSSL_DSA_SIG* sig, WOLFSSL_DSA* dsa)
  4803. {
  4804. int dsacheck, sz;
  4805. byte sigBin[DSA_MAX_SIG_SIZE];
  4806. byte* sigBinPtr = sigBin;
  4807. DsaKey* key;
  4808. int qSz;
  4809. WOLFSSL_ENTER("wolfSSL_DSA_do_verify_ex");
  4810. if (!digest || !sig || !dsa || digest_len != WC_SHA_DIGEST_SIZE) {
  4811. WOLFSSL_MSG("Bad function arguments");
  4812. return 0;
  4813. }
  4814. if (!sig->r || !sig->s) {
  4815. WOLFSSL_MSG("No signature found in DSA_SIG");
  4816. return 0;
  4817. }
  4818. if (dsa->inSet == 0) {
  4819. WOLFSSL_MSG("No DSA internal set, do it");
  4820. if (SetDsaInternal(dsa) != 1) {
  4821. WOLFSSL_MSG("SetDsaInternal failed");
  4822. return 0;
  4823. }
  4824. }
  4825. key = (DsaKey*)dsa->internal;
  4826. if (key == NULL) {
  4827. WOLFSSL_MSG("dsa->internal is null");
  4828. return 0;
  4829. }
  4830. qSz = mp_unsigned_bin_size(&key->q);
  4831. if (qSz < 0 || qSz > DSA_MAX_HALF_SIZE) {
  4832. WOLFSSL_MSG("mp_unsigned_bin_size error");
  4833. return 0;
  4834. }
  4835. /* read r */
  4836. /* front pad with zeros */
  4837. if ((sz = wolfSSL_BN_num_bytes(sig->r)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4838. return 0;
  4839. while (sz++ < qSz)
  4840. *sigBinPtr++ = 0;
  4841. if (wolfSSL_BN_bn2bin(sig->r, sigBinPtr) == -1)
  4842. return 0;
  4843. /* Move to s */
  4844. sigBinPtr = sigBin + qSz;
  4845. /* read s */
  4846. /* front pad with zeros */
  4847. if ((sz = wolfSSL_BN_num_bytes(sig->s)) < 0 || sz > DSA_MAX_HALF_SIZE)
  4848. return 0;
  4849. while (sz++ < qSz)
  4850. *sigBinPtr++ = 0;
  4851. if (wolfSSL_BN_bn2bin(sig->s, sigBinPtr) == -1)
  4852. return 0;
  4853. if ((wolfSSL_DSA_do_verify(digest, sigBin, dsa, &dsacheck)
  4854. != 1) || dsacheck != 1) {
  4855. return 0;
  4856. }
  4857. return 1;
  4858. }
  4859. #endif /* !HAVE_SELFTEST */
  4860. WOLFSSL_API int wolfSSL_i2d_DSAparams(const WOLFSSL_DSA* dsa,
  4861. unsigned char** out)
  4862. {
  4863. int ret = 0;
  4864. word32 derLen = 0;
  4865. int preAllocated = 1;
  4866. DsaKey* key = NULL;
  4867. WOLFSSL_ENTER("wolfSSL_i2d_DSAparams");
  4868. if (dsa == NULL || dsa->internal == NULL || out == NULL) {
  4869. ret = BAD_FUNC_ARG;
  4870. }
  4871. if (ret == 0) {
  4872. key = (DsaKey*)dsa->internal;
  4873. ret = wc_DsaKeyToParamsDer_ex(key, NULL, &derLen);
  4874. if (ret == LENGTH_ONLY_E) {
  4875. ret = 0;
  4876. }
  4877. }
  4878. if (ret == 0 && *out == NULL) {
  4879. /* If we're allocating out for the caller, we don't increment out just
  4880. past the end of the DER buffer. If out is already allocated, we do.
  4881. (OpenSSL convention) */
  4882. preAllocated = 0;
  4883. *out = (unsigned char*)XMALLOC(derLen, key->heap, DYNAMIC_TYPE_OPENSSL);
  4884. if (*out == NULL) {
  4885. ret = MEMORY_E;
  4886. }
  4887. }
  4888. if (ret == 0) {
  4889. ret = wc_DsaKeyToParamsDer_ex(key, *out, &derLen);
  4890. }
  4891. if (ret >= 0 && preAllocated == 1) {
  4892. *out += derLen;
  4893. }
  4894. if (ret < 0 && preAllocated == 0) {
  4895. XFREE(*out, key ? key->heap : NULL, DYNAMIC_TYPE_OPENSSL);
  4896. }
  4897. WOLFSSL_LEAVE("wolfSSL_i2d_DSAparams", ret);
  4898. return ret;
  4899. }
  4900. WOLFSSL_DSA* wolfSSL_d2i_DSAparams(WOLFSSL_DSA** dsa, const unsigned char** der,
  4901. long derLen)
  4902. {
  4903. WOLFSSL_DSA* ret = NULL;
  4904. int err = 0;
  4905. word32 idx = 0;
  4906. int asnLen;
  4907. DsaKey* internalKey = NULL;
  4908. WOLFSSL_ENTER("wolfSSL_d2i_DSAparams");
  4909. if (der == NULL || *der == NULL || derLen <= 0) {
  4910. err = 1;
  4911. }
  4912. if (err == 0) {
  4913. ret = wolfSSL_DSA_new();
  4914. err = ret == NULL;
  4915. }
  4916. if (err == 0) {
  4917. err = GetSequence(*der, &idx, &asnLen, (word32)derLen) <= 0;
  4918. }
  4919. if (err == 0) {
  4920. internalKey = (DsaKey*)ret->internal;
  4921. err = GetInt(&internalKey->p, *der, &idx, (word32)derLen) != 0;
  4922. }
  4923. if (err == 0) {
  4924. err = GetInt(&internalKey->q, *der, &idx, (word32)derLen) != 0;
  4925. }
  4926. if (err == 0) {
  4927. err = GetInt(&internalKey->g, *der, &idx, (word32)derLen) != 0;
  4928. }
  4929. if (err == 0) {
  4930. err = wolfssl_bn_set_value(&ret->p, &internalKey->p)
  4931. != 1;
  4932. }
  4933. if (err == 0) {
  4934. err = wolfssl_bn_set_value(&ret->q, &internalKey->q)
  4935. != 1;
  4936. }
  4937. if (err == 0) {
  4938. err = wolfssl_bn_set_value(&ret->g, &internalKey->g)
  4939. != 1;
  4940. }
  4941. if (err == 0 && dsa != NULL) {
  4942. *dsa = ret;
  4943. }
  4944. if (err != 0 && ret != NULL) {
  4945. wolfSSL_DSA_free(ret);
  4946. ret = NULL;
  4947. }
  4948. return ret;
  4949. }
  4950. #if defined(WOLFSSL_KEY_GEN)
  4951. #ifndef NO_BIO
  4952. /* Takes a DSA Privatekey and writes it out to a WOLFSSL_BIO
  4953. * Returns 1 or 0
  4954. */
  4955. int wolfSSL_PEM_write_bio_DSAPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa,
  4956. const EVP_CIPHER* cipher,
  4957. unsigned char* passwd, int len,
  4958. wc_pem_password_cb* cb, void* arg)
  4959. {
  4960. int ret = 0, der_max_len = 0, derSz = 0;
  4961. byte *derBuf;
  4962. WOLFSSL_EVP_PKEY* pkey;
  4963. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSAPrivateKey");
  4964. if (bio == NULL || dsa == NULL) {
  4965. WOLFSSL_MSG("Bad Function Arguments");
  4966. return 0;
  4967. }
  4968. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  4969. if (pkey == NULL) {
  4970. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  4971. return 0;
  4972. }
  4973. pkey->type = EVP_PKEY_DSA;
  4974. pkey->dsa = dsa;
  4975. pkey->ownDsa = 0;
  4976. /* 4 > size of pub, priv, p, q, g + ASN.1 additional information */
  4977. der_max_len = MAX_DSA_PRIVKEY_SZ;
  4978. derBuf = (byte*)XMALLOC(der_max_len, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4979. if (derBuf == NULL) {
  4980. WOLFSSL_MSG("Malloc failed");
  4981. wolfSSL_EVP_PKEY_free(pkey);
  4982. return 0;
  4983. }
  4984. /* convert key to der format */
  4985. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len);
  4986. if (derSz < 0) {
  4987. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  4988. XFREE(derBuf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4989. wolfSSL_EVP_PKEY_free(pkey);
  4990. return 0;
  4991. }
  4992. pkey->pkey.ptr = (char*)XMALLOC(derSz, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4993. if (pkey->pkey.ptr == NULL) {
  4994. WOLFSSL_MSG("key malloc failed");
  4995. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  4996. wolfSSL_EVP_PKEY_free(pkey);
  4997. return 0;
  4998. }
  4999. /* add der info to the evp key */
  5000. pkey->pkey_sz = derSz;
  5001. XMEMCPY(pkey->pkey.ptr, derBuf, derSz);
  5002. XFREE(derBuf, bio->heap, DYNAMIC_TYPE_TMP_BUFFER);
  5003. ret = wolfSSL_PEM_write_bio_PrivateKey(bio, pkey, cipher, passwd, len,
  5004. cb, arg);
  5005. wolfSSL_EVP_PKEY_free(pkey);
  5006. return ret;
  5007. }
  5008. #ifndef HAVE_SELFTEST
  5009. /* Takes a DSA public key and writes it out to a WOLFSSL_BIO
  5010. * Returns 1 or 0
  5011. */
  5012. int wolfSSL_PEM_write_bio_DSA_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_DSA* dsa)
  5013. {
  5014. int ret = 0;
  5015. WOLFSSL_EVP_PKEY* pkey;
  5016. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_DSA_PUBKEY");
  5017. if (bio == NULL || dsa == NULL) {
  5018. WOLFSSL_MSG("Bad function arguments");
  5019. return 0;
  5020. }
  5021. pkey = wolfSSL_EVP_PKEY_new_ex(bio->heap);
  5022. if (pkey == NULL) {
  5023. WOLFSSL_MSG("wolfSSL_EVP_PKEY_new_ex failed");
  5024. return 0;
  5025. }
  5026. pkey->type = EVP_PKEY_DSA;
  5027. pkey->dsa = dsa;
  5028. pkey->ownDsa = 0;
  5029. ret = pem_write_bio_pubkey(bio, pkey);
  5030. wolfSSL_EVP_PKEY_free(pkey);
  5031. return ret;
  5032. }
  5033. #endif /* HAVE_SELFTEST */
  5034. #endif /* !NO_BIO */
  5035. /* return code compliant with OpenSSL :
  5036. * 1 if success, 0 if error
  5037. */
  5038. int wolfSSL_PEM_write_mem_DSAPrivateKey(WOLFSSL_DSA* dsa,
  5039. const EVP_CIPHER* cipher,
  5040. unsigned char* passwd, int passwdSz,
  5041. unsigned char **pem, int *pLen)
  5042. {
  5043. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  5044. byte *derBuf, *tmp, *cipherInfo = NULL;
  5045. int der_max_len = 0, derSz = 0;
  5046. const int type = DSA_PRIVATEKEY_TYPE;
  5047. const char* header = NULL;
  5048. const char* footer = NULL;
  5049. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey");
  5050. if (pem == NULL || pLen == NULL || dsa == NULL || dsa->internal == NULL) {
  5051. WOLFSSL_MSG("Bad function arguments");
  5052. return 0;
  5053. }
  5054. if (wc_PemGetHeaderFooter(type, &header, &footer) != 0)
  5055. return 0;
  5056. if (dsa->inSet == 0) {
  5057. WOLFSSL_MSG("No DSA internal set, do it");
  5058. if (SetDsaInternal(dsa) != 1) {
  5059. WOLFSSL_MSG("SetDsaInternal failed");
  5060. return 0;
  5061. }
  5062. }
  5063. der_max_len = MAX_DSA_PRIVKEY_SZ;
  5064. derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_DER);
  5065. if (derBuf == NULL) {
  5066. WOLFSSL_MSG("malloc failed");
  5067. return 0;
  5068. }
  5069. /* Key to DER */
  5070. derSz = wc_DsaKeyToDer((DsaKey*)dsa->internal, derBuf, der_max_len);
  5071. if (derSz < 0) {
  5072. WOLFSSL_MSG("wc_DsaKeyToDer failed");
  5073. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5074. return 0;
  5075. }
  5076. /* encrypt DER buffer if required */
  5077. if (passwd != NULL && passwdSz > 0 && cipher != NULL) {
  5078. int ret;
  5079. ret = EncryptDerKey(derBuf, &derSz, cipher,
  5080. passwd, passwdSz, &cipherInfo, der_max_len);
  5081. if (ret != 1) {
  5082. WOLFSSL_MSG("EncryptDerKey failed");
  5083. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5084. return ret;
  5085. }
  5086. /* tmp buffer with a max size */
  5087. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5088. (int)XSTRLEN(footer) + 1 + HEADER_ENCRYPTED_KEY_SIZE;
  5089. }
  5090. else { /* tmp buffer with a max size */
  5091. *pLen = (derSz * 2) + (int)XSTRLEN(header) + 1 +
  5092. (int)XSTRLEN(footer) + 1;
  5093. }
  5094. tmp = (byte*)XMALLOC(*pLen, NULL, DYNAMIC_TYPE_PEM);
  5095. if (tmp == NULL) {
  5096. WOLFSSL_MSG("malloc failed");
  5097. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5098. if (cipherInfo != NULL)
  5099. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5100. return 0;
  5101. }
  5102. /* DER to PEM */
  5103. *pLen = wc_DerToPemEx(derBuf, derSz, tmp, *pLen, cipherInfo, type);
  5104. if (*pLen <= 0) {
  5105. WOLFSSL_MSG("wc_DerToPemEx failed");
  5106. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5107. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5108. if (cipherInfo != NULL)
  5109. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5110. return 0;
  5111. }
  5112. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  5113. if (cipherInfo != NULL)
  5114. XFREE(cipherInfo, NULL, DYNAMIC_TYPE_STRING);
  5115. *pem = (byte*)XMALLOC((*pLen)+1, NULL, DYNAMIC_TYPE_KEY);
  5116. if (*pem == NULL) {
  5117. WOLFSSL_MSG("malloc failed");
  5118. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5119. return 0;
  5120. }
  5121. XMEMSET(*pem, 0, (*pLen)+1);
  5122. if (XMEMCPY(*pem, tmp, *pLen) == NULL) {
  5123. WOLFSSL_MSG("XMEMCPY failed");
  5124. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5125. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5126. return 0;
  5127. }
  5128. XFREE(tmp, NULL, DYNAMIC_TYPE_PEM);
  5129. return 1;
  5130. #else
  5131. (void)dsa;
  5132. (void)cipher;
  5133. (void)passwd;
  5134. (void)passwdSz;
  5135. (void)pem;
  5136. (void)pLen;
  5137. return 0;
  5138. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  5139. }
  5140. #ifndef NO_FILESYSTEM
  5141. /* return code compliant with OpenSSL :
  5142. * 1 if success, 0 if error
  5143. */
  5144. int wolfSSL_PEM_write_DSAPrivateKey(XFILE fp, WOLFSSL_DSA *dsa,
  5145. const EVP_CIPHER *enc,
  5146. unsigned char *kstr, int klen,
  5147. wc_pem_password_cb *cb, void *u)
  5148. {
  5149. byte *pem;
  5150. int pLen, ret;
  5151. (void)cb;
  5152. (void)u;
  5153. WOLFSSL_MSG("wolfSSL_PEM_write_DSAPrivateKey");
  5154. if (fp == XBADFILE || dsa == NULL || dsa->internal == NULL) {
  5155. WOLFSSL_MSG("Bad function arguments");
  5156. return 0;
  5157. }
  5158. ret = wolfSSL_PEM_write_mem_DSAPrivateKey(dsa, enc, kstr, klen, &pem,
  5159. &pLen);
  5160. if (ret != 1) {
  5161. WOLFSSL_MSG("wolfSSL_PEM_write_mem_DSAPrivateKey failed");
  5162. return 0;
  5163. }
  5164. ret = (int)XFWRITE(pem, pLen, 1, fp);
  5165. if (ret != 1) {
  5166. WOLFSSL_MSG("DSA private key file write failed");
  5167. return 0;
  5168. }
  5169. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  5170. return 1;
  5171. }
  5172. #endif /* NO_FILESYSTEM */
  5173. #endif /* defined(WOLFSSL_KEY_GEN) */
  5174. #ifndef NO_FILESYSTEM
  5175. /* return code compliant with OpenSSL :
  5176. * 1 if success, 0 if error
  5177. */
  5178. #ifndef NO_WOLFSSL_STUB
  5179. int wolfSSL_PEM_write_DSA_PUBKEY(XFILE fp, WOLFSSL_DSA *x)
  5180. {
  5181. (void)fp;
  5182. (void)x;
  5183. WOLFSSL_STUB("PEM_write_DSA_PUBKEY");
  5184. WOLFSSL_MSG("wolfSSL_PEM_write_DSA_PUBKEY not implemented");
  5185. return 0;
  5186. }
  5187. #endif
  5188. #endif /* NO_FILESYSTEM */
  5189. #ifndef NO_BIO
  5190. #if (defined(OPENSSL_EXTRA) || defined(OPENSSL_ALL)) && (!defined(NO_CERTS) && \
  5191. !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN))
  5192. /* Uses the same format of input as wolfSSL_PEM_read_bio_PrivateKey but expects
  5193. * the results to be an DSA key.
  5194. *
  5195. * bio structure to read DSA private key from
  5196. * dsa if not null is then set to the result
  5197. * cb password callback for reading PEM
  5198. * pass password string
  5199. *
  5200. * returns a pointer to a new WOLFSSL_DSA structure on success and NULL on fail
  5201. */
  5202. WOLFSSL_DSA* wolfSSL_PEM_read_bio_DSAPrivateKey(WOLFSSL_BIO* bio,
  5203. WOLFSSL_DSA** dsa,
  5204. wc_pem_password_cb* cb,
  5205. void* pass)
  5206. {
  5207. WOLFSSL_EVP_PKEY* pkey = NULL;
  5208. WOLFSSL_DSA* local;
  5209. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAPrivateKey");
  5210. pkey = wolfSSL_PEM_read_bio_PrivateKey(bio, NULL, cb, pass);
  5211. if (pkey == NULL) {
  5212. WOLFSSL_MSG("Error in PEM_read_bio_PrivateKey");
  5213. return NULL;
  5214. }
  5215. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5216. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5217. * to avoid having it free'd */
  5218. pkey->ownDsa = 0;
  5219. local = pkey->dsa;
  5220. if (dsa != NULL) {
  5221. *dsa = local;
  5222. }
  5223. wolfSSL_EVP_PKEY_free(pkey);
  5224. return local;
  5225. }
  5226. /* Reads an DSA public key from a WOLFSSL_BIO into a WOLFSSL_DSA.
  5227. * Returns 1 or 0
  5228. */
  5229. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSA_PUBKEY(WOLFSSL_BIO* bio,WOLFSSL_DSA** dsa,
  5230. wc_pem_password_cb* cb, void* pass)
  5231. {
  5232. WOLFSSL_EVP_PKEY* pkey;
  5233. WOLFSSL_DSA* local;
  5234. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSA_PUBKEY");
  5235. pkey = wolfSSL_PEM_read_bio_PUBKEY(bio, NULL, cb, pass);
  5236. if (pkey == NULL) {
  5237. WOLFSSL_MSG("wolfSSL_PEM_read_bio_PUBKEY failed");
  5238. return NULL;
  5239. }
  5240. /* Since the WOLFSSL_DSA structure is being taken from WOLFSSL_EVP_PKEY the
  5241. * flag indicating that the WOLFSSL_DSA structure is owned should be FALSE
  5242. * to avoid having it free'd */
  5243. pkey->ownDsa = 0;
  5244. local = pkey->dsa;
  5245. if (dsa != NULL) {
  5246. *dsa = local;
  5247. }
  5248. wolfSSL_EVP_PKEY_free(pkey);
  5249. return local;
  5250. }
  5251. #endif /* (OPENSSL_EXTRA || OPENSSL_ALL) && (!NO_CERTS &&
  5252. !NO_FILESYSTEM && WOLFSSL_KEY_GEN) */
  5253. #endif /* NO_BIO */
  5254. #endif /* OPENSSL_EXTRA */
  5255. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  5256. /* return 1 if success, -1 if error */
  5257. int wolfSSL_DSA_LoadDer(WOLFSSL_DSA* dsa, const unsigned char* derBuf, int derSz)
  5258. {
  5259. word32 idx = 0;
  5260. int ret;
  5261. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5262. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5263. WOLFSSL_MSG("Bad function arguments");
  5264. return -1;
  5265. }
  5266. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5267. if (ret < 0) {
  5268. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5269. return -1;
  5270. }
  5271. if (SetDsaExternal(dsa) != 1) {
  5272. WOLFSSL_MSG("SetDsaExternal failed");
  5273. return -1;
  5274. }
  5275. dsa->inSet = 1;
  5276. return 1;
  5277. }
  5278. /* Loads DSA key from DER buffer. opt = DSA_LOAD_PRIVATE or DSA_LOAD_PUBLIC.
  5279. returns 1 on success, or 0 on failure. */
  5280. int wolfSSL_DSA_LoadDer_ex(WOLFSSL_DSA* dsa, const unsigned char* derBuf,
  5281. int derSz, int opt)
  5282. {
  5283. word32 idx = 0;
  5284. int ret;
  5285. WOLFSSL_ENTER("wolfSSL_DSA_LoadDer");
  5286. if (dsa == NULL || dsa->internal == NULL || derBuf == NULL || derSz <= 0) {
  5287. WOLFSSL_MSG("Bad function arguments");
  5288. return -1;
  5289. }
  5290. if (opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5291. ret = DsaPrivateKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5292. }
  5293. else {
  5294. ret = DsaPublicKeyDecode(derBuf, &idx, (DsaKey*)dsa->internal, derSz);
  5295. }
  5296. if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PRIVATE) {
  5297. WOLFSSL_ERROR_VERBOSE(ret);
  5298. WOLFSSL_MSG("DsaPrivateKeyDecode failed");
  5299. return -1;
  5300. }
  5301. else if (ret < 0 && opt == WOLFSSL_DSA_LOAD_PUBLIC) {
  5302. WOLFSSL_ERROR_VERBOSE(ret);
  5303. WOLFSSL_MSG("DsaPublicKeyDecode failed");
  5304. return -1;
  5305. }
  5306. if (SetDsaExternal(dsa) != 1) {
  5307. WOLFSSL_MSG("SetDsaExternal failed");
  5308. return -1;
  5309. }
  5310. dsa->inSet = 1;
  5311. return 1;
  5312. }
  5313. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  5314. #ifdef OPENSSL_EXTRA
  5315. #ifndef NO_BIO
  5316. WOLFSSL_DSA *wolfSSL_PEM_read_bio_DSAparams(WOLFSSL_BIO *bp, WOLFSSL_DSA **x,
  5317. wc_pem_password_cb *cb, void *u)
  5318. {
  5319. WOLFSSL_DSA* dsa;
  5320. DsaKey* key;
  5321. int length;
  5322. unsigned char* buf;
  5323. word32 bufSz;
  5324. int ret;
  5325. word32 idx = 0;
  5326. DerBuffer* pDer;
  5327. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DSAparams");
  5328. ret = wolfSSL_BIO_get_mem_data(bp, &buf);
  5329. if (ret <= 0) {
  5330. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5331. return NULL;
  5332. }
  5333. bufSz = (word32)ret;
  5334. if (cb != NULL || u != NULL) {
  5335. /*
  5336. * cb is for a call back when encountering encrypted PEM files
  5337. * if cb == NULL and u != NULL then u = null terminated password string
  5338. */
  5339. WOLFSSL_MSG("Not yet supporting call back or password for encrypted PEM");
  5340. }
  5341. if (PemToDer(buf, (long)bufSz, DSA_PARAM_TYPE, &pDer, NULL, NULL,
  5342. NULL) < 0 ) {
  5343. WOLFSSL_MSG("Issue converting from PEM to DER");
  5344. return NULL;
  5345. }
  5346. if (GetSequence(pDer->buffer, &idx, &length, pDer->length) < 0) {
  5347. WOLFSSL_LEAVE("wolfSSL_PEM_read_bio_DSAparams", ret);
  5348. FreeDer(&pDer);
  5349. return NULL;
  5350. }
  5351. dsa = wolfSSL_DSA_new();
  5352. if (dsa == NULL) {
  5353. FreeDer(&pDer);
  5354. WOLFSSL_MSG("Error creating DSA struct");
  5355. return NULL;
  5356. }
  5357. key = (DsaKey*)dsa->internal;
  5358. if (key == NULL) {
  5359. FreeDer(&pDer);
  5360. wolfSSL_DSA_free(dsa);
  5361. WOLFSSL_MSG("Error finding DSA key struct");
  5362. return NULL;
  5363. }
  5364. if (GetInt(&key->p, pDer->buffer, &idx, pDer->length) < 0 ||
  5365. GetInt(&key->q, pDer->buffer, &idx, pDer->length) < 0 ||
  5366. GetInt(&key->g, pDer->buffer, &idx, pDer->length) < 0 ) {
  5367. WOLFSSL_MSG("dsa key error");
  5368. FreeDer(&pDer);
  5369. wolfSSL_DSA_free(dsa);
  5370. return NULL;
  5371. }
  5372. if (wolfssl_bn_set_value(&dsa->p, &key->p) != 1) {
  5373. WOLFSSL_MSG("dsa p key error");
  5374. FreeDer(&pDer);
  5375. wolfSSL_DSA_free(dsa);
  5376. return NULL;
  5377. }
  5378. if (wolfssl_bn_set_value(&dsa->q, &key->q) != 1) {
  5379. WOLFSSL_MSG("dsa q key error");
  5380. FreeDer(&pDer);
  5381. wolfSSL_DSA_free(dsa);
  5382. return NULL;
  5383. }
  5384. if (wolfssl_bn_set_value(&dsa->g, &key->g) != 1) {
  5385. WOLFSSL_MSG("dsa g key error");
  5386. FreeDer(&pDer);
  5387. wolfSSL_DSA_free(dsa);
  5388. return NULL;
  5389. }
  5390. if (x != NULL) {
  5391. *x = dsa;
  5392. }
  5393. FreeDer(&pDer);
  5394. return dsa;
  5395. }
  5396. #endif /* !NO_BIO */
  5397. #if !defined(NO_DH)
  5398. WOLFSSL_DH *wolfSSL_DSA_dup_DH(const WOLFSSL_DSA *dsa)
  5399. {
  5400. WOLFSSL_DH* dh;
  5401. DhKey* key;
  5402. WOLFSSL_ENTER("wolfSSL_DSA_dup_DH");
  5403. if (dsa == NULL) {
  5404. return NULL;
  5405. }
  5406. dh = wolfSSL_DH_new();
  5407. if (dh == NULL) {
  5408. return NULL;
  5409. }
  5410. key = (DhKey*)dh->internal;
  5411. if (dsa->p != NULL &&
  5412. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->p, &key->p)
  5413. != 1) {
  5414. WOLFSSL_MSG("rsa p key error");
  5415. wolfSSL_DH_free(dh);
  5416. return NULL;
  5417. }
  5418. if (dsa->g != NULL &&
  5419. wolfssl_bn_get_value(((WOLFSSL_DSA*)dsa)->g, &key->g)
  5420. != 1) {
  5421. WOLFSSL_MSG("rsa g key error");
  5422. wolfSSL_DH_free(dh);
  5423. return NULL;
  5424. }
  5425. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  5426. WOLFSSL_MSG("dsa p key error");
  5427. wolfSSL_DH_free(dh);
  5428. return NULL;
  5429. }
  5430. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  5431. WOLFSSL_MSG("dsa g key error");
  5432. wolfSSL_DH_free(dh);
  5433. return NULL;
  5434. }
  5435. return dh;
  5436. }
  5437. #endif /* !NO_DH */
  5438. #endif /* OPENSSL_EXTRA */
  5439. #endif /* !NO_DSA */
  5440. /*******************************************************************************
  5441. * END OF DSA API
  5442. ******************************************************************************/
  5443. /*******************************************************************************
  5444. * START OF DH API
  5445. ******************************************************************************/
  5446. #ifndef NO_DH
  5447. #ifdef OPENSSL_EXTRA
  5448. /*
  5449. * DH constructor/deconstructor APIs
  5450. */
  5451. /* Allocate and initialize a new DH key.
  5452. *
  5453. * @return DH key on success.
  5454. * @return NULL on failure.
  5455. */
  5456. WOLFSSL_DH* wolfSSL_DH_new(void)
  5457. {
  5458. int err = 0;
  5459. WOLFSSL_DH* dh = NULL;
  5460. DhKey* key = NULL;
  5461. WOLFSSL_ENTER("wolfSSL_DH_new");
  5462. /* Allocate OpenSSL DH key. */
  5463. dh = (WOLFSSL_DH*)XMALLOC(sizeof(WOLFSSL_DH), NULL, DYNAMIC_TYPE_DH);
  5464. if (dh == NULL) {
  5465. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc WOLFSSL_DH failure");
  5466. err = 1;
  5467. }
  5468. if (!err) {
  5469. /* Clear key data. */
  5470. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5471. /* Initialize reference counting. */
  5472. wolfSSL_RefInit(&dh->ref, &err);
  5473. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  5474. }
  5475. if (!err) {
  5476. #endif
  5477. /* Allocate wolfSSL DH key. */
  5478. key = (DhKey*)XMALLOC(sizeof(DhKey), NULL, DYNAMIC_TYPE_DH);
  5479. if (key == NULL) {
  5480. WOLFSSL_ERROR_MSG("wolfSSL_DH_new malloc DhKey failure");
  5481. err = 1;
  5482. }
  5483. }
  5484. if (!err) {
  5485. /* Set and initialize wolfSSL DH key. */
  5486. dh->internal = key;
  5487. if (wc_InitDhKey(key) != 0) {
  5488. WOLFSSL_ERROR_MSG("wolfSSL_DH_new InitDhKey failure");
  5489. err = 1;
  5490. }
  5491. }
  5492. if (err && (dh != NULL)) {
  5493. /* Dispose of the allocated memory. */
  5494. XFREE(key, NULL, DYNAMIC_TYPE_DH);
  5495. wolfSSL_RefFree(&dh->ref);
  5496. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5497. dh = NULL;
  5498. }
  5499. return dh;
  5500. }
  5501. #if defined(HAVE_PUBLIC_FFDHE) || (defined(HAVE_FIPS) && FIPS_VERSION_EQ(2,0))
  5502. /* Set the DH parameters based on the NID.
  5503. *
  5504. * @param [in, out] dh DH key to set.
  5505. * @param [in] nid Numeric ID of predefined DH parameters.
  5506. * @return 0 on success.
  5507. * @return 1 on failure.
  5508. */
  5509. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5510. {
  5511. int err = 0;
  5512. const DhParams* params = NULL;
  5513. /* HAVE_PUBLIC_FFDHE not required to expose wc_Dh_ffdhe* functions in
  5514. * FIPS v2 module */
  5515. switch (nid) {
  5516. #ifdef HAVE_FFDHE_2048
  5517. case NID_ffdhe2048:
  5518. params = wc_Dh_ffdhe2048_Get();
  5519. break;
  5520. #endif /* HAVE_FFDHE_2048 */
  5521. #ifdef HAVE_FFDHE_3072
  5522. case NID_ffdhe3072:
  5523. params = wc_Dh_ffdhe3072_Get();
  5524. break;
  5525. #endif /* HAVE_FFDHE_3072 */
  5526. #ifdef HAVE_FFDHE_4096
  5527. case NID_ffdhe4096:
  5528. params = wc_Dh_ffdhe4096_Get();
  5529. break;
  5530. #endif /* HAVE_FFDHE_4096 */
  5531. default:
  5532. break;
  5533. }
  5534. if (params == NULL) {
  5535. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5536. err = 1;
  5537. }
  5538. if (!err) {
  5539. /* Set prime from data retrieved. */
  5540. dh->p = wolfSSL_BN_bin2bn(params->p, params->p_len, NULL);
  5541. if (dh->p == NULL) {
  5542. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5543. err = 1;
  5544. }
  5545. }
  5546. if (!err) {
  5547. /* Set generator from data retrieved. */
  5548. dh->g = wolfSSL_BN_bin2bn(params->g, params->g_len, NULL);
  5549. if (dh->g == NULL) {
  5550. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5551. err = 1;
  5552. }
  5553. }
  5554. #ifdef HAVE_FFDHE_Q
  5555. if (!err) {
  5556. /* Set order from data retrieved. */
  5557. dh->q = wolfSSL_BN_bin2bn(params->q, params->q_len, NULL);
  5558. if (dh->q == NULL) {
  5559. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5560. err = 1;
  5561. }
  5562. }
  5563. #endif
  5564. /* Synchronize the external into internal DH key's parameters. */
  5565. if ((!err) && (SetDhInternal(dh) != 1)) {
  5566. WOLFSSL_ERROR_MSG("Failed to set internal DH params.");
  5567. err = 1;
  5568. }
  5569. if (!err) {
  5570. /* External DH key parameters were set. */
  5571. dh->exSet = 1;
  5572. }
  5573. if (err == 1) {
  5574. /* Dispose of any external parameters. */
  5575. #ifdef HAVE_FFDHE_Q
  5576. wolfSSL_BN_free(dh->q);
  5577. dh->q = NULL;
  5578. #endif
  5579. wolfSSL_BN_free(dh->p);
  5580. dh->p = NULL;
  5581. wolfSSL_BN_free(dh->g);
  5582. dh->g = NULL;
  5583. }
  5584. return err;
  5585. }
  5586. #elif !defined(HAVE_PUBLIC_FFDHE) && (!defined(HAVE_FIPS) || \
  5587. FIPS_VERSION_GT(2,0))
  5588. /* Set the DH parameters based on the NID.
  5589. *
  5590. * FIPS v2 and lower doesn't support wc_DhSetNamedKey.
  5591. *
  5592. * @param [in, out] dh DH key to set.
  5593. * @param [in] nid Numeric ID of predefined DH parameters.
  5594. * @return 0 on success.
  5595. * @return 1 on failure.
  5596. */
  5597. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5598. {
  5599. int err = 0;
  5600. int name = 0;
  5601. #ifdef HAVE_FFDHE_Q
  5602. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_Q;
  5603. #else
  5604. int elements = ELEMENT_P | ELEMENT_G;
  5605. #endif /* HAVE_FFDHE_Q */
  5606. switch (nid) {
  5607. #ifdef HAVE_FFDHE_2048
  5608. case NID_ffdhe2048:
  5609. name = WC_FFDHE_2048;
  5610. break;
  5611. #endif /* HAVE_FFDHE_2048 */
  5612. #ifdef HAVE_FFDHE_3072
  5613. case NID_ffdhe3072:
  5614. name = WC_FFDHE_3072;
  5615. break;
  5616. #endif /* HAVE_FFDHE_3072 */
  5617. #ifdef HAVE_FFDHE_4096
  5618. case NID_ffdhe4096:
  5619. name = WC_FFDHE_4096;
  5620. break;
  5621. #endif /* HAVE_FFDHE_4096 */
  5622. default:
  5623. err = 1;
  5624. WOLFSSL_ERROR_MSG("Unable to find DH params for nid.");
  5625. break;
  5626. }
  5627. /* Set the internal DH key's parameters based on name. */
  5628. if ((!err) && (wc_DhSetNamedKey((DhKey*)dh->internal, name) != 0)) {
  5629. WOLFSSL_ERROR_MSG("wc_DhSetNamedKey failed.");
  5630. err = 1;
  5631. }
  5632. /* Synchronize the internal into external DH key's parameters. */
  5633. if (!err && (SetDhExternal_ex(dh, elements) != 1)) {
  5634. WOLFSSL_ERROR_MSG("Failed to set external DH params.");
  5635. err = 1;
  5636. }
  5637. return err;
  5638. }
  5639. #else
  5640. /* Set the DH parameters based on the NID.
  5641. *
  5642. * Pre-defined DH parameters not available.
  5643. *
  5644. * @param [in, out] dh DH key to set.
  5645. * @param [in] nid Numeric ID of predefined DH parameters.
  5646. * @return 1 for failure.
  5647. */
  5648. static int wolfssl_dh_set_nid(WOLFSSL_DH* dh, int nid)
  5649. {
  5650. return 1;
  5651. }
  5652. #endif
  5653. /* Allocate and initialize a new DH key with the parameters based on the NID.
  5654. *
  5655. * @param [in] nid Numeric ID of DH parameters.
  5656. *
  5657. * @return DH key on success.
  5658. * @return NULL on failure.
  5659. */
  5660. WOLFSSL_DH* wolfSSL_DH_new_by_nid(int nid)
  5661. {
  5662. WOLFSSL_DH* dh = NULL;
  5663. int err = 0;
  5664. WOLFSSL_ENTER("wolfSSL_DH_new_by_nid");
  5665. /* Allocate a new DH key. */
  5666. dh = wolfSSL_DH_new();
  5667. if (dh == NULL) {
  5668. WOLFSSL_ERROR_MSG("Failed to create WOLFSSL_DH.");
  5669. err = 1;
  5670. }
  5671. if (!err) {
  5672. /* Set the parameters based on NID. */
  5673. err = wolfssl_dh_set_nid(dh, nid);
  5674. }
  5675. if (err && (dh != NULL)) {
  5676. /* Dispose of the key on failure to set. */
  5677. wolfSSL_DH_free(dh);
  5678. dh = NULL;
  5679. }
  5680. WOLFSSL_LEAVE("wolfSSL_DH_new_by_nid", err);
  5681. return dh;
  5682. }
  5683. /* Dispose of DH key and allocated data.
  5684. *
  5685. * Cannot use dh after this call.
  5686. *
  5687. * @param [in] dh DH key to free.
  5688. */
  5689. void wolfSSL_DH_free(WOLFSSL_DH* dh)
  5690. {
  5691. int doFree = 0;
  5692. WOLFSSL_ENTER("wolfSSL_DH_free");
  5693. if (dh != NULL) {
  5694. int err;
  5695. /* Only free if all references to it are done */
  5696. wolfSSL_RefDec(&dh->ref, &doFree, &err);
  5697. /* Ignore errors - doFree will be 0 on error. */
  5698. (void)err;
  5699. }
  5700. if (doFree) {
  5701. /* Dispose of allocated reference counting data. */
  5702. wolfSSL_RefFree(&dh->ref);
  5703. /* Dispose of wolfSSL DH key. */
  5704. if (dh->internal) {
  5705. wc_FreeDhKey((DhKey*)dh->internal);
  5706. XFREE(dh->internal, NULL, DYNAMIC_TYPE_DH);
  5707. dh->internal = NULL;
  5708. }
  5709. /* Dispose of any allocated BNs. */
  5710. wolfSSL_BN_free(dh->priv_key);
  5711. wolfSSL_BN_free(dh->pub_key);
  5712. wolfSSL_BN_free(dh->g);
  5713. wolfSSL_BN_free(dh->p);
  5714. wolfSSL_BN_free(dh->q);
  5715. /* Set back to NULLs for safety. */
  5716. XMEMSET(dh, 0, sizeof(WOLFSSL_DH));
  5717. XFREE(dh, NULL, DYNAMIC_TYPE_DH);
  5718. }
  5719. }
  5720. /* Increments ref count of DH key.
  5721. *
  5722. * @param [in, out] dh DH key.
  5723. * @return 1 on success
  5724. * @return 0 on error
  5725. */
  5726. int wolfSSL_DH_up_ref(WOLFSSL_DH* dh)
  5727. {
  5728. int err = 1;
  5729. WOLFSSL_ENTER("wolfSSL_DH_up_ref");
  5730. if (dh != NULL) {
  5731. wolfSSL_RefInc(&dh->ref, &err);
  5732. }
  5733. return !err;
  5734. }
  5735. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) || defined(WOLFSSL_OPENSSH) || \
  5736. defined(OPENSSL_EXTRA)
  5737. #ifdef WOLFSSL_DH_EXTRA
  5738. /* Duplicate the DH key.
  5739. *
  5740. * Internal DH key in 'dh' is updated if necessary.
  5741. *
  5742. * @param [in, out] dh DH key to duplicate.
  5743. * @return NULL on failure.
  5744. * @return DH key on success.
  5745. */
  5746. WOLFSSL_DH* wolfSSL_DH_dup(WOLFSSL_DH* dh)
  5747. {
  5748. WOLFSSL_DH* ret = NULL;
  5749. int err = 0;
  5750. WOLFSSL_ENTER("wolfSSL_DH_dup");
  5751. /* Validate parameters. */
  5752. if (dh == NULL) {
  5753. WOLFSSL_ERROR_MSG("Bad parameter");
  5754. err = 1;
  5755. }
  5756. /* Ensure internal DH key is set. */
  5757. if ((!err) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  5758. WOLFSSL_ERROR_MSG("Bad DH set internal");
  5759. err = 1;
  5760. }
  5761. /* Create a new DH key object. */
  5762. if ((!err) && (!(ret = wolfSSL_DH_new()))) {
  5763. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  5764. err = 1;
  5765. }
  5766. /* Copy internal DH key from original to new. */
  5767. if ((!err) && (wc_DhKeyCopy((DhKey*)dh->internal, (DhKey*)ret->internal) !=
  5768. MP_OKAY)) {
  5769. WOLFSSL_ERROR_MSG("wc_DhKeyCopy error");
  5770. err = 1;
  5771. }
  5772. if (!err) {
  5773. ret->inSet = 1;
  5774. /* Synchronize the internal into external DH key's parameters. */
  5775. if (SetDhExternal(ret) != 1) {
  5776. WOLFSSL_ERROR_MSG("SetDhExternal error");
  5777. err = 1;
  5778. }
  5779. }
  5780. /* Dispose of any allocated DH key on error. */
  5781. if (err && (ret != NULL)) {
  5782. wolfSSL_DH_free(ret);
  5783. ret = NULL;
  5784. }
  5785. return ret;
  5786. }
  5787. #endif /* WOLFSSL_DH_EXTRA */
  5788. #endif
  5789. /* Allocate and initialize a new DH key with 2048-bit parameters.
  5790. *
  5791. * See RFC 5114 section 2.3, "2048-bit MODP Group with 256-bit Prime Order
  5792. * Subgroup."
  5793. *
  5794. * @return NULL on failure.
  5795. * @return DH Key on success.
  5796. */
  5797. WOLFSSL_DH* wolfSSL_DH_get_2048_256(void)
  5798. {
  5799. WOLFSSL_DH* dh;
  5800. int err = 0;
  5801. static const byte pHex[] = {
  5802. 0x87, 0xA8, 0xE6, 0x1D, 0xB4, 0xB6, 0x66, 0x3C, 0xFF, 0xBB, 0xD1, 0x9C,
  5803. 0x65, 0x19, 0x59, 0x99, 0x8C, 0xEE, 0xF6, 0x08, 0x66, 0x0D, 0xD0, 0xF2,
  5804. 0x5D, 0x2C, 0xEE, 0xD4, 0x43, 0x5E, 0x3B, 0x00, 0xE0, 0x0D, 0xF8, 0xF1,
  5805. 0xD6, 0x19, 0x57, 0xD4, 0xFA, 0xF7, 0xDF, 0x45, 0x61, 0xB2, 0xAA, 0x30,
  5806. 0x16, 0xC3, 0xD9, 0x11, 0x34, 0x09, 0x6F, 0xAA, 0x3B, 0xF4, 0x29, 0x6D,
  5807. 0x83, 0x0E, 0x9A, 0x7C, 0x20, 0x9E, 0x0C, 0x64, 0x97, 0x51, 0x7A, 0xBD,
  5808. 0x5A, 0x8A, 0x9D, 0x30, 0x6B, 0xCF, 0x67, 0xED, 0x91, 0xF9, 0xE6, 0x72,
  5809. 0x5B, 0x47, 0x58, 0xC0, 0x22, 0xE0, 0xB1, 0xEF, 0x42, 0x75, 0xBF, 0x7B,
  5810. 0x6C, 0x5B, 0xFC, 0x11, 0xD4, 0x5F, 0x90, 0x88, 0xB9, 0x41, 0xF5, 0x4E,
  5811. 0xB1, 0xE5, 0x9B, 0xB8, 0xBC, 0x39, 0xA0, 0xBF, 0x12, 0x30, 0x7F, 0x5C,
  5812. 0x4F, 0xDB, 0x70, 0xC5, 0x81, 0xB2, 0x3F, 0x76, 0xB6, 0x3A, 0xCA, 0xE1,
  5813. 0xCA, 0xA6, 0xB7, 0x90, 0x2D, 0x52, 0x52, 0x67, 0x35, 0x48, 0x8A, 0x0E,
  5814. 0xF1, 0x3C, 0x6D, 0x9A, 0x51, 0xBF, 0xA4, 0xAB, 0x3A, 0xD8, 0x34, 0x77,
  5815. 0x96, 0x52, 0x4D, 0x8E, 0xF6, 0xA1, 0x67, 0xB5, 0xA4, 0x18, 0x25, 0xD9,
  5816. 0x67, 0xE1, 0x44, 0xE5, 0x14, 0x05, 0x64, 0x25, 0x1C, 0xCA, 0xCB, 0x83,
  5817. 0xE6, 0xB4, 0x86, 0xF6, 0xB3, 0xCA, 0x3F, 0x79, 0x71, 0x50, 0x60, 0x26,
  5818. 0xC0, 0xB8, 0x57, 0xF6, 0x89, 0x96, 0x28, 0x56, 0xDE, 0xD4, 0x01, 0x0A,
  5819. 0xBD, 0x0B, 0xE6, 0x21, 0xC3, 0xA3, 0x96, 0x0A, 0x54, 0xE7, 0x10, 0xC3,
  5820. 0x75, 0xF2, 0x63, 0x75, 0xD7, 0x01, 0x41, 0x03, 0xA4, 0xB5, 0x43, 0x30,
  5821. 0xC1, 0x98, 0xAF, 0x12, 0x61, 0x16, 0xD2, 0x27, 0x6E, 0x11, 0x71, 0x5F,
  5822. 0x69, 0x38, 0x77, 0xFA, 0xD7, 0xEF, 0x09, 0xCA, 0xDB, 0x09, 0x4A, 0xE9,
  5823. 0x1E, 0x1A, 0x15, 0x97
  5824. };
  5825. static const byte gHex[] = {
  5826. 0x3F, 0xB3, 0x2C, 0x9B, 0x73, 0x13, 0x4D, 0x0B, 0x2E, 0x77, 0x50, 0x66,
  5827. 0x60, 0xED, 0xBD, 0x48, 0x4C, 0xA7, 0xB1, 0x8F, 0x21, 0xEF, 0x20, 0x54,
  5828. 0x07, 0xF4, 0x79, 0x3A, 0x1A, 0x0B, 0xA1, 0x25, 0x10, 0xDB, 0xC1, 0x50,
  5829. 0x77, 0xBE, 0x46, 0x3F, 0xFF, 0x4F, 0xED, 0x4A, 0xAC, 0x0B, 0xB5, 0x55,
  5830. 0xBE, 0x3A, 0x6C, 0x1B, 0x0C, 0x6B, 0x47, 0xB1, 0xBC, 0x37, 0x73, 0xBF,
  5831. 0x7E, 0x8C, 0x6F, 0x62, 0x90, 0x12, 0x28, 0xF8, 0xC2, 0x8C, 0xBB, 0x18,
  5832. 0xA5, 0x5A, 0xE3, 0x13, 0x41, 0x00, 0x0A, 0x65, 0x01, 0x96, 0xF9, 0x31,
  5833. 0xC7, 0x7A, 0x57, 0xF2, 0xDD, 0xF4, 0x63, 0xE5, 0xE9, 0xEC, 0x14, 0x4B,
  5834. 0x77, 0x7D, 0xE6, 0x2A, 0xAA, 0xB8, 0xA8, 0x62, 0x8A, 0xC3, 0x76, 0xD2,
  5835. 0x82, 0xD6, 0xED, 0x38, 0x64, 0xE6, 0x79, 0x82, 0x42, 0x8E, 0xBC, 0x83,
  5836. 0x1D, 0x14, 0x34, 0x8F, 0x6F, 0x2F, 0x91, 0x93, 0xB5, 0x04, 0x5A, 0xF2,
  5837. 0x76, 0x71, 0x64, 0xE1, 0xDF, 0xC9, 0x67, 0xC1, 0xFB, 0x3F, 0x2E, 0x55,
  5838. 0xA4, 0xBD, 0x1B, 0xFF, 0xE8, 0x3B, 0x9C, 0x80, 0xD0, 0x52, 0xB9, 0x85,
  5839. 0xD1, 0x82, 0xEA, 0x0A, 0xDB, 0x2A, 0x3B, 0x73, 0x13, 0xD3, 0xFE, 0x14,
  5840. 0xC8, 0x48, 0x4B, 0x1E, 0x05, 0x25, 0x88, 0xB9, 0xB7, 0xD2, 0xBB, 0xD2,
  5841. 0xDF, 0x01, 0x61, 0x99, 0xEC, 0xD0, 0x6E, 0x15, 0x57, 0xCD, 0x09, 0x15,
  5842. 0xB3, 0x35, 0x3B, 0xBB, 0x64, 0xE0, 0xEC, 0x37, 0x7F, 0xD0, 0x28, 0x37,
  5843. 0x0D, 0xF9, 0x2B, 0x52, 0xC7, 0x89, 0x14, 0x28, 0xCD, 0xC6, 0x7E, 0xB6,
  5844. 0x18, 0x4B, 0x52, 0x3D, 0x1D, 0xB2, 0x46, 0xC3, 0x2F, 0x63, 0x07, 0x84,
  5845. 0x90, 0xF0, 0x0E, 0xF8, 0xD6, 0x47, 0xD1, 0x48, 0xD4, 0x79, 0x54, 0x51,
  5846. 0x5E, 0x23, 0x27, 0xCF, 0xEF, 0x98, 0xC5, 0x82, 0x66, 0x4B, 0x4C, 0x0F,
  5847. 0x6C, 0xC4, 0x16, 0x59
  5848. };
  5849. static const byte qHex[] = {
  5850. 0x8C, 0xF8, 0x36, 0x42, 0xA7, 0x09, 0xA0, 0x97, 0xB4, 0x47, 0x99, 0x76,
  5851. 0x40, 0x12, 0x9D, 0xA2, 0x99, 0xB1, 0xA4, 0x7D, 0x1E, 0xB3, 0x75, 0x0B,
  5852. 0xA3, 0x08, 0xB0, 0xFE, 0x64, 0xF5, 0xFB, 0xD3
  5853. };
  5854. /* Create a new DH key to return. */
  5855. dh = wolfSSL_DH_new();
  5856. if (dh == NULL) {
  5857. err = 1;
  5858. }
  5859. if (!err) {
  5860. /* Set prime. */
  5861. dh->p = wolfSSL_BN_bin2bn(pHex, (int)sizeof(pHex), NULL);
  5862. if (dh->p == NULL) {
  5863. WOLFSSL_ERROR_MSG("Error converting p hex to WOLFSSL_BIGNUM.");
  5864. err = 1;
  5865. }
  5866. }
  5867. if (!err) {
  5868. /* Set generator. */
  5869. dh->g = wolfSSL_BN_bin2bn(gHex, (int)sizeof(gHex), NULL);
  5870. if (dh->g == NULL) {
  5871. WOLFSSL_ERROR_MSG("Error converting g hex to WOLFSSL_BIGNUM.");
  5872. err = 1;
  5873. }
  5874. }
  5875. if (!err) {
  5876. /* Set order. */
  5877. dh->q = wolfSSL_BN_bin2bn(qHex, (int)sizeof(qHex), NULL);
  5878. if (dh->q == NULL) {
  5879. WOLFSSL_ERROR_MSG("Error converting q hex to WOLFSSL_BIGNUM.");
  5880. err = 1;
  5881. }
  5882. }
  5883. /* Set values into wolfSSL DH key. */
  5884. if ((!err) && (SetDhInternal(dh) != 1)) {
  5885. WOLFSSL_ERROR_MSG("Error setting DH parameters.");
  5886. err = 1;
  5887. }
  5888. if (!err) {
  5889. /* External DH key parameters were set. */
  5890. dh->exSet = 1;
  5891. }
  5892. /* Dispose of any allocated DH key on error. */
  5893. if (err && (dh != NULL)) {
  5894. wolfSSL_DH_free(dh);
  5895. dh = NULL;
  5896. }
  5897. return dh;
  5898. }
  5899. /* TODO: consider changing strings to byte arrays. */
  5900. /* Returns a big number with the 768-bit prime from RFC 2409.
  5901. *
  5902. * @param [in, out] bn If not NULL then this BN is set and returned.
  5903. * If NULL then a new BN is created, set and returned.
  5904. *
  5905. * @return NULL on failure.
  5906. * @return WOLFSSL_BIGNUM with value set to 768-bit prime on success.
  5907. */
  5908. WOLFSSL_BIGNUM* wolfSSL_DH_768_prime(WOLFSSL_BIGNUM* bn)
  5909. {
  5910. #if WOLFSSL_MAX_BN_BITS >= 768
  5911. static const char prm[] = {
  5912. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5913. "C4C6628B80DC1CD129024E088A67CC74"
  5914. "020BBEA63B139B22514A08798E3404DD"
  5915. "EF9519B3CD3A431B302B0A6DF25F1437"
  5916. "4FE1356D6D51C245E485B576625E7EC6"
  5917. "F44C42E9A63A3620FFFFFFFFFFFFFFFF"
  5918. };
  5919. WOLFSSL_ENTER("wolfSSL_DH_768_prime");
  5920. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5921. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5922. WOLFSSL_ERROR_MSG("Error converting DH 768 prime to big number");
  5923. bn = NULL;
  5924. }
  5925. return bn;
  5926. #else
  5927. (void)bn;
  5928. return NULL;
  5929. #endif
  5930. }
  5931. /* Returns a big number with the 1024-bit prime from RFC 2409.
  5932. *
  5933. * @param [in, out] bn If not NULL then this BN is set and returned.
  5934. * If NULL then a new BN is created, set and returned.
  5935. *
  5936. * @return NULL on failure.
  5937. * @return WOLFSSL_BIGNUM with value set to 1024-bit prime on success.
  5938. */
  5939. WOLFSSL_BIGNUM* wolfSSL_DH_1024_prime(WOLFSSL_BIGNUM* bn)
  5940. {
  5941. #if WOLFSSL_MAX_BN_BITS >= 1024
  5942. static const char prm[] = {
  5943. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5944. "C4C6628B80DC1CD129024E088A67CC74"
  5945. "020BBEA63B139B22514A08798E3404DD"
  5946. "EF9519B3CD3A431B302B0A6DF25F1437"
  5947. "4FE1356D6D51C245E485B576625E7EC6"
  5948. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5949. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5950. "49286651ECE65381FFFFFFFFFFFFFFFF"
  5951. };
  5952. WOLFSSL_ENTER("wolfSSL_DH_1024_prime");
  5953. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5954. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5955. WOLFSSL_ERROR_MSG("Error converting DH 1024 prime to big number");
  5956. bn = NULL;
  5957. }
  5958. return bn;
  5959. #else
  5960. (void)bn;
  5961. return NULL;
  5962. #endif
  5963. }
  5964. /* Returns a big number with the 1536-bit prime from RFC 3526.
  5965. *
  5966. * @param [in, out] bn If not NULL then this BN is set and returned.
  5967. * If NULL then a new BN is created, set and returned.
  5968. *
  5969. * @return NULL on failure.
  5970. * @return WOLFSSL_BIGNUM with value set to 1536-bit prime on success.
  5971. */
  5972. WOLFSSL_BIGNUM* wolfSSL_DH_1536_prime(WOLFSSL_BIGNUM* bn)
  5973. {
  5974. #if WOLFSSL_MAX_BN_BITS >= 1536
  5975. static const char prm[] = {
  5976. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  5977. "C4C6628B80DC1CD129024E088A67CC74"
  5978. "020BBEA63B139B22514A08798E3404DD"
  5979. "EF9519B3CD3A431B302B0A6DF25F1437"
  5980. "4FE1356D6D51C245E485B576625E7EC6"
  5981. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  5982. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  5983. "49286651ECE45B3DC2007CB8A163BF05"
  5984. "98DA48361C55D39A69163FA8FD24CF5F"
  5985. "83655D23DCA3AD961C62F356208552BB"
  5986. "9ED529077096966D670C354E4ABC9804"
  5987. "F1746C08CA237327FFFFFFFFFFFFFFFF"
  5988. };
  5989. WOLFSSL_ENTER("wolfSSL_DH_1536_prime");
  5990. /* Set prime into BN. Creates a new BN when bn is NULL. */
  5991. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  5992. WOLFSSL_ERROR_MSG("Error converting DH 1536 prime to big number");
  5993. bn = NULL;
  5994. }
  5995. return bn;
  5996. #else
  5997. (void)bn;
  5998. return NULL;
  5999. #endif
  6000. }
  6001. /* Returns a big number with the 2048-bit prime from RFC 3526.
  6002. *
  6003. * @param [in, out] bn If not NULL then this BN is set and returned.
  6004. * If NULL then a new BN is created, set and returned.
  6005. *
  6006. * @return NULL on failure.
  6007. * @return WOLFSSL_BIGNUM with value set to 2048-bit prime on success.
  6008. */
  6009. WOLFSSL_BIGNUM* wolfSSL_DH_2048_prime(WOLFSSL_BIGNUM* bn)
  6010. {
  6011. #if WOLFSSL_MAX_BN_BITS >= 2048
  6012. static const char prm[] = {
  6013. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6014. "C4C6628B80DC1CD129024E088A67CC74"
  6015. "020BBEA63B139B22514A08798E3404DD"
  6016. "EF9519B3CD3A431B302B0A6DF25F1437"
  6017. "4FE1356D6D51C245E485B576625E7EC6"
  6018. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6019. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6020. "49286651ECE45B3DC2007CB8A163BF05"
  6021. "98DA48361C55D39A69163FA8FD24CF5F"
  6022. "83655D23DCA3AD961C62F356208552BB"
  6023. "9ED529077096966D670C354E4ABC9804"
  6024. "F1746C08CA18217C32905E462E36CE3B"
  6025. "E39E772C180E86039B2783A2EC07A28F"
  6026. "B5C55DF06F4C52C9DE2BCBF695581718"
  6027. "3995497CEA956AE515D2261898FA0510"
  6028. "15728E5A8AACAA68FFFFFFFFFFFFFFFF"
  6029. };
  6030. WOLFSSL_ENTER("wolfSSL_DH_2048_prime");
  6031. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6032. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6033. WOLFSSL_ERROR_MSG("Error converting DH 2048 prime to big number");
  6034. bn = NULL;
  6035. }
  6036. return bn;
  6037. #else
  6038. (void)bn;
  6039. return NULL;
  6040. #endif
  6041. }
  6042. /* Returns a big number with the 3072-bit prime from RFC 3526.
  6043. *
  6044. * @param [in, out] bn If not NULL then this BN is set and returned.
  6045. * If NULL then a new BN is created, set and returned.
  6046. *
  6047. * @return NULL on failure.
  6048. * @return WOLFSSL_BIGNUM with value set to 3072-bit prime on success.
  6049. */
  6050. WOLFSSL_BIGNUM* wolfSSL_DH_3072_prime(WOLFSSL_BIGNUM* bn)
  6051. {
  6052. #if WOLFSSL_MAX_BN_BITS >= 3072
  6053. static const char prm[] = {
  6054. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6055. "C4C6628B80DC1CD129024E088A67CC74"
  6056. "020BBEA63B139B22514A08798E3404DD"
  6057. "EF9519B3CD3A431B302B0A6DF25F1437"
  6058. "4FE1356D6D51C245E485B576625E7EC6"
  6059. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6060. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6061. "49286651ECE45B3DC2007CB8A163BF05"
  6062. "98DA48361C55D39A69163FA8FD24CF5F"
  6063. "83655D23DCA3AD961C62F356208552BB"
  6064. "9ED529077096966D670C354E4ABC9804"
  6065. "F1746C08CA18217C32905E462E36CE3B"
  6066. "E39E772C180E86039B2783A2EC07A28F"
  6067. "B5C55DF06F4C52C9DE2BCBF695581718"
  6068. "3995497CEA956AE515D2261898FA0510"
  6069. "15728E5A8AAAC42DAD33170D04507A33"
  6070. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6071. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6072. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6073. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6074. "D87602733EC86A64521F2B18177B200C"
  6075. "BBE117577A615D6C770988C0BAD946E2"
  6076. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6077. "4B82D120A93AD2CAFFFFFFFFFFFFFFFF"
  6078. };
  6079. WOLFSSL_ENTER("wolfSSL_DH_3072_prime");
  6080. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6081. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6082. WOLFSSL_ERROR_MSG("Error converting DH 3072 prime to big number");
  6083. bn = NULL;
  6084. }
  6085. return bn;
  6086. #else
  6087. (void)bn;
  6088. return NULL;
  6089. #endif
  6090. }
  6091. /* Returns a big number with the 4096-bit prime from RFC 3526.
  6092. *
  6093. * @param [in, out] bn If not NULL then this BN is set and returned.
  6094. * If NULL then a new BN is created, set and returned.
  6095. *
  6096. * @return NULL on failure.
  6097. * @return WOLFSSL_BIGNUM with value set to 4096-bit prime on success.
  6098. */
  6099. WOLFSSL_BIGNUM* wolfSSL_DH_4096_prime(WOLFSSL_BIGNUM* bn)
  6100. {
  6101. #if WOLFSSL_MAX_BN_BITS >= 4096
  6102. static const char prm[] = {
  6103. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6104. "C4C6628B80DC1CD129024E088A67CC74"
  6105. "020BBEA63B139B22514A08798E3404DD"
  6106. "EF9519B3CD3A431B302B0A6DF25F1437"
  6107. "4FE1356D6D51C245E485B576625E7EC6"
  6108. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6109. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6110. "49286651ECE45B3DC2007CB8A163BF05"
  6111. "98DA48361C55D39A69163FA8FD24CF5F"
  6112. "83655D23DCA3AD961C62F356208552BB"
  6113. "9ED529077096966D670C354E4ABC9804"
  6114. "F1746C08CA18217C32905E462E36CE3B"
  6115. "E39E772C180E86039B2783A2EC07A28F"
  6116. "B5C55DF06F4C52C9DE2BCBF695581718"
  6117. "3995497CEA956AE515D2261898FA0510"
  6118. "15728E5A8AAAC42DAD33170D04507A33"
  6119. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6120. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6121. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6122. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6123. "D87602733EC86A64521F2B18177B200C"
  6124. "BBE117577A615D6C770988C0BAD946E2"
  6125. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6126. "4B82D120A92108011A723C12A787E6D7"
  6127. "88719A10BDBA5B2699C327186AF4E23C"
  6128. "1A946834B6150BDA2583E9CA2AD44CE8"
  6129. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6130. "287C59474E6BC05D99B2964FA090C3A2"
  6131. "233BA186515BE7ED1F612970CEE2D7AF"
  6132. "B81BDD762170481CD0069127D5B05AA9"
  6133. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6134. "4DF435C934063199FFFFFFFFFFFFFFFF"
  6135. };
  6136. WOLFSSL_ENTER("wolfSSL_DH_4096_prime");
  6137. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6138. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6139. WOLFSSL_ERROR_MSG("Error converting DH 4096 prime to big number");
  6140. bn = NULL;
  6141. }
  6142. return bn;
  6143. #else
  6144. (void)bn;
  6145. return NULL;
  6146. #endif
  6147. }
  6148. /* Returns a big number with the 6144-bit prime from RFC 3526.
  6149. *
  6150. * @param [in, out] bn If not NULL then this BN is set and returned.
  6151. * If NULL then a new BN is created, set and returned.
  6152. *
  6153. * @return NULL on failure.
  6154. * @return WOLFSSL_BIGNUM with value set to 6144-bit prime on success.
  6155. */
  6156. WOLFSSL_BIGNUM* wolfSSL_DH_6144_prime(WOLFSSL_BIGNUM* bn)
  6157. {
  6158. #if WOLFSSL_MAX_BN_BITS >= 6144
  6159. static const char prm[] = {
  6160. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6161. "C4C6628B80DC1CD129024E088A67CC74"
  6162. "020BBEA63B139B22514A08798E3404DD"
  6163. "EF9519B3CD3A431B302B0A6DF25F1437"
  6164. "4FE1356D6D51C245E485B576625E7EC6"
  6165. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6166. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6167. "49286651ECE45B3DC2007CB8A163BF05"
  6168. "98DA48361C55D39A69163FA8FD24CF5F"
  6169. "83655D23DCA3AD961C62F356208552BB"
  6170. "9ED529077096966D670C354E4ABC9804"
  6171. "F1746C08CA18217C32905E462E36CE3B"
  6172. "E39E772C180E86039B2783A2EC07A28F"
  6173. "B5C55DF06F4C52C9DE2BCBF695581718"
  6174. "3995497CEA956AE515D2261898FA0510"
  6175. "15728E5A8AAAC42DAD33170D04507A33"
  6176. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6177. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6178. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6179. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6180. "D87602733EC86A64521F2B18177B200C"
  6181. "BBE117577A615D6C770988C0BAD946E2"
  6182. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6183. "4B82D120A92108011A723C12A787E6D7"
  6184. "88719A10BDBA5B2699C327186AF4E23C"
  6185. "1A946834B6150BDA2583E9CA2AD44CE8"
  6186. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6187. "287C59474E6BC05D99B2964FA090C3A2"
  6188. "233BA186515BE7ED1F612970CEE2D7AF"
  6189. "B81BDD762170481CD0069127D5B05AA9"
  6190. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6191. "4DF435C93402849236C3FAB4D27C7026"
  6192. "C1D4DCB2602646DEC9751E763DBA37BD"
  6193. "F8FF9406AD9E530EE5DB382F413001AE"
  6194. "B06A53ED9027D831179727B0865A8918"
  6195. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6196. "DB7F1447E6CC254B332051512BD7AF42"
  6197. "6FB8F401378CD2BF5983CA01C64B92EC"
  6198. "F032EA15D1721D03F482D7CE6E74FEF6"
  6199. "D55E702F46980C82B5A84031900B1C9E"
  6200. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6201. "0F1D45B7FF585AC54BD407B22B4154AA"
  6202. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6203. "A79715EEF29BE32806A1D58BB7C5DA76"
  6204. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6205. "DA56C9EC2EF29632387FE8D76E3C0468"
  6206. "043E8F663F4860EE12BF2D5B0B7474D6"
  6207. "E694F91E6DCC4024FFFFFFFFFFFFFFFF"
  6208. };
  6209. WOLFSSL_ENTER("wolfSSL_DH_6144_prime");
  6210. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6211. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6212. WOLFSSL_ERROR_MSG("Error converting DH 6144 prime to big number");
  6213. bn = NULL;
  6214. }
  6215. return bn;
  6216. #else
  6217. (void)bn;
  6218. return NULL;
  6219. #endif
  6220. }
  6221. /* Returns a big number with the 8192-bit prime from RFC 3526.
  6222. *
  6223. * @param [in, out] bn If not NULL then this BN is set and returned.
  6224. * If NULL then a new BN is created, set and returned.
  6225. *
  6226. * @return NULL on failure.
  6227. * @return WOLFSSL_BIGNUM with value set to 8192-bit prime on success.
  6228. */
  6229. WOLFSSL_BIGNUM* wolfSSL_DH_8192_prime(WOLFSSL_BIGNUM* bn)
  6230. {
  6231. #if WOLFSSL_MAX_BN_BITS >= 8192
  6232. static const char prm[] = {
  6233. "FFFFFFFFFFFFFFFFC90FDAA22168C234"
  6234. "C4C6628B80DC1CD129024E088A67CC74"
  6235. "020BBEA63B139B22514A08798E3404DD"
  6236. "EF9519B3CD3A431B302B0A6DF25F1437"
  6237. "4FE1356D6D51C245E485B576625E7EC6"
  6238. "F44C42E9A637ED6B0BFF5CB6F406B7ED"
  6239. "EE386BFB5A899FA5AE9F24117C4B1FE6"
  6240. "49286651ECE45B3DC2007CB8A163BF05"
  6241. "98DA48361C55D39A69163FA8FD24CF5F"
  6242. "83655D23DCA3AD961C62F356208552BB"
  6243. "9ED529077096966D670C354E4ABC9804"
  6244. "F1746C08CA18217C32905E462E36CE3B"
  6245. "E39E772C180E86039B2783A2EC07A28F"
  6246. "B5C55DF06F4C52C9DE2BCBF695581718"
  6247. "3995497CEA956AE515D2261898FA0510"
  6248. "15728E5A8AAAC42DAD33170D04507A33"
  6249. "A85521ABDF1CBA64ECFB850458DBEF0A"
  6250. "8AEA71575D060C7DB3970F85A6E1E4C7"
  6251. "ABF5AE8CDB0933D71E8C94E04A25619D"
  6252. "CEE3D2261AD2EE6BF12FFA06D98A0864"
  6253. "D87602733EC86A64521F2B18177B200C"
  6254. "BBE117577A615D6C770988C0BAD946E2"
  6255. "08E24FA074E5AB3143DB5BFCE0FD108E"
  6256. "4B82D120A92108011A723C12A787E6D7"
  6257. "88719A10BDBA5B2699C327186AF4E23C"
  6258. "1A946834B6150BDA2583E9CA2AD44CE8"
  6259. "DBBBC2DB04DE8EF92E8EFC141FBECAA6"
  6260. "287C59474E6BC05D99B2964FA090C3A2"
  6261. "233BA186515BE7ED1F612970CEE2D7AF"
  6262. "B81BDD762170481CD0069127D5B05AA9"
  6263. "93B4EA988D8FDDC186FFB7DC90A6C08F"
  6264. "4DF435C93402849236C3FAB4D27C7026"
  6265. "C1D4DCB2602646DEC9751E763DBA37BD"
  6266. "F8FF9406AD9E530EE5DB382F413001AE"
  6267. "B06A53ED9027D831179727B0865A8918"
  6268. "DA3EDBEBCF9B14ED44CE6CBACED4BB1B"
  6269. "DB7F1447E6CC254B332051512BD7AF42"
  6270. "6FB8F401378CD2BF5983CA01C64B92EC"
  6271. "F032EA15D1721D03F482D7CE6E74FEF6"
  6272. "D55E702F46980C82B5A84031900B1C9E"
  6273. "59E7C97FBEC7E8F323A97A7E36CC88BE"
  6274. "0F1D45B7FF585AC54BD407B22B4154AA"
  6275. "CC8F6D7EBF48E1D814CC5ED20F8037E0"
  6276. "A79715EEF29BE32806A1D58BB7C5DA76"
  6277. "F550AA3D8A1FBFF0EB19CCB1A313D55C"
  6278. "DA56C9EC2EF29632387FE8D76E3C0468"
  6279. "043E8F663F4860EE12BF2D5B0B7474D6"
  6280. "E694F91E6DBE115974A3926F12FEE5E4"
  6281. "38777CB6A932DF8CD8BEC4D073B931BA"
  6282. "3BC832B68D9DD300741FA7BF8AFC47ED"
  6283. "2576F6936BA424663AAB639C5AE4F568"
  6284. "3423B4742BF1C978238F16CBE39D652D"
  6285. "E3FDB8BEFC848AD922222E04A4037C07"
  6286. "13EB57A81A23F0C73473FC646CEA306B"
  6287. "4BCBC8862F8385DDFA9D4B7FA2C087E8"
  6288. "79683303ED5BDD3A062B3CF5B3A278A6"
  6289. "6D2A13F83F44F82DDF310EE074AB6A36"
  6290. "4597E899A0255DC164F31CC50846851D"
  6291. "F9AB48195DED7EA1B1D510BD7EE74D73"
  6292. "FAF36BC31ECFA268359046F4EB879F92"
  6293. "4009438B481C6CD7889A002ED5EE382B"
  6294. "C9190DA6FC026E479558E4475677E9AA"
  6295. "9E3050E2765694DFC81F56E880B96E71"
  6296. "60C980DD98EDD3DFFFFFFFFFFFFFFFFF"
  6297. };
  6298. WOLFSSL_ENTER("wolfSSL_DH_8192_prime");
  6299. /* Set prime into BN. Creates a new BN when bn is NULL. */
  6300. if (wolfSSL_BN_hex2bn(&bn, prm) != 1) {
  6301. WOLFSSL_ERROR_MSG("Error converting DH 8192 prime to big number");
  6302. bn = NULL;
  6303. }
  6304. return bn;
  6305. #else
  6306. (void)bn;
  6307. return NULL;
  6308. #endif
  6309. }
  6310. /*
  6311. * DH to/from bin APIs
  6312. */
  6313. #ifndef NO_CERTS
  6314. /* Load the DER encoded DH parameters/key into DH key.
  6315. *
  6316. * @param [in, out] dh DH key to load parameters into.
  6317. * @param [in] der Buffer holding DER encoded parameters data.
  6318. * @param [in, out] idx On in, index at which DH key DER data starts.
  6319. * On out, index after DH key DER data.
  6320. * @param [in] derSz Size of DER buffer in bytes.
  6321. *
  6322. * @return 0 on success.
  6323. * @return 1 when decoding DER or setting the external key fails.
  6324. */
  6325. static int wolfssl_dh_load_key(WOLFSSL_DH* dh, const unsigned char* der,
  6326. word32* idx, word32 derSz)
  6327. {
  6328. int err = 0;
  6329. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6330. int ret;
  6331. /* Decode DH parameters/key from DER. */
  6332. ret = wc_DhKeyDecode(der, idx, (DhKey*)dh->internal, derSz);
  6333. if (ret != 0) {
  6334. WOLFSSL_ERROR_MSG("DhKeyDecode() failed");
  6335. err = 1;
  6336. }
  6337. if (!err) {
  6338. /* wolfSSL DH key set. */
  6339. dh->inSet = 1;
  6340. /* Set the external DH key based on wolfSSL DH key. */
  6341. if (SetDhExternal(dh) != 1) {
  6342. WOLFSSL_ERROR_MSG("SetDhExternal failed");
  6343. err = 1;
  6344. }
  6345. }
  6346. #else
  6347. byte* p;
  6348. byte* g;
  6349. word32 pSz = MAX_DH_SIZE;
  6350. word32 gSz = MAX_DH_SIZE;
  6351. /* Only DH parameters supported. */
  6352. /* Load external and set internal. */
  6353. p = (byte*)XMALLOC(pSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6354. g = (byte*)XMALLOC(gSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6355. if ((p == NULL) || (g == NULL)) {
  6356. err = 1;
  6357. }
  6358. /* Extract the p and g as data from the DER encoded DH parameters. */
  6359. if ((!err) && (wc_DhParamsLoad(der + *idx, derSz - *idx, p, &pSz, g,
  6360. &gSz) < 0)) {
  6361. err = 1;
  6362. }
  6363. if (!err) {
  6364. /* Put p and g in as big numbers - free existing BNs. */
  6365. if (dh->p != NULL) {
  6366. wolfSSL_BN_free(dh->p);
  6367. dh->p = NULL;
  6368. }
  6369. if (dh->g != NULL) {
  6370. wolfSSL_BN_free(dh->g);
  6371. dh->g = NULL;
  6372. }
  6373. dh->p = wolfSSL_BN_bin2bn(p, (int)pSz, NULL);
  6374. dh->g = wolfSSL_BN_bin2bn(g, (int)gSz, NULL);
  6375. if (dh->p == NULL || dh->g == NULL) {
  6376. err = 1;
  6377. }
  6378. else {
  6379. /* External DH key parameters were set. */
  6380. dh->exSet = 1;
  6381. }
  6382. }
  6383. /* Set internal as the outside has been updated. */
  6384. if ((!err) && (SetDhInternal(dh) != 1)) {
  6385. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6386. err = 1;
  6387. }
  6388. if (!err) {
  6389. *idx += wolfssl_der_length(der + *idx, derSz - *idx);
  6390. }
  6391. XFREE(p, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6392. XFREE(g, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  6393. #endif
  6394. return err;
  6395. }
  6396. #ifdef OPENSSL_ALL
  6397. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  6398. /* Convert DER encoded DH parameters to a WOLFSSL_DH structure.
  6399. *
  6400. * @param [out] dh DH key to put parameters into. May be NULL.
  6401. * @param [in, out] pp Pointer to DER encoded DH parameters.
  6402. * Value updated to end of data when dh is not NULL.
  6403. * @param [in] length Length of data available in bytes.
  6404. *
  6405. * @return DH key on success.
  6406. * @return NULL on failure.
  6407. */
  6408. WOLFSSL_DH *wolfSSL_d2i_DHparams(WOLFSSL_DH** dh, const unsigned char** pp,
  6409. long length)
  6410. {
  6411. WOLFSSL_DH *newDh = NULL;
  6412. word32 idx = 0;
  6413. int err = 0;
  6414. WOLFSSL_ENTER("wolfSSL_d2i_DHparams");
  6415. /* Validate parameters. */
  6416. if ((pp == NULL) || (length <= 0)) {
  6417. WOLFSSL_ERROR_MSG("bad argument");
  6418. err = 1;
  6419. }
  6420. /* Create new DH key to return. */
  6421. if ((!err) && ((newDh = wolfSSL_DH_new()) == NULL)) {
  6422. WOLFSSL_ERROR_MSG("wolfSSL_DH_new() failed");
  6423. err = 1;
  6424. }
  6425. if ((!err) && (wolfssl_dh_load_key(newDh, *pp, &idx,
  6426. (word32)length) != 0)) {
  6427. WOLFSSL_ERROR_MSG("Loading DH parameters failed");
  6428. err = 1;
  6429. }
  6430. if ((!err) && (dh != NULL)) {
  6431. /* Return through parameter too. */
  6432. *dh = newDh;
  6433. /* Move buffer on by the used amount. */
  6434. *pp += idx;
  6435. }
  6436. if (err && (newDh != NULL)) {
  6437. /* Dispose of any created DH key. */
  6438. wolfSSL_DH_free(newDh);
  6439. newDh = NULL;
  6440. }
  6441. return newDh;
  6442. }
  6443. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  6444. /* Converts internal WOLFSSL_DH structure to DER encoded DH parameters.
  6445. *
  6446. * @params [in] dh DH key with parameters to encode.
  6447. * @params [in, out] out Pointer to buffer to encode into.
  6448. * When NULL or pointer to NULL, only length returned.
  6449. * @return 0 on error.
  6450. * @return Size of DER encoding in bytes on success.
  6451. */
  6452. int wolfSSL_i2d_DHparams(const WOLFSSL_DH *dh, unsigned char **out)
  6453. {
  6454. #if (!defined(HAVE_FIPS) || FIPS_VERSION_GT(5,0)) && defined(WOLFSSL_DH_EXTRA)
  6455. /* Set length to an arbitrarily large value for wc_DhParamsToDer(). */
  6456. word32 len = (word32)-1;
  6457. int err = 0;
  6458. /* Validate parameters. */
  6459. if (dh == NULL) {
  6460. WOLFSSL_ERROR_MSG("Bad parameters");
  6461. err = 1;
  6462. }
  6463. /* Push external DH data into internal DH key if not set. */
  6464. if ((!err) && (!dh->inSet) && (SetDhInternal((WOLFSSL_DH*)dh) != 1)) {
  6465. WOLFSSL_ERROR_MSG("Bad DH set internal");
  6466. err = 1;
  6467. }
  6468. if (!err) {
  6469. int ret;
  6470. unsigned char* der = NULL;
  6471. /* Use *out when available otherwise NULL. */
  6472. if (out != NULL) {
  6473. der = *out;
  6474. }
  6475. /* Get length and/or encode. */
  6476. ret = wc_DhParamsToDer((DhKey*)dh->internal, der, &len);
  6477. /* Length of encoded data is returned on success. */
  6478. if (ret > 0) {
  6479. *out += len;
  6480. }
  6481. /* An error occurred unless only length returned. */
  6482. else if (ret != LENGTH_ONLY_E) {
  6483. err = 1;
  6484. }
  6485. }
  6486. /* Set return to 0 on error. */
  6487. if (err) {
  6488. len = 0;
  6489. }
  6490. return (int)len;
  6491. #else
  6492. word32 len;
  6493. int ret = 0;
  6494. int pSz;
  6495. int gSz;
  6496. WOLFSSL_ENTER("wolfSSL_i2d_DHparams");
  6497. /* Validate parameters. */
  6498. if (dh == NULL) {
  6499. WOLFSSL_ERROR_MSG("Bad parameters");
  6500. len = 0;
  6501. }
  6502. else {
  6503. /* SEQ <len>
  6504. * INT <len> [0x00] <prime>
  6505. * INT <len> [0x00] <generator>
  6506. * Integers have 0x00 prepended if the top bit of positive number is
  6507. * set.
  6508. */
  6509. /* Get total length of prime including any prepended zeros. */
  6510. pSz = mp_unsigned_bin_size((mp_int*)dh->p->internal) +
  6511. mp_leading_bit((mp_int*)dh->p->internal);
  6512. /* Get total length of generator including any prepended zeros. */
  6513. gSz = mp_unsigned_bin_size((mp_int*)dh->g->internal) +
  6514. mp_leading_bit((mp_int*)dh->g->internal);
  6515. /* Calculate length of data in sequence. */
  6516. len = 1 + ASN_LEN_SIZE(pSz) + pSz +
  6517. 1 + ASN_LEN_SIZE(gSz) + gSz;
  6518. /* Add in the length of the SEQUENCE. */
  6519. len += 1 + ASN_LEN_SIZE(len);
  6520. if ((out != NULL) && (*out != NULL)) {
  6521. /* Encode parameters. */
  6522. ret = StoreDHparams(*out, &len, (mp_int*)dh->p->internal,
  6523. (mp_int*)dh->g->internal);
  6524. if (ret != MP_OKAY) {
  6525. WOLFSSL_ERROR_MSG("StoreDHparams error");
  6526. len = 0;
  6527. }
  6528. else {
  6529. /* Move pointer on if encoded. */
  6530. *out += len;
  6531. }
  6532. }
  6533. }
  6534. return (int)len;
  6535. #endif
  6536. }
  6537. #endif /* OPENSSL_ALL */
  6538. #endif /* !NO_CERTS */
  6539. #endif /* OPENSSL_EXTRA */
  6540. #if defined(OPENSSL_EXTRA) || \
  6541. ((!defined(NO_BIO) || !defined(NO_FILESYSTEM)) && \
  6542. defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) || \
  6543. defined(WOLFSSL_MYSQL_COMPATIBLE))
  6544. /* Load the DER encoded DH parameters into DH key.
  6545. *
  6546. * @param [in, out] dh DH key to load parameters into.
  6547. * @param [in] derBuf Buffer holding DER encoded parameters data.
  6548. * @param [in] derSz Size of DER data in buffer in bytes.
  6549. *
  6550. * @return 1 on success.
  6551. * @return -1 when DH or derBuf is NULL,
  6552. * internal DH key in DH is NULL,
  6553. * derSz is 0 or less,
  6554. * error decoding DER data or
  6555. * setting external parameter values fails.
  6556. */
  6557. int wolfSSL_DH_LoadDer(WOLFSSL_DH* dh, const unsigned char* derBuf, int derSz)
  6558. {
  6559. int ret = 1;
  6560. word32 idx = 0;
  6561. /* Validate parameters. */
  6562. if ((dh == NULL) || (dh->internal == NULL) || (derBuf == NULL) ||
  6563. (derSz <= 0)) {
  6564. WOLFSSL_ERROR_MSG("Bad function arguments");
  6565. ret = -1;
  6566. }
  6567. if ((ret == 1) && (wolfssl_dh_load_key(dh, derBuf, &idx,
  6568. (word32)derSz) != 0)) {
  6569. WOLFSSL_ERROR_MSG("DH key decode failed");
  6570. ret = -1;
  6571. }
  6572. return ret;
  6573. }
  6574. #endif
  6575. /*
  6576. * DH PEM APIs
  6577. */
  6578. #if defined(HAVE_LIGHTY) || defined(HAVE_STUNNEL) \
  6579. || defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(OPENSSL_EXTRA)
  6580. #if !defined(NO_BIO) || !defined(NO_FILESYSTEM)
  6581. /* Create a DH key by reading the PEM encoded data from the BIO.
  6582. *
  6583. * @param [in] bio BIO object to read from.
  6584. * @param [in, out] dh DH key to use. May be NULL.
  6585. * @param [in] pem PEM data to decode.
  6586. * @param [in] pemSz Size of PEM data in bytes.
  6587. * @param [in] memAlloced Indicates that pem was allocated and is to be
  6588. * freed after use.
  6589. * @return DH key on success.
  6590. * @return NULL on failure.
  6591. */
  6592. static WOLFSSL_DH *wolfssl_dhparams_read_pem(WOLFSSL_DH **dh,
  6593. unsigned char* pem, int pemSz, int memAlloced)
  6594. {
  6595. WOLFSSL_DH* localDh = NULL;
  6596. DerBuffer *der = NULL;
  6597. int err = 0;
  6598. /* Convert PEM to DER assuming DH Parameter format. */
  6599. if ((!err) && (PemToDer(pem, pemSz, DH_PARAM_TYPE, &der, NULL, NULL,
  6600. NULL) < 0)) {
  6601. /* Convert PEM to DER assuming X9.42 DH Parameter format. */
  6602. if (PemToDer(pem, pemSz, X942_PARAM_TYPE, &der, NULL, NULL, NULL)
  6603. != 0) {
  6604. err = 1;
  6605. }
  6606. /* If Success on X9.42 DH format, clear error from failed DH format */
  6607. else {
  6608. wolfSSL_ERR_clear_error();
  6609. }
  6610. }
  6611. if (memAlloced) {
  6612. /* PEM data no longer needed. */
  6613. XFREE(pem, NULL, DYNAMIC_TYPE_PEM);
  6614. }
  6615. if (!err) {
  6616. /* Use the DH key passed in or allocate a new one. */
  6617. if (dh != NULL) {
  6618. localDh = *dh;
  6619. }
  6620. if (localDh == NULL) {
  6621. localDh = wolfSSL_DH_new();
  6622. if (localDh == NULL) {
  6623. err = 1;
  6624. }
  6625. }
  6626. }
  6627. /* Load the DER encoded DH parameters from buffer into a DH key. */
  6628. if ((!err) && (wolfSSL_DH_LoadDer(localDh, der->buffer, der->length)
  6629. != 1)) {
  6630. /* Free an allocated DH key. */
  6631. if ((dh == NULL) || (localDh != *dh)) {
  6632. wolfSSL_DH_free(localDh);
  6633. }
  6634. localDh = NULL;
  6635. err = 1;
  6636. }
  6637. /* Return the DH key on success. */
  6638. if ((!err) && (dh != NULL)) {
  6639. *dh = localDh;
  6640. }
  6641. /* Dispose of DER data. */
  6642. if (der != NULL) {
  6643. FreeDer(&der);
  6644. }
  6645. return localDh;
  6646. }
  6647. #endif /* !NO_BIO || !NO_FILESYSTEM */
  6648. #ifndef NO_BIO
  6649. /* Create a DH key by reading the PEM encoded data from the BIO.
  6650. *
  6651. * DH parameters are public data and are not expected to be encrypted.
  6652. *
  6653. * @param [in] bio BIO object to read from.
  6654. * @param [in, out] dh DH key to When pointer to
  6655. * NULL, a new DH key is created.
  6656. * @param [in] cb Password callback when PEM encrypted. Not used.
  6657. * @param [in] pass NUL terminated string for passphrase when PEM
  6658. * encrypted. Not used.
  6659. * @return DH key on success.
  6660. * @return NULL on failure.
  6661. */
  6662. WOLFSSL_DH *wolfSSL_PEM_read_bio_DHparams(WOLFSSL_BIO *bio, WOLFSSL_DH **dh,
  6663. wc_pem_password_cb *cb, void *pass)
  6664. {
  6665. WOLFSSL_DH* localDh = NULL;
  6666. int err = 0;
  6667. unsigned char* mem = NULL;
  6668. int size = 0;
  6669. int memAlloced = 0;
  6670. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_DHparams");
  6671. (void)cb;
  6672. (void)pass;
  6673. /* Validate parameters. */
  6674. if (bio == NULL) {
  6675. WOLFSSL_ERROR_MSG("Bad Function Argument bio is NULL");
  6676. err = 1;
  6677. }
  6678. /* Get buffer of data from BIO or read data from the BIO into a new buffer.
  6679. */
  6680. if ((!err) && (wolfssl_read_bio(bio, (char**)&mem, &size, &memAlloced)
  6681. != 0)) {
  6682. err = 1;
  6683. }
  6684. if (!err) {
  6685. /* Create a DH key from the PEM - try two different headers. */
  6686. localDh = wolfssl_dhparams_read_pem(dh, mem, size, memAlloced);
  6687. }
  6688. return localDh;
  6689. }
  6690. #endif /* !NO_BIO */
  6691. #ifndef NO_FILESYSTEM
  6692. /* Read DH parameters from a file pointer into DH key.
  6693. *
  6694. * DH parameters are public data and are not expected to be encrypted.
  6695. *
  6696. * @param [in] fp File pointer to read DH parameter file from.
  6697. * @param [in, out] dh DH key with parameters if not NULL. When pointer to
  6698. * NULL, a new DH key is created.
  6699. * @param [in] cb Password callback when PEM encrypted. Not used.
  6700. * @param [in] pass NUL terminated string for passphrase when PEM
  6701. * encrypted. Not used.
  6702. *
  6703. * @return NULL on failure.
  6704. * @return DH key with parameters set on success.
  6705. */
  6706. WOLFSSL_DH* wolfSSL_PEM_read_DHparams(XFILE fp, WOLFSSL_DH** dh,
  6707. wc_pem_password_cb* cb, void* pass)
  6708. {
  6709. WOLFSSL_DH* localDh = NULL;
  6710. int err = 0;
  6711. unsigned char* mem = NULL;
  6712. int size = 0;
  6713. (void)cb;
  6714. (void)pass;
  6715. /* Read data from file pointer. */
  6716. if (wolfssl_read_file(fp, (char**)&mem, &size) != 0) {
  6717. err = 1;
  6718. }
  6719. if (!err) {
  6720. localDh = wolfssl_dhparams_read_pem(dh, mem, size, 1);
  6721. }
  6722. return localDh;
  6723. }
  6724. #endif /* !NO_FILESYSTEM */
  6725. #if defined(WOLFSSL_DH_EXTRA) && !defined(NO_FILESYSTEM)
  6726. /* Encoded parameter data in DH key as DER.
  6727. *
  6728. * @param [in, out] dh DH key object to encode.
  6729. * @param [out] out Buffer containing DER encoding.
  6730. * @param [in] heap Heap hint.
  6731. * @return <0 on error.
  6732. * @return Length of DER encoded DH parameters in bytes.
  6733. */
  6734. static int wolfssl_dhparams_to_der(WOLFSSL_DH* dh, unsigned char** out,
  6735. void* heap)
  6736. {
  6737. int ret = -1;
  6738. int err = 0;
  6739. byte* der = NULL;
  6740. word32 derSz;
  6741. DhKey* key;
  6742. (void)heap;
  6743. /* Set internal parameters based on external parameters. */
  6744. if ((dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  6745. WOLFSSL_ERROR_MSG("Unable to set internal DH structure");
  6746. err = 1;
  6747. }
  6748. if (!err) {
  6749. /* Use wolfSSL API to get length of DER encode DH parameters. */
  6750. key = (DhKey*)dh->internal;
  6751. ret = wc_DhParamsToDer(key, NULL, &derSz);
  6752. if (ret != LENGTH_ONLY_E) {
  6753. WOLFSSL_ERROR_MSG("Failed to get size of DH params");
  6754. err = 1;
  6755. }
  6756. }
  6757. if (!err) {
  6758. /* Allocate memory for DER encoding. */
  6759. der = (byte*)XMALLOC(derSz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6760. if (der == NULL) {
  6761. WOLFSSL_LEAVE("wolfssl_dhparams_to_der", MEMORY_E);
  6762. err = 1;
  6763. }
  6764. }
  6765. if (!err) {
  6766. /* Encode DH parameters into DER buffer. */
  6767. ret = wc_DhParamsToDer(key, der, &derSz);
  6768. if (ret < 0) {
  6769. WOLFSSL_ERROR_MSG("Failed to export DH params");
  6770. err = 1;
  6771. }
  6772. }
  6773. if (!err) {
  6774. *out = der;
  6775. der = NULL;
  6776. }
  6777. if (der != NULL) {
  6778. XFREE(der, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6779. }
  6780. return ret;
  6781. }
  6782. /* Writes the DH parameters in PEM format from "dh" out to the file pointer
  6783. * passed in.
  6784. *
  6785. * @param [in] fp File pointer to write to.
  6786. * @param [in] dh DH key to write.
  6787. * @return 1 on success.
  6788. * @return 0 on failure.
  6789. */
  6790. int wolfSSL_PEM_write_DHparams(XFILE fp, WOLFSSL_DH* dh)
  6791. {
  6792. int ret = 1;
  6793. int derSz;
  6794. byte* derBuf = NULL;
  6795. void* heap = NULL;
  6796. WOLFSSL_ENTER("wolfSSL_PEM_write_DHparams");
  6797. /* Validate parameters. */
  6798. if ((fp == XBADFILE) || (dh == NULL)) {
  6799. WOLFSSL_ERROR_MSG("Bad Function Arguments");
  6800. ret = 0;
  6801. }
  6802. if (ret == 1) {
  6803. DhKey* key = (DhKey*)dh->internal;
  6804. if (key)
  6805. heap = key->heap;
  6806. if ((derSz = wolfssl_dhparams_to_der(dh, &derBuf, heap)) < 0) {
  6807. WOLFSSL_ERROR_MSG("DER encoding failed");
  6808. ret = 0;
  6809. }
  6810. if (derBuf == NULL) {
  6811. WOLFSSL_ERROR_MSG("DER encoding failed to get buffer");
  6812. ret = 0;
  6813. }
  6814. }
  6815. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  6816. DH_PARAM_TYPE, NULL) != WOLFSSL_SUCCESS)) {
  6817. ret = 0;
  6818. }
  6819. /* Dispose of DER buffer. */
  6820. XFREE(derBuf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  6821. WOLFSSL_LEAVE("wolfSSL_PEM_write_DHparams", ret);
  6822. return ret;
  6823. }
  6824. #endif /* WOLFSSL_DH_EXTRA && !NO_FILESYSTEM */
  6825. #endif /* HAVE_LIGHTY || HAVE_STUNNEL || WOLFSSL_MYSQL_COMPATIBLE ||
  6826. * OPENSSL_EXTRA */
  6827. /*
  6828. * DH get/set APIs
  6829. */
  6830. #ifdef OPENSSL_EXTRA
  6831. #if defined(WOLFSSL_QT) || defined(OPENSSL_ALL) \
  6832. || defined(WOLFSSL_OPENSSH) || defined(OPENSSL_EXTRA)
  6833. /* Set the members of DhKey into WOLFSSL_DH
  6834. * Specify elements to set via the 2nd parameter
  6835. *
  6836. * @param [in, out] dh DH key to synchronize.
  6837. * @param [in] elm Elements to synchronize.
  6838. * @return 1 on success.
  6839. * @return -1 on failure.
  6840. */
  6841. int SetDhExternal_ex(WOLFSSL_DH *dh, int elm)
  6842. {
  6843. int ret = 1;
  6844. DhKey *key = NULL;
  6845. WOLFSSL_ENTER("SetDhExternal_ex");
  6846. /* Validate parameters. */
  6847. if ((dh == NULL) || (dh->internal == NULL)) {
  6848. WOLFSSL_ERROR_MSG("dh key NULL error");
  6849. ret = -1;
  6850. }
  6851. if (ret == 1) {
  6852. /* Get the wolfSSL DH key. */
  6853. key = (DhKey*)dh->internal;
  6854. }
  6855. if ((ret == 1) && (elm & ELEMENT_P)) {
  6856. /* Set the prime. */
  6857. if (wolfssl_bn_set_value(&dh->p, &key->p) != 1) {
  6858. WOLFSSL_ERROR_MSG("dh param p error");
  6859. ret = -1;
  6860. }
  6861. }
  6862. if ((ret == 1) && (elm & ELEMENT_G)) {
  6863. /* Set the generator. */
  6864. if (wolfssl_bn_set_value(&dh->g, &key->g) != 1) {
  6865. WOLFSSL_ERROR_MSG("dh param g error");
  6866. ret = -1;
  6867. }
  6868. }
  6869. if ((ret == 1) && (elm & ELEMENT_Q)) {
  6870. /* Set the order. */
  6871. if (wolfssl_bn_set_value(&dh->q, &key->q) != 1) {
  6872. WOLFSSL_ERROR_MSG("dh param q error");
  6873. ret = -1;
  6874. }
  6875. }
  6876. #ifdef WOLFSSL_DH_EXTRA
  6877. if ((ret == 1) && (elm & ELEMENT_PRV)) {
  6878. /* Set the private key. */
  6879. if (wolfssl_bn_set_value(&dh->priv_key, &key->priv) != 1) {
  6880. WOLFSSL_ERROR_MSG("No DH Private Key");
  6881. ret = -1;
  6882. }
  6883. }
  6884. if ((ret == 1) && (elm & ELEMENT_PUB)) {
  6885. /* Set the public key. */
  6886. if (wolfssl_bn_set_value(&dh->pub_key, &key->pub) != 1) {
  6887. WOLFSSL_ERROR_MSG("No DH Public Key");
  6888. ret = -1;
  6889. }
  6890. }
  6891. #endif /* WOLFSSL_DH_EXTRA */
  6892. if (ret == 1) {
  6893. /* On success record that the external values have been set. */
  6894. dh->exSet = 1;
  6895. }
  6896. return ret;
  6897. }
  6898. /* Set the members of DhKey into WOLFSSL_DH
  6899. * DhKey was populated from wc_DhKeyDecode
  6900. * p, g, pub_key and priv_key are set.
  6901. *
  6902. * @param [in, out] dh DH key to synchronize.
  6903. * @return 1 on success.
  6904. * @return -1 on failure.
  6905. */
  6906. int SetDhExternal(WOLFSSL_DH *dh)
  6907. {
  6908. /* Assuming Q not required when using this API. */
  6909. int elements = ELEMENT_P | ELEMENT_G | ELEMENT_PUB | ELEMENT_PRV;
  6910. WOLFSSL_ENTER("SetDhExternal");
  6911. return SetDhExternal_ex(dh, elements);
  6912. }
  6913. #endif /* WOLFSSL_QT || OPENSSL_ALL || WOLFSSL_OPENSSH || OPENSSL_EXTRA */
  6914. /* Set the internal/wolfSSL DH key with data from the external parts.
  6915. *
  6916. * @param [in, out] dh DH key to synchronize.
  6917. * @return 1 on success.
  6918. * @return -1 on failure.
  6919. */
  6920. int SetDhInternal(WOLFSSL_DH* dh)
  6921. {
  6922. int ret = 1;
  6923. DhKey *key = NULL;
  6924. WOLFSSL_ENTER("SetDhInternal");
  6925. /* Validate parameters. */
  6926. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  6927. WOLFSSL_ERROR_MSG("Bad function arguments");
  6928. ret = -1;
  6929. }
  6930. if (ret == 1) {
  6931. /* Get the wolfSSL DH key. */
  6932. key = (DhKey*)dh->internal;
  6933. /* Clear out key and initialize. */
  6934. wc_FreeDhKey(key);
  6935. if (wc_InitDhKey(key) != 0) {
  6936. ret = -1;
  6937. }
  6938. }
  6939. if (ret == 1) {
  6940. /* Transfer prime. */
  6941. if (wolfssl_bn_get_value(dh->p, &key->p) != 1) {
  6942. ret = -1;
  6943. }
  6944. }
  6945. if (ret == 1) {
  6946. /* Transfer generator. */
  6947. if (wolfssl_bn_get_value(dh->g, &key->g) != 1) {
  6948. ret = -1;
  6949. }
  6950. }
  6951. #ifdef HAVE_FFDHE_Q
  6952. /* Transfer order if available. */
  6953. if ((ret == 1) && (dh->q != NULL)) {
  6954. if (wolfssl_bn_get_value(dh->q, &key->q) != 1) {
  6955. ret = -1;
  6956. }
  6957. }
  6958. #endif
  6959. #ifdef WOLFSSL_DH_EXTRA
  6960. /* Transfer private key if available. */
  6961. if ((ret == 1) && (dh->priv_key != NULL) &&
  6962. (!wolfSSL_BN_is_zero(dh->priv_key))) {
  6963. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  6964. ret = -1;
  6965. }
  6966. }
  6967. /* Transfer public key if available. */
  6968. if ((ret == 1) && (dh->pub_key != NULL) &&
  6969. (!wolfSSL_BN_is_zero(dh->pub_key))) {
  6970. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  6971. ret = -1;
  6972. }
  6973. }
  6974. #endif /* WOLFSSL_DH_EXTRA */
  6975. if (ret == 1) {
  6976. /* On success record that the internal values have been set. */
  6977. dh->inSet = 1;
  6978. }
  6979. return ret;
  6980. }
  6981. /* Get the size, in bytes, of the DH key.
  6982. *
  6983. * Return code compliant with OpenSSL.
  6984. *
  6985. * @param [in] dh DH key.
  6986. * @return -1 on error.
  6987. * @return Size of DH key in bytes on success.
  6988. */
  6989. int wolfSSL_DH_size(WOLFSSL_DH* dh)
  6990. {
  6991. int ret = -1;
  6992. WOLFSSL_ENTER("wolfSSL_DH_size");
  6993. /* Validate parameter. */
  6994. if (dh != NULL) {
  6995. /* Size of key is size of prime in bytes. */
  6996. ret = wolfSSL_BN_num_bytes(dh->p);
  6997. }
  6998. return ret;
  6999. }
  7000. /**
  7001. * Return parameters p, q and/or g of the DH key.
  7002. *
  7003. * @param [in] dh DH key to retrieve parameters from.
  7004. * @param [out] p Pointer to return prime in. May be NULL.
  7005. * @param [out] q Pointer to return order in. May be NULL.
  7006. * @param [out] g Pointer to return generator in. May be NULL.
  7007. */
  7008. void wolfSSL_DH_get0_pqg(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **p,
  7009. const WOLFSSL_BIGNUM **q, const WOLFSSL_BIGNUM **g)
  7010. {
  7011. WOLFSSL_ENTER("wolfSSL_DH_get0_pqg");
  7012. if (dh != NULL) {
  7013. /* Return prime if required. */
  7014. if (p != NULL) {
  7015. *p = dh->p;
  7016. }
  7017. /* Return order if required. */
  7018. if (q != NULL) {
  7019. *q = dh->q;
  7020. }
  7021. /* Return generator if required. */
  7022. if (g != NULL) {
  7023. *g = dh->g;
  7024. }
  7025. }
  7026. }
  7027. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7028. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7029. #if defined(OPENSSL_ALL) || \
  7030. defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
  7031. /* Sets the parameters p, g and optionally q into the DH key.
  7032. *
  7033. * Ownership of p, q and g get taken over by "dh" on success and should be
  7034. * free'd with a call to wolfSSL_DH_free -- not individually.
  7035. *
  7036. * @param [in, out] dh DH key to set.
  7037. * @parma [in] p Prime value to set. May be NULL when value already
  7038. * present.
  7039. * @parma [in] q Order value to set. May be NULL.
  7040. * @parma [in] g Generator value to set. May be NULL when value already
  7041. * present.
  7042. * @return 1 on success.
  7043. * @return 0 on failure.
  7044. */
  7045. int wolfSSL_DH_set0_pqg(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *p,
  7046. WOLFSSL_BIGNUM *q, WOLFSSL_BIGNUM *g)
  7047. {
  7048. int ret = 1;
  7049. WOLFSSL_ENTER("wolfSSL_DH_set0_pqg");
  7050. /* Validate parameters - q is optional. */
  7051. if (dh == NULL) {
  7052. WOLFSSL_ERROR_MSG("Bad function arguments");
  7053. ret = 0;
  7054. }
  7055. /* p can be NULL if we already have one set. */
  7056. if ((ret == 1) && (p == NULL) && (dh->p == NULL)) {
  7057. WOLFSSL_ERROR_MSG("Bad function arguments");
  7058. ret = 0;
  7059. }
  7060. /* g can be NULL if we already have one set. */
  7061. if ((ret == 1) && (g == NULL) && (dh->g == NULL)) {
  7062. WOLFSSL_ERROR_MSG("Bad function arguments");
  7063. ret = 0;
  7064. }
  7065. if (ret == 1) {
  7066. /* Invalidate internal key. */
  7067. dh->inSet = 0;
  7068. /* Free external representation of parameters and set with those passed
  7069. * in. */
  7070. if (p != NULL) {
  7071. wolfSSL_BN_free(dh->p);
  7072. dh->p = p;
  7073. }
  7074. if (q != NULL) {
  7075. wolfSSL_BN_free(dh->q);
  7076. dh->q = q;
  7077. }
  7078. if (g != NULL) {
  7079. wolfSSL_BN_free(dh->g);
  7080. dh->g = g;
  7081. }
  7082. /* External DH key parameters were set. */
  7083. dh->exSet = 1;
  7084. /* Set internal/wolfSSL DH key as well. */
  7085. if (SetDhInternal(dh) != 1) {
  7086. WOLFSSL_ERROR_MSG("Unable to set internal DH key");
  7087. /* Don't keep parameters on failure. */
  7088. dh->p = NULL;
  7089. dh->q = NULL;
  7090. dh->g = NULL;
  7091. /* Internal and external DH key not set. */
  7092. dh->inSet = 0;
  7093. dh->exSet = 0;
  7094. ret = 0;
  7095. }
  7096. }
  7097. return ret;
  7098. }
  7099. /* Set the length of the DH private key in bits.
  7100. *
  7101. * Length field is checked at generation.
  7102. *
  7103. * @param [in, out] dh DH key to set.
  7104. * @param [in] len Length of DH private key in bytes.
  7105. * @return 0 on failure.
  7106. * @return 1 on success.
  7107. */
  7108. int wolfSSL_DH_set_length(WOLFSSL_DH *dh, long len)
  7109. {
  7110. int ret = 1;
  7111. WOLFSSL_ENTER("wolfSSL_DH_set_length");
  7112. /* Validate parameter. */
  7113. if (dh == NULL) {
  7114. WOLFSSL_ERROR_MSG("Bad function arguments");
  7115. ret = 0;
  7116. }
  7117. else {
  7118. /* Store length. */
  7119. dh->length = (int)len;
  7120. }
  7121. return ret;
  7122. }
  7123. #endif /* OPENSSL_ALL || (v1.1.0 or later) */
  7124. #endif
  7125. /* Get the public and private keys requested.
  7126. *
  7127. * @param [in] dh DH key to get keys from.
  7128. * @param [out] pub_key Pointer to return public key in. May be NULL.
  7129. * @param [out] priv_key Pointer to return private key in. May be NULL.
  7130. */
  7131. void wolfSSL_DH_get0_key(const WOLFSSL_DH *dh, const WOLFSSL_BIGNUM **pub_key,
  7132. const WOLFSSL_BIGNUM **priv_key)
  7133. {
  7134. WOLFSSL_ENTER("wolfSSL_DH_get0_key");
  7135. /* Get only when valid DH passed in. */
  7136. if (dh != NULL) {
  7137. /* Return public key if required and available. */
  7138. if ((pub_key != NULL) && (dh->pub_key != NULL)) {
  7139. *pub_key = dh->pub_key;
  7140. }
  7141. /* Return private key if required and available. */
  7142. if ((priv_key != NULL) && (dh->priv_key != NULL)) {
  7143. *priv_key = dh->priv_key;
  7144. }
  7145. }
  7146. }
  7147. /* Set the public and/or private key.
  7148. *
  7149. * @param [in, out] dh DH key to have keys set into.
  7150. * @param [in] pub_key Public key to set. May be NULL.
  7151. * @param [in] priv_key Private key to set. May be NULL.
  7152. * @return 0 on failure.
  7153. * @return 1 on success.
  7154. */
  7155. int wolfSSL_DH_set0_key(WOLFSSL_DH *dh, WOLFSSL_BIGNUM *pub_key,
  7156. WOLFSSL_BIGNUM *priv_key)
  7157. {
  7158. int ret = 1;
  7159. #ifdef WOLFSSL_DH_EXTRA
  7160. DhKey *key = NULL;
  7161. #endif
  7162. WOLFSSL_ENTER("wolfSSL_DH_set0_key");
  7163. /* Validate parameters. */
  7164. if (dh == NULL) {
  7165. ret = 0;
  7166. }
  7167. #ifdef WOLFSSL_DH_EXTRA
  7168. else {
  7169. key = (DhKey*)dh->internal;
  7170. }
  7171. #endif
  7172. /* Replace public key when one passed in. */
  7173. if ((ret == 1) && (pub_key != NULL)) {
  7174. wolfSSL_BN_free(dh->pub_key);
  7175. dh->pub_key = pub_key;
  7176. #ifdef WOLFSSL_DH_EXTRA
  7177. if (wolfssl_bn_get_value(dh->pub_key, &key->pub) != 1) {
  7178. ret = 0;
  7179. }
  7180. #endif
  7181. }
  7182. /* Replace private key when one passed in. */
  7183. if ((ret == 1) && (priv_key != NULL)) {
  7184. wolfSSL_BN_clear_free(dh->priv_key);
  7185. dh->priv_key = priv_key;
  7186. #ifdef WOLFSSL_DH_EXTRA
  7187. if (wolfssl_bn_get_value(dh->priv_key, &key->priv) != 1) {
  7188. ret = 0;
  7189. }
  7190. #endif
  7191. }
  7192. return ret;
  7193. }
  7194. #endif /* OPENSSL_EXTRA */
  7195. /*
  7196. * DH check APIs
  7197. */
  7198. #ifdef OPENSSL_EXTRA
  7199. #ifndef NO_CERTS
  7200. #ifdef OPENSSL_ALL
  7201. /* Check whether BN number is a prime.
  7202. *
  7203. * @param [in] n Number to check.
  7204. * @param [out] isPrime MP_YES when prime and MP_NO when not.
  7205. * @return 1 on success.
  7206. * @return 0 on error.
  7207. */
  7208. static int wolfssl_dh_check_prime(WOLFSSL_BIGNUM* n, int* isPrime)
  7209. {
  7210. int ret = 1;
  7211. #ifdef WOLFSSL_SMALL_STACK
  7212. WC_RNG* tmpRng = NULL;
  7213. #else
  7214. WC_RNG tmpRng[1];
  7215. #endif
  7216. WC_RNG* rng;
  7217. int localRng;
  7218. /* Make an RNG with tmpRng or get global. */
  7219. rng = wolfssl_make_rng(tmpRng, &localRng);
  7220. if (rng == NULL) {
  7221. ret = 0;
  7222. }
  7223. if (ret == 1) {
  7224. mp_int* prime = (mp_int*)n->internal;
  7225. if (mp_prime_is_prime_ex(prime, 8, isPrime, rng) != 0) {
  7226. ret = 0;
  7227. }
  7228. /* Free local random number generator if created. */
  7229. if (localRng) {
  7230. wc_FreeRng(rng);
  7231. #ifdef WOLFSSL_SMALL_STACK
  7232. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7233. #endif
  7234. }
  7235. }
  7236. return ret;
  7237. }
  7238. /* Checks the Diffie-Hellman parameters.
  7239. *
  7240. * Checks that the generator and prime are available.
  7241. * Checks that the prime is prime.
  7242. * OpenSSL expects codes to be non-NULL.
  7243. *
  7244. * @param [in] dh DH key to check.
  7245. * @param [out] codes Codes of checks that failed.
  7246. * @return 1 on success.
  7247. * @return 0 when DH is NULL, there were errors or failed to create a random
  7248. * number generator.
  7249. */
  7250. int wolfSSL_DH_check(const WOLFSSL_DH *dh, int *codes)
  7251. {
  7252. int ret = 1;
  7253. int errors = 0;
  7254. WOLFSSL_ENTER("wolfSSL_DH_check");
  7255. /* Validate parameters. */
  7256. if (dh == NULL) {
  7257. ret = 0;
  7258. }
  7259. /* Check generator available. */
  7260. if ((ret == 1) && ((dh->g == NULL) || (dh->g->internal == NULL))) {
  7261. errors |= DH_NOT_SUITABLE_GENERATOR;
  7262. }
  7263. if (ret == 1) {
  7264. /* Check prime available. */
  7265. if ((dh->p == NULL) || (dh->p->internal == NULL)) {
  7266. errors |= DH_CHECK_P_NOT_PRIME;
  7267. }
  7268. else {
  7269. /* Test if dh->p is prime. */
  7270. int isPrime = MP_NO;
  7271. ret = wolfssl_dh_check_prime(dh->p, &isPrime);
  7272. /* Set error code if parameter p is not prime. */
  7273. if ((ret == 1) && (isPrime != MP_YES)) {
  7274. errors |= DH_CHECK_P_NOT_PRIME;
  7275. }
  7276. }
  7277. }
  7278. /* Return errors when user wants exact issues. */
  7279. if (codes != NULL) {
  7280. *codes = errors;
  7281. }
  7282. else if (errors) {
  7283. ret = 0;
  7284. }
  7285. return ret;
  7286. }
  7287. #endif /* OPENSSL_ALL */
  7288. #endif /* !NO_CERTS */
  7289. #endif /* OPENSSL_EXTRA */
  7290. /*
  7291. * DH generate APIs
  7292. */
  7293. #if defined(OPENSSL_ALL) || (defined(OPENSSL_EXTRA) && \
  7294. (defined(HAVE_STUNNEL) || defined(WOLFSSL_NGINX) || \
  7295. defined(HAVE_LIGHTY) || defined(WOLFSSL_HAPROXY) || \
  7296. defined(WOLFSSL_OPENSSH) || defined(HAVE_SBLIM_SFCB)))
  7297. #if defined(WOLFSSL_KEY_GEN) && !defined(HAVE_SELFTEST)
  7298. /* Generate DH parameters.
  7299. *
  7300. * @param [in] prime_len Length of prime in bits.
  7301. * @param [in] generator Gnerator value to use.
  7302. * @param [in] callback Called with progress information. Unused.
  7303. * @param [in] cb_arg User callback argument. Unused.
  7304. * @return NULL on failure.
  7305. * @return DH key on success.
  7306. */
  7307. WOLFSSL_DH *wolfSSL_DH_generate_parameters(int prime_len, int generator,
  7308. void (*callback) (int, int, void *), void *cb_arg)
  7309. {
  7310. WOLFSSL_DH* dh = NULL;
  7311. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters");
  7312. /* Not supported by wolfSSl APIs. */
  7313. (void)callback;
  7314. (void)cb_arg;
  7315. /* Create an empty DH key. */
  7316. if ((dh = wolfSSL_DH_new()) == NULL) {
  7317. WOLFSSL_ERROR_MSG("wolfSSL_DH_new error");
  7318. }
  7319. /* Generate parameters into DH key. */
  7320. else if (wolfSSL_DH_generate_parameters_ex(dh, prime_len, generator, NULL)
  7321. != 1) {
  7322. WOLFSSL_ERROR_MSG("wolfSSL_DH_generate_parameters_ex error");
  7323. wolfSSL_DH_free(dh);
  7324. dh = NULL;
  7325. }
  7326. return dh;
  7327. }
  7328. /* Generate DH parameters.
  7329. *
  7330. * @param [in] dh DH key to generate parameters into.
  7331. * @param [in] prime_len Length of prime in bits.
  7332. * @param [in] generator Gnerator value to use.
  7333. * @param [in] callback Called with progress information. Unused.
  7334. * @param [in] cb_arg User callback argument. Unused.
  7335. * @return 0 on failure.
  7336. * @return 1 on success.
  7337. */
  7338. int wolfSSL_DH_generate_parameters_ex(WOLFSSL_DH* dh, int prime_len,
  7339. int generator, void (*callback) (int, int, void *))
  7340. {
  7341. int ret = 1;
  7342. DhKey* key;
  7343. #ifdef WOLFSSL_SMALL_STACK
  7344. WC_RNG* tmpRng = NULL;
  7345. #else
  7346. WC_RNG tmpRng[1];
  7347. #endif
  7348. WC_RNG* rng = NULL;
  7349. int localRng = 0;
  7350. WOLFSSL_ENTER("wolfSSL_DH_generate_parameters_ex");
  7351. /* Not supported by wolfSSL APIs. */
  7352. (void)callback;
  7353. (void)generator;
  7354. /* Validate parameters. */
  7355. if (dh == NULL) {
  7356. WOLFSSL_ERROR_MSG("Bad parameter");
  7357. ret = 0;
  7358. }
  7359. if (ret == 1) {
  7360. /* Make an RNG with tmpRng or get global. */
  7361. rng = wolfssl_make_rng(tmpRng, &localRng);
  7362. if (rng == NULL) {
  7363. WOLFSSL_ERROR_MSG("No RNG to use");
  7364. ret = 0;
  7365. }
  7366. }
  7367. if (ret == 1) {
  7368. /* Get internal/wolfSSL DH key. */
  7369. key = (DhKey*)dh->internal;
  7370. /* Clear out data from internal DH key. */
  7371. wc_FreeDhKey(key);
  7372. /* Re-initialize internal DH key. */
  7373. if (wc_InitDhKey(key) != 0) {
  7374. ret = 0;
  7375. }
  7376. }
  7377. if (ret == 1) {
  7378. /* Generate parameters into internal DH key. */
  7379. if (wc_DhGenerateParams(rng, prime_len, key) != 0) {
  7380. WOLFSSL_ERROR_MSG("wc_DhGenerateParams error");
  7381. ret = 0;
  7382. }
  7383. }
  7384. /* Free local random number generator if created. */
  7385. if (localRng) {
  7386. wc_FreeRng(rng);
  7387. #ifdef WOLFSSL_SMALL_STACK
  7388. XFREE(rng, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  7389. #endif
  7390. }
  7391. if (ret == 1) {
  7392. /* Internal parameters set by generation. */
  7393. dh->inSet = 1;
  7394. WOLFSSL_MSG("wolfSSL does not support using a custom generator.");
  7395. /* Synchronize the external to the internal parameters. */
  7396. if (SetDhExternal(dh) != 1) {
  7397. WOLFSSL_ERROR_MSG("SetDhExternal error");
  7398. ret = 0;
  7399. }
  7400. }
  7401. return ret;
  7402. }
  7403. #endif /* WOLFSSL_KEY_GEN && !HAVE_SELFTEST */
  7404. #endif /* OPENSSL_ALL || (OPENSSL_EXTRA && (HAVE_STUNNEL || WOLFSSL_NGINX ||
  7405. * HAVE_LIGHTY || WOLFSSL_HAPROXY || WOLFSSL_OPENSSH ||
  7406. * HAVE_SBLIM_SFCB)) */
  7407. #ifdef OPENSSL_EXTRA
  7408. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && !defined(WOLFSSL_DH_EXTRA)) \
  7409. || (defined(HAVE_FIPS_VERSION) && FIPS_VERSION_GT(2,0))
  7410. /* Generate a public/private key pair base on parameters.
  7411. *
  7412. * @param [in, out] dh DH key to generate keys into.
  7413. * @return 1 on success.
  7414. * @return 0 on error.
  7415. */
  7416. int wolfSSL_DH_generate_key(WOLFSSL_DH* dh)
  7417. {
  7418. int ret = 1;
  7419. word32 pubSz = 0;
  7420. word32 privSz = 0;
  7421. int localRng = 0;
  7422. WC_RNG* rng = NULL;
  7423. #ifdef WOLFSSL_SMALL_STACK
  7424. WC_RNG* tmpRng = NULL;
  7425. #else
  7426. WC_RNG tmpRng[1];
  7427. #endif
  7428. unsigned char* pub = NULL;
  7429. unsigned char* priv = NULL;
  7430. WOLFSSL_ENTER("wolfSSL_DH_generate_key");
  7431. /* Validate parameters. */
  7432. if ((dh == NULL) || (dh->p == NULL) || (dh->g == NULL)) {
  7433. WOLFSSL_ERROR_MSG("Bad function arguments");
  7434. ret = 0;
  7435. }
  7436. /* Synchronize the external and internal parameters. */
  7437. if ((ret == 1) && (dh->inSet == 0) && (SetDhInternal(dh) != 1)) {
  7438. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7439. ret = 0;
  7440. }
  7441. if (ret == 1) {
  7442. /* Make a new RNG or use global. */
  7443. rng = wolfssl_make_rng(tmpRng, &localRng);
  7444. /* Check we have a random number generator. */
  7445. if (rng == NULL) {
  7446. ret = 0;
  7447. }
  7448. }
  7449. if (ret == 1) {
  7450. /* Get the size of the prime in bytes. */
  7451. pubSz = wolfSSL_BN_num_bytes(dh->p);
  7452. if (pubSz == 0) {
  7453. WOLFSSL_ERROR_MSG("Prime parameter invalid");
  7454. ret = 0;
  7455. }
  7456. }
  7457. if (ret == 1) {
  7458. /* Private key size can be as much as the size of the prime. */
  7459. if (dh->length) {
  7460. privSz = dh->length / 8; /* to bytes */
  7461. }
  7462. else {
  7463. privSz = pubSz;
  7464. }
  7465. /* Allocate public and private key arrays. */
  7466. pub = (unsigned char*)XMALLOC(pubSz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7467. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7468. if (pub == NULL || priv == NULL) {
  7469. WOLFSSL_ERROR_MSG("Unable to malloc memory");
  7470. ret = 0;
  7471. }
  7472. }
  7473. if (ret == 1) {
  7474. /* Dispose of old public and private keys. */
  7475. wolfSSL_BN_free(dh->pub_key);
  7476. wolfSSL_BN_free(dh->priv_key);
  7477. /* Allocate new public and private keys. */
  7478. dh->pub_key = wolfSSL_BN_new();
  7479. dh->priv_key = wolfSSL_BN_new();
  7480. if (dh->pub_key == NULL) {
  7481. WOLFSSL_ERROR_MSG("Bad DH new pub");
  7482. ret = 0;
  7483. }
  7484. if (dh->priv_key == NULL) {
  7485. WOLFSSL_ERROR_MSG("Bad DH new priv");
  7486. ret = 0;
  7487. }
  7488. }
  7489. PRIVATE_KEY_UNLOCK();
  7490. /* Generate public and private keys into arrays. */
  7491. if ((ret == 1) && (wc_DhGenerateKeyPair((DhKey*)dh->internal, rng, priv,
  7492. &privSz, pub, &pubSz) < 0)) {
  7493. WOLFSSL_ERROR_MSG("Bad wc_DhGenerateKeyPair");
  7494. ret = 0;
  7495. }
  7496. /* Set public key from array. */
  7497. if ((ret == 1) && (wolfSSL_BN_bin2bn(pub, pubSz, dh->pub_key) == NULL)) {
  7498. WOLFSSL_ERROR_MSG("Bad DH bn2bin error pub");
  7499. ret = 0;
  7500. }
  7501. /* Set private key from array. */
  7502. if ((ret == 1) && (wolfSSL_BN_bin2bn(priv, privSz, dh->priv_key) == NULL)) {
  7503. WOLFSSL_ERROR_MSG("Bad DH bn2bin error priv");
  7504. ret = 0;
  7505. }
  7506. PRIVATE_KEY_LOCK();
  7507. if (localRng) {
  7508. /* Free an initialized local random number generator. */
  7509. wc_FreeRng(rng);
  7510. #ifdef WOLFSSL_SMALL_STACK
  7511. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  7512. #endif
  7513. }
  7514. /* Dispose of allocated data. */
  7515. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7516. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7517. return ret;
  7518. }
  7519. /* Compute the shared key from the private key and peer's public key.
  7520. *
  7521. * Return code compliant with OpenSSL.
  7522. * OpenSSL returns 0 when number of bits in p are smaller than minimum
  7523. * supported.
  7524. *
  7525. * @param [out] key Buffer to place shared key.
  7526. * @param [in] otherPub Peer's public key.
  7527. * @param [in] dh DH key containing private key.
  7528. * @return -1 on error.
  7529. * @return Size of shared secret in bytes on success.
  7530. */
  7531. int wolfSSL_DH_compute_key(unsigned char* key, const WOLFSSL_BIGNUM* otherPub,
  7532. WOLFSSL_DH* dh)
  7533. {
  7534. int ret = 0;
  7535. word32 keySz = 0;
  7536. int pubSz = MAX_DHKEY_SZ;
  7537. int privSz = MAX_DHKEY_SZ;
  7538. int sz;
  7539. #ifdef WOLFSSL_SMALL_STACK
  7540. unsigned char* pub = NULL;
  7541. unsigned char* priv = NULL;
  7542. #else
  7543. unsigned char pub [MAX_DHKEY_SZ];
  7544. unsigned char priv[MAX_DHKEY_SZ];
  7545. #endif
  7546. WOLFSSL_ENTER("wolfSSL_DH_compute_key");
  7547. /* Validate parameters. */
  7548. if ((dh == NULL) || (dh->priv_key == NULL) || (otherPub == NULL)) {
  7549. WOLFSSL_ERROR_MSG("Bad function arguments");
  7550. ret = -1;
  7551. }
  7552. /* Get the maximum size of computed DH key. */
  7553. if ((ret == 0) && ((keySz = (word32)DH_size(dh)) == 0)) {
  7554. WOLFSSL_ERROR_MSG("Bad DH_size");
  7555. ret = -1;
  7556. }
  7557. if (ret == 0) {
  7558. /* Validate the size of the private key. */
  7559. sz = wolfSSL_BN_num_bytes(dh->priv_key);
  7560. if (sz > (int)privSz) {
  7561. WOLFSSL_ERROR_MSG("Bad priv internal size");
  7562. ret = -1;
  7563. }
  7564. }
  7565. if (ret == 0) {
  7566. #ifdef WOLFSSL_SMALL_STACK
  7567. /* Keep real private key size to minimize amount allocated. */
  7568. privSz = sz;
  7569. #endif
  7570. /* Validate the size of the public key. */
  7571. sz = wolfSSL_BN_num_bytes(otherPub);
  7572. if (sz > (int)pubSz) {
  7573. WOLFSSL_ERROR_MSG("Bad otherPub size");
  7574. ret = -1;
  7575. }
  7576. }
  7577. if (ret == 0) {
  7578. #ifdef WOLFSSL_SMALL_STACK
  7579. /* Allocate memory for the public key array. */
  7580. pub = (unsigned char*)XMALLOC(sz, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7581. if (pub == NULL)
  7582. ret = -1;
  7583. }
  7584. if (ret == 0) {
  7585. /* Allocate memory for the private key array. */
  7586. priv = (unsigned char*)XMALLOC(privSz, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7587. if (priv == NULL) {
  7588. ret = -1;
  7589. }
  7590. }
  7591. if (ret == 0) {
  7592. #endif
  7593. /* Get the private key into the array. */
  7594. privSz = wolfSSL_BN_bn2bin(dh->priv_key, priv);
  7595. if (privSz <= 0) {
  7596. ret = -1;
  7597. }
  7598. }
  7599. if (ret == 0) {
  7600. /* Get the public key into the array. */
  7601. pubSz = wolfSSL_BN_bn2bin(otherPub, pub);
  7602. if (privSz <= 0) {
  7603. ret = -1;
  7604. }
  7605. }
  7606. /* Synchronize the external into the internal parameters. */
  7607. if ((ret == 0) && ((dh->inSet == 0) && (SetDhInternal(dh) != 1))) {
  7608. WOLFSSL_ERROR_MSG("Bad DH set internal");
  7609. ret = -1;
  7610. }
  7611. PRIVATE_KEY_UNLOCK();
  7612. /* Calculate shared secret from private and public keys. */
  7613. if ((ret == 0) && (wc_DhAgree((DhKey*)dh->internal, key, &keySz, priv,
  7614. privSz, pub, pubSz) < 0)) {
  7615. WOLFSSL_ERROR_MSG("wc_DhAgree failed");
  7616. ret = -1;
  7617. }
  7618. if (ret == 0) {
  7619. /* Return actual length. */
  7620. ret = (int)keySz;
  7621. }
  7622. PRIVATE_KEY_LOCK();
  7623. #ifdef WOLFSSL_SMALL_STACK
  7624. if (priv != NULL)
  7625. #endif
  7626. {
  7627. /* Zeroize sensitive data. */
  7628. ForceZero(priv, privSz);
  7629. }
  7630. #ifdef WOLFSSL_SMALL_STACK
  7631. XFREE(pub, NULL, DYNAMIC_TYPE_PUBLIC_KEY);
  7632. XFREE(priv, NULL, DYNAMIC_TYPE_PRIVATE_KEY);
  7633. #endif
  7634. WOLFSSL_LEAVE("wolfSSL_DH_compute_key", ret);
  7635. return ret;
  7636. }
  7637. #endif /* !HAVE_FIPS || (HAVE_FIPS && !WOLFSSL_DH_EXTRA) ||
  7638. * HAVE_FIPS_VERSION > 2 */
  7639. #endif /* OPENSSL_EXTRA */
  7640. #endif /* NO_DH */
  7641. /*******************************************************************************
  7642. * END OF DH API
  7643. ******************************************************************************/
  7644. /*******************************************************************************
  7645. * START OF EC API
  7646. ******************************************************************************/
  7647. #ifdef HAVE_ECC
  7648. #if defined(OPENSSL_EXTRA)
  7649. /* Start EC_curve */
  7650. /* Get the NIST name for the numeric ID.
  7651. *
  7652. * @param [in] nid Numeric ID of an EC curve.
  7653. * @return String representing NIST name of EC curve on success.
  7654. * @return NULL on error.
  7655. */
  7656. const char* wolfSSL_EC_curve_nid2nist(int nid)
  7657. {
  7658. const char* name = NULL;
  7659. const WOLF_EC_NIST_NAME* nist_name;
  7660. /* Attempt to find the curve info matching the NID passed in. */
  7661. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7662. if (nist_name->nid == nid) {
  7663. /* NID found - return name. */
  7664. name = nist_name->name;
  7665. break;
  7666. }
  7667. }
  7668. return name;
  7669. }
  7670. /* Get the numeric ID for the NIST name.
  7671. *
  7672. * @param [in] name NIST name of EC curve.
  7673. * @return NID matching NIST name on success.
  7674. * @return 0 on error.
  7675. */
  7676. int wolfSSL_EC_curve_nist2nid(const char* name)
  7677. {
  7678. int nid = 0;
  7679. const WOLF_EC_NIST_NAME* nist_name;
  7680. /* Attempt to find the curve info matching the NIST name passed in. */
  7681. for (nist_name = kNistCurves; nist_name->name != NULL; nist_name++) {
  7682. if (XSTRCMP(nist_name->name, name) == 0) {
  7683. /* Name found - return NID. */
  7684. nid = nist_name->nid;
  7685. break;
  7686. }
  7687. }
  7688. return nid;
  7689. }
  7690. #endif /* OPENSSL_EXTRA */
  7691. /* End EC_curve */
  7692. /* Start EC_METHOD */
  7693. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7694. /* Get the EC method of the EC group object.
  7695. *
  7696. * wolfSSL doesn't use method tables. Implementation used is dependent upon
  7697. * the NID.
  7698. *
  7699. * @param [in] group EC group object.
  7700. * @return EC method.
  7701. */
  7702. const WOLFSSL_EC_METHOD* wolfSSL_EC_GROUP_method_of(
  7703. const WOLFSSL_EC_GROUP *group)
  7704. {
  7705. /* No method table used so just return the same object. */
  7706. return group;
  7707. }
  7708. /* Get field type for method.
  7709. *
  7710. * Only prime fields are supported.
  7711. *
  7712. * @param [in] meth EC method.
  7713. * @return X9.63 prime field NID on success.
  7714. * @return 0 on error.
  7715. */
  7716. int wolfSSL_EC_METHOD_get_field_type(const WOLFSSL_EC_METHOD *meth)
  7717. {
  7718. int nid = 0;
  7719. if (meth != NULL) {
  7720. /* Only field type supported by code base. */
  7721. nid = NID_X9_62_prime_field;
  7722. }
  7723. return nid;
  7724. }
  7725. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7726. /* End EC_METHOD */
  7727. /* Start EC_GROUP */
  7728. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7729. /* Converts ECC curve enum values in ecc_curve_id to the associated OpenSSL NID
  7730. * value.
  7731. *
  7732. * @param [in] n ECC curve id.
  7733. * @return ECC curve NID (OpenSSL compatible value).
  7734. */
  7735. int EccEnumToNID(int n)
  7736. {
  7737. WOLFSSL_ENTER("EccEnumToNID");
  7738. switch(n) {
  7739. case ECC_SECP192R1:
  7740. return NID_X9_62_prime192v1;
  7741. case ECC_PRIME192V2:
  7742. return NID_X9_62_prime192v2;
  7743. case ECC_PRIME192V3:
  7744. return NID_X9_62_prime192v3;
  7745. case ECC_PRIME239V1:
  7746. return NID_X9_62_prime239v1;
  7747. case ECC_PRIME239V2:
  7748. return NID_X9_62_prime239v2;
  7749. case ECC_PRIME239V3:
  7750. return NID_X9_62_prime239v3;
  7751. case ECC_SECP256R1:
  7752. return NID_X9_62_prime256v1;
  7753. case ECC_SECP112R1:
  7754. return NID_secp112r1;
  7755. case ECC_SECP112R2:
  7756. return NID_secp112r2;
  7757. case ECC_SECP128R1:
  7758. return NID_secp128r1;
  7759. case ECC_SECP128R2:
  7760. return NID_secp128r2;
  7761. case ECC_SECP160R1:
  7762. return NID_secp160r1;
  7763. case ECC_SECP160R2:
  7764. return NID_secp160r2;
  7765. case ECC_SECP224R1:
  7766. return NID_secp224r1;
  7767. case ECC_SECP384R1:
  7768. return NID_secp384r1;
  7769. case ECC_SECP521R1:
  7770. return NID_secp521r1;
  7771. case ECC_SECP160K1:
  7772. return NID_secp160k1;
  7773. case ECC_SECP192K1:
  7774. return NID_secp192k1;
  7775. case ECC_SECP224K1:
  7776. return NID_secp224k1;
  7777. case ECC_SECP256K1:
  7778. return NID_secp256k1;
  7779. case ECC_BRAINPOOLP160R1:
  7780. return NID_brainpoolP160r1;
  7781. case ECC_BRAINPOOLP192R1:
  7782. return NID_brainpoolP192r1;
  7783. case ECC_BRAINPOOLP224R1:
  7784. return NID_brainpoolP224r1;
  7785. case ECC_BRAINPOOLP256R1:
  7786. return NID_brainpoolP256r1;
  7787. case ECC_BRAINPOOLP320R1:
  7788. return NID_brainpoolP320r1;
  7789. case ECC_BRAINPOOLP384R1:
  7790. return NID_brainpoolP384r1;
  7791. case ECC_BRAINPOOLP512R1:
  7792. return NID_brainpoolP512r1;
  7793. default:
  7794. WOLFSSL_MSG("NID not found");
  7795. return -1;
  7796. }
  7797. }
  7798. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7799. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  7800. /* Converts OpenSSL NID of EC curve to the enum value in ecc_curve_id
  7801. *
  7802. * Used by ecc_sets[].
  7803. *
  7804. * @param [in] n OpenSSL NID of EC curve.
  7805. * @return wolfCrypt EC curve id.
  7806. * @return -1 on error.
  7807. */
  7808. int NIDToEccEnum(int nid)
  7809. {
  7810. /* -1 on error. */
  7811. int id = -1;
  7812. WOLFSSL_ENTER("NIDToEccEnum");
  7813. switch (nid) {
  7814. case NID_X9_62_prime192v1:
  7815. id = ECC_SECP192R1;
  7816. break;
  7817. case NID_X9_62_prime192v2:
  7818. id = ECC_PRIME192V2;
  7819. break;
  7820. case NID_X9_62_prime192v3:
  7821. id = ECC_PRIME192V3;
  7822. break;
  7823. case NID_X9_62_prime239v1:
  7824. id = ECC_PRIME239V1;
  7825. break;
  7826. case NID_X9_62_prime239v2:
  7827. id = ECC_PRIME239V2;
  7828. break;
  7829. case NID_X9_62_prime239v3:
  7830. id = ECC_PRIME239V3;
  7831. break;
  7832. case NID_X9_62_prime256v1:
  7833. id = ECC_SECP256R1;
  7834. break;
  7835. case NID_secp112r1:
  7836. id = ECC_SECP112R1;
  7837. break;
  7838. case NID_secp112r2:
  7839. id = ECC_SECP112R2;
  7840. break;
  7841. case NID_secp128r1:
  7842. id = ECC_SECP128R1;
  7843. break;
  7844. case NID_secp128r2:
  7845. id = ECC_SECP128R2;
  7846. break;
  7847. case NID_secp160r1:
  7848. id = ECC_SECP160R1;
  7849. break;
  7850. case NID_secp160r2:
  7851. id = ECC_SECP160R2;
  7852. break;
  7853. case NID_secp224r1:
  7854. id = ECC_SECP224R1;
  7855. break;
  7856. case NID_secp384r1:
  7857. id = ECC_SECP384R1;
  7858. break;
  7859. case NID_secp521r1:
  7860. id = ECC_SECP521R1;
  7861. break;
  7862. case NID_secp160k1:
  7863. id = ECC_SECP160K1;
  7864. break;
  7865. case NID_secp192k1:
  7866. id = ECC_SECP192K1;
  7867. break;
  7868. case NID_secp224k1:
  7869. id = ECC_SECP224K1;
  7870. break;
  7871. case NID_secp256k1:
  7872. id = ECC_SECP256K1;
  7873. break;
  7874. case NID_brainpoolP160r1:
  7875. id = ECC_BRAINPOOLP160R1;
  7876. break;
  7877. case NID_brainpoolP192r1:
  7878. id = ECC_BRAINPOOLP192R1;
  7879. break;
  7880. case NID_brainpoolP224r1:
  7881. id = ECC_BRAINPOOLP224R1;
  7882. break;
  7883. case NID_brainpoolP256r1:
  7884. id = ECC_BRAINPOOLP256R1;
  7885. break;
  7886. case NID_brainpoolP320r1:
  7887. id = ECC_BRAINPOOLP320R1;
  7888. break;
  7889. case NID_brainpoolP384r1:
  7890. id = ECC_BRAINPOOLP384R1;
  7891. break;
  7892. case NID_brainpoolP512r1:
  7893. id = ECC_BRAINPOOLP512R1;
  7894. break;
  7895. default:
  7896. WOLFSSL_MSG("NID not found");
  7897. }
  7898. return id;
  7899. }
  7900. /* Set the fields of the EC group based on numeric ID.
  7901. *
  7902. * @param [in, out] group EC group.
  7903. * @param [in] nid Numeric ID of an EC curve.
  7904. */
  7905. static void ec_group_set_nid(WOLFSSL_EC_GROUP* group, int nid)
  7906. {
  7907. int eccEnum;
  7908. int realNid;
  7909. /* Convert ecc_curve_id enum to NID. */
  7910. if ((realNid = EccEnumToNID(nid)) != -1) {
  7911. /* ecc_curve_id enum passed in - have real NID value set. */
  7912. eccEnum = nid;
  7913. }
  7914. else {
  7915. /* NID passed in is OpenSSL type. */
  7916. realNid = nid;
  7917. /* Convert NID to ecc_curve_id enum. */
  7918. eccEnum = NIDToEccEnum(nid);
  7919. }
  7920. /* Set the numeric ID of the curve */
  7921. group->curve_nid = realNid;
  7922. /* Initialize index to -1 (i.e. wolfCrypt doesn't support curve). */
  7923. group->curve_idx = -1;
  7924. /* Find index and OID sum for curve if wolfCrypt supports it. */
  7925. if (eccEnum != -1) {
  7926. int i;
  7927. /* Find id and set the internal curve idx and OID sum. */
  7928. for (i = 0; ecc_sets[i].size != 0; i++) {
  7929. if (ecc_sets[i].id == eccEnum) {
  7930. /* Found id in wolfCrypt supported EC curves. */
  7931. group->curve_idx = i;
  7932. group->curve_oid = ecc_sets[i].oidSum;
  7933. break;
  7934. }
  7935. }
  7936. }
  7937. }
  7938. /* Create a new EC group with the numeric ID for an EC curve.
  7939. *
  7940. * @param [in] nid Numeric ID of an EC curve.
  7941. * @return New, allocated EC group on success.
  7942. * @return NULL on error.
  7943. */
  7944. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_new_by_curve_name(int nid)
  7945. {
  7946. int err = 0;
  7947. WOLFSSL_EC_GROUP* group;
  7948. WOLFSSL_ENTER("wolfSSL_EC_GROUP_new_by_curve_name");
  7949. /* Allocate EC group. */
  7950. group = (WOLFSSL_EC_GROUP*)XMALLOC(sizeof(WOLFSSL_EC_GROUP), NULL,
  7951. DYNAMIC_TYPE_ECC);
  7952. if (group == NULL) {
  7953. WOLFSSL_MSG("wolfSSL_EC_GROUP_new_by_curve_name malloc failure");
  7954. err = 1;
  7955. }
  7956. if (!err) {
  7957. /* Reset all fields. */
  7958. XMEMSET(group, 0, sizeof(WOLFSSL_EC_GROUP));
  7959. /* Set the fields of group based on the numeric ID. */
  7960. ec_group_set_nid(group, nid);
  7961. }
  7962. return group;
  7963. }
  7964. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  7965. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  7966. /* Dispose of the EC group.
  7967. *
  7968. * Cannot use group after this call.
  7969. *
  7970. * @param [in] group EC group to free.
  7971. */
  7972. void wolfSSL_EC_GROUP_free(WOLFSSL_EC_GROUP *group)
  7973. {
  7974. WOLFSSL_ENTER("wolfSSL_EC_GROUP_free");
  7975. /* Dispose of EC group. */
  7976. XFREE(group, NULL, DYNAMIC_TYPE_ECC);
  7977. }
  7978. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  7979. #ifdef OPENSSL_EXTRA
  7980. #ifndef NO_BIO
  7981. /* Creates an EC group from the DER encoding.
  7982. *
  7983. * Only named curves supported.
  7984. *
  7985. * @param [out] group Reference to EC group object.
  7986. * @param [in] in Buffer holding DER encoding of curve.
  7987. * @param [in] inSz Length of data in buffer.
  7988. * @return EC group on success.
  7989. * @return NULL on error.
  7990. */
  7991. static WOLFSSL_EC_GROUP* wolfssl_ec_group_d2i(WOLFSSL_EC_GROUP** group,
  7992. const unsigned char* in, long inSz)
  7993. {
  7994. int err = 0;
  7995. WOLFSSL_EC_GROUP* ret = NULL;
  7996. word32 idx = 0;
  7997. word32 oid = 0;
  7998. int id = 0;
  7999. /* Use the group passed in. */
  8000. if ((group != NULL) && (*group != NULL)) {
  8001. ret = *group;
  8002. }
  8003. /* Only support named curves. */
  8004. if (in[0] != ASN_OBJECT_ID) {
  8005. WOLFSSL_ERROR_MSG("Invalid or unsupported encoding");
  8006. err = 1;
  8007. }
  8008. /* Decode the OBJECT ID - expecting an EC curve OID. */
  8009. if ((!err) && (GetObjectId(in, &idx, &oid, oidCurveType, (word32)inSz) !=
  8010. 0)) {
  8011. err = 1;
  8012. }
  8013. if (!err) {
  8014. /* Get the internal ID for OID. */
  8015. id = wc_ecc_get_oid(oid, NULL, NULL);
  8016. if (id < 0) {
  8017. err = 1;
  8018. }
  8019. }
  8020. if (!err) {
  8021. /* Get the NID for the internal ID. */
  8022. int nid = EccEnumToNID(id);
  8023. if (ret == NULL) {
  8024. /* Create a new EC group with the numeric ID. */
  8025. ret = wolfSSL_EC_GROUP_new_by_curve_name(nid);
  8026. if (ret == NULL) {
  8027. err = 1;
  8028. }
  8029. }
  8030. else {
  8031. ec_group_set_nid(ret, nid);
  8032. }
  8033. }
  8034. if ((!err) && (group != NULL)) {
  8035. /* Return the EC group through reference. */
  8036. *group = ret;
  8037. }
  8038. if (err) {
  8039. if ((ret != NULL) && (ret != *group)) {
  8040. wolfSSL_EC_GROUP_free(ret);
  8041. }
  8042. ret = NULL;
  8043. }
  8044. return ret;
  8045. }
  8046. /* Creates a new EC group from the PEM encoding in the BIO.
  8047. *
  8048. * @param [in] bio BIO to read PEM encoding from.
  8049. * @param [out] group Reference to EC group object.
  8050. * @param [in] cb Password callback when PEM encrypted.
  8051. * @param [in] pass NUL terminated string for passphrase when PEM encrypted.
  8052. * @return EC group on success.
  8053. * @return NULL on error.
  8054. */
  8055. WOLFSSL_EC_GROUP* wolfSSL_PEM_read_bio_ECPKParameters(WOLFSSL_BIO* bio,
  8056. WOLFSSL_EC_GROUP** group, wc_pem_password_cb* cb, void* pass)
  8057. {
  8058. int err = 0;
  8059. WOLFSSL_EC_GROUP* ret = NULL;
  8060. DerBuffer* der = NULL;
  8061. int keyFormat = 0;
  8062. if (bio == NULL) {
  8063. err = 1;
  8064. }
  8065. /* Read parameters from BIO and convert PEM to DER. */
  8066. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PARAM_TYPE,
  8067. &keyFormat, &der) < 0)) {
  8068. err = 1;
  8069. }
  8070. if (!err) {
  8071. /* Create EC group from DER encoding. */
  8072. ret = wolfssl_ec_group_d2i(group, der->buffer, der->length);
  8073. if (ret == NULL) {
  8074. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_GROUP");
  8075. }
  8076. }
  8077. /* Dispose of any allocated data. */
  8078. FreeDer(&der);
  8079. return ret;
  8080. }
  8081. #endif /* !NO_BIO */
  8082. #if defined(OPENSSL_ALL) && !defined(NO_CERTS)
  8083. /* Copy an EC group.
  8084. *
  8085. * Only used by wolfSSL_EC_KEY_dup at this time.
  8086. *
  8087. * @param [in, out] dst Destination EC group.
  8088. * @param [in] src Source EC group.
  8089. * @return 0 on success.
  8090. */
  8091. static int wolfssl_ec_group_copy(WOLFSSL_EC_GROUP* dst,
  8092. const WOLFSSL_EC_GROUP* src)
  8093. {
  8094. /* Copy the fields. */
  8095. dst->curve_idx = src->curve_idx;
  8096. dst->curve_nid = src->curve_nid;
  8097. dst->curve_oid = src->curve_oid;
  8098. return 0;
  8099. }
  8100. #endif /* OPENSSL_ALL && !NO_CERTS */
  8101. /* Copies ecc_key into new WOLFSSL_EC_GROUP object
  8102. *
  8103. * @param [in] src EC group to duplicate.
  8104. *
  8105. * @return EC group on success.
  8106. * @return NULL on error.
  8107. */
  8108. WOLFSSL_EC_GROUP* wolfSSL_EC_GROUP_dup(const WOLFSSL_EC_GROUP *src)
  8109. {
  8110. WOLFSSL_EC_GROUP* newGroup = NULL;
  8111. if (src != NULL) {
  8112. /* Create new group base on NID in original EC group. */
  8113. newGroup = wolfSSL_EC_GROUP_new_by_curve_name(src->curve_nid);
  8114. }
  8115. return newGroup;
  8116. }
  8117. /* Compare two EC groups.
  8118. *
  8119. * Return code compliant with OpenSSL.
  8120. *
  8121. * @param [in] a First EC group.
  8122. * @param [in] b Second EC group.
  8123. * @param [in] ctx Big number context to use when comparing fields. Unused.
  8124. *
  8125. * @return 0 if equal.
  8126. * @return 1 if not equal.
  8127. * @return -1 on error.
  8128. */
  8129. int wolfSSL_EC_GROUP_cmp(const WOLFSSL_EC_GROUP *a, const WOLFSSL_EC_GROUP *b,
  8130. WOLFSSL_BN_CTX *ctx)
  8131. {
  8132. int ret;
  8133. /* No BN operations performed. */
  8134. (void)ctx;
  8135. WOLFSSL_ENTER("wolfSSL_EC_GROUP_cmp");
  8136. /* Validate parameters. */
  8137. if ((a == NULL) || (b == NULL)) {
  8138. WOLFSSL_MSG("wolfSSL_EC_GROUP_cmp Bad arguments");
  8139. /* Return error value. */
  8140. ret = -1;
  8141. }
  8142. /* Compare NID and wolfSSL curve index. */
  8143. else {
  8144. /* 0 when same, 1 when not. */
  8145. ret = ((a->curve_nid == b->curve_nid) &&
  8146. (a->curve_idx == b->curve_idx)) ? 0 : 1;
  8147. }
  8148. return ret;
  8149. }
  8150. #ifndef NO_WOLFSSL_STUB
  8151. /* Set the ASN.1 flag that indicate encoding of curve.
  8152. *
  8153. * Stub function - flag not used elsewhere.
  8154. * Always encoded as named curve.
  8155. *
  8156. * @param [in] group EC group to modify.
  8157. * @param [in] flag ASN.1 flag to set. Valid values:
  8158. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  8159. */
  8160. void wolfSSL_EC_GROUP_set_asn1_flag(WOLFSSL_EC_GROUP *group, int flag)
  8161. {
  8162. (void)group;
  8163. (void)flag;
  8164. WOLFSSL_ENTER("wolfSSL_EC_GROUP_set_asn1_flag");
  8165. WOLFSSL_STUB("EC_GROUP_set_asn1_flag");
  8166. }
  8167. #endif
  8168. /* Get the curve NID of the group.
  8169. *
  8170. * Return code compliant with OpenSSL.
  8171. *
  8172. * @param [in] group EC group.
  8173. * @return Curve NID on success.
  8174. * @return 0 on error.
  8175. */
  8176. int wolfSSL_EC_GROUP_get_curve_name(const WOLFSSL_EC_GROUP *group)
  8177. {
  8178. int nid = 0;
  8179. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_curve_name");
  8180. if (group == NULL) {
  8181. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_curve_name Bad arguments");
  8182. }
  8183. else {
  8184. nid = group->curve_nid;
  8185. }
  8186. return nid;
  8187. }
  8188. /* Get the degree (curve size in bits) of the EC group.
  8189. *
  8190. * Return code compliant with OpenSSL.
  8191. *
  8192. * @return Degree of the curve on success.
  8193. * @return 0 on error.
  8194. */
  8195. int wolfSSL_EC_GROUP_get_degree(const WOLFSSL_EC_GROUP *group)
  8196. {
  8197. int degree = 0;
  8198. WOLFSSL_ENTER("wolfSSL_EC_GROUP_get_degree");
  8199. if (group == NULL) {
  8200. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_degree Bad arguments");
  8201. }
  8202. else {
  8203. switch (group->curve_nid) {
  8204. case NID_secp112r1:
  8205. case NID_secp112r2:
  8206. degree = 112;
  8207. break;
  8208. case NID_secp128r1:
  8209. case NID_secp128r2:
  8210. degree = 128;
  8211. break;
  8212. case NID_secp160k1:
  8213. case NID_secp160r1:
  8214. case NID_secp160r2:
  8215. case NID_brainpoolP160r1:
  8216. degree = 160;
  8217. break;
  8218. case NID_secp192k1:
  8219. case NID_brainpoolP192r1:
  8220. case NID_X9_62_prime192v1:
  8221. case NID_X9_62_prime192v2:
  8222. case NID_X9_62_prime192v3:
  8223. degree = 192;
  8224. break;
  8225. case NID_secp224k1:
  8226. case NID_secp224r1:
  8227. case NID_brainpoolP224r1:
  8228. degree = 224;
  8229. break;
  8230. case NID_X9_62_prime239v1:
  8231. case NID_X9_62_prime239v2:
  8232. case NID_X9_62_prime239v3:
  8233. degree = 239;
  8234. break;
  8235. case NID_secp256k1:
  8236. case NID_brainpoolP256r1:
  8237. case NID_X9_62_prime256v1:
  8238. degree = 256;
  8239. break;
  8240. case NID_brainpoolP320r1:
  8241. degree = 320;
  8242. break;
  8243. case NID_secp384r1:
  8244. case NID_brainpoolP384r1:
  8245. degree = 384;
  8246. break;
  8247. case NID_brainpoolP512r1:
  8248. degree = 512;
  8249. break;
  8250. case NID_secp521r1:
  8251. degree = 521;
  8252. break;
  8253. }
  8254. }
  8255. return degree;
  8256. }
  8257. #endif /* OPENSSL_EXTRA */
  8258. #if defined(OPENSSL_EXTRA) || defined(WOLFSSL_WPAS_SMALL)
  8259. /* Get the length of the order in bits of the EC group.
  8260. *
  8261. * TODO: consider switch statement or calculating directly from hex string
  8262. * array instead of using mp_int.
  8263. *
  8264. * @param [in] group EC group.
  8265. * @return Length of order in bits on success.
  8266. * @return 0 on error.
  8267. */
  8268. int wolfSSL_EC_GROUP_order_bits(const WOLFSSL_EC_GROUP *group)
  8269. {
  8270. int ret = 0;
  8271. #ifdef WOLFSSL_SMALL_STACK
  8272. mp_int *order = NULL;
  8273. #else
  8274. mp_int order[1];
  8275. #endif
  8276. /* Validate parameter. */
  8277. if ((group == NULL) || (group->curve_idx < 0)) {
  8278. WOLFSSL_MSG("wolfSSL_EC_GROUP_order_bits NULL error");
  8279. ret = -1;
  8280. }
  8281. #ifdef WOLFSSL_SMALL_STACK
  8282. if (ret == 0) {
  8283. /* Allocate memory for mp_int that will hold order value. */
  8284. order = (mp_int *)XMALLOC(sizeof(*order), NULL,
  8285. DYNAMIC_TYPE_TMP_BUFFER);
  8286. if (order == NULL) {
  8287. ret = -1;
  8288. }
  8289. }
  8290. #endif
  8291. if (ret == 0) {
  8292. /* Initialize mp_int. */
  8293. ret = mp_init(order);
  8294. }
  8295. if (ret == 0) {
  8296. /* Read hex string of order from wolfCrypt array of curves. */
  8297. ret = mp_read_radix(order, ecc_sets[group->curve_idx].order,
  8298. MP_RADIX_HEX);
  8299. if (ret == 0) {
  8300. /* Get bits of order. */
  8301. ret = mp_count_bits(order);
  8302. }
  8303. /* Clear and free mp_int. */
  8304. mp_clear(order);
  8305. }
  8306. #ifdef WOLFSSL_SMALL_STACK
  8307. /* Deallocate order. */
  8308. XFREE(order, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8309. #endif
  8310. /* Convert error code to length of 0. */
  8311. if (ret < 0) {
  8312. ret = 0;
  8313. }
  8314. return ret;
  8315. }
  8316. #endif /* OPENSSL_EXTRA || WOLFSSL_WPAS_SMALL */
  8317. #if defined(OPENSSL_EXTRA)
  8318. /* Get the order of the group as a BN.
  8319. *
  8320. * Return code compliant with OpenSSL.
  8321. *
  8322. * @param [in] group EC group.
  8323. * @param [in, out] order BN to hold order value.
  8324. * @param [in] ctx Context to use for BN operations. Unused.
  8325. * @return 1 on success.
  8326. * @return 0 on error.
  8327. */
  8328. int wolfSSL_EC_GROUP_get_order(const WOLFSSL_EC_GROUP *group,
  8329. WOLFSSL_BIGNUM *order, WOLFSSL_BN_CTX *ctx)
  8330. {
  8331. int ret = 1;
  8332. mp_int* mp = NULL;
  8333. /* No BN operations performed - done with mp_int in BN. */
  8334. (void)ctx;
  8335. /* Validate parameters. */
  8336. if ((group == NULL) || (order == NULL) || (order->internal == NULL)) {
  8337. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order NULL error");
  8338. ret = 0;
  8339. }
  8340. if (ret == 1) {
  8341. mp = (mp_int*)order->internal;
  8342. }
  8343. /* Initialize */
  8344. if ((ret == 1) && (mp_init(mp) != MP_OKAY)) {
  8345. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_init failure");
  8346. ret = 0;
  8347. }
  8348. /* Read hex string of order from wolfCrypt array of curves. */
  8349. if ((ret == 1) && (mp_read_radix(mp, ecc_sets[group->curve_idx].order,
  8350. MP_RADIX_HEX) != MP_OKAY)) {
  8351. WOLFSSL_MSG("wolfSSL_EC_GROUP_get_order mp_read order failure");
  8352. /* Zero out any partial value but don't free. */
  8353. mp_zero(mp);
  8354. ret = 0;
  8355. }
  8356. return ret;
  8357. }
  8358. #endif /* OPENSSL_EXTRA */
  8359. /* End EC_GROUP */
  8360. /* Start EC_POINT */
  8361. #if defined(OPENSSL_EXTRA)
  8362. /* Set data of EC point into internal, wolfCrypt EC point object.
  8363. *
  8364. * EC_POINT Openssl -> WolfSSL
  8365. *
  8366. * @param [in, out] p EC point to update.
  8367. * @return 1 on success.
  8368. * @return -1 on failure.
  8369. */
  8370. static int ec_point_internal_set(WOLFSSL_EC_POINT *p)
  8371. {
  8372. int ret = 1;
  8373. WOLFSSL_ENTER("ec_point_internal_set");
  8374. /* Validate parameter. */
  8375. if ((p == NULL) || (p->internal == NULL)) {
  8376. WOLFSSL_MSG("ECPoint NULL error");
  8377. ret = -1;
  8378. }
  8379. else {
  8380. /* Get internal point as a wolfCrypt EC point. */
  8381. ecc_point* point = (ecc_point*)p->internal;
  8382. /* Set X ordinate if available. */
  8383. if ((p->X != NULL) && (wolfssl_bn_get_value(p->X, point->x) != 1)) {
  8384. WOLFSSL_MSG("ecc point X error");
  8385. ret = -1;
  8386. }
  8387. /* Set Y ordinate if available. */
  8388. if ((ret == 1) && (p->Y != NULL) && (wolfssl_bn_get_value(p->Y,
  8389. point->y) != 1)) {
  8390. WOLFSSL_MSG("ecc point Y error");
  8391. ret = -1;
  8392. }
  8393. /* Set Z ordinate if available. */
  8394. if ((ret == 1) && (p->Z != NULL) && (wolfssl_bn_get_value(p->Z,
  8395. point->z) != 1)) {
  8396. WOLFSSL_MSG("ecc point Z error");
  8397. ret = -1;
  8398. }
  8399. /* Internal values set when operations succeeded. */
  8400. p->inSet = (ret == 1);
  8401. }
  8402. return ret;
  8403. }
  8404. /* Set data of internal, wolfCrypt EC point object into EC point.
  8405. *
  8406. * EC_POINT WolfSSL -> OpenSSL
  8407. *
  8408. * @param [in, out] p EC point to update.
  8409. * @return 1 on success.
  8410. * @return -1 on failure.
  8411. */
  8412. static int ec_point_external_set(WOLFSSL_EC_POINT *p)
  8413. {
  8414. int ret = 1;
  8415. WOLFSSL_ENTER("ec_point_external_set");
  8416. /* Validate parameter. */
  8417. if ((p == NULL) || (p->internal == NULL)) {
  8418. WOLFSSL_MSG("ECPoint NULL error");
  8419. ret = -1;
  8420. }
  8421. else {
  8422. /* Get internal point as a wolfCrypt EC point. */
  8423. ecc_point* point = (ecc_point*)p->internal;
  8424. /* Set X ordinate. */
  8425. if (wolfssl_bn_set_value(&p->X, point->x) != 1) {
  8426. WOLFSSL_MSG("ecc point X error");
  8427. ret = -1;
  8428. }
  8429. /* Set Y ordinate. */
  8430. if ((ret == 1) && (wolfssl_bn_set_value(&p->Y, point->y) != 1)) {
  8431. WOLFSSL_MSG("ecc point Y error");
  8432. ret = -1;
  8433. }
  8434. /* Set Z ordinate. */
  8435. if ((ret == 1) && (wolfssl_bn_set_value(&p->Z, point->z) != 1)) {
  8436. WOLFSSL_MSG("ecc point Z error");
  8437. ret = -1;
  8438. }
  8439. /* External values set when operations succeeded. */
  8440. p->exSet = (ret == 1);
  8441. }
  8442. return ret;
  8443. }
  8444. /* Setup internals of EC point.
  8445. *
  8446. * Assumes point is not NULL.
  8447. *
  8448. * @param [in, out] point EC point to update.
  8449. * @return 1 on success.
  8450. * @return 0 on failure.
  8451. */
  8452. static int ec_point_setup(const WOLFSSL_EC_POINT *point) {
  8453. int ret = 1;
  8454. /* Check if internal values need setting. */
  8455. if (!point->inSet) {
  8456. WOLFSSL_MSG("No ECPoint internal set, do it");
  8457. /* Forcing to non-constant type to update internals. */
  8458. if (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1) {
  8459. WOLFSSL_MSG("ec_point_internal_set failed");
  8460. ret = 0;
  8461. }
  8462. }
  8463. return ret;
  8464. }
  8465. /* Create a new EC point from the group.
  8466. *
  8467. * @param [in] group EC group.
  8468. * @return EC point on success.
  8469. * @return NULL on error.
  8470. */
  8471. WOLFSSL_EC_POINT* wolfSSL_EC_POINT_new(const WOLFSSL_EC_GROUP* group)
  8472. {
  8473. int err = 0;
  8474. WOLFSSL_EC_POINT* point = NULL;
  8475. WOLFSSL_ENTER("wolfSSL_EC_POINT_new");
  8476. /* Validate parameter. */
  8477. if (group == NULL) {
  8478. WOLFSSL_MSG("wolfSSL_EC_POINT_new NULL error");
  8479. err = 1;
  8480. }
  8481. if (!err) {
  8482. /* Allocate memory for new EC point. */
  8483. point = (WOLFSSL_EC_POINT*)XMALLOC(sizeof(WOLFSSL_EC_POINT), NULL,
  8484. DYNAMIC_TYPE_ECC);
  8485. if (point == NULL) {
  8486. WOLFSSL_MSG("wolfSSL_EC_POINT_new malloc ecc point failure");
  8487. err = 1;
  8488. }
  8489. }
  8490. if (!err) {
  8491. /* Clear fields of EC point. */
  8492. XMEMSET(point, 0, sizeof(WOLFSSL_EC_POINT));
  8493. /* Allocate internal EC point. */
  8494. point->internal = wc_ecc_new_point();
  8495. if (point->internal == NULL) {
  8496. WOLFSSL_MSG("ecc_new_point failure");
  8497. err = 1;
  8498. }
  8499. }
  8500. if (err) {
  8501. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8502. point = NULL;
  8503. }
  8504. return point;
  8505. }
  8506. #endif /* OPENSSL_EXTRA */
  8507. #if defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
  8508. /* Dispose of the EC point.
  8509. *
  8510. * Cannot use point after this call.
  8511. *
  8512. * @param [in, out] point EC point to free.
  8513. */
  8514. void wolfSSL_EC_POINT_free(WOLFSSL_EC_POINT *point)
  8515. {
  8516. WOLFSSL_ENTER("wolfSSL_EC_POINT_free");
  8517. if (point != NULL) {
  8518. if (point->internal != NULL) {
  8519. wc_ecc_del_point((ecc_point*)point->internal);
  8520. point->internal = NULL;
  8521. }
  8522. /* Free ordinates. */
  8523. wolfSSL_BN_free(point->X);
  8524. wolfSSL_BN_free(point->Y);
  8525. wolfSSL_BN_free(point->Z);
  8526. /* Clear fields. */
  8527. point->X = NULL;
  8528. point->Y = NULL;
  8529. point->Z = NULL;
  8530. point->inSet = 0;
  8531. point->exSet = 0;
  8532. /* Dispose of EC point. */
  8533. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8534. }
  8535. }
  8536. #endif /* OPENSSL_EXTRA || OPENSSL_EXTRA_X509_SMALL */
  8537. #ifdef OPENSSL_EXTRA
  8538. /* Clear and dispose of the EC point.
  8539. *
  8540. * Cannot use point after this call.
  8541. *
  8542. * @param [in, out] point EC point to free.
  8543. */
  8544. void wolfSSL_EC_POINT_clear_free(WOLFSSL_EC_POINT *point)
  8545. {
  8546. WOLFSSL_ENTER("wolfSSL_EC_POINT_clear_free");
  8547. if (point != NULL) {
  8548. if (point->internal != NULL) {
  8549. /* Force internal point to be zeros. */
  8550. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8551. wc_ecc_forcezero_point((ecc_point*)point->internal);
  8552. #else
  8553. ecc_point* p = (ecc_point*)point->internal;
  8554. mp_forcezero(p->x);
  8555. mp_forcezero(p->y);
  8556. mp_forcezero(p->z);
  8557. #endif
  8558. wc_ecc_del_point((ecc_point*)point->internal);
  8559. point->internal = NULL;
  8560. }
  8561. /* Clear the ordinates before freeing. */
  8562. wolfSSL_BN_clear_free(point->X);
  8563. wolfSSL_BN_clear_free(point->Y);
  8564. wolfSSL_BN_clear_free(point->Z);
  8565. /* Clear fields. */
  8566. point->X = NULL;
  8567. point->Y = NULL;
  8568. point->Z = NULL;
  8569. point->inSet = 0;
  8570. point->exSet = 0;
  8571. /* Dispose of EC point. */
  8572. XFREE(point, NULL, DYNAMIC_TYPE_ECC);
  8573. }
  8574. }
  8575. /* Print out the internals of EC point in debug and when logging callback set.
  8576. *
  8577. * Not an OpenSSL API.
  8578. *
  8579. * TODO: Use WOLFSSL_MSG_EX()?
  8580. *
  8581. * @param [in] msg Message to prepend.
  8582. * @param [in] point EC point to print.
  8583. */
  8584. void wolfSSL_EC_POINT_dump(const char *msg, const WOLFSSL_EC_POINT *point)
  8585. {
  8586. #if defined(DEBUG_WOLFSSL)
  8587. char *num;
  8588. WOLFSSL_ENTER("wolfSSL_EC_POINT_dump");
  8589. /* Only print when debugging on and logging callback set. */
  8590. if (WOLFSSL_IS_DEBUG_ON() && (wolfSSL_GetLoggingCb() == NULL)) {
  8591. if (point == NULL) {
  8592. /* No point passed in so just put out "NULL". */
  8593. XFPRINTF(stderr, "%s = NULL\n", msg);
  8594. }
  8595. else {
  8596. /* Put out message and status of internal/external data set. */
  8597. XFPRINTF(stderr, "%s:\n\tinSet=%d, exSet=%d\n", msg, point->inSet,
  8598. point->exSet);
  8599. /* Get x-ordinate as a hex string and print. */
  8600. num = wolfSSL_BN_bn2hex(point->X);
  8601. XFPRINTF(stderr, "\tX = %s\n", num);
  8602. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8603. /* Get x-ordinate as a hex string and print. */
  8604. num = wolfSSL_BN_bn2hex(point->Y);
  8605. XFPRINTF(stderr, "\tY = %s\n", num);
  8606. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8607. /* Get z-ordinate as a hex string and print. */
  8608. num = wolfSSL_BN_bn2hex(point->Z);
  8609. XFPRINTF(stderr, "\tZ = %s\n", num);
  8610. XFREE(num, NULL, DYNAMIC_TYPE_OPENSSL);
  8611. }
  8612. }
  8613. #else
  8614. (void)msg;
  8615. (void)point;
  8616. #endif
  8617. }
  8618. #ifndef HAVE_SELFTEST
  8619. /* Convert EC point to hex string that as either uncompressed or compressed.
  8620. *
  8621. * ECC point compression types were not included in selftest ecc.h
  8622. *
  8623. * @param [in] group EC group for point.
  8624. * @param [in] point EC point to encode.
  8625. * @param [in] form Format of encoding. Valid values:
  8626. * POINT_CONVERSION_UNCOMPRESSED, POINT_CONVERSION_COMPRESSED
  8627. * @param [in] ctx Context to use for BN operations. Unused.
  8628. * @return Allocated hex string on success.
  8629. * @return NULL on error.
  8630. */
  8631. char* wolfSSL_EC_POINT_point2hex(const WOLFSSL_EC_GROUP* group,
  8632. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BN_CTX* ctx)
  8633. {
  8634. static const char* hexDigit = "0123456789ABCDEF";
  8635. char* hex = NULL;
  8636. int i;
  8637. int sz = 0;
  8638. int len = 0;
  8639. int err = 0;
  8640. /* No BN operations performed. */
  8641. (void)ctx;
  8642. /* Validate parameters. */
  8643. if ((group == NULL) || (point == NULL)) {
  8644. err = 1;
  8645. }
  8646. /* Get curve id expects a positive index. */
  8647. if ((!err) && (group->curve_idx < 0)) {
  8648. err = 1;
  8649. }
  8650. if (!err) {
  8651. /* Get curve id to look up ordinate size. */
  8652. int id = wc_ecc_get_curve_id(group->curve_idx);
  8653. /* Get size of ordinate. */
  8654. if ((sz = wc_ecc_get_curve_size_from_id(id)) < 0) {
  8655. err = 1;
  8656. }
  8657. }
  8658. if (!err) {
  8659. /* <format byte> <x-ordinate> [<y-ordinate>] */
  8660. len = sz + 1;
  8661. if (form == POINT_CONVERSION_UNCOMPRESSED) {
  8662. /* Include y ordinate when uncompressed. */
  8663. len += sz;
  8664. }
  8665. /* Hex string: allocate 2 bytes to represent each byte plus 1 for '\0'.
  8666. */
  8667. hex = (char*)XMALLOC(2 * len + 1, NULL, DYNAMIC_TYPE_ECC);
  8668. if (hex == NULL) {
  8669. err = 1;
  8670. }
  8671. }
  8672. if (!err) {
  8673. /* Make bytes all zeros to allow for ordinate values less than max size.
  8674. */
  8675. XMEMSET(hex, 0, 2 * len + 1);
  8676. /* Calculate offset as leading zeros not encoded. */
  8677. i = sz - mp_unsigned_bin_size((mp_int*)point->X->internal) + 1;
  8678. /* Put in x-ordinate after format byte. */
  8679. if (mp_to_unsigned_bin((mp_int*)point->X->internal, (byte*)(hex + i)) <
  8680. 0) {
  8681. err = 1;
  8682. }
  8683. }
  8684. if (!err) {
  8685. if (form == POINT_CONVERSION_COMPRESSED) {
  8686. /* Compressed format byte value dependent on whether y-ordinate is
  8687. * odd.
  8688. */
  8689. hex[0] = mp_isodd((mp_int*)point->Y->internal) ?
  8690. ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN;
  8691. /* No y-ordinate. */
  8692. }
  8693. else {
  8694. /* Put in uncompressed format byte. */
  8695. hex[0] = ECC_POINT_UNCOMP;
  8696. /* Calculate offset as leading zeros not encoded. */
  8697. i = 1 + 2 * sz - mp_unsigned_bin_size((mp_int*)point->Y->internal);
  8698. /* Put in y-ordinate after x-ordinate. */
  8699. if (mp_to_unsigned_bin((mp_int*)point->Y->internal,
  8700. (byte*)(hex + i)) < 0) {
  8701. err = 1;
  8702. }
  8703. }
  8704. }
  8705. if (!err) {
  8706. /* Convert binary encoding to hex string. */
  8707. /* Start at end so as not to overwrite. */
  8708. for (i = len-1; i >= 0; i--) {
  8709. /* Get byte value and store has hex string. */
  8710. byte b = (byte)hex[i];
  8711. hex[i * 2 + 1] = hexDigit[b & 0xf];
  8712. hex[i * 2 ] = hexDigit[b >> 4];
  8713. }
  8714. /* Memset put trailing zero or '\0' on end of string. */
  8715. }
  8716. if (err && (hex != NULL)) {
  8717. /* Dispose of allocated data not being returned. */
  8718. XFREE(hex, NULL, DYNAMIC_TYPE_ECC);
  8719. hex = NULL;
  8720. }
  8721. /* Return hex string encoding. */
  8722. return hex;
  8723. }
  8724. #endif /* HAVE_SELFTEST */
  8725. /* Encode the EC point as an uncompressed point in DER.
  8726. *
  8727. * Return code compliant with OpenSSL.
  8728. * Not OpenSSL API.
  8729. *
  8730. * @param [in] group EC group point belongs to.
  8731. * @param [in] point EC point to encode.
  8732. * @param [out] out Buffer to encode into. May be NULL.
  8733. * @param [in, out] len On in, length of buffer in bytes.
  8734. * On out, length of encoding in bytes.
  8735. * @return 1 on success.
  8736. * @return 0 on error.
  8737. */
  8738. int wolfSSL_ECPoint_i2d(const WOLFSSL_EC_GROUP *group,
  8739. const WOLFSSL_EC_POINT *point, unsigned char *out, unsigned int *len)
  8740. {
  8741. int res = 1;
  8742. WOLFSSL_ENTER("wolfSSL_ECPoint_i2d");
  8743. /* Validate parameters. */
  8744. if ((group == NULL) || (point == NULL) || (len == NULL)) {
  8745. WOLFSSL_MSG("wolfSSL_ECPoint_i2d NULL error");
  8746. res = 0;
  8747. }
  8748. /* Ensure points internals are set up. */
  8749. if ((res == 1) && (ec_point_setup(point) != 1)) {
  8750. res = 0;
  8751. }
  8752. /* Dump the point if encoding. */
  8753. if ((res == 1) && (out != NULL)) {
  8754. wolfSSL_EC_POINT_dump("i2d p", point);
  8755. }
  8756. if (res == 1) {
  8757. /* DER encode point in uncompressed format. */
  8758. int ret = wc_ecc_export_point_der(group->curve_idx,
  8759. (ecc_point*)point->internal, out, len);
  8760. /* Check return. When out is NULL, return will be length only error. */
  8761. if ((ret != MP_OKAY) && ((out != NULL) || (ret != LENGTH_ONLY_E))) {
  8762. WOLFSSL_MSG("wolfSSL_ECPoint_i2d wc_ecc_export_point_der failed");
  8763. res = 0;
  8764. }
  8765. }
  8766. return res;
  8767. }
  8768. /* Decode the uncompressed point in DER into EC point.
  8769. *
  8770. * Return code compliant with OpenSSL.
  8771. * Not OpenSSL API.
  8772. *
  8773. * @param [in] in Buffer containing DER encoded point.
  8774. * @param [in] len Length of data in bytes.
  8775. * @param [in] group EC group associated with point.
  8776. * @param [in, out] point EC point to set data into.
  8777. * @return 1 on success.
  8778. * @return 0 on error.
  8779. */
  8780. int wolfSSL_ECPoint_d2i(const unsigned char *in, unsigned int len,
  8781. const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *point)
  8782. {
  8783. int ret = 1;
  8784. WOLFSSL_ENTER("wolfSSL_ECPoint_d2i");
  8785. /* Validate parameters. */
  8786. if ((in == NULL) || (group == NULL) || (point == NULL) ||
  8787. (point->internal == NULL)) {
  8788. WOLFSSL_MSG("wolfSSL_ECPoint_d2i NULL error");
  8789. ret = 0;
  8790. }
  8791. if (ret == 1) {
  8792. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8793. /* Import point into internal EC point. */
  8794. if (wc_ecc_import_point_der_ex(in, len, group->curve_idx,
  8795. (ecc_point*)point->internal, 0) != MP_OKAY) {
  8796. WOLFSSL_MSG("wc_ecc_import_point_der_ex failed");
  8797. ret = 0;
  8798. }
  8799. #else
  8800. /* ECC_POINT_UNCOMP is not defined CAVP self test so use magic number */
  8801. if (in[0] == 0x04) {
  8802. /* Import point into internal EC point. */
  8803. if (wc_ecc_import_point_der((unsigned char *)in, len,
  8804. group->curve_idx, (ecc_point*)point->internal) != MP_OKAY) {
  8805. WOLFSSL_MSG("wc_ecc_import_point_der failed");
  8806. ret = 0;
  8807. }
  8808. }
  8809. else {
  8810. WOLFSSL_MSG("Only uncompressed points supported with "
  8811. "HAVE_SELFTEST");
  8812. ret = 0;
  8813. }
  8814. #endif
  8815. }
  8816. /* Set new external point. */
  8817. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  8818. WOLFSSL_MSG("ec_point_external_set failed");
  8819. ret = 0;
  8820. }
  8821. if (ret == 1) {
  8822. /* Dump new point. */
  8823. wolfSSL_EC_POINT_dump("d2i p", point);
  8824. }
  8825. return ret;
  8826. }
  8827. /* Encode point as octet string.
  8828. *
  8829. * HYBRID not supported.
  8830. *
  8831. * @param [in] group EC group that point belongs to.
  8832. * @param [in] point EC point to encode.
  8833. * @param [in] form Format of encoding. Valid values:
  8834. * POINT_CONVERSION_UNCOMPRESSED,POINT_CONVERSION_COMPRESSED
  8835. * @param [out] buf Buffer to write encoding into.
  8836. * @param [in] len Length of buffer.
  8837. * @param [in] ctx Context to use for BN operations. Unused.
  8838. * @return Length of encoded data on success.
  8839. * @return 0 on error.
  8840. */
  8841. size_t wolfSSL_EC_POINT_point2oct(const WOLFSSL_EC_GROUP *group,
  8842. const WOLFSSL_EC_POINT *point, int form, byte *buf, size_t len,
  8843. WOLFSSL_BN_CTX *ctx)
  8844. {
  8845. int err = 0;
  8846. word32 enc_len = (word32)len;
  8847. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8848. int compressed = ((form == POINT_CONVERSION_COMPRESSED) ? 1 : 0);
  8849. #endif /* !HAVE_SELFTEST */
  8850. WOLFSSL_ENTER("wolfSSL_EC_POINT_point2oct");
  8851. /* No BN operations performed. */
  8852. (void)ctx;
  8853. /* Validate parameters. */
  8854. if ((group == NULL) || (point == NULL)) {
  8855. err = 1;
  8856. }
  8857. /* Ensure points internals are set up. */
  8858. if ((!err) && (ec_point_setup(point) != 1)) {
  8859. err = 1;
  8860. }
  8861. /* Special case when point is infinity. */
  8862. if ((!err) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  8863. /* Encoding is a single octet: 0x00. */
  8864. enc_len = 1;
  8865. if (buf != NULL) {
  8866. /* Check whether buffer has space. */
  8867. if (len < 1) {
  8868. ECerr(EC_F_EC_GFP_SIMPLE_POINT2OCT, EC_R_BUFFER_TOO_SMALL);
  8869. err = 1;
  8870. }
  8871. else {
  8872. /* Put in encoding of infinity. */
  8873. buf[0] = 0x00;
  8874. }
  8875. }
  8876. }
  8877. /* Not infinity. */
  8878. else if (!err) {
  8879. /* Validate format. */
  8880. if (form != POINT_CONVERSION_UNCOMPRESSED
  8881. #ifndef HAVE_SELFTEST
  8882. && form != POINT_CONVERSION_COMPRESSED
  8883. #endif /* !HAVE_SELFTEST */
  8884. ) {
  8885. WOLFSSL_MSG("Unsupported point form");
  8886. err = 1;
  8887. }
  8888. if (!err) {
  8889. int ret;
  8890. #if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8891. /* Encode as compressed or uncompressed. */
  8892. ret = wc_ecc_export_point_der_ex(group->curve_idx,
  8893. (ecc_point*)point->internal, buf, &enc_len, compressed);
  8894. #else
  8895. /* Encode uncompressed point in DER format. */
  8896. ret = wc_ecc_export_point_der(group->curve_idx,
  8897. (ecc_point*)point->internal, buf, &enc_len);
  8898. #endif /* !HAVE_SELFTEST */
  8899. /* Check return. When buf is NULL, return will be length only
  8900. * error.
  8901. */
  8902. if (ret != ((buf != NULL) ? MP_OKAY : LENGTH_ONLY_E)) {
  8903. err = 1;
  8904. }
  8905. }
  8906. }
  8907. /* On error, return encoding length of 0. */
  8908. if (err) {
  8909. enc_len = 0;
  8910. }
  8911. return (size_t)enc_len;
  8912. }
  8913. /* Convert octet string to EC point.
  8914. *
  8915. * @param [in] group EC group.
  8916. * @param [in, out] point EC point to set data into.
  8917. * @param [in] buf Buffer holding octet string.
  8918. * @param [in] len Length of data in buffer in bytes.
  8919. * @param [in] ctx Context to use for BN operations. Unused.
  8920. */
  8921. int wolfSSL_EC_POINT_oct2point(const WOLFSSL_EC_GROUP *group,
  8922. WOLFSSL_EC_POINT *point, const unsigned char *buf, size_t len,
  8923. WOLFSSL_BN_CTX *ctx)
  8924. {
  8925. int ret;
  8926. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  8927. /* No BN operations performed. */
  8928. (void)ctx;
  8929. /* Validate parameters. */
  8930. if ((group == NULL) || (point == NULL)) {
  8931. ret = 0;
  8932. }
  8933. else {
  8934. /* Decode DER encoding into EC point. */
  8935. ret = wolfSSL_ECPoint_d2i((unsigned char*)buf, (unsigned int)len, group,
  8936. point);
  8937. }
  8938. return ret;
  8939. }
  8940. /* Convert an EC point to a single BN.
  8941. *
  8942. * @param [in] group EC group.
  8943. * @param [in] point EC point.
  8944. * @param [in] form Format of encoding. Valid values:
  8945. * POINT_CONVERSION_UNCOMPRESSED,
  8946. * POINT_CONVERSION_COMPRESSED.
  8947. * @param [in, out] bn BN to hold point value.
  8948. * When NULL a new BN is allocated otherwise this is
  8949. * returned on success.
  8950. * @param [in] ctx Context to use for BN operations. Unused.
  8951. * @return BN object with point as a value on success.
  8952. * @return NULL on error.
  8953. */
  8954. WOLFSSL_BIGNUM *wolfSSL_EC_POINT_point2bn(const WOLFSSL_EC_GROUP* group,
  8955. const WOLFSSL_EC_POINT* point, int form, WOLFSSL_BIGNUM* bn,
  8956. WOLFSSL_BN_CTX* ctx)
  8957. {
  8958. int err = 0;
  8959. size_t len = 0;
  8960. byte *buf = NULL;
  8961. WOLFSSL_BIGNUM *ret = NULL;
  8962. WOLFSSL_ENTER("wolfSSL_EC_POINT_oct2point");
  8963. /* Validate parameters. */
  8964. if ((group == NULL) || (point == NULL)) {
  8965. err = 1;
  8966. }
  8967. /* Calculate length of octet encoding. */
  8968. if ((!err) && ((len = wolfSSL_EC_POINT_point2oct(group, point, form, NULL,
  8969. 0, ctx)) == 0)) {
  8970. err = 1;
  8971. }
  8972. /* Allocate buffer to hold octet encoding. */
  8973. if ((!err) && ((buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER)) ==
  8974. NULL)) {
  8975. WOLFSSL_MSG("malloc failed");
  8976. err = 1;
  8977. }
  8978. /* Encode EC point as an octet string. */
  8979. if ((!err) && (wolfSSL_EC_POINT_point2oct(group, point, form, buf, len,
  8980. ctx) != len)) {
  8981. err = 1;
  8982. }
  8983. /* Load BN with octet string data. */
  8984. if (!err) {
  8985. ret = wolfSSL_BN_bin2bn(buf, (int)len, bn);
  8986. }
  8987. /* Dispose of any allocated data. */
  8988. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  8989. return ret;
  8990. }
  8991. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  8992. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  8993. /* Check if EC point is on the the curve defined by the EC group.
  8994. *
  8995. * @param [in] group EC group defining curve.
  8996. * @param [in] point EC point to check.
  8997. * @param [in] ctx Context to use for BN operations. Unused.
  8998. * @return 1 when point is on curve.
  8999. * @return 0 when point is not on curve or error.
  9000. */
  9001. int wolfSSL_EC_POINT_is_on_curve(const WOLFSSL_EC_GROUP *group,
  9002. const WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9003. {
  9004. int err = 0;
  9005. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_on_curve");
  9006. /* No BN operations performed. */
  9007. (void)ctx;
  9008. /* Validate parameters. */
  9009. if ((group == NULL) || (point == NULL)) {
  9010. WOLFSSL_MSG("Invalid arguments");
  9011. err = 1;
  9012. }
  9013. /* Ensure internal EC point set. */
  9014. if ((!err) && (!point->inSet) && ec_point_internal_set(
  9015. (WOLFSSL_EC_POINT*)point) != 1) {
  9016. WOLFSSL_MSG("ec_point_internal_set error");
  9017. err = 1;
  9018. }
  9019. /* Check point is on curve from group. */
  9020. if ((!err) && (wc_ecc_point_is_on_curve((ecc_point*)point->internal,
  9021. group->curve_idx) != MP_OKAY)) {
  9022. err = 1;
  9023. }
  9024. /* Return boolean of on curve. No error means on curve. */
  9025. return !err;
  9026. }
  9027. #endif /* USE_ECC_B_PARAM && !HAVE_SELFTEST && !(FIPS_VERSION <= 2) */
  9028. #if !defined(WOLFSSL_SP_MATH) && !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9029. /* Convert Jacobian ordinates to affine.
  9030. *
  9031. * @param [in] group EC group.
  9032. * @param [in] point EC point to get co-ordinates from.
  9033. * @return 1 on success.
  9034. * @return 0 on error.
  9035. */
  9036. static int ec_point_convert_to_affine(const WOLFSSL_EC_GROUP *group,
  9037. WOLFSSL_EC_POINT *point)
  9038. {
  9039. int err = 0;
  9040. mp_digit mp;
  9041. #ifdef WOLFSSL_SMALL_STACK
  9042. mp_int* modulus;
  9043. #else
  9044. mp_int modulus[1];
  9045. #endif
  9046. #ifdef WOLFSSL_SMALL_STACK
  9047. /* Allocate memory for curve's prime modulus. */
  9048. modulus = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9049. if (modulus == NULL) {
  9050. err = 1;
  9051. }
  9052. #endif
  9053. /* Initialize the MP integer. */
  9054. if ((!err) && (mp_init(modulus) != MP_OKAY)) {
  9055. WOLFSSL_MSG("mp_init failed");
  9056. err = 1;
  9057. }
  9058. if (!err) {
  9059. /* Get the modulus from the hex string in the EC curve set. */
  9060. if (mp_read_radix(modulus, ecc_sets[group->curve_idx].prime,
  9061. MP_RADIX_HEX) != MP_OKAY) {
  9062. WOLFSSL_MSG("mp_read_radix failed");
  9063. err = 1;
  9064. }
  9065. /* Get Montgomery multiplier for the modulus as ordinates in
  9066. * Montgomery form.
  9067. */
  9068. if ((!err) && (mp_montgomery_setup(modulus, &mp) != MP_OKAY)) {
  9069. WOLFSSL_MSG("mp_montgomery_setup failed");
  9070. err = 1;
  9071. }
  9072. /* Map internal EC point from Jacobian to affine. */
  9073. if ((!err) && (ecc_map((ecc_point*)point->internal, modulus, mp) !=
  9074. MP_OKAY)) {
  9075. WOLFSSL_MSG("ecc_map failed");
  9076. err = 1;
  9077. }
  9078. /* Set new ordinates into external EC point. */
  9079. if ((!err) && (ec_point_external_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9080. WOLFSSL_MSG("ec_point_external_set failed");
  9081. err = 1;
  9082. }
  9083. point->exSet = !err;
  9084. mp_clear(modulus);
  9085. }
  9086. #ifdef WOLFSSL_SMALL_STACK
  9087. XFREE(modulus, NULL, DYNAMIC_TYPE_BIGINT);
  9088. #endif
  9089. return err;
  9090. }
  9091. /* Get the affine co-ordinates of the EC point on a Prime curve.
  9092. *
  9093. * When z-ordinate is not one then co-ordinates are Jacobian and need to be
  9094. * converted to affine before storing in BNs.
  9095. *
  9096. * Return code compliant with OpenSSL.
  9097. *
  9098. * TODO: OpenSSL doesn't change point when Jacobian. Do the same?
  9099. *
  9100. * @param [in] group EC group.
  9101. * @param [in] point EC point to get co-ordinates from.
  9102. * @param [in, out] x BN to hold x-ordinate.
  9103. * @param [in, out] y BN to hold y-ordinate.
  9104. * @param [in] ctx Context to use for BN operations. Unused.
  9105. * @return 1 on success.
  9106. * @return 0 on error.
  9107. */
  9108. int wolfSSL_EC_POINT_get_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9109. const WOLFSSL_EC_POINT* point, WOLFSSL_BIGNUM* x, WOLFSSL_BIGNUM* y,
  9110. WOLFSSL_BN_CTX* ctx)
  9111. {
  9112. int ret = 1;
  9113. /* BN operations don't need context. */
  9114. (void)ctx;
  9115. WOLFSSL_ENTER("wolfSSL_EC_POINT_get_affine_coordinates_GFp");
  9116. /* Validate parameters. */
  9117. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9118. (x == NULL) || (y == NULL)) {
  9119. WOLFSSL_MSG("wolfSSL_EC_POINT_get_affine_coordinates_GFp NULL error");
  9120. ret = 0;
  9121. }
  9122. /* Don't return point at infinity. */
  9123. if ((ret == 1) && wolfSSL_EC_POINT_is_at_infinity(group, point)) {
  9124. ret = 0;
  9125. }
  9126. /* Ensure internal EC point has values of external EC point. */
  9127. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9128. ret = 0;
  9129. }
  9130. /* Check whether ordinates are in Jacobian form. */
  9131. if ((ret == 1) && (!wolfSSL_BN_is_one(point->Z))) {
  9132. /* Convert from Jacobian to affine. */
  9133. if (ec_point_convert_to_affine(group, (WOLFSSL_EC_POINT*)point) == 1) {
  9134. ret = 0;
  9135. }
  9136. }
  9137. /* Copy the externally set x and y ordinates. */
  9138. if ((ret == 1) && (BN_copy(x, point->X) == NULL)) {
  9139. ret = 0;
  9140. }
  9141. if ((ret == 1) && (BN_copy(y, point->Y) == NULL)) {
  9142. ret = 0;
  9143. }
  9144. return ret;
  9145. }
  9146. #endif /* !WOLFSSL_SP_MATH && !WOLF_CRYPTO_CB_ONLY_ECC */
  9147. /* Sets the affine co-ordinates that belong on a prime curve.
  9148. *
  9149. * @param [in] group EC group.
  9150. * @param [in, out] point EC point to set co-ordinates into.
  9151. * @param [in] x BN holding x-ordinate.
  9152. * @param [in] y BN holding y-ordinate.
  9153. * @param [in] ctx Context to use for BN operations. Unused.
  9154. * @return 1 on success.
  9155. * @return 0 on error.
  9156. */
  9157. int wolfSSL_EC_POINT_set_affine_coordinates_GFp(const WOLFSSL_EC_GROUP* group,
  9158. WOLFSSL_EC_POINT* point, const WOLFSSL_BIGNUM* x, const WOLFSSL_BIGNUM* y,
  9159. WOLFSSL_BN_CTX* ctx)
  9160. {
  9161. int ret = 1;
  9162. /* BN operations don't need context. */
  9163. (void)ctx;
  9164. WOLFSSL_ENTER("wolfSSL_EC_POINT_set_affine_coordinates_GFp");
  9165. /* Validate parameters. */
  9166. if ((group == NULL) || (point == NULL) || (point->internal == NULL) ||
  9167. (x == NULL) || (y == NULL)) {
  9168. WOLFSSL_MSG("wolfSSL_EC_POINT_set_affine_coordinates_GFp NULL error");
  9169. ret = 0;
  9170. }
  9171. /* Ensure we have a object for x-ordinate. */
  9172. if ((ret == 1) && (point->X == NULL) &&
  9173. ((point->X = wolfSSL_BN_new()) == NULL)) {
  9174. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9175. ret = 0;
  9176. }
  9177. /* Ensure we have a object for y-ordinate. */
  9178. if ((ret == 1) && (point->Y == NULL) &&
  9179. ((point->Y = wolfSSL_BN_new()) == NULL)) {
  9180. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9181. ret = 0;
  9182. }
  9183. /* Ensure we have a object for z-ordinate. */
  9184. if ((ret == 1) && (point->Z == NULL) &&
  9185. ((point->Z = wolfSSL_BN_new()) == NULL)) {
  9186. WOLFSSL_MSG("wolfSSL_BN_new failed");
  9187. ret = 0;
  9188. }
  9189. /* Copy the x-ordinate. */
  9190. if ((ret == 1) && ((wolfSSL_BN_copy(point->X, x)) == NULL)) {
  9191. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9192. ret = 0;
  9193. }
  9194. /* Copy the y-ordinate. */
  9195. if ((ret == 1) && ((wolfSSL_BN_copy(point->Y, y)) == NULL)) {
  9196. WOLFSSL_MSG("wolfSSL_BN_copy failed");
  9197. ret = 0;
  9198. }
  9199. /* z-ordinate is one for affine co-ordinates. */
  9200. if ((ret == 1) && ((wolfSSL_BN_one(point->Z)) == 0)) {
  9201. WOLFSSL_MSG("wolfSSL_BN_one failed");
  9202. ret = 0;
  9203. }
  9204. /* Copy the new point data to internal object. */
  9205. if ((ret == 1) && (ec_point_internal_set((WOLFSSL_EC_POINT *)point) != 1)) {
  9206. WOLFSSL_MSG("ec_point_internal_set failed");
  9207. ret = 0;
  9208. }
  9209. #if defined(USE_ECC_B_PARAM) && !defined(HAVE_SELFTEST) && \
  9210. (!defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0))
  9211. /* Check that the point is valid. */
  9212. if ((ret == 1) && (wolfSSL_EC_POINT_is_on_curve(group,
  9213. (WOLFSSL_EC_POINT *)point, ctx) != 1)) {
  9214. WOLFSSL_MSG("EC_POINT_is_on_curve failed");
  9215. ret = 0;
  9216. }
  9217. #endif
  9218. return ret;
  9219. }
  9220. #if !defined(WOLFSSL_ATECC508A) && !defined(WOLFSSL_ATECC608A) && \
  9221. !defined(HAVE_SELFTEST) && !defined(WOLFSSL_SP_MATH) && \
  9222. !defined(WOLF_CRYPTO_CB_ONLY_ECC)
  9223. /* Add two points on the same together.
  9224. *
  9225. * @param [in] curveIdx Index of curve in ecc_set.
  9226. * @oaram [out] r Result point.
  9227. * @param [in] p1 First point to add.
  9228. * @param [in] p2 Second point to add.
  9229. * @return 1 on success.
  9230. * @return 0 on error.
  9231. */
  9232. static int wolfssl_ec_point_add(int curveIdx, ecc_point* r, ecc_point* p1,
  9233. ecc_point* p2)
  9234. {
  9235. int ret = 1;
  9236. #ifdef WOLFSSL_SMALL_STACK
  9237. mp_int* a = NULL;
  9238. mp_int* prime = NULL;
  9239. mp_int* mu = NULL;
  9240. #else
  9241. mp_int a[1];
  9242. mp_int prime[1];
  9243. mp_int mu[1];
  9244. #endif
  9245. mp_digit mp = 0;
  9246. ecc_point* montP1 = NULL;
  9247. ecc_point* montP2 = NULL;
  9248. #ifdef WOLFSSL_SMALL_STACK
  9249. if (ret == 1) {
  9250. /* Allocate memory for curve parameter: a. */
  9251. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9252. if (a == NULL) {
  9253. WOLFSSL_MSG("Failed to allocate memory for mp_int a");
  9254. ret = 0;
  9255. }
  9256. }
  9257. if (ret == 1) {
  9258. /* Allocate memory for curve parameter: prime. */
  9259. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9260. if (prime == NULL) {
  9261. WOLFSSL_MSG("Failed to allocate memory for mp_int prime");
  9262. ret = 0;
  9263. }
  9264. }
  9265. if (ret == 1) {
  9266. /* Allocate memory for mu (Montgomery normalizer). */
  9267. mu = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9268. if (mu == NULL) {
  9269. WOLFSSL_MSG("Failed to allocate memory for mp_int mu");
  9270. ret = 0;
  9271. }
  9272. }
  9273. if (ret == 1) {
  9274. /* Zero out all MP int data in case initialization fails. */
  9275. XMEMSET(a, 0, sizeof(mp_int));
  9276. XMEMSET(prime, 0, sizeof(mp_int));
  9277. XMEMSET(mu, 0, sizeof(mp_int));
  9278. }
  9279. #endif
  9280. /* Initialize the MP ints. */
  9281. if ((ret == 1) && (mp_init_multi(prime, a, mu, NULL, NULL, NULL) !=
  9282. MP_OKAY)) {
  9283. WOLFSSL_MSG("mp_init_multi error");
  9284. ret = 0;
  9285. }
  9286. /* Read the curve parameter: a. */
  9287. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af, MP_RADIX_HEX) !=
  9288. MP_OKAY)) {
  9289. WOLFSSL_MSG("mp_read_radix a error");
  9290. ret = 0;
  9291. }
  9292. /* Read the curve parameter: prime. */
  9293. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9294. MP_RADIX_HEX) != MP_OKAY)) {
  9295. WOLFSSL_MSG("mp_read_radix prime error");
  9296. ret = 0;
  9297. }
  9298. /* Calculate the Montgomery product. */
  9299. if ((ret == 1) && (mp_montgomery_setup(prime, &mp) != MP_OKAY)) {
  9300. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9301. ret = 0;
  9302. }
  9303. /* TODO: use the heap filed of one of the points? */
  9304. /* Allocate new points to hold the Montgomery form values. */
  9305. if ((ret == 1) && (((montP1 = wc_ecc_new_point_h(NULL)) == NULL) ||
  9306. ((montP2 = wc_ecc_new_point_h(NULL)) == NULL))) {
  9307. WOLFSSL_MSG("wc_ecc_new_point_h nqm error");
  9308. ret = 0;
  9309. }
  9310. /* Calculate the Montgomery normalizer. */
  9311. if ((ret == 1) && (mp_montgomery_calc_normalization(mu, prime) !=
  9312. MP_OKAY)) {
  9313. WOLFSSL_MSG("mp_montgomery_calc_normalization error");
  9314. ret = 0;
  9315. }
  9316. /* Convert to Montgomery form. */
  9317. if ((ret == 1) && (mp_cmp_d(mu, 1) == MP_EQ)) {
  9318. /* Copy the points if the normalizer is 1. */
  9319. if ((wc_ecc_copy_point(p1, montP1) != MP_OKAY) ||
  9320. (wc_ecc_copy_point(p2, montP2) != MP_OKAY)) {
  9321. WOLFSSL_MSG("wc_ecc_copy_point error");
  9322. ret = 0;
  9323. }
  9324. }
  9325. else if (ret == 1) {
  9326. /* Multiply each ordinate by the Montgomery normalizer. */
  9327. if ((mp_mulmod(p1->x, mu, prime, montP1->x) != MP_OKAY) ||
  9328. (mp_mulmod(p1->y, mu, prime, montP1->y) != MP_OKAY) ||
  9329. (mp_mulmod(p1->z, mu, prime, montP1->z) != MP_OKAY)) {
  9330. WOLFSSL_MSG("mp_mulmod error");
  9331. ret = 0;
  9332. }
  9333. /* Multiply each ordinate by the Montgomery normalizer. */
  9334. if ((mp_mulmod(p2->x, mu, prime, montP2->x) != MP_OKAY) ||
  9335. (mp_mulmod(p2->y, mu, prime, montP2->y) != MP_OKAY) ||
  9336. (mp_mulmod(p2->z, mu, prime, montP2->z) != MP_OKAY)) {
  9337. WOLFSSL_MSG("mp_mulmod error");
  9338. ret = 0;
  9339. }
  9340. }
  9341. /* Perform point addition with internal EC point objects - Jacobian form
  9342. * result.
  9343. */
  9344. if ((ret == 1) && (ecc_projective_add_point(montP1, montP2, r, a, prime,
  9345. mp) != MP_OKAY)) {
  9346. WOLFSSL_MSG("ecc_projective_add_point error");
  9347. ret = 0;
  9348. }
  9349. /* Map point back to affine co-ordinates. Converts from Montogomery form. */
  9350. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9351. WOLFSSL_MSG("ecc_map error");
  9352. ret = 0;
  9353. }
  9354. /* Dispose of allocated memory. */
  9355. mp_clear(a);
  9356. mp_clear(prime);
  9357. mp_clear(mu);
  9358. wc_ecc_del_point_h(montP1, NULL);
  9359. wc_ecc_del_point_h(montP2, NULL);
  9360. #ifdef WOLFSSL_SMALL_STACK
  9361. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9362. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9363. XFREE(mu, NULL, DYNAMIC_TYPE_BIGINT);
  9364. #endif
  9365. return ret;
  9366. }
  9367. /* Add two points on the same curve together.
  9368. *
  9369. * @param [in] group EC group.
  9370. * @param [out] r EC point that is result of point addition.
  9371. * @param [in] p1 First EC point to add.
  9372. * @param [in] p2 Second EC point to add.
  9373. * @param [in] ctx Context to use for BN operations. Unused.
  9374. * @return 1 on success.
  9375. * @return 0 on error.
  9376. */
  9377. int wolfSSL_EC_POINT_add(const WOLFSSL_EC_GROUP* group, WOLFSSL_EC_POINT* r,
  9378. const WOLFSSL_EC_POINT* p1, const WOLFSSL_EC_POINT* p2, WOLFSSL_BN_CTX* ctx)
  9379. {
  9380. int ret = 1;
  9381. /* No BN operations performed. */
  9382. (void)ctx;
  9383. /* Validate parameters. */
  9384. if ((group == NULL) || (r == NULL) || (p1 == NULL) || (p2 == NULL)) {
  9385. WOLFSSL_MSG("wolfSSL_EC_POINT_add error");
  9386. ret = 0;
  9387. }
  9388. /* Ensure the internal objects of the EC points are setup. */
  9389. if ((ret == 1) && ((ec_point_setup(r) != 1) || (ec_point_setup(p1) != 1) ||
  9390. (ec_point_setup(p2) != 1))) {
  9391. WOLFSSL_MSG("ec_point_setup error");
  9392. ret = 0;
  9393. }
  9394. if (ret == 1) {
  9395. /* Add points using wolfCrypt objects. */
  9396. ret = wolfssl_ec_point_add(group->curve_idx, (ecc_point*)r->internal,
  9397. (ecc_point*)p1->internal, (ecc_point*)p2->internal);
  9398. }
  9399. /* Copy internal EC point values out to external EC point. */
  9400. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9401. WOLFSSL_MSG("ec_point_external_set error");
  9402. ret = 0;
  9403. }
  9404. return ret;
  9405. }
  9406. /* Sum the scalar multiplications of the base point and n, and q and m.
  9407. *
  9408. * r = base point * n + q * m
  9409. *
  9410. * @param [out] r EC point that is result of operation.
  9411. * @param [in] b Base point of curve.
  9412. * @param [in] n Scalar to multiply by base point.
  9413. * @param [in] q EC point to be scalar multiplied.
  9414. * @param [in] m Scalar to multiply q by.
  9415. * @param [in] a Parameter A of curve.
  9416. * @param [in] prime Prime (modulus) of curve.
  9417. * @return 1 on success.
  9418. * @return 0 on error.
  9419. */
  9420. static int ec_mul2add(ecc_point* r, ecc_point* b, mp_int* n, ecc_point* q,
  9421. mp_int* m, mp_int* a, mp_int* prime)
  9422. {
  9423. int ret = 1;
  9424. #if defined(ECC_SHAMIR) && !defined(WOLFSSL_KCAPI_ECC)
  9425. if (ecc_mul2add(b, n, q, m, r, a, prime, NULL) != MP_OKAY) {
  9426. WOLFSSL_MSG("ecc_mul2add error");
  9427. ret = 0;
  9428. }
  9429. #else
  9430. ecc_point* tmp = NULL;
  9431. mp_digit mp = 0;
  9432. /* Calculate Montgomery product. */
  9433. if (mp_montgomery_setup(prime, &mp) != MP_OKAY) {
  9434. WOLFSSL_MSG("mp_montgomery_setup nqm error");
  9435. ret = 0;
  9436. }
  9437. /* Create temporary point to hold: q * m */
  9438. if ((ret == 1) && ((tmp = wc_ecc_new_point()) == NULL)) {
  9439. WOLFSSL_MSG("wolfSSL_EC_POINT_new nqm error");
  9440. ret = 0;
  9441. }
  9442. /* r = base point * n */
  9443. if ((ret == 1) && (wc_ecc_mulmod(n, b, r, a, prime, 0) !=
  9444. MP_OKAY)) {
  9445. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9446. ret = 0;
  9447. }
  9448. /* tmp = q * m */
  9449. if ((ret == 1) && (wc_ecc_mulmod(m, q, tmp, a, prime, 0) != MP_OKAY)) {
  9450. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9451. ret = 0;
  9452. }
  9453. /* r = r + tmp */
  9454. if ((ret == 1) && (ecc_projective_add_point(tmp, r, r, a, prime, mp) !=
  9455. MP_OKAY)) {
  9456. WOLFSSL_MSG("wc_ecc_mulmod nqm error");
  9457. ret = 0;
  9458. }
  9459. /* Map point back to affine co-ordinates. Converts from Montogomery
  9460. * form. */
  9461. if ((ret == 1) && (ecc_map(r, prime, mp) != MP_OKAY)) {
  9462. WOLFSSL_MSG("ecc_map nqm error");
  9463. ret = 0;
  9464. }
  9465. /* Dispose of allocated temporary point. */
  9466. wc_ecc_del_point(tmp);
  9467. #endif
  9468. return ret;
  9469. }
  9470. /* Sum the scalar multiplications of the base point and n, and q and m.
  9471. *
  9472. * r = base point * n + q * m
  9473. *
  9474. * @param [in] curveIdx Index of curve in ecc_set.
  9475. * @param [out] r EC point that is result of operation.
  9476. * @param [in] n Scalar to multiply by base point. May be NULL.
  9477. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9478. * @param [in] m Scalar to multiply q by. May be NULL.
  9479. * @return 1 on success.
  9480. * @return 0 on error.
  9481. */
  9482. static int wolfssl_ec_point_mul(int curveIdx, ecc_point* r, mp_int* n,
  9483. ecc_point* q, mp_int* m)
  9484. {
  9485. int ret = 1;
  9486. #ifdef WOLFSSL_SMALL_STACK
  9487. mp_int* a = NULL;
  9488. mp_int* prime = NULL;
  9489. #else
  9490. mp_int a[1], prime[1];
  9491. #endif
  9492. #ifdef WOLFSSL_SMALL_STACK
  9493. /* Allocate MP integer for curve parameter: a. */
  9494. a = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9495. if (a == NULL) {
  9496. ret = 0;
  9497. }
  9498. if (ret == 1) {
  9499. /* Allocate MP integer for curve parameter: prime. */
  9500. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9501. if (prime == NULL) {
  9502. ret = 0;
  9503. }
  9504. }
  9505. #endif
  9506. /* Initialize the MP ints. */
  9507. if ((ret == 1) && (mp_init_multi(prime, a, NULL, NULL, NULL, NULL) !=
  9508. MP_OKAY)) {
  9509. WOLFSSL_MSG("mp_init_multi error");
  9510. ret = 0;
  9511. }
  9512. /* Read the curve parameter: prime. */
  9513. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9514. MP_RADIX_HEX) != MP_OKAY)) {
  9515. WOLFSSL_MSG("mp_read_radix prime error");
  9516. ret = 0;
  9517. }
  9518. /* Read the curve parameter: a. */
  9519. if ((ret == 1) && (mp_read_radix(a, ecc_sets[curveIdx].Af,
  9520. MP_RADIX_HEX) != MP_OKAY)) {
  9521. WOLFSSL_MSG("mp_read_radix a error");
  9522. ret = 0;
  9523. }
  9524. if ((ret == 1) && (n != NULL)) {
  9525. /* Get generator - base point. */
  9526. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  9527. if ((ret == 1) && (wc_ecc_get_generator(r, curveIdx) != MP_OKAY)) {
  9528. WOLFSSL_MSG("wc_ecc_get_generator error");
  9529. ret = 0;
  9530. }
  9531. #else
  9532. /* wc_ecc_get_generator is not defined in the FIPS v2 module. */
  9533. /* Read generator (base point) x-ordinate. */
  9534. if ((ret == 1) && (mp_read_radix(r->x, ecc_sets[curveIdx].Gx,
  9535. MP_RADIX_HEX) != MP_OKAY)) {
  9536. WOLFSSL_MSG("mp_read_radix Gx error");
  9537. ret = 0;
  9538. }
  9539. /* Read generator (base point) y-ordinate. */
  9540. if ((ret == 1) && (mp_read_radix(r->y, ecc_sets[curveIdx].Gy,
  9541. MP_RADIX_HEX) != MP_OKAY)) {
  9542. WOLFSSL_MSG("mp_read_radix Gy error");
  9543. ret = 0;
  9544. }
  9545. /* z-ordinate is one as point is affine. */
  9546. if ((ret == 1) && (mp_set(r->z, 1) != MP_OKAY)) {
  9547. WOLFSSL_MSG("mp_set Gz error");
  9548. ret = 0;
  9549. }
  9550. #endif /* NOPT_FIPS_VERSION == 2 */
  9551. }
  9552. if ((ret == 1) && (n != NULL) && (q != NULL) && (m != NULL)) {
  9553. /* r = base point * n + q * m */
  9554. ec_mul2add(r, r, m, q, n, a, prime);
  9555. }
  9556. /* Not all values present, see if we are only doing base point * n. */
  9557. else if ((ret == 1) && (n != NULL)) {
  9558. /* r = base point * n */
  9559. if (wc_ecc_mulmod(n, r, r, a, prime, 1) != MP_OKAY) {
  9560. WOLFSSL_MSG("wc_ecc_mulmod gn error");
  9561. ret = 0;
  9562. }
  9563. }
  9564. /* Not all values present, see if we are only doing q * m. */
  9565. else if ((ret == 1) && (q != NULL) && (m != NULL)) {
  9566. /* r = q * m */
  9567. if (wc_ecc_mulmod(m, q, r, a, prime, 1) != MP_OKAY) {
  9568. WOLFSSL_MSG("wc_ecc_mulmod qm error");
  9569. ret = 0;
  9570. }
  9571. }
  9572. /* No values to use. */
  9573. else if (ret == 1) {
  9574. /* Set result to infinity as no values passed in. */
  9575. mp_zero(r->x);
  9576. mp_zero(r->y);
  9577. mp_zero(r->z);
  9578. }
  9579. mp_clear(a);
  9580. mp_clear(prime);
  9581. #ifdef WOLFSSL_SMALL_STACK
  9582. XFREE(a, NULL, DYNAMIC_TYPE_BIGINT);
  9583. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9584. #endif
  9585. return ret;
  9586. }
  9587. /* Sum the scalar multiplications of the base point and n, and q and m.
  9588. *
  9589. * r = base point * n + q * m
  9590. *
  9591. * Return code compliant with OpenSSL.
  9592. *
  9593. * @param [in] group EC group.
  9594. * @param [out] r EC point that is result of operation.
  9595. * @param [in] n Scalar to multiply by base point. May be NULL.
  9596. * @param [in] q EC point to be scalar multiplied. May be NULL.
  9597. * @param [in] m Scalar to multiply q by. May be NULL.
  9598. * @param [in] ctx Context to use for BN operations. Unused.
  9599. * @return 1 on success.
  9600. * @return 0 on error.
  9601. */
  9602. int wolfSSL_EC_POINT_mul(const WOLFSSL_EC_GROUP *group, WOLFSSL_EC_POINT *r,
  9603. const WOLFSSL_BIGNUM *n, const WOLFSSL_EC_POINT *q, const WOLFSSL_BIGNUM *m,
  9604. WOLFSSL_BN_CTX *ctx)
  9605. {
  9606. int ret = 1;
  9607. /* No BN operations performed. */
  9608. (void)ctx;
  9609. WOLFSSL_ENTER("wolfSSL_EC_POINT_mul");
  9610. /* Validate parameters. */
  9611. if ((group == NULL) || (r == NULL)) {
  9612. WOLFSSL_MSG("wolfSSL_EC_POINT_mul NULL error");
  9613. ret = 0;
  9614. }
  9615. /* Ensure the internal representation of the EC point q is setup. */
  9616. if ((ret == 1) && (q != NULL) && (ec_point_setup(q) != 1)) {
  9617. WOLFSSL_MSG("ec_point_setup error");
  9618. ret = 0;
  9619. }
  9620. if (ret == 1) {
  9621. mp_int* ni = (n != NULL) ? (mp_int*)n->internal : NULL;
  9622. ecc_point* qi = (q != NULL) ? (ecc_point*)q->internal : NULL;
  9623. mp_int* mi = (m != NULL) ? (mp_int*)m->internal : NULL;
  9624. /* Perform multiplication with wolfCrypt objects. */
  9625. ret = wolfssl_ec_point_mul(group->curve_idx, (ecc_point*)r->internal,
  9626. ni, qi, mi);
  9627. }
  9628. /* Only on success is the internal point guaranteed to be set. */
  9629. if (r != NULL) {
  9630. r->inSet = (ret == 1);
  9631. }
  9632. /* Copy internal EC point values out to external EC point. */
  9633. if ((ret == 1) && (ec_point_external_set(r) != 1)) {
  9634. WOLFSSL_MSG("ec_point_external_set error");
  9635. ret = 0;
  9636. }
  9637. return ret;
  9638. }
  9639. #endif /* !WOLFSSL_ATECC508A && !WOLFSSL_ATECC608A && !HAVE_SELFTEST &&
  9640. * !WOLFSSL_SP_MATH */
  9641. /* Invert the point on the curve.
  9642. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9643. *
  9644. * @param [in] curveIdx Index of curve in ecc_set.
  9645. * @param [in, out] point EC point to invert.
  9646. * @return 1 on success.
  9647. * @return 0 on error.
  9648. */
  9649. static int wolfssl_ec_point_invert(int curveIdx, ecc_point* point)
  9650. {
  9651. int ret = 1;
  9652. #ifdef WOLFSSL_SMALL_STACK
  9653. mp_int* prime = NULL;
  9654. #else
  9655. mp_int prime[1];
  9656. #endif
  9657. #ifdef WOLFSSL_SMALL_STACK
  9658. /* Allocate memory for an MP int to hold the prime of the curve. */
  9659. prime = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_BIGINT);
  9660. if (prime == NULL) {
  9661. ret = 0;
  9662. }
  9663. #endif
  9664. /* Initialize MP int. */
  9665. if ((ret == 1) && (mp_init(prime) != MP_OKAY)) {
  9666. WOLFSSL_MSG("mp_init_multi error");
  9667. ret = 0;
  9668. }
  9669. /* Read the curve parameter: prime. */
  9670. if ((ret == 1) && (mp_read_radix(prime, ecc_sets[curveIdx].prime,
  9671. MP_RADIX_HEX) != MP_OKAY)) {
  9672. WOLFSSL_MSG("mp_read_radix prime error");
  9673. ret = 0;
  9674. }
  9675. /* y = (prime - y) mod prime. */
  9676. if ((ret == 1) && (!mp_iszero(point->y)) && (mp_sub(prime, point->y,
  9677. point->y) != MP_OKAY)) {
  9678. WOLFSSL_MSG("mp_sub error");
  9679. ret = 0;
  9680. }
  9681. /* Dispose of memory associated with MP. */
  9682. mp_free(prime);
  9683. #ifdef WOLFSSL_SMALL_STACK
  9684. /* Dispose of dynamically allocated temporaries. */
  9685. XFREE(prime, NULL, DYNAMIC_TYPE_BIGINT);
  9686. #endif
  9687. return ret;
  9688. }
  9689. /* Invert the point on the curve.
  9690. * (x, y) -> (x, -y) = (x, (prime - y) % prime)
  9691. *
  9692. * @param [in] group EC group.
  9693. * @param [in, out] point EC point to invert.
  9694. * @param [in] ctx Context to use for BN operations. Unused.
  9695. * @return 1 on success.
  9696. * @return 0 on error.
  9697. */
  9698. int wolfSSL_EC_POINT_invert(const WOLFSSL_EC_GROUP *group,
  9699. WOLFSSL_EC_POINT *point, WOLFSSL_BN_CTX *ctx)
  9700. {
  9701. int ret = 1;
  9702. /* No BN operations performed. */
  9703. (void)ctx;
  9704. WOLFSSL_ENTER("wolfSSL_EC_POINT_invert");
  9705. /* Validate parameters. */
  9706. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9707. ret = 0;
  9708. }
  9709. /* Ensure internal representation of point is setup. */
  9710. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9711. ret = 0;
  9712. }
  9713. if (ret == 1) {
  9714. /* Perform inversion using wolfCrypt objects. */
  9715. ret = wolfssl_ec_point_invert(group->curve_idx,
  9716. (ecc_point*)point->internal);
  9717. }
  9718. /* Set the external EC point representation based on internal. */
  9719. if ((ret == 1) && (ec_point_external_set(point) != 1)) {
  9720. WOLFSSL_MSG("ec_point_external_set error");
  9721. ret = 0;
  9722. }
  9723. return ret;
  9724. }
  9725. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  9726. /* Compare two points on a the same curve.
  9727. *
  9728. * (Ax, Ay, Az) => (Ax / (Az ^ 2), Ay / (Az ^ 3))
  9729. * (Bx, By, Bz) => (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9730. * When equal:
  9731. * (Ax / (Az ^ 2), Ay / (Az ^ 3)) = (Bx / (Bz ^ 2), By / (Bz ^ 3))
  9732. * => (Ax * (Bz ^ 2), Ay * (Bz ^ 3)) = (Bx * (Az ^ 2), By * (Az ^ 3))
  9733. *
  9734. * @param [in] group EC group.
  9735. * @param [in] a EC point to compare.
  9736. * @param [in] b EC point to compare.
  9737. * @return 0 when equal.
  9738. * @return 1 when different.
  9739. * @return -1 on error.
  9740. */
  9741. static int ec_point_cmp_jacobian(const WOLFSSL_EC_GROUP* group,
  9742. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  9743. {
  9744. int ret = 0;
  9745. BIGNUM* at = BN_new();
  9746. BIGNUM* bt = BN_new();
  9747. BIGNUM* az = BN_new();
  9748. BIGNUM* bz = BN_new();
  9749. BIGNUM* mod = BN_new();
  9750. /* Check that the big numbers were allocated. */
  9751. if ((at == NULL) || (bt == NULL) || (az == NULL) || (bz == NULL) ||
  9752. (mod == NULL)) {
  9753. ret = -1;
  9754. }
  9755. /* Get the modulus for the curve. */
  9756. if ((ret == 0) &&
  9757. (BN_hex2bn(&mod, ecc_sets[group->curve_idx].prime) != 1)) {
  9758. ret = -1;
  9759. }
  9760. if (ret == 0) {
  9761. /* bt = Bx * (Az ^ 2). When Az is one then just copy. */
  9762. if (BN_is_one(a->Z)) {
  9763. if (BN_copy(bt, b->X) == NULL) {
  9764. ret = -1;
  9765. }
  9766. }
  9767. /* az = Az ^ 2 */
  9768. else if ((BN_mod_mul(az, a->Z, a->Z, mod, ctx) != 1)) {
  9769. ret = -1;
  9770. }
  9771. /* bt = Bx * az = Bx * (Az ^ 2) */
  9772. else if (BN_mod_mul(bt, b->X, az, mod, ctx) != 1) {
  9773. ret = -1;
  9774. }
  9775. }
  9776. if (ret == 0) {
  9777. /* at = Ax * (Bz ^ 2). When Bz is one then just copy. */
  9778. if (BN_is_one(b->Z)) {
  9779. if (BN_copy(at, a->X) == NULL) {
  9780. ret = -1;
  9781. }
  9782. }
  9783. /* bz = Bz ^ 2 */
  9784. else if (BN_mod_mul(bz, b->Z, b->Z, mod, ctx) != 1) {
  9785. ret = -1;
  9786. }
  9787. /* at = Ax * bz = Ax * (Bz ^ 2) */
  9788. else if (BN_mod_mul(at, a->X, bz, mod, ctx) != 1) {
  9789. ret = -1;
  9790. }
  9791. }
  9792. /* Compare x-ordinates. */
  9793. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9794. ret = 1;
  9795. }
  9796. if (ret == 0) {
  9797. /* bt = By * (Az ^ 3). When Az is one then just copy. */
  9798. if (BN_is_one(a->Z)) {
  9799. if (BN_copy(bt, b->Y) == NULL) {
  9800. ret = -1;
  9801. }
  9802. }
  9803. /* az = az * Az = Az ^ 3 */
  9804. else if ((BN_mod_mul(az, az, a->Z, mod, ctx) != 1)) {
  9805. ret = -1;
  9806. }
  9807. /* bt = By * az = By * (Az ^ 3) */
  9808. else if (BN_mod_mul(bt, b->Y, az, mod, ctx) != 1) {
  9809. ret = -1;
  9810. }
  9811. }
  9812. if (ret == 0) {
  9813. /* at = Ay * (Bz ^ 3). When Bz is one then just copy. */
  9814. if (BN_is_one(b->Z)) {
  9815. if (BN_copy(at, a->Y) == NULL) {
  9816. ret = -1;
  9817. }
  9818. }
  9819. /* bz = bz * Bz = Bz ^ 3 */
  9820. else if (BN_mod_mul(bz, bz, b->Z, mod, ctx) != 1) {
  9821. ret = -1;
  9822. }
  9823. /* at = Ay * bz = Ay * (Bz ^ 3) */
  9824. else if (BN_mod_mul(at, a->Y, bz, mod, ctx) != 1) {
  9825. ret = -1;
  9826. }
  9827. }
  9828. /* Compare y-ordinates. */
  9829. if ((ret == 0) && (BN_cmp(at, bt) != 0)) {
  9830. ret = 1;
  9831. }
  9832. BN_free(mod);
  9833. BN_free(bz);
  9834. BN_free(az);
  9835. BN_free(bt);
  9836. BN_free(at);
  9837. return ret;
  9838. }
  9839. #endif
  9840. /* Compare two points on a the same curve.
  9841. *
  9842. * Return code compliant with OpenSSL.
  9843. *
  9844. * @param [in] group EC group.
  9845. * @param [in] a EC point to compare.
  9846. * @param [in] b EC point to compare.
  9847. * @param [in] ctx Context to use for BN operations. Unused.
  9848. * @return 0 when equal.
  9849. * @return 1 when different.
  9850. * @return -1 on error.
  9851. */
  9852. int wolfSSL_EC_POINT_cmp(const WOLFSSL_EC_GROUP *group,
  9853. const WOLFSSL_EC_POINT *a, const WOLFSSL_EC_POINT *b, WOLFSSL_BN_CTX *ctx)
  9854. {
  9855. int ret = 0;
  9856. WOLFSSL_ENTER("wolfSSL_EC_POINT_cmp");
  9857. /* Validate parameters. */
  9858. if ((group == NULL) || (a == NULL) || (a->internal == NULL) ||
  9859. (b == NULL) || (b->internal == NULL)) {
  9860. WOLFSSL_MSG("wolfSSL_EC_POINT_cmp Bad arguments");
  9861. ret = -1;
  9862. }
  9863. if (ret != -1) {
  9864. #ifdef WOLFSSL_EC_POINT_CMP_JACOBIAN
  9865. /* If same Z ordinate then no need to convert to affine. */
  9866. if (BN_cmp(a->Z, b->Z) == 0) {
  9867. /* Compare */
  9868. ret = ((BN_cmp(a->X, b->X) != 0) || (BN_cmp(a->Y, b->Y) != 0));
  9869. }
  9870. else {
  9871. ret = ec_point_cmp_jacobian(group, a, b, ctx);
  9872. }
  9873. #else
  9874. /* No BN operations performed. */
  9875. (void)ctx;
  9876. ret = (wc_ecc_cmp_point((ecc_point*)a->internal,
  9877. (ecc_point*)b->internal) != MP_EQ);
  9878. #endif
  9879. }
  9880. return ret;
  9881. }
  9882. /* Copy EC point.
  9883. *
  9884. * @param [out] dest EC point to copy into.
  9885. * @param [in] src EC point to copy.
  9886. * @return 1 on success.
  9887. * @return 0 on error.
  9888. */
  9889. int wolfSSL_EC_POINT_copy(WOLFSSL_EC_POINT *dest, const WOLFSSL_EC_POINT *src)
  9890. {
  9891. int ret = 1;
  9892. WOLFSSL_ENTER("wolfSSL_EC_POINT_copy");
  9893. /* Validate parameters. */
  9894. if ((dest == NULL) || (src == NULL)) {
  9895. ret = 0;
  9896. }
  9897. /* Ensure internal EC point of src is setup. */
  9898. if ((ret == 1) && (ec_point_setup(src) != 1)) {
  9899. ret = 0;
  9900. }
  9901. /* Copy internal EC points. */
  9902. if ((ret == 1) && (wc_ecc_copy_point((ecc_point*)src->internal,
  9903. (ecc_point*)dest->internal) != MP_OKAY)) {
  9904. ret = 0;
  9905. }
  9906. if (ret == 1) {
  9907. /* Destinatation internal point is set. */
  9908. dest->inSet = 1;
  9909. /* Set the external EC point of dest based on internal. */
  9910. if (ec_point_external_set(dest) != 1) {
  9911. ret = 0;
  9912. }
  9913. }
  9914. return ret;
  9915. }
  9916. /* Checks whether point is at infinity.
  9917. *
  9918. * Return code compliant with OpenSSL.
  9919. *
  9920. * @param [in] group EC group.
  9921. * @param [in] point EC point to check.
  9922. * @return 1 when at infinity.
  9923. * @return 0 when not at infinity.
  9924. */
  9925. int wolfSSL_EC_POINT_is_at_infinity(const WOLFSSL_EC_GROUP *group,
  9926. const WOLFSSL_EC_POINT *point)
  9927. {
  9928. int ret = 1;
  9929. WOLFSSL_ENTER("wolfSSL_EC_POINT_is_at_infinity");
  9930. /* Validate parameters. */
  9931. if ((group == NULL) || (point == NULL) || (point->internal == NULL)) {
  9932. WOLFSSL_MSG("wolfSSL_EC_POINT_is_at_infinity NULL error");
  9933. ret = 0;
  9934. }
  9935. /* Ensure internal EC point is setup. */
  9936. if ((ret == 1) && (ec_point_setup(point) != 1)) {
  9937. ret = 0;
  9938. }
  9939. if (ret == 1) {
  9940. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  9941. /* Check for infinity. */
  9942. ret = wc_ecc_point_is_at_infinity((ecc_point*)point->internal);
  9943. if (ret < 0) {
  9944. WOLFSSL_MSG("ecc_point_is_at_infinity failure");
  9945. /* Error return is 0 by OpenSSL. */
  9946. ret = 0;
  9947. }
  9948. #else
  9949. WOLFSSL_MSG("ecc_point_is_at_infinitiy compiled out");
  9950. ret = 0;
  9951. #endif
  9952. }
  9953. return ret;
  9954. }
  9955. #endif /* OPENSSL_EXTRA */
  9956. /* End EC_POINT */
  9957. /* Start EC_KEY */
  9958. #ifdef OPENSSL_EXTRA
  9959. /*
  9960. * EC key constructor/deconstructor APIs
  9961. */
  9962. /* Allocate a new EC key.
  9963. *
  9964. * Not OpenSSL API.
  9965. *
  9966. * @param [in] heap Heap hint for dynamic memory allocation.
  9967. * @param [in] devId Device identifier value.
  9968. * @return New, allocated EC key on success.
  9969. * @return NULL on error.
  9970. */
  9971. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_ex(void* heap, int devId)
  9972. {
  9973. WOLFSSL_EC_KEY *key = NULL;
  9974. int err = 0;
  9975. WOLFSSL_ENTER("wolfSSL_EC_KEY_new");
  9976. /* Allocate memory for EC key. */
  9977. key = (WOLFSSL_EC_KEY*)XMALLOC(sizeof(WOLFSSL_EC_KEY), heap,
  9978. DYNAMIC_TYPE_ECC);
  9979. if (key == NULL) {
  9980. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_KEY failure");
  9981. err = 1;
  9982. }
  9983. if (!err) {
  9984. /* Reset all fields to 0. */
  9985. XMEMSET(key, 0, sizeof(WOLFSSL_EC_KEY));
  9986. /* Cache heap hint. */
  9987. key->heap = heap;
  9988. /* Initialize fields to defaults. */
  9989. key->form = POINT_CONVERSION_UNCOMPRESSED;
  9990. /* Initialize reference count. */
  9991. wolfSSL_RefInit(&key->ref, &err);
  9992. #ifdef WOLFSSL_REFCNT_ERROR_RETURN
  9993. }
  9994. if (!err) {
  9995. #endif
  9996. /* Allocate memory for internal EC key representation. */
  9997. key->internal = (ecc_key*)XMALLOC(sizeof(ecc_key), heap,
  9998. DYNAMIC_TYPE_ECC);
  9999. if (key->internal == NULL) {
  10000. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc ecc key failure");
  10001. err = 1;
  10002. }
  10003. }
  10004. if (!err) {
  10005. /* Initialize wolfCrypt EC key. */
  10006. if (wc_ecc_init_ex((ecc_key*)key->internal, heap, devId) != 0) {
  10007. WOLFSSL_MSG("wolfSSL_EC_KEY_new init ecc key failure");
  10008. err = 1;
  10009. }
  10010. }
  10011. if (!err) {
  10012. /* Group unknown at creation */
  10013. key->group = wolfSSL_EC_GROUP_new_by_curve_name(NID_undef);
  10014. if (key->group == NULL) {
  10015. WOLFSSL_MSG("wolfSSL_EC_KEY_new malloc WOLFSSL_EC_GROUP failure");
  10016. err = 1;
  10017. }
  10018. }
  10019. if (!err) {
  10020. /* Allocate a point as public key. */
  10021. key->pub_key = wolfSSL_EC_POINT_new(key->group);
  10022. if (key->pub_key == NULL) {
  10023. WOLFSSL_MSG("wolfSSL_EC_POINT_new failure");
  10024. err = 1;
  10025. }
  10026. }
  10027. if (!err) {
  10028. /* Allocate a BN as private key. */
  10029. key->priv_key = wolfSSL_BN_new();
  10030. if (key->priv_key == NULL) {
  10031. WOLFSSL_MSG("wolfSSL_BN_new failure");
  10032. err = 1;
  10033. }
  10034. }
  10035. if (err) {
  10036. /* Dispose of EC key on error. */
  10037. wolfSSL_EC_KEY_free(key);
  10038. key = NULL;
  10039. }
  10040. /* Return new EC key object. */
  10041. return key;
  10042. }
  10043. /* Allocate a new EC key.
  10044. *
  10045. * @return New, allocated EC key on success.
  10046. * @return NULL on error.
  10047. */
  10048. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new(void)
  10049. {
  10050. return wolfSSL_EC_KEY_new_ex(NULL, INVALID_DEVID);
  10051. }
  10052. /* Create new EC key with the group having the specified numeric ID.
  10053. *
  10054. * @param [in] nid Numeric ID.
  10055. * @return New, allocated EC key on success.
  10056. * @return NULL on error.
  10057. */
  10058. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_new_by_curve_name(int nid)
  10059. {
  10060. WOLFSSL_EC_KEY *key;
  10061. int err = 0;
  10062. WOLFSSL_ENTER("wolfSSL_EC_KEY_new_by_curve_name");
  10063. /* Allocate empty, EC key. */
  10064. key = wolfSSL_EC_KEY_new();
  10065. if (key == NULL) {
  10066. WOLFSSL_MSG("wolfSSL_EC_KEY_new failure");
  10067. err = 1;
  10068. }
  10069. if (!err) {
  10070. /* Set group to be nid. */
  10071. ec_group_set_nid(key->group, nid);
  10072. if (key->group->curve_idx == -1) {
  10073. wolfSSL_EC_KEY_free(key);
  10074. key = NULL;
  10075. }
  10076. }
  10077. /* Return the new EC key object. */
  10078. return key;
  10079. }
  10080. /* Dispose of the EC key and allocated data.
  10081. *
  10082. * Cannot use key after this call.
  10083. *
  10084. * @param [in] key EC key to free.
  10085. */
  10086. void wolfSSL_EC_KEY_free(WOLFSSL_EC_KEY *key)
  10087. {
  10088. int doFree = 0;
  10089. int err;
  10090. (void)err;
  10091. WOLFSSL_ENTER("wolfSSL_EC_KEY_free");
  10092. if (key != NULL) {
  10093. void* heap = key->heap;
  10094. /* Decrement reference count. */
  10095. wolfSSL_RefDec(&key->ref, &doFree, &err);
  10096. if (doFree) {
  10097. /* Dispose of allocated reference counting data. */
  10098. wolfSSL_RefFree(&key->ref);
  10099. /* Dispose of private key. */
  10100. wolfSSL_BN_free(key->priv_key);
  10101. wolfSSL_EC_POINT_free(key->pub_key);
  10102. wolfSSL_EC_GROUP_free(key->group);
  10103. if (key->internal != NULL) {
  10104. /* Dispose of wolfCrypt representation of EC key. */
  10105. wc_ecc_free((ecc_key*)key->internal);
  10106. XFREE(key->internal, heap, DYNAMIC_TYPE_ECC);
  10107. }
  10108. /* Set back to NULLs for safety. */
  10109. ForceZero(key, sizeof(*key));
  10110. /* Dispose of the memory associated with the EC key. */
  10111. XFREE(key, heap, DYNAMIC_TYPE_ECC);
  10112. (void)heap;
  10113. }
  10114. }
  10115. }
  10116. /* Increments ref count of EC key.
  10117. *
  10118. * @param [in, out] key EC key.
  10119. * @return 1 on success
  10120. * @return 0 on error
  10121. */
  10122. int wolfSSL_EC_KEY_up_ref(WOLFSSL_EC_KEY* key)
  10123. {
  10124. int err = 1;
  10125. if (key != NULL) {
  10126. wolfSSL_RefInc(&key->ref, &err);
  10127. }
  10128. return !err;
  10129. }
  10130. #ifndef NO_CERTS
  10131. #if defined(OPENSSL_ALL)
  10132. /* Copy the internal, wolfCrypt EC key.
  10133. *
  10134. * @param [in, out] dst Destination wolfCrypt EC key.
  10135. * @param [in] src Source wolfCrypt EC key.
  10136. * @return 0 on success.
  10137. * @return Negative on error.
  10138. */
  10139. static int wolfssl_ec_key_int_copy(ecc_key* dst, const ecc_key* src)
  10140. {
  10141. int ret;
  10142. /* Copy public key. */
  10143. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  10144. ret = wc_ecc_copy_point(&src->pubkey, &dst->pubkey);
  10145. #else
  10146. ret = wc_ecc_copy_point((ecc_point*)&src->pubkey, &dst->pubkey);
  10147. #endif
  10148. if (ret != MP_OKAY) {
  10149. WOLFSSL_MSG("wc_ecc_copy_point error");
  10150. }
  10151. if (ret == 0) {
  10152. /* Copy private key. */
  10153. ret = mp_copy(wc_ecc_key_get_priv(src), wc_ecc_key_get_priv(dst));
  10154. if (ret != MP_OKAY) {
  10155. WOLFSSL_MSG("mp_copy error");
  10156. }
  10157. }
  10158. if (ret == 0) {
  10159. /* Copy domain parameters. */
  10160. if (src->dp) {
  10161. ret = wc_ecc_set_curve(dst, 0, src->dp->id);
  10162. if (ret != 0) {
  10163. WOLFSSL_MSG("wc_ecc_set_curve error");
  10164. }
  10165. }
  10166. }
  10167. if (ret == 0) {
  10168. /* Copy the other components. */
  10169. dst->type = src->type;
  10170. dst->idx = src->idx;
  10171. dst->state = src->state;
  10172. dst->flags = src->flags;
  10173. }
  10174. return ret;
  10175. }
  10176. /* Copies ecc_key into new WOLFSSL_EC_KEY object
  10177. *
  10178. * Copies the internal representation as well.
  10179. *
  10180. * @param [in] src EC key to duplicate.
  10181. *
  10182. * @return EC key on success.
  10183. * @return NULL on error.
  10184. */
  10185. WOLFSSL_EC_KEY *wolfSSL_EC_KEY_dup(const WOLFSSL_EC_KEY *src)
  10186. {
  10187. int err = 0;
  10188. WOLFSSL_EC_KEY* newKey = NULL;
  10189. WOLFSSL_ENTER("wolfSSL_EC_KEY_dup");
  10190. /* Validate EC key. */
  10191. if ((src == NULL) || (src->internal == NULL) || (src->group == NULL) ||
  10192. (src->pub_key == NULL) || (src->priv_key == NULL)) {
  10193. WOLFSSL_MSG("src NULL error");
  10194. err = 1;
  10195. }
  10196. if (!err) {
  10197. /* Create a new, empty key. */
  10198. newKey = wolfSSL_EC_KEY_new();
  10199. if (newKey == NULL) {
  10200. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10201. err = 1;
  10202. }
  10203. }
  10204. if (!err) {
  10205. /* Copy internal EC key. */
  10206. if (wolfssl_ec_key_int_copy((ecc_key*)newKey->internal,
  10207. (ecc_key*)src->internal) != 0) {
  10208. WOLFSSL_MSG("Copying internal EC key error");
  10209. err = 1;
  10210. }
  10211. }
  10212. if (!err) {
  10213. /* Internal key set. */
  10214. newKey->inSet = 1;
  10215. /* Copy group */
  10216. err = wolfssl_ec_group_copy(newKey->group, src->group);
  10217. }
  10218. /* Copy public key. */
  10219. if ((!err) && (wolfSSL_EC_POINT_copy(newKey->pub_key, src->pub_key) != 1)) {
  10220. WOLFSSL_MSG("Copying EC public key error");
  10221. err = 1;
  10222. }
  10223. if (!err) {
  10224. /* Set header size of private key in PKCS#8 format.*/
  10225. newKey->pkcs8HeaderSz = src->pkcs8HeaderSz;
  10226. /* Copy private key. */
  10227. if (wolfSSL_BN_copy(newKey->priv_key, src->priv_key) == NULL) {
  10228. WOLFSSL_MSG("Copying EC private key error");
  10229. err = 1;
  10230. }
  10231. }
  10232. if (err) {
  10233. /* Dispose of EC key on error. */
  10234. wolfSSL_EC_KEY_free(newKey);
  10235. newKey = NULL;
  10236. }
  10237. /* Return the new EC key. */
  10238. return newKey;
  10239. }
  10240. #endif /* OPENSSL_ALL */
  10241. #endif /* !NO_CERTS */
  10242. /*
  10243. * EC key to/from bin/octet APIs
  10244. */
  10245. /* Create an EC key from the octet encoded public key.
  10246. *
  10247. * Behaviour checked against OpenSSL.
  10248. *
  10249. * @param [out] key Reference to EC key. Must pass in a valid object with
  10250. * group set.
  10251. * @param [in, out] in On in, reference to buffer that contains data.
  10252. * On out, reference to buffer after public key data.
  10253. * @param [in] len Length of data in the buffer. Must be length of the
  10254. * encoded public key.
  10255. * @return Allocated EC key on success.
  10256. * @return NULL on error.
  10257. */
  10258. WOLFSSL_EC_KEY *wolfSSL_o2i_ECPublicKey(WOLFSSL_EC_KEY **key,
  10259. const unsigned char **in, long len)
  10260. {
  10261. int err = 0;
  10262. WOLFSSL_EC_KEY* ret = NULL;
  10263. WOLFSSL_ENTER("wolfSSL_o2i_ECPublicKey");
  10264. /* Validate parameters: EC group needed to perform import. */
  10265. if ((key == NULL) || (*key == NULL) || ((*key)->group == NULL) ||
  10266. (in == NULL) || (*in == NULL) || (len <= 0)) {
  10267. WOLFSSL_MSG("wolfSSL_o2i_ECPublicKey Bad arguments");
  10268. err = 1;
  10269. }
  10270. if (!err) {
  10271. /* Return the EC key object passed in. */
  10272. ret = *key;
  10273. /* Import point into public key field. */
  10274. if (wolfSSL_EC_POINT_oct2point(ret->group, ret->pub_key, *in, len,
  10275. NULL) != 1) {
  10276. WOLFSSL_MSG("wolfSSL_EC_POINT_oct2point error");
  10277. ret = NULL;
  10278. err = 1;
  10279. }
  10280. }
  10281. if (!err) {
  10282. /* Assumed length passed in is all the data. */
  10283. *in += len;
  10284. }
  10285. return ret;
  10286. }
  10287. /* Puts the encoded public key into out.
  10288. *
  10289. * Passing in NULL for out returns length only.
  10290. * Passing in NULL for *out has buffer allocated, encoded into and passed back.
  10291. * Passing non-NULL for *out has it encoded into and pointer moved past.
  10292. *
  10293. * @param [in] key EC key to encode.
  10294. * @param [in, out] out Reference to buffer to encode into. May be NULL or
  10295. * point to NULL.
  10296. * @return Length of encoding in bytes on success.
  10297. * @return 0 on error.
  10298. */
  10299. int wolfSSL_i2o_ECPublicKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10300. {
  10301. int ret = 1;
  10302. size_t len = 0;
  10303. int form = POINT_CONVERSION_UNCOMPRESSED;
  10304. WOLFSSL_ENTER("wolfSSL_i2o_ECPublicKey");
  10305. /* Validate parameters. */
  10306. if (key == NULL) {
  10307. WOLFSSL_MSG("wolfSSL_i2o_ECPublicKey Bad arguments");
  10308. ret = 0;
  10309. }
  10310. /* Ensure the external key data is set from the internal EC key. */
  10311. if ((ret == 1) && (!key->exSet) && (SetECKeyExternal((WOLFSSL_EC_KEY*)
  10312. key) != 1)) {
  10313. WOLFSSL_MSG("SetECKeyExternal failure");
  10314. ret = 0;
  10315. }
  10316. if (ret == 1) {
  10317. #ifdef HAVE_COMP_KEY
  10318. /* Default to compressed form if not set */
  10319. form = (key->form != POINT_CONVERSION_UNCOMPRESSED) ?
  10320. POINT_CONVERSION_UNCOMPRESSED :
  10321. POINT_CONVERSION_COMPRESSED;
  10322. #endif
  10323. /* Calculate length of point encoding. */
  10324. len = wolfSSL_EC_POINT_point2oct(key->group, key->pub_key, form, NULL,
  10325. 0, NULL);
  10326. }
  10327. /* Encode if length calculated and pointer supplied to update. */
  10328. if ((ret == 1) && (len != 0) && (out != NULL)) {
  10329. unsigned char *tmp = NULL;
  10330. /* Allocate buffer for encoding if no buffer supplied. */
  10331. if (*out == NULL) {
  10332. tmp = (unsigned char*)XMALLOC(len, NULL, DYNAMIC_TYPE_OPENSSL);
  10333. if (tmp == NULL) {
  10334. WOLFSSL_MSG("malloc failed");
  10335. ret = 0;
  10336. }
  10337. }
  10338. else {
  10339. /* Get buffer to encode into. */
  10340. tmp = *out;
  10341. }
  10342. /* Encode public key into buffer. */
  10343. if ((ret == 1) && (wolfSSL_EC_POINT_point2oct(key->group, key->pub_key,
  10344. form, tmp, len, NULL) == 0)) {
  10345. ret = 0;
  10346. }
  10347. if (ret == 1) {
  10348. /* Return buffer if allocated. */
  10349. if (*out == NULL) {
  10350. *out = tmp;
  10351. }
  10352. else {
  10353. /* Step over encoded data if not allocated. */
  10354. *out += len;
  10355. }
  10356. }
  10357. else if (*out == NULL) {
  10358. /* Dispose of allocated buffer. */
  10359. XFREE(tmp, NULL, DYNAMIC_TYPE_OPENSSL);
  10360. }
  10361. }
  10362. if (ret == 1) {
  10363. /* Return length on success. */
  10364. ret = (int)len;
  10365. }
  10366. return ret;
  10367. }
  10368. #ifdef HAVE_ECC_KEY_IMPORT
  10369. /* Create a EC key from the DER encoded private key.
  10370. *
  10371. * @param [out] key Reference to EC key.
  10372. * @param [in, out] in On in, reference to buffer that contains DER data.
  10373. * On out, reference to buffer after private key data.
  10374. * @param [in] long Length of data in the buffer. May be larger than the
  10375. * length of the encoded private key.
  10376. * @return Allocated EC key on success.
  10377. * @return NULL on error.
  10378. */
  10379. WOLFSSL_EC_KEY* wolfSSL_d2i_ECPrivateKey(WOLFSSL_EC_KEY** key,
  10380. const unsigned char** in, long len)
  10381. {
  10382. int err = 0;
  10383. word32 idx = 0;
  10384. WOLFSSL_EC_KEY* ret = NULL;
  10385. WOLFSSL_ENTER("wolfSSL_d2i_ECPrivateKey");
  10386. /* Validate parameters. */
  10387. if ((in == NULL) || (*in == NULL) || (len <= 0)) {
  10388. WOLFSSL_MSG("wolfSSL_d2i_ECPrivateKey Bad arguments");
  10389. err = 1;
  10390. }
  10391. /* Create a new, empty EC key. */
  10392. if ((!err) && ((ret = wolfSSL_EC_KEY_new()) == NULL)) {
  10393. WOLFSSL_MSG("wolfSSL_EC_KEY_new error");
  10394. err = 1;
  10395. }
  10396. /* Decode the private key DER data into internal EC key. */
  10397. if ((!err) && (wc_EccPrivateKeyDecode(*in, &idx, (ecc_key*)ret->internal,
  10398. (word32)len) != 0)) {
  10399. WOLFSSL_MSG("wc_EccPrivateKeyDecode error");
  10400. err = 1;
  10401. }
  10402. if (!err) {
  10403. /* Internal EC key setup. */
  10404. ret->inSet = 1;
  10405. /* Set the EC key from the internal values. */
  10406. if (SetECKeyExternal(ret) != 1) {
  10407. WOLFSSL_MSG("SetECKeyExternal error");
  10408. err = 1;
  10409. }
  10410. }
  10411. if (!err) {
  10412. /* Move buffer on to next byte after data used. */
  10413. *in += idx;
  10414. if (key) {
  10415. /* Return new EC key through reference. */
  10416. *key = ret;
  10417. }
  10418. }
  10419. if (err && (ret != NULL)) {
  10420. /* Dispose of allocated EC key. */
  10421. wolfSSL_EC_KEY_free(ret);
  10422. ret = NULL;
  10423. }
  10424. return ret;
  10425. }
  10426. #endif /* HAVE_ECC_KEY_IMPORT */
  10427. /* Enecode the private key of the EC key into the buffer as DER.
  10428. *
  10429. * @param [in] key EC key to encode.
  10430. * @param [in, out] out On in, reference to buffer to place DER encoding into.
  10431. * On out, reference to buffer adter the encoding.
  10432. * May be NULL.
  10433. * @return Length of DER encoding on success.
  10434. * @return 0 on error.
  10435. */
  10436. int wolfSSL_i2d_ECPrivateKey(const WOLFSSL_EC_KEY *key, unsigned char **out)
  10437. {
  10438. int err = 0;
  10439. word32 len = 0;
  10440. WOLFSSL_ENTER("wolfSSL_i2d_ECPrivateKey");
  10441. /* Validate parameters. */
  10442. if (key == NULL) {
  10443. WOLFSSL_MSG("wolfSSL_i2d_ECPrivateKey Bad arguments");
  10444. err = 1;
  10445. }
  10446. /* Update the internal EC key if not set. */
  10447. if ((!err) && (!key->inSet) && (SetECKeyInternal((WOLFSSL_EC_KEY*)key) !=
  10448. 1)) {
  10449. WOLFSSL_MSG("SetECKeyInternal error");
  10450. err = 1;
  10451. }
  10452. /* Calculate the length of the private key DER encoding using internal EC
  10453. * key. */
  10454. if ((!err) && ((int)(len = wc_EccKeyDerSize((ecc_key*)key->internal, 0)) <=
  10455. 0)) {
  10456. WOLFSSL_MSG("wc_EccKeyDerSize error");
  10457. err = 1;
  10458. }
  10459. /* Only return length when out is NULL. */
  10460. if ((!err) && (out != NULL)) {
  10461. unsigned char* buf = NULL;
  10462. /* Must have a buffer to encode into. */
  10463. if (*out == NULL) {
  10464. /* Allocate a new buffer of appropriate length. */
  10465. buf = (byte*)XMALLOC(len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10466. if (buf == NULL) {
  10467. /* Error and return 0. */
  10468. err = 1;
  10469. len = 0;
  10470. }
  10471. else {
  10472. /* Return the allocated buffer. */
  10473. *out = buf;
  10474. }
  10475. }
  10476. /* Encode the internal EC key as a private key in DER format. */
  10477. if ((!err) && wc_EccPrivateKeyToDer((ecc_key*)key->internal, *out,
  10478. len) < 0) {
  10479. WOLFSSL_MSG("wc_EccPrivateKeyToDer error");
  10480. err = 1;
  10481. }
  10482. else if (buf != *out) {
  10483. /* Move the reference to byte past encoded private key. */
  10484. *out += len;
  10485. }
  10486. /* Dispose of any allocated buffer on error. */
  10487. if (err && (*out == buf)) {
  10488. XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10489. *out = NULL;
  10490. }
  10491. }
  10492. return (int)len;
  10493. }
  10494. /* Load private key into EC key from DER encoding.
  10495. *
  10496. * Not an OpenSSL compatibility API.
  10497. *
  10498. * @param [in, out] key EC key to put private key values into.
  10499. * @param [in] derBuf Buffer holding DER encoding.
  10500. * @param [in] derSz Size of DER encoding in bytes.
  10501. * @return 1 on success.
  10502. * @return -1 on error.
  10503. */
  10504. int wolfSSL_EC_KEY_LoadDer(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10505. int derSz)
  10506. {
  10507. return wolfSSL_EC_KEY_LoadDer_ex(key, derBuf, derSz,
  10508. WOLFSSL_EC_KEY_LOAD_PRIVATE);
  10509. }
  10510. /* Load private/public key into EC key from DER encoding.
  10511. *
  10512. * Not an OpenSSL compatibility API.
  10513. *
  10514. * @param [in, out] key EC key to put private/public key values into.
  10515. * @param [in] derBuf Buffer holding DER encoding.
  10516. * @param [in] derSz Size of DER encoding in bytes.
  10517. * @param [in] opt Key type option. Valid values:
  10518. * WOLFSSL_EC_KEY_LOAD_PRIVATE,
  10519. * WOLFSSL_EC_KEY_LOAD_PUBLIC.
  10520. * @return 1 on success.
  10521. * @return -1 on error.
  10522. */
  10523. int wolfSSL_EC_KEY_LoadDer_ex(WOLFSSL_EC_KEY* key, const unsigned char* derBuf,
  10524. int derSz, int opt)
  10525. {
  10526. int res = 1;
  10527. int ret;
  10528. word32 idx = 0;
  10529. word32 algId;
  10530. WOLFSSL_ENTER("wolfSSL_EC_KEY_LoadDer");
  10531. /* Validate parameters. */
  10532. if ((key == NULL) || (key->internal == NULL) || (derBuf == NULL) ||
  10533. (derSz <= 0)) {
  10534. WOLFSSL_MSG("Bad function arguments");
  10535. res = -1;
  10536. }
  10537. if ((res == 1) && (opt != WOLFSSL_EC_KEY_LOAD_PRIVATE) &&
  10538. (opt != WOLFSSL_EC_KEY_LOAD_PUBLIC)) {
  10539. res = -1;
  10540. }
  10541. if (res == 1) {
  10542. /* Assume no PKCS#8 header. */
  10543. key->pkcs8HeaderSz = 0;
  10544. /* Check if input buffer has PKCS8 header. In the case that it does not
  10545. * have a PKCS8 header then do not error out.
  10546. */
  10547. if ((ret = ToTraditionalInline_ex((const byte*)derBuf, &idx,
  10548. (word32)derSz, &algId)) > 0) {
  10549. WOLFSSL_MSG("Found PKCS8 header");
  10550. key->pkcs8HeaderSz = (word16)idx;
  10551. res = 1;
  10552. }
  10553. /* Error out on parsing error. */
  10554. else if (ret != ASN_PARSE_E) {
  10555. WOLFSSL_MSG("Unexpected error with trying to remove PKCS8 header");
  10556. res = -1;
  10557. }
  10558. }
  10559. if (res == 1) {
  10560. /* Load into internal EC key based on key type option. */
  10561. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10562. ret = wc_EccPrivateKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10563. derSz);
  10564. }
  10565. else {
  10566. ret = wc_EccPublicKeyDecode(derBuf, &idx, (ecc_key*)key->internal,
  10567. derSz);
  10568. if (ret < 0) {
  10569. ecc_key *tmp = (ecc_key*)XMALLOC(sizeof(ecc_key),
  10570. ((ecc_key*)key->internal)->heap, DYNAMIC_TYPE_ECC);
  10571. if (tmp == NULL) {
  10572. ret = -1;
  10573. }
  10574. else {
  10575. /* We now try again as x.963 [point type][x][opt y]. */
  10576. ret = wc_ecc_init_ex(tmp, ((ecc_key*)key->internal)->heap,
  10577. INVALID_DEVID);
  10578. if (ret == 0) {
  10579. ret = wc_ecc_import_x963(derBuf, derSz, tmp);
  10580. if (ret == 0) {
  10581. /* Take ownership of new key - set tmp to the old
  10582. * key which will then be freed below. */
  10583. ecc_key *old = (ecc_key *)key->internal;
  10584. key->internal = tmp;
  10585. tmp = old;
  10586. idx = derSz;
  10587. }
  10588. wc_ecc_free(tmp);
  10589. }
  10590. XFREE(tmp, ((ecc_key*)key->internal)->heap,
  10591. DYNAMIC_TYPE_ECC);
  10592. }
  10593. }
  10594. }
  10595. if (ret < 0) {
  10596. /* Error returned from wolfSSL. */
  10597. if (opt == WOLFSSL_EC_KEY_LOAD_PRIVATE) {
  10598. WOLFSSL_MSG("wc_EccPrivateKeyDecode failed");
  10599. }
  10600. else {
  10601. WOLFSSL_MSG("wc_EccPublicKeyDecode failed");
  10602. }
  10603. res = -1;
  10604. }
  10605. /* Internal key updated - update whether it is a valid key. */
  10606. key->inSet = (res == 1);
  10607. }
  10608. /* Set the external EC key based on value in internal. */
  10609. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  10610. WOLFSSL_MSG("SetECKeyExternal failed");
  10611. res = -1;
  10612. }
  10613. return res;
  10614. }
  10615. /*
  10616. * EC key PEM APIs
  10617. */
  10618. #if (defined(WOLFSSL_KEY_GEN) && !defined(NO_FILESYSTEM)) || \
  10619. (!defined(NO_BIO) && (defined(WOLFSSL_KEY_GEN) || \
  10620. defined(HAVE_ECC) && defined(HAVE_ECC_KEY_EXPORT)))
  10621. /* Encode the EC public key as DER.
  10622. *
  10623. * Also used by pem_write_pubkey().
  10624. *
  10625. * @param [in] key EC key to encode.
  10626. * @param [out] der Pointer through which buffer is returned.
  10627. * @param [in] heap Heap hint.
  10628. * @return Size of encoding on success.
  10629. * @return 0 on error.
  10630. */
  10631. static int wolfssl_ec_key_to_pubkey_der(WOLFSSL_EC_KEY* key,
  10632. unsigned char** der, void* heap)
  10633. {
  10634. int sz;
  10635. unsigned char* buf = NULL;
  10636. (void)heap;
  10637. /* Calculate encoded size to allocate. */
  10638. sz = wc_EccPublicKeyDerSize((ecc_key*)key->internal, 1);
  10639. if (sz <= 0) {
  10640. WOLFSSL_MSG("wc_EccPublicKeyDerSize failed");
  10641. sz = 0;
  10642. }
  10643. if (sz > 0) {
  10644. /* Allocate memory to hold encoding. */
  10645. buf = (byte*)XMALLOC(sz, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10646. if (buf == NULL) {
  10647. WOLFSSL_MSG("malloc failed");
  10648. sz = 0;
  10649. }
  10650. }
  10651. if (sz > 0) {
  10652. /* Encode public key to DER using wolfSSL. */
  10653. sz = wc_EccPublicKeyToDer((ecc_key*)key->internal, buf, sz, 1);
  10654. if (sz < 0) {
  10655. WOLFSSL_MSG("wc_EccPublicKeyToDer failed");
  10656. sz = 0;
  10657. }
  10658. }
  10659. /* Return buffer on success. */
  10660. if (sz > 0) {
  10661. *der = buf;
  10662. }
  10663. else {
  10664. /* Dispose of any dynamically allocated data not returned. */
  10665. XFREE(buf, heap, DYNAMIC_TYPE_TMP_BUFFER);
  10666. }
  10667. return sz;
  10668. }
  10669. #endif
  10670. #if !defined(NO_FILESYSTEM) && defined(WOLFSSL_KEY_GEN)
  10671. /*
  10672. * Return code compliant with OpenSSL.
  10673. *
  10674. * @param [in] fp File pointer to write PEM encoding to.
  10675. * @param [in] key EC key to encode and write.
  10676. * @return 1 on success.
  10677. * @return 0 on error.
  10678. */
  10679. int wolfSSL_PEM_write_EC_PUBKEY(XFILE fp, WOLFSSL_EC_KEY* key)
  10680. {
  10681. int ret = 1;
  10682. unsigned char* derBuf = NULL;
  10683. int derSz = 0;
  10684. WOLFSSL_ENTER("wolfSSL_PEM_write_EC_PUBKEY");
  10685. /* Validate parameters. */
  10686. if ((fp == XBADFILE) || (key == NULL)) {
  10687. WOLFSSL_MSG("Bad argument.");
  10688. return 0;
  10689. }
  10690. /* Encode public key in EC key as DER. */
  10691. derSz = wolfssl_ec_key_to_pubkey_der(key, &derBuf, key->heap);
  10692. if (derSz == 0) {
  10693. ret = 0;
  10694. }
  10695. /* Write out to file the PEM encoding of the DER. */
  10696. if ((ret == 1) && (der_write_to_file_as_pem(derBuf, derSz, fp,
  10697. ECC_PUBLICKEY_TYPE, key->heap) != 1)) {
  10698. ret = 0;
  10699. }
  10700. /* Dispose of any dynamically allocated data. */
  10701. XFREE(derBuf, key->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10702. WOLFSSL_LEAVE("wolfSSL_PEM_write_EC_PUBKEY", ret);
  10703. return ret;
  10704. }
  10705. #endif
  10706. #ifndef NO_BIO
  10707. /* Read a PEM encoded EC public key from a BIO.
  10708. *
  10709. * @param [in] bio BIO to read EC public key from.
  10710. * @param [out] out Pointer to return EC key object through. May be NULL.
  10711. * @param [in] cb Password callback when PEM encrypted.
  10712. * @param [in] pass NUL terminated string for passphrase when PEM
  10713. * encrypted.
  10714. * @return New EC key object on success.
  10715. * @return NULL on error.
  10716. */
  10717. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_EC_PUBKEY(WOLFSSL_BIO* bio,
  10718. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10719. {
  10720. int err = 0;
  10721. WOLFSSL_EC_KEY* ec = NULL;
  10722. DerBuffer* der = NULL;
  10723. int keyFormat = 0;
  10724. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_EC_PUBKEY");
  10725. /* Validate parameters. */
  10726. if (bio == NULL) {
  10727. err = 1;
  10728. }
  10729. if (!err) {
  10730. /* Create an empty EC key. */
  10731. ec = wolfSSL_EC_KEY_new();
  10732. if (ec == NULL) {
  10733. err = 1;
  10734. }
  10735. }
  10736. /* Read a PEM key in to a new DER buffer. */
  10737. if ((!err) && (pem_read_bio_key(bio, cb, pass, ECC_PUBLICKEY_TYPE,
  10738. &keyFormat, &der) <= 0)) {
  10739. err = 1;
  10740. }
  10741. /* Load the EC key with the public key from the DER encoding. */
  10742. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, der->length,
  10743. WOLFSSL_EC_KEY_LOAD_PUBLIC) != 1)) {
  10744. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10745. err = 1;
  10746. }
  10747. /* Dispose of dynamically allocated data not needed anymore. */
  10748. FreeDer(&der);
  10749. if (err) {
  10750. wolfSSL_EC_KEY_free(ec);
  10751. ec = NULL;
  10752. }
  10753. /* Return EC key through out if required. */
  10754. if ((out != NULL) && (ec != NULL)) {
  10755. *out = ec;
  10756. }
  10757. return ec;
  10758. }
  10759. /* Read a PEM encoded EC private key from a BIO.
  10760. *
  10761. * @param [in] bio BIO to read EC private key from.
  10762. * @param [out] out Pointer to return EC key object through. May be NULL.
  10763. * @param [in] cb Password callback when PEM encrypted.
  10764. * @param [in] pass NUL terminated string for passphrase when PEM
  10765. * encrypted.
  10766. * @return New EC key object on success.
  10767. * @return NULL on error.
  10768. */
  10769. WOLFSSL_EC_KEY* wolfSSL_PEM_read_bio_ECPrivateKey(WOLFSSL_BIO* bio,
  10770. WOLFSSL_EC_KEY** out, wc_pem_password_cb* cb, void *pass)
  10771. {
  10772. int err = 0;
  10773. WOLFSSL_EC_KEY* ec = NULL;
  10774. DerBuffer* der = NULL;
  10775. int keyFormat = 0;
  10776. WOLFSSL_ENTER("wolfSSL_PEM_read_bio_ECPrivateKey");
  10777. /* Validate parameters. */
  10778. if (bio == NULL) {
  10779. err = 1;
  10780. }
  10781. if (!err) {
  10782. /* Create an empty EC key. */
  10783. ec = wolfSSL_EC_KEY_new();
  10784. if (ec == NULL) {
  10785. err = 1;
  10786. }
  10787. }
  10788. /* Read a PEM key in to a new DER buffer.
  10789. * To check ENC EC PRIVATE KEY, it uses PRIVATEKEY_TYPE to call
  10790. * pem_read_bio_key(), and then check key format if it is EC.
  10791. */
  10792. if ((!err) && (pem_read_bio_key(bio, cb, pass, PRIVATEKEY_TYPE,
  10793. &keyFormat, &der) <= 0)) {
  10794. err = 1;
  10795. }
  10796. if (keyFormat != ECDSAk) {
  10797. WOLFSSL_ERROR_MSG("Error not EC key format");
  10798. err = 1;
  10799. }
  10800. /* Load the EC key with the private key from the DER encoding. */
  10801. if ((!err) && (wolfSSL_EC_KEY_LoadDer_ex(ec, der->buffer, der->length,
  10802. WOLFSSL_EC_KEY_LOAD_PRIVATE) != 1)) {
  10803. WOLFSSL_ERROR_MSG("Error loading DER buffer into WOLFSSL_EC_KEY");
  10804. err = 1;
  10805. }
  10806. /* Dispose of dynamically allocated data not needed anymore. */
  10807. FreeDer(&der);
  10808. if (err) {
  10809. wolfSSL_EC_KEY_free(ec);
  10810. ec = NULL;
  10811. }
  10812. /* Return EC key through out if required. */
  10813. if ((out != NULL) && (ec != NULL)) {
  10814. *out = ec;
  10815. }
  10816. return ec;
  10817. }
  10818. #endif /* !NO_BIO */
  10819. #if defined(WOLFSSL_KEY_GEN)
  10820. #ifndef NO_BIO
  10821. /* Write out the EC public key as PEM to the BIO.
  10822. *
  10823. * @param [in] bio BIO to write PEM encoding to.
  10824. * @param [in] ec EC public key to encode.
  10825. * @return 1 on success.
  10826. * @return 0 on error.
  10827. */
  10828. int wolfSSL_PEM_write_bio_EC_PUBKEY(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec)
  10829. {
  10830. int ret = 1;
  10831. unsigned char* derBuf = NULL;
  10832. int derSz = 0;
  10833. WOLFSSL_ENTER("wolfSSL_PEM_write_bio_EC_PUBKEY");
  10834. /* Validate parameters. */
  10835. if ((bio == NULL) || (ec == NULL)) {
  10836. WOLFSSL_MSG("Bad Function Arguments");
  10837. return 0;
  10838. }
  10839. /* Encode public key in EC key as DER. */
  10840. derSz = wolfssl_ec_key_to_pubkey_der(ec, &derBuf, ec->heap);
  10841. if (derSz == 0) {
  10842. ret = 0;
  10843. }
  10844. /* Write out to BIO the PEM encoding of the EC private key. */
  10845. if ((ret == 1) && (der_write_to_bio_as_pem(derBuf, derSz, bio,
  10846. ECC_PUBLICKEY_TYPE) != 1)) {
  10847. ret = 0;
  10848. }
  10849. /* Dispose of any dynamically allocated data. */
  10850. XFREE(derBuf, ec->heap, DYNAMIC_TYPE_TMP_BUFFER);
  10851. return ret;
  10852. }
  10853. /* Write out the EC private key as PEM to the BIO.
  10854. *
  10855. * Return code compliant with OpenSSL.
  10856. *
  10857. * @param [in] bio BIO to write PEM encoding to.
  10858. * @param [in] ec EC private key to encode.
  10859. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  10860. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  10861. * @param [in] passwdSz Length of password string when PEM encrypted.
  10862. * @param [in] cb Password callback when PEM encrypted. Unused.
  10863. * @param [in] pass NUL terminated string for passphrase when PEM
  10864. * encrypted. Unused.
  10865. * @return 1 on success.
  10866. * @return 0 on error.
  10867. */
  10868. int wolfSSL_PEM_write_bio_ECPrivateKey(WOLFSSL_BIO* bio, WOLFSSL_EC_KEY* ec,
  10869. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  10870. wc_pem_password_cb* cb, void* arg)
  10871. {
  10872. int ret = 1;
  10873. unsigned char* pem = NULL;
  10874. int pLen = 0;
  10875. (void)cb;
  10876. (void)arg;
  10877. /* Validate parameters. */
  10878. if ((bio == NULL) || (ec == NULL)) {
  10879. ret = 0;
  10880. }
  10881. /* Write EC private key to PEM. */
  10882. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  10883. passwdSz, &pem, &pLen) != 1)) {
  10884. ret = 0;
  10885. }
  10886. /* Write PEM to BIO. */
  10887. if ((ret == 1) && (wolfSSL_BIO_write(bio, pem, pLen) != pLen)) {
  10888. WOLFSSL_ERROR_MSG("EC private key BIO write failed");
  10889. ret = 0;
  10890. }
  10891. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  10892. return ret;
  10893. }
  10894. #endif /* !NO_BIO */
  10895. /* Encode the EC private key as PEM into buffer.
  10896. *
  10897. * Return code compliant with OpenSSL.
  10898. * Not an OpenSSL API.
  10899. *
  10900. * @param [in] ec EC private key to encode.
  10901. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  10902. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  10903. * @param [in] passwdSz Length of password string when PEM encrypted.
  10904. * @param [out] pem Newly allocated buffer holding PEM encoding.
  10905. * @param [out] pLen Length of PEM encoding in bytes.
  10906. * @return 1 on success.
  10907. * @return 0 on error.
  10908. */
  10909. int wolfSSL_PEM_write_mem_ECPrivateKey(WOLFSSL_EC_KEY* ec,
  10910. const EVP_CIPHER* cipher, unsigned char* passwd, int passwdSz,
  10911. unsigned char **pem, int *pLen)
  10912. {
  10913. #if defined(WOLFSSL_PEM_TO_DER) || defined(WOLFSSL_DER_TO_PEM)
  10914. int ret = 1;
  10915. byte* derBuf = NULL;
  10916. int der_max_len = 0;
  10917. int derSz = 0;
  10918. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey");
  10919. /* Validate parameters. */
  10920. if ((pem == NULL) || (pLen == NULL) || (ec == NULL) ||
  10921. (ec->internal == NULL)) {
  10922. WOLFSSL_MSG("Bad function arguments");
  10923. ret = 0;
  10924. }
  10925. /* Ensure internal EC key is set from external. */
  10926. if ((ret == 1) && (ec->inSet == 0)) {
  10927. WOLFSSL_MSG("No ECC internal set, do it");
  10928. if (SetECKeyInternal(ec) != 1) {
  10929. WOLFSSL_MSG("SetECKeyInternal failed");
  10930. ret = 0;
  10931. }
  10932. }
  10933. if (ret == 1) {
  10934. /* Calculate maximum size of DER encoding.
  10935. * 4 > size of pub, priv + ASN.1 additional information */
  10936. der_max_len = 4 * wc_ecc_size((ecc_key*)ec->internal) + AES_BLOCK_SIZE;
  10937. /* Allocate buffer big enough to hold encoding. */
  10938. derBuf = (byte*)XMALLOC(der_max_len, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  10939. if (derBuf == NULL) {
  10940. WOLFSSL_MSG("malloc failed");
  10941. ret = 0;
  10942. }
  10943. }
  10944. if (ret == 1) {
  10945. /* Encode EC private key as DER. */
  10946. derSz = wc_EccKeyToDer((ecc_key*)ec->internal, derBuf, der_max_len);
  10947. if (derSz < 0) {
  10948. WOLFSSL_MSG("wc_EccKeyToDer failed");
  10949. XFREE(derBuf, NULL, DYNAMIC_TYPE_DER);
  10950. ret = 0;
  10951. }
  10952. }
  10953. /* Convert DER to PEM - possibly encrypting. */
  10954. if ((ret == 1) && (der_to_enc_pem_alloc(derBuf, derSz, cipher, passwd,
  10955. passwdSz, ECC_PRIVATEKEY_TYPE, NULL, pem, pLen) != 1)) {
  10956. WOLFSSL_ERROR_MSG("der_to_enc_pem_alloc failed");
  10957. ret = 0;
  10958. }
  10959. return ret;
  10960. #else
  10961. (void)ec;
  10962. (void)cipher;
  10963. (void)passwd;
  10964. (void)passwdSz;
  10965. (void)pem;
  10966. (void)pLen;
  10967. return 0;
  10968. #endif /* WOLFSSL_PEM_TO_DER || WOLFSSL_DER_TO_PEM */
  10969. }
  10970. #ifndef NO_FILESYSTEM
  10971. /* Write out the EC private key as PEM to file.
  10972. *
  10973. * Return code compliant with OpenSSL.
  10974. *
  10975. * @param [in] fp File pointer to write PEM encoding to.
  10976. * @param [in] ec EC private key to encode.
  10977. * @param [in] cipher Cipher to use when PEM encrypted. May be NULL.
  10978. * @param [in] passwd Password string when PEM encrypted. May be NULL.
  10979. * @param [in] passwdSz Length of password string when PEM encrypted.
  10980. * @param [in] cb Password callback when PEM encrypted. Unused.
  10981. * @param [in] pass NUL terminated string for passphrase when PEM
  10982. * encrypted. Unused.
  10983. * @return 1 on success.
  10984. * @return 0 on error.
  10985. */
  10986. int wolfSSL_PEM_write_ECPrivateKey(XFILE fp, WOLFSSL_EC_KEY *ec,
  10987. const EVP_CIPHER *cipher, unsigned char *passwd, int passwdSz,
  10988. wc_pem_password_cb *cb, void *pass)
  10989. {
  10990. int ret = 1;
  10991. byte *pem = NULL;
  10992. int pLen = 0;
  10993. (void)cb;
  10994. (void)pass;
  10995. WOLFSSL_MSG("wolfSSL_PEM_write_ECPrivateKey");
  10996. /* Validate parameters. */
  10997. if ((fp == XBADFILE) || (ec == NULL) || (ec->internal == NULL)) {
  10998. WOLFSSL_MSG("Bad function arguments");
  10999. ret = 0;
  11000. }
  11001. /* Write EC private key to PEM. */
  11002. if ((ret == 1) && (wolfSSL_PEM_write_mem_ECPrivateKey(ec, cipher, passwd,
  11003. passwdSz, &pem, &pLen) != 1)) {
  11004. WOLFSSL_MSG("wolfSSL_PEM_write_mem_ECPrivateKey failed");
  11005. ret = 0;
  11006. }
  11007. /* Write out to file the PEM encoding of the EC private key. */
  11008. if ((ret == 1) && (XFWRITE(pem, pLen, 1, fp) != 1)) {
  11009. WOLFSSL_MSG("ECC private key file write failed");
  11010. ret = 0;
  11011. }
  11012. /* Dispose of any dynamically allocated data. */
  11013. XFREE(pem, NULL, DYNAMIC_TYPE_KEY);
  11014. return ret;
  11015. }
  11016. #endif /* NO_FILESYSTEM */
  11017. #endif /* defined(WOLFSSL_KEY_GEN) */
  11018. /*
  11019. * EC key print APIs
  11020. */
  11021. #ifndef NO_CERTS
  11022. #if defined(XFPRINTF) && !defined(NO_FILESYSTEM) && \
  11023. !defined(NO_STDIO_FILESYSTEM)
  11024. /* Print the EC key to a file pointer as text.
  11025. *
  11026. * @param [in] fp File pointer.
  11027. * @param [in] key EC key to print.
  11028. * @param [in] indent Number of spaces to place before each line printed.
  11029. * @return 1 on success.
  11030. * @return 0 on failure.
  11031. */
  11032. int wolfSSL_EC_KEY_print_fp(XFILE fp, WOLFSSL_EC_KEY* key, int indent)
  11033. {
  11034. int ret = 1;
  11035. int bits = 0;
  11036. int priv = 0;
  11037. WOLFSSL_ENTER("wolfSSL_EC_KEY_print_fp");
  11038. /* Validate parameters. */
  11039. if ((fp == XBADFILE) || (key == NULL) || (key->group == NULL) ||
  11040. (indent < 0)) {
  11041. ret = 0;
  11042. }
  11043. if (ret == 1) {
  11044. /* Get EC groups order size in bits. */
  11045. bits = wolfSSL_EC_GROUP_order_bits(key->group);
  11046. if (bits <= 0) {
  11047. WOLFSSL_MSG("Failed to get group order bits.");
  11048. ret = 0;
  11049. }
  11050. }
  11051. if (ret == 1) {
  11052. const char* keyType;
  11053. /* Determine whether this is a private or public key. */
  11054. if ((key->priv_key != NULL) && (!wolfSSL_BN_is_zero(key->priv_key))) {
  11055. keyType = "Private-Key";
  11056. priv = 1;
  11057. }
  11058. else {
  11059. keyType = "Public-Key";
  11060. }
  11061. /* Print key header. */
  11062. if (XFPRINTF(fp, "%*s%s: (%d bit)\n", indent, "", keyType, bits) < 0) {
  11063. ret = 0;
  11064. }
  11065. }
  11066. if ((ret == 1) && priv) {
  11067. /* Print the private key BN. */
  11068. ret = pk_bn_field_print_fp(fp, indent, "priv", key->priv_key);
  11069. }
  11070. /* Check for public key data in EC key. */
  11071. if ((ret == 1) && (key->pub_key != NULL) && (key->pub_key->exSet)) {
  11072. /* Get the public key point as one BN. */
  11073. WOLFSSL_BIGNUM* pubBn = wolfSSL_EC_POINT_point2bn(key->group,
  11074. key->pub_key, POINT_CONVERSION_UNCOMPRESSED, NULL, NULL);
  11075. if (pubBn == NULL) {
  11076. WOLFSSL_MSG("wolfSSL_EC_POINT_point2bn failed.");
  11077. ret = 0;
  11078. }
  11079. else {
  11080. /* Print the public key in a BN. */
  11081. ret = pk_bn_field_print_fp(fp, indent, "pub", pubBn);
  11082. wolfSSL_BN_free(pubBn);
  11083. }
  11084. }
  11085. if (ret == 1) {
  11086. /* Get the NID of the group. */
  11087. int nid = wolfSSL_EC_GROUP_get_curve_name(key->group);
  11088. if (nid > 0) {
  11089. /* Convert the NID into a long name and NIST name. */
  11090. const char* curve = wolfSSL_OBJ_nid2ln(nid);
  11091. const char* nistName = wolfSSL_EC_curve_nid2nist(nid);
  11092. /* Print OID name if known. */
  11093. if ((curve != NULL) &&
  11094. (XFPRINTF(fp, "%*sASN1 OID: %s\n", indent, "", curve) < 0)) {
  11095. ret = 0;
  11096. }
  11097. /* Print NIST curve name if known. */
  11098. if ((nistName != NULL) &&
  11099. (XFPRINTF(fp, "%*sNIST CURVE: %s\n", indent, "",
  11100. nistName) < 0)) {
  11101. ret = 0;
  11102. }
  11103. }
  11104. }
  11105. WOLFSSL_LEAVE("wolfSSL_EC_KEY_print_fp", ret);
  11106. return ret;
  11107. }
  11108. #endif /* XFPRINTF && !NO_FILESYSTEM && !NO_STDIO_FILESYSTEM */
  11109. #endif /* !NO_CERTS */
  11110. /*
  11111. * EC_KEY get/set/test APIs
  11112. */
  11113. /* Set data of internal, wolfCrypt EC key object into EC key.
  11114. *
  11115. * EC_KEY wolfSSL -> OpenSSL
  11116. *
  11117. * @param [in, out] p EC key to update.
  11118. * @return 1 on success.
  11119. * @return -1 on failure.
  11120. */
  11121. int SetECKeyExternal(WOLFSSL_EC_KEY* eckey)
  11122. {
  11123. int ret = 1;
  11124. WOLFSSL_ENTER("SetECKeyExternal");
  11125. /* Validate parameter. */
  11126. if ((eckey == NULL) || (eckey->internal == NULL)) {
  11127. WOLFSSL_MSG("ec key NULL error");
  11128. ret = -1;
  11129. }
  11130. else {
  11131. ecc_key* key = (ecc_key*)eckey->internal;
  11132. /* Set group (OID, nid and idx) from wolfCrypt EC key. */
  11133. eckey->group->curve_oid = key->dp->oidSum;
  11134. eckey->group->curve_nid = EccEnumToNID(key->dp->id);
  11135. eckey->group->curve_idx = key->idx;
  11136. if (eckey->pub_key->internal != NULL) {
  11137. /* Copy internal public point from internal key's public point. */
  11138. if (wc_ecc_copy_point(&key->pubkey,
  11139. (ecc_point*)eckey->pub_key->internal) != MP_OKAY) {
  11140. WOLFSSL_MSG("SetECKeyExternal ecc_copy_point failed");
  11141. ret = -1;
  11142. }
  11143. /* Set external public key from internal wolfCrypt, public key. */
  11144. if ((ret == 1) && (ec_point_external_set(eckey->pub_key) != 1)) {
  11145. WOLFSSL_MSG("SetECKeyExternal ec_point_external_set failed");
  11146. ret = -1;
  11147. }
  11148. }
  11149. /* set the external privkey */
  11150. if ((ret == 1) && (key->type == ECC_PRIVATEKEY) &&
  11151. (wolfssl_bn_set_value(&eckey->priv_key,
  11152. wc_ecc_key_get_priv(key)) != 1)) {
  11153. WOLFSSL_MSG("ec priv key error");
  11154. ret = -1;
  11155. }
  11156. /* External values set when operations succeeded. */
  11157. eckey->exSet = (ret == 1);
  11158. }
  11159. return ret;
  11160. }
  11161. /* Set data of EC key into internal, wolfCrypt EC key object.
  11162. *
  11163. * EC_KEY Openssl -> WolfSSL
  11164. *
  11165. * @param [in, out] p EC key to update.
  11166. * @return 1 on success.
  11167. * @return -1 on failure.
  11168. */
  11169. int SetECKeyInternal(WOLFSSL_EC_KEY* eckey)
  11170. {
  11171. int ret = 1;
  11172. WOLFSSL_ENTER("SetECKeyInternal");
  11173. /* Validate parameter. */
  11174. if ((eckey == NULL) || (eckey->internal == NULL) ||
  11175. (eckey->group == NULL)) {
  11176. WOLFSSL_MSG("ec key NULL error");
  11177. ret = -1;
  11178. }
  11179. else {
  11180. ecc_key* key = (ecc_key*)eckey->internal;
  11181. int pubSet = 0;
  11182. /* Validate group. */
  11183. if ((eckey->group->curve_idx < 0) ||
  11184. (wc_ecc_is_valid_idx(eckey->group->curve_idx) == 0)) {
  11185. WOLFSSL_MSG("invalid curve idx");
  11186. ret = -1;
  11187. }
  11188. if (ret == 1) {
  11189. /* Set group (idx of curve and corresponding domain parameters). */
  11190. key->idx = eckey->group->curve_idx;
  11191. key->dp = &ecc_sets[key->idx];
  11192. pubSet = (eckey->pub_key != NULL);
  11193. }
  11194. /* Set public key (point). */
  11195. if ((ret == 1) && pubSet) {
  11196. if (ec_point_internal_set(eckey->pub_key) != 1) {
  11197. WOLFSSL_MSG("ec key pub error");
  11198. ret = -1;
  11199. }
  11200. /* Copy public point to key. */
  11201. if ((ret == 1) && (wc_ecc_copy_point(
  11202. (ecc_point*)eckey->pub_key->internal, &key->pubkey) !=
  11203. MP_OKAY)) {
  11204. WOLFSSL_MSG("wc_ecc_copy_point error");
  11205. ret = -1;
  11206. }
  11207. if (ret == 1) {
  11208. /* Set that the internal key is a public key */
  11209. key->type = ECC_PUBLICKEY;
  11210. }
  11211. }
  11212. /* set privkey */
  11213. if ((ret == 1) && (eckey->priv_key != NULL)) {
  11214. if (wolfssl_bn_get_value(eckey->priv_key,
  11215. wc_ecc_key_get_priv(key)) != 1) {
  11216. WOLFSSL_MSG("ec key priv error");
  11217. ret = -1;
  11218. }
  11219. /* private key */
  11220. if ((ret == 1) && (!mp_iszero(wc_ecc_key_get_priv(key)))) {
  11221. if (pubSet) {
  11222. key->type = ECC_PRIVATEKEY;
  11223. }
  11224. else {
  11225. key->type = ECC_PRIVATEKEY_ONLY;
  11226. }
  11227. }
  11228. }
  11229. /* Internal values set when operations succeeded. */
  11230. eckey->inSet = (ret == 1);
  11231. }
  11232. return ret;
  11233. }
  11234. /* Get point conversion format of EC key.
  11235. *
  11236. * @param [in] key EC key.
  11237. * @return Point conversion format on success.
  11238. * @return -1 on error.
  11239. */
  11240. point_conversion_form_t wolfSSL_EC_KEY_get_conv_form(const WOLFSSL_EC_KEY* key)
  11241. {
  11242. int ret = -1;
  11243. if (key != NULL) {
  11244. ret = key->form;
  11245. }
  11246. return ret;
  11247. }
  11248. /* Set point conversion format into EC key.
  11249. *
  11250. * @param [in, out] key EC key to set format into.
  11251. * @param [in] form Point conversion format. Valid values:
  11252. * POINT_CONVERSION_UNCOMPRESSED,
  11253. * POINT_CONVERSION_COMPRESSED (when HAVE_COMP_KEY)
  11254. */
  11255. void wolfSSL_EC_KEY_set_conv_form(WOLFSSL_EC_KEY *key, int form)
  11256. {
  11257. if (key == NULL) {
  11258. WOLFSSL_MSG("Key passed in NULL");
  11259. }
  11260. else if (form == POINT_CONVERSION_UNCOMPRESSED
  11261. #ifdef HAVE_COMP_KEY
  11262. || form == POINT_CONVERSION_COMPRESSED
  11263. #endif
  11264. ) {
  11265. key->form = (char)form;
  11266. }
  11267. else {
  11268. WOLFSSL_MSG("Incorrect form or HAVE_COMP_KEY not compiled in");
  11269. }
  11270. }
  11271. /* Get the EC group object that is in EC key.
  11272. *
  11273. * @param [in] key EC key.
  11274. * @return EC group object on success.
  11275. * @return NULL when key is NULL.
  11276. */
  11277. const WOLFSSL_EC_GROUP *wolfSSL_EC_KEY_get0_group(const WOLFSSL_EC_KEY *key)
  11278. {
  11279. WOLFSSL_EC_GROUP* group = NULL;
  11280. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_group");
  11281. if (key != NULL) {
  11282. group = key->group;
  11283. }
  11284. return group;
  11285. }
  11286. /* Set the group in WOLFSSL_EC_KEY
  11287. *
  11288. * @param [in, out] key EC key to update.
  11289. * @param [in] group EC group to copy.
  11290. * @return 1 on success
  11291. * @return 0 on failure.
  11292. */
  11293. int wolfSSL_EC_KEY_set_group(WOLFSSL_EC_KEY *key, WOLFSSL_EC_GROUP *group)
  11294. {
  11295. int ret = 1;
  11296. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_group");
  11297. /* Validate parameters. */
  11298. if ((key == NULL) || (group == NULL)) {
  11299. ret = 0;
  11300. }
  11301. if (ret == 1) {
  11302. /* Dispose of the current group. */
  11303. if (key->group != NULL) {
  11304. wolfSSL_EC_GROUP_free(key->group);
  11305. }
  11306. /* Duplicate the passed in group into EC key. */
  11307. key->group = wolfSSL_EC_GROUP_dup(group);
  11308. if (key->group == NULL) {
  11309. ret = 0;
  11310. }
  11311. }
  11312. return ret;
  11313. }
  11314. /* Get the BN object that is the private key in the EC key.
  11315. *
  11316. * @param [in] key EC key.
  11317. * @return BN object on success.
  11318. * @return NULL when key is NULL or private key is not set.
  11319. */
  11320. WOLFSSL_BIGNUM *wolfSSL_EC_KEY_get0_private_key(const WOLFSSL_EC_KEY *key)
  11321. {
  11322. WOLFSSL_BIGNUM* priv_key = NULL;
  11323. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_private_key");
  11324. /* Validate parameter. */
  11325. if (key == NULL) {
  11326. WOLFSSL_MSG("wolfSSL_EC_KEY_get0_private_key Bad arguments");
  11327. }
  11328. /* Only return private key if it is not 0. */
  11329. else if (!wolfSSL_BN_is_zero(key->priv_key)) {
  11330. priv_key = key->priv_key;
  11331. }
  11332. return priv_key;
  11333. }
  11334. /* Sets the private key value into EC key.
  11335. *
  11336. * Return code compliant with OpenSSL.
  11337. *
  11338. * @param [in, out] key EC key to set.
  11339. * @param [in] priv_key Private key value in a BN.
  11340. * @return 1 on success
  11341. * @return 0 on failure.
  11342. */
  11343. int wolfSSL_EC_KEY_set_private_key(WOLFSSL_EC_KEY *key,
  11344. const WOLFSSL_BIGNUM *priv_key)
  11345. {
  11346. int ret = 1;
  11347. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_private_key");
  11348. /* Validate parameters. */
  11349. if ((key == NULL) || (priv_key == NULL)) {
  11350. WOLFSSL_MSG("Bad arguments");
  11351. ret = 0;
  11352. }
  11353. /* Check for obvious invalid values. */
  11354. if (wolfSSL_BN_is_negative(priv_key) || wolfSSL_BN_is_zero(priv_key) ||
  11355. wolfSSL_BN_is_one(priv_key)) {
  11356. WOLFSSL_MSG("Invalid private key value");
  11357. ret = 0;
  11358. }
  11359. if (ret == 1) {
  11360. /* Free key if previously set. */
  11361. if (key->priv_key != NULL) {
  11362. wolfSSL_BN_free(key->priv_key);
  11363. }
  11364. /* Duplicate the BN passed in. */
  11365. key->priv_key = wolfSSL_BN_dup(priv_key);
  11366. if (key->priv_key == NULL) {
  11367. WOLFSSL_MSG("key ecc priv key NULL");
  11368. ret = 0;
  11369. }
  11370. }
  11371. /* Set the external values into internal EC key. */
  11372. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11373. WOLFSSL_MSG("SetECKeyInternal failed");
  11374. /* Dispose of new private key on error. */
  11375. wolfSSL_BN_free(key->priv_key);
  11376. key->priv_key = NULL;
  11377. ret = 0;
  11378. }
  11379. return ret;
  11380. }
  11381. /* Get the public key EC point object that is in EC key.
  11382. *
  11383. * @param [in] key EC key.
  11384. * @return EC point object that is the public key on success.
  11385. * @return NULL when key is NULL.
  11386. */
  11387. WOLFSSL_EC_POINT* wolfSSL_EC_KEY_get0_public_key(const WOLFSSL_EC_KEY *key)
  11388. {
  11389. WOLFSSL_EC_POINT* pub_key = NULL;
  11390. WOLFSSL_ENTER("wolfSSL_EC_KEY_get0_public_key");
  11391. if (key != NULL) {
  11392. pub_key = key->pub_key;
  11393. }
  11394. return pub_key;
  11395. }
  11396. /*
  11397. * Return code compliant with OpenSSL.
  11398. *
  11399. * @param [in, out] key EC key.
  11400. * @param [in] pub Public key as an EC point.
  11401. * @return 1 on success
  11402. * @return 0 on failure.
  11403. */
  11404. int wolfSSL_EC_KEY_set_public_key(WOLFSSL_EC_KEY *key,
  11405. const WOLFSSL_EC_POINT *pub)
  11406. {
  11407. int ret = 1;
  11408. ecc_point *pub_p = NULL;
  11409. ecc_point *key_p = NULL;
  11410. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_public_key");
  11411. /* Validate parameters. */
  11412. if ((key == NULL) || (key->internal == NULL) || (pub == NULL) ||
  11413. (pub->internal == NULL)) {
  11414. WOLFSSL_MSG("wolfSSL_EC_KEY_set_public_key Bad arguments");
  11415. ret = 0;
  11416. }
  11417. /* Ensure the internal EC key is set. */
  11418. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(key) != 1)) {
  11419. WOLFSSL_MSG("SetECKeyInternal failed");
  11420. ret = 0;
  11421. }
  11422. /* Ensure the internal EC point of pub is setup. */
  11423. if ((ret == 1) && (ec_point_setup(pub) != 1)) {
  11424. ret = 0;
  11425. }
  11426. if (ret == 1) {
  11427. /* Get the internal point of pub and the public key in key. */
  11428. pub_p = (ecc_point*)pub->internal;
  11429. key_p = (ecc_point*)key->pub_key->internal;
  11430. /* Create new point if required. */
  11431. if (key_p == NULL) {
  11432. key_p = wc_ecc_new_point();
  11433. key->pub_key->internal = (void*)key_p;
  11434. }
  11435. /* Check point available. */
  11436. if (key_p == NULL) {
  11437. WOLFSSL_MSG("key ecc point NULL");
  11438. ret = 0;
  11439. }
  11440. }
  11441. /* Copy the internal pub point into internal key point. */
  11442. if ((ret == 1) && (wc_ecc_copy_point(pub_p, key_p) != MP_OKAY)) {
  11443. WOLFSSL_MSG("ecc_copy_point failure");
  11444. ret = 0;
  11445. }
  11446. /* Copy the internal point data into external. */
  11447. if ((ret == 1) && (ec_point_external_set(key->pub_key) != 1)) {
  11448. WOLFSSL_MSG("SetECKeyInternal failed");
  11449. ret = 0;
  11450. }
  11451. /* Copy the internal key into external. */
  11452. if ((ret == 1) && (SetECKeyInternal(key) != 1)) {
  11453. WOLFSSL_MSG("SetECKeyInternal failed");
  11454. ret = 0;
  11455. }
  11456. if (ret == 1) {
  11457. /* Dump out the point and the key's public key for debug. */
  11458. wolfSSL_EC_POINT_dump("pub", pub);
  11459. wolfSSL_EC_POINT_dump("key->pub_key", key->pub_key);
  11460. }
  11461. return ret;
  11462. }
  11463. #ifndef NO_WOLFSSL_STUB
  11464. /* Set the ASN.1 encoding flag against the EC key.
  11465. *
  11466. * No implementation as only named curves supported for encoding.
  11467. *
  11468. * @param [in, out] key EC key.
  11469. * @param [in] flag ASN.1 flag to set. Valid values:
  11470. * OPENSSL_EC_EXPLICIT_CURVE, OPENSSL_EC_NAMED_CURVE
  11471. */
  11472. void wolfSSL_EC_KEY_set_asn1_flag(WOLFSSL_EC_KEY *key, int asn1_flag)
  11473. {
  11474. (void)key;
  11475. (void)asn1_flag;
  11476. WOLFSSL_ENTER("wolfSSL_EC_KEY_set_asn1_flag");
  11477. WOLFSSL_STUB("EC_KEY_set_asn1_flag");
  11478. }
  11479. #endif
  11480. /*
  11481. * EC key generate key APIs
  11482. */
  11483. /* Generate an EC key.
  11484. *
  11485. * Uses the internal curve index set in the EC key or the default.
  11486. *
  11487. * @param [in, out] key EC key.
  11488. * @return 1 on success
  11489. * @return 0 on failure.
  11490. */
  11491. int wolfSSL_EC_KEY_generate_key(WOLFSSL_EC_KEY *key)
  11492. {
  11493. int res = 1;
  11494. int initTmpRng = 0;
  11495. WC_RNG* rng = NULL;
  11496. #ifdef WOLFSSL_SMALL_STACK
  11497. WC_RNG* tmpRng = NULL;
  11498. #else
  11499. WC_RNG tmpRng[1];
  11500. #endif
  11501. WOLFSSL_ENTER("wolfSSL_EC_KEY_generate_key");
  11502. /* Validate parameters. */
  11503. if ((key == NULL) || (key->internal == NULL) || (key->group == NULL)) {
  11504. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key Bad arguments");
  11505. res = 0;
  11506. }
  11507. if (res == 1) {
  11508. /* Check if we know which internal curve index to use. */
  11509. if (key->group->curve_idx < 0) {
  11510. /* Generate key using the default curve. */
  11511. key->group->curve_idx = ECC_CURVE_DEF;
  11512. }
  11513. /* Create a random number generator. */
  11514. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  11515. if (rng == NULL) {
  11516. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key failed to set RNG");
  11517. res = 0;
  11518. }
  11519. }
  11520. if (res == 1) {
  11521. /* NIDToEccEnum returns -1 for invalid NID so if key->group->curve_nid
  11522. * is 0 then pass ECC_CURVE_DEF as arg */
  11523. int eccEnum = key->group->curve_nid ?
  11524. NIDToEccEnum(key->group->curve_nid) : ECC_CURVE_DEF;
  11525. /* Get the internal EC key. */
  11526. ecc_key* ecKey = (ecc_key*)key->internal;
  11527. /* Make the key using internal API. */
  11528. int ret = wc_ecc_make_key_ex(rng, 0, ecKey, eccEnum);
  11529. #if defined(WOLFSSL_ASYNC_CRYPT)
  11530. /* Wait on asynchronouse operation. */
  11531. ret = wc_AsyncWait(ret, &ecKey->asyncDev, WC_ASYNC_FLAG_NONE);
  11532. #endif
  11533. if (ret != 0) {
  11534. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key wc_ecc_make_key failed");
  11535. res = 0;
  11536. }
  11537. }
  11538. /* Dispose of local random number generator if initialized. */
  11539. if (initTmpRng) {
  11540. wc_FreeRng(rng);
  11541. #ifdef WOLFSSL_SMALL_STACK
  11542. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  11543. #endif
  11544. }
  11545. /* Set the external key from new internal key values. */
  11546. if ((res == 1) && (SetECKeyExternal(key) != 1)) {
  11547. WOLFSSL_MSG("wolfSSL_EC_KEY_generate_key SetECKeyExternal failed");
  11548. res = 0;
  11549. }
  11550. return res;
  11551. }
  11552. /*
  11553. * EC key check key APIs
  11554. */
  11555. /* Check that the EC key is valid.
  11556. *
  11557. * @param [in] key EC key.
  11558. * @return 1 on valid.
  11559. * @return 0 on invalid or error.
  11560. */
  11561. int wolfSSL_EC_KEY_check_key(const WOLFSSL_EC_KEY *key)
  11562. {
  11563. int ret = 1;
  11564. WOLFSSL_ENTER("wolfSSL_EC_KEY_check_key");
  11565. /* Validate parameter. */
  11566. if ((key == NULL) || (key->internal == NULL)) {
  11567. WOLFSSL_MSG("Bad parameter");
  11568. ret = 0;
  11569. }
  11570. /* Set the external EC key values into internal if not already. */
  11571. if ((ret == 1) && (key->inSet == 0) && (SetECKeyInternal(
  11572. (WOLFSSL_EC_KEY*)key) != 1)) {
  11573. WOLFSSL_MSG("SetECKeyInternal failed");
  11574. ret = 0;
  11575. }
  11576. if (ret == 1) {
  11577. /* Have internal EC implementation check key. */
  11578. ret = wc_ecc_check_key((ecc_key*)key->internal) == 0;
  11579. }
  11580. return ret;
  11581. }
  11582. /* End EC_KEY */
  11583. #if !defined(HAVE_FIPS) || FIPS_VERSION_GT(2,0)
  11584. /* Get the supported, built-in EC curves
  11585. *
  11586. * @param [in, out] curves Pre-allocated list to put supported curves into.
  11587. * @param [in] len Maximum number of items to place in list.
  11588. * @return Number of built-in EC curves when curves is NULL or len is 0.
  11589. * @return Number of items placed in list otherwise.
  11590. */
  11591. size_t wolfSSL_EC_get_builtin_curves(WOLFSSL_EC_BUILTIN_CURVE *curves,
  11592. size_t len)
  11593. {
  11594. size_t i;
  11595. size_t cnt;
  11596. #ifdef HAVE_SELFTEST
  11597. /* Defined in ecc.h when available. */
  11598. size_t ecc_sets_count;
  11599. /* Count the pre-defined curves since global not available. */
  11600. for (i = 0; ecc_sets[i].size != 0 && ecc_sets[i].name != NULL; i++) {
  11601. /* Do nothing. */
  11602. }
  11603. ecc_sets_count = i;
  11604. #endif
  11605. /* Assume we are going to return total count. */
  11606. cnt = ecc_sets_count;
  11607. /* Check we have a list that can hold data. */
  11608. if ((curves != NULL) && (len != 0)) {
  11609. /* Limit count to length of list. */
  11610. if (cnt > len) {
  11611. cnt = len;
  11612. }
  11613. /* Put in built-in EC curve nid and short name. */
  11614. for (i = 0; i < cnt; i++) {
  11615. curves[i].nid = EccEnumToNID(ecc_sets[i].id);
  11616. curves[i].comment = wolfSSL_OBJ_nid2sn(curves[i].nid);
  11617. }
  11618. }
  11619. return cnt;
  11620. }
  11621. #endif /* !HAVE_FIPS || FIPS_VERSION_GT(2,0) */
  11622. /* Start ECDSA_SIG */
  11623. /* Allocate a new ECDSA signature object.
  11624. *
  11625. * @return New, allocated ECDSA signature object on success.
  11626. * @return NULL on error.
  11627. */
  11628. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_SIG_new(void)
  11629. {
  11630. int err = 0;
  11631. WOLFSSL_ECDSA_SIG *sig;
  11632. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_new");
  11633. /* Allocate memory for ECDSA signature object. */
  11634. sig = (WOLFSSL_ECDSA_SIG*)XMALLOC(sizeof(WOLFSSL_ECDSA_SIG), NULL,
  11635. DYNAMIC_TYPE_ECC);
  11636. if (sig == NULL) {
  11637. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA signature failure");
  11638. err = 1;
  11639. }
  11640. if (!err) {
  11641. /* Set s to NULL in case of error. */
  11642. sig->s = NULL;
  11643. /* Allocate BN into r. */
  11644. sig->r = wolfSSL_BN_new();
  11645. if (sig->r == NULL) {
  11646. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA r failure");
  11647. err = 1;
  11648. }
  11649. }
  11650. if (!err) {
  11651. /* Allocate BN into s. */
  11652. sig->s = wolfSSL_BN_new();
  11653. if (sig->s == NULL) {
  11654. WOLFSSL_MSG("wolfSSL_ECDSA_SIG_new malloc ECDSA s failure");
  11655. err = 1;
  11656. }
  11657. }
  11658. if (err && (sig != NULL)) {
  11659. /* Dispose of allocated memory. */
  11660. wolfSSL_ECDSA_SIG_free(sig);
  11661. sig = NULL;
  11662. }
  11663. return sig;
  11664. }
  11665. /* Dispose of ECDSA signature object.
  11666. *
  11667. * Cannot use object after this call.
  11668. *
  11669. * @param [in] sig ECDSA signature object to free.
  11670. */
  11671. void wolfSSL_ECDSA_SIG_free(WOLFSSL_ECDSA_SIG *sig)
  11672. {
  11673. WOLFSSL_ENTER("wolfSSL_ECDSA_SIG_free");
  11674. if (sig != NULL) {
  11675. /* Dispose of BNs allocated for r and s. */
  11676. wolfSSL_BN_free(sig->r);
  11677. wolfSSL_BN_free(sig->s);
  11678. /* Dispose of memory associated with ECDSA signature object. */
  11679. XFREE(sig, NULL, DYNAMIC_TYPE_ECC);
  11680. }
  11681. }
  11682. /* Create an ECDSA signature from the DER encoding.
  11683. *
  11684. * @param [in, out] sig Reference to ECDSA signature object. May be NULL.
  11685. * @param [in, out] pp On in, reference to buffer containing DER encoding.
  11686. * On out, reference to buffer after signature data.
  11687. * @param [in] len Length of the data in the buffer. May be more than
  11688. * the length of the signature.
  11689. * @return ECDSA signature object on success.
  11690. * @return NULL on error.
  11691. */
  11692. WOLFSSL_ECDSA_SIG* wolfSSL_d2i_ECDSA_SIG(WOLFSSL_ECDSA_SIG** sig,
  11693. const unsigned char** pp, long len)
  11694. {
  11695. int err = 0;
  11696. /* ECDSA signature object to return. */
  11697. WOLFSSL_ECDSA_SIG *s = NULL;
  11698. /* Validate parameter. */
  11699. if (pp == NULL) {
  11700. err = 1;
  11701. }
  11702. if (!err) {
  11703. if (sig != NULL) {
  11704. /* Use the ECDSA signature object passed in. */
  11705. s = *sig;
  11706. }
  11707. if (s == NULL) {
  11708. /* No ECDSA signature object passed in - create a new one. */
  11709. s = wolfSSL_ECDSA_SIG_new();
  11710. if (s == NULL) {
  11711. err = 1;
  11712. }
  11713. }
  11714. }
  11715. if (!err) {
  11716. /* DecodeECC_DSA_Sig calls mp_init, so free these. */
  11717. mp_free((mp_int*)s->r->internal);
  11718. mp_free((mp_int*)s->s->internal);
  11719. /* Decode the signature into internal r and s fields. */
  11720. if (DecodeECC_DSA_Sig(*pp, (word32)len, (mp_int*)s->r->internal,
  11721. (mp_int*)s->s->internal) != MP_OKAY) {
  11722. err = 1;
  11723. }
  11724. }
  11725. if (!err) {
  11726. /* Move pointer passed signature data successfully decoded. */
  11727. *pp += wolfssl_der_length(*pp, (int)len);
  11728. if (sig != NULL) {
  11729. /* Update reference to ECDSA signature object. */
  11730. *sig = s;
  11731. }
  11732. }
  11733. /* Dispose of newly allocated object on error. */
  11734. if (err) {
  11735. if ((s != NULL) && ((sig == NULL) || (*sig != s))) {
  11736. wolfSSL_ECDSA_SIG_free(s);
  11737. }
  11738. /* Return NULL for object on error. */
  11739. s = NULL;
  11740. }
  11741. return s;
  11742. }
  11743. /* Encode the ECDSA signature as DER.
  11744. *
  11745. * @param [in] sig ECDSA signature object.
  11746. * @param [in, out] pp On in, reference to buffer in which to place encoding.
  11747. * On out, reference to buffer after encoding.
  11748. * May be NULL or point to NULL in which case no encoding
  11749. * is done.
  11750. * @return Length of encoding on success.
  11751. * @return 0 on error.
  11752. */
  11753. int wolfSSL_i2d_ECDSA_SIG(const WOLFSSL_ECDSA_SIG *sig, unsigned char **pp)
  11754. {
  11755. word32 len = 0;
  11756. /* Validate parameter. */
  11757. if (sig != NULL) {
  11758. /* ASN.1: SEQ + INT + INT
  11759. * ASN.1 Integer must be a positive value - prepend zero if number has
  11760. * top bit set.
  11761. */
  11762. /* Get total length of r including any prepended zero. */
  11763. word32 rLen = mp_leading_bit((mp_int*)sig->r->internal) +
  11764. mp_unsigned_bin_size((mp_int*)sig->r->internal);
  11765. /* Get total length of s including any prepended zero. */
  11766. word32 sLen = mp_leading_bit((mp_int*)sig->s->internal) +
  11767. mp_unsigned_bin_size((mp_int*)sig->s->internal);
  11768. /* Calculate length of data in sequence. */
  11769. len = 1 + ASN_LEN_SIZE(rLen) + rLen +
  11770. 1 + ASN_LEN_SIZE(sLen) + sLen;
  11771. /* Add in the length of the SEQUENCE. */
  11772. len += 1 + ASN_LEN_SIZE(len);
  11773. /* Encode only if there is a buffer to encode into. */
  11774. if ((pp != NULL) && (*pp != NULL)) {
  11775. /* Encode using the internal representations of r and s. */
  11776. if (StoreECC_DSA_Sig(*pp, &len, (mp_int*)sig->r->internal,
  11777. (mp_int*)sig->s->internal) != MP_OKAY) {
  11778. /* No bytes encoded. */
  11779. len = 0;
  11780. }
  11781. else {
  11782. /* Update pointer to after encoding. */
  11783. *pp += len;
  11784. }
  11785. }
  11786. }
  11787. return (int)len;
  11788. }
  11789. /* Get the pointer to the feilds of the ECDSA signature.
  11790. *
  11791. * r and s untouched when sig is NULL.
  11792. *
  11793. * @param [in] sig ECDSA signature object.
  11794. * @param [out] r R field of ECDSA signature as a BN. May be NULL.
  11795. * @param [out] s S field of ECDSA signature as a BN. May be NULL.
  11796. */
  11797. void wolfSSL_ECDSA_SIG_get0(const WOLFSSL_ECDSA_SIG* sig,
  11798. const WOLFSSL_BIGNUM** r, const WOLFSSL_BIGNUM** s)
  11799. {
  11800. /* Validate parameter. */
  11801. if (sig != NULL) {
  11802. /* Return the r BN when pointer to return through. */
  11803. if (r != NULL) {
  11804. *r = sig->r;
  11805. }
  11806. /* Return the s BN when pointer to return through. */
  11807. if (s != NULL) {
  11808. *s = sig->s;
  11809. }
  11810. }
  11811. }
  11812. /* Set the pointers to the fields of the ECDSA signature.
  11813. *
  11814. * @param [in, out] sig ECDSA signature object to update.
  11815. * @param [in] r R field of ECDSA signature as a BN.
  11816. * @param [in] s S field of ECDSA signature as a BN.
  11817. * @return 1 on success.
  11818. * @return 0 on error.
  11819. */
  11820. int wolfSSL_ECDSA_SIG_set0(WOLFSSL_ECDSA_SIG* sig, WOLFSSL_BIGNUM* r,
  11821. WOLFSSL_BIGNUM* s)
  11822. {
  11823. int ret = 1;
  11824. /* Validate parameters. */
  11825. if ((sig == NULL) || (r == NULL) || (s == NULL)) {
  11826. ret = 0;
  11827. }
  11828. if (ret == 1) {
  11829. /* Dispose of old BN objects. */
  11830. wolfSSL_BN_free(sig->r);
  11831. wolfSSL_BN_free(sig->s);
  11832. /* Assign new BN objects. */
  11833. sig->r = r;
  11834. sig->s = s;
  11835. }
  11836. return ret;
  11837. }
  11838. /* End ECDSA_SIG */
  11839. /* Start ECDSA */
  11840. /* Calculate maximum size of the DER encoded ECDSA signature for the curve.
  11841. *
  11842. * @param [in] key EC key.
  11843. * @return Size of DER encoded signature on success.
  11844. * @return 0 on error.
  11845. */
  11846. int wolfSSL_ECDSA_size(const WOLFSSL_EC_KEY *key)
  11847. {
  11848. int err = 0;
  11849. int len = 0;
  11850. const EC_GROUP *group = NULL;
  11851. int bits = 0;
  11852. /* Validate parameter. */
  11853. if (key == NULL) {
  11854. err = 1;
  11855. }
  11856. /* Get group from key to get order bits. */
  11857. if ((!err) && ((group = wolfSSL_EC_KEY_get0_group(key)) == NULL)) {
  11858. err = 1;
  11859. }
  11860. /* Get order bits of group. */
  11861. if ((!err) && ((bits = wolfSSL_EC_GROUP_order_bits(group)) == 0)) {
  11862. /* Group is not set. */
  11863. err = 1;
  11864. }
  11865. if (!err) {
  11866. /* r and s are mod order. */
  11867. int bytes = (bits + 7) / 8; /* Bytes needed to hold bits. */
  11868. len = SIG_HEADER_SZ + /* 2*ASN_TAG + 2*LEN(ENUM) */
  11869. ECC_MAX_PAD_SZ + /* possible leading zeroes in r and s */
  11870. bytes + bytes; /* max r and s in bytes */
  11871. }
  11872. return len;
  11873. }
  11874. /* Create ECDSA signature by signing digest with key.
  11875. *
  11876. * @param [in] dgst Digest to sign.
  11877. * @param [in] dLen Length of digest in bytes.
  11878. * @param [in] key EC key to sign with.
  11879. * @return ECDSA signature object on success.
  11880. * @return NULL on error.
  11881. */
  11882. WOLFSSL_ECDSA_SIG *wolfSSL_ECDSA_do_sign(const unsigned char *dgst, int dLen,
  11883. WOLFSSL_EC_KEY *key)
  11884. {
  11885. int err = 0;
  11886. WOLFSSL_ECDSA_SIG *sig = NULL;
  11887. #ifdef WOLFSSL_SMALL_STACK
  11888. byte* out = NULL;
  11889. #else
  11890. byte out[ECC_BUFSIZE];
  11891. #endif
  11892. unsigned int outLen = ECC_BUFSIZE;
  11893. WOLFSSL_ENTER("wolfSSL_ECDSA_do_sign");
  11894. /* Validate parameters. */
  11895. if ((dgst == NULL) || (key == NULL) || (key->internal == NULL)) {
  11896. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign Bad arguments");
  11897. err = 1;
  11898. }
  11899. /* Ensure internal EC key is set from external. */
  11900. if ((!err) && (key->inSet == 0)) {
  11901. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign No EC key internal set, do it");
  11902. if (SetECKeyInternal(key) != 1) {
  11903. WOLFSSL_MSG("wolfSSL_ECDSA_do_sign SetECKeyInternal failed");
  11904. err = 1;
  11905. }
  11906. }
  11907. #ifdef WOLFSSL_SMALL_STACK
  11908. if (!err) {
  11909. /* Allocate buffer to hold encoded signature. */
  11910. out = (byte*)XMALLOC(outLen, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11911. if (out == NULL) {
  11912. err = 1;
  11913. }
  11914. }
  11915. #endif
  11916. /* Sign the digest with the key to create encoded ECDSA signature. */
  11917. if ((!err) && (wolfSSL_ECDSA_sign(0, dgst, dLen, out, &outLen, key) != 1)) {
  11918. err = 1;
  11919. }
  11920. if (!err) {
  11921. const byte* p = out;
  11922. /* Decode the ECDSA signature into a new object. */
  11923. sig = wolfSSL_d2i_ECDSA_SIG(NULL, &p, outLen);
  11924. }
  11925. #ifdef WOLFSSL_SMALL_STACK
  11926. /* Dispose of any temporary dynamically allocated data. */
  11927. XFREE(out, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  11928. #endif
  11929. return sig;
  11930. }
  11931. /* Verify ECDSA signature in the object using digest and key.
  11932. *
  11933. * Return code compliant with OpenSSL.
  11934. *
  11935. * @param [in] dgst Digest to verify.
  11936. * @param [in] dLen Length of the digest in bytes.
  11937. * @param [in] sig ECDSA signature object.
  11938. * @param [in] key EC key containing public key.
  11939. * @return 1 when signature is valid.
  11940. * @return 0 when signature is invalid.
  11941. * @return -1 on error.
  11942. */
  11943. int wolfSSL_ECDSA_do_verify(const unsigned char *dgst, int dLen,
  11944. const WOLFSSL_ECDSA_SIG *sig, WOLFSSL_EC_KEY *key)
  11945. {
  11946. int ret = 1;
  11947. int verified = 0;
  11948. #ifdef WOLF_CRYPTO_CB_ONLY_ECC
  11949. byte signature[ECC_MAX_SIG_SIZE];
  11950. int signatureLen;
  11951. byte* p = signature;
  11952. #endif
  11953. WOLFSSL_ENTER("wolfSSL_ECDSA_do_verify");
  11954. /* Validate parameters. */
  11955. if ((dgst == NULL) || (sig == NULL) || (key == NULL) ||
  11956. (key->internal == NULL)) {
  11957. WOLFSSL_MSG("wolfSSL_ECDSA_do_verify Bad arguments");
  11958. ret = -1;
  11959. }
  11960. /* Ensure internal EC key is set from external. */
  11961. if ((ret == 1) && (key->inSet == 0)) {
  11962. WOLFSSL_MSG("No EC key internal set, do it");
  11963. if (SetECKeyInternal(key) != 1) {
  11964. WOLFSSL_MSG("SetECKeyInternal failed");
  11965. ret = -1;
  11966. }
  11967. }
  11968. if (ret == 1) {
  11969. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  11970. /* Verify hash using digest, r and s as MP ints and internal EC key. */
  11971. if (wc_ecc_verify_hash_ex((mp_int*)sig->r->internal,
  11972. (mp_int*)sig->s->internal, dgst, dLen, &verified,
  11973. (ecc_key *)key->internal) != MP_OKAY) {
  11974. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  11975. ret = -1;
  11976. }
  11977. else if (verified == 0) {
  11978. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  11979. ret = 0;
  11980. }
  11981. #else
  11982. signatureLen = i2d_ECDSA_SIG(sig, &p);
  11983. if (signatureLen > 0) {
  11984. /* verify hash. expects to call wc_CryptoCb_EccVerify internally */
  11985. ret = wc_ecc_verify_hash(signature, signatureLen, dgst, dLen,
  11986. &verified, (ecc_key*)key->internal);
  11987. if (ret != MP_OKAY) {
  11988. WOLFSSL_MSG("wc_ecc_verify_hash failed");
  11989. ret = -1;
  11990. }
  11991. else if (verified == 0) {
  11992. WOLFSSL_MSG("wc_ecc_verify_hash incorrect signature detected");
  11993. ret = 0;
  11994. }
  11995. }
  11996. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  11997. }
  11998. return ret;
  11999. }
  12000. /* Sign the digest with the key to produce a DER encode signature.
  12001. *
  12002. * @param [in] type Digest algorithm used to create digest. Unused.
  12003. * @param [in] digest Digest of the message to sign.
  12004. * @param [in] digestSz Size of the digest in bytes.
  12005. * @param [out] sig Buffer to hold signature.
  12006. * @param [in, out] sigSz On in, size of buffer in bytes.
  12007. * On out, size of signatre in bytes.
  12008. * @param [in] key EC key containing private key.
  12009. * @return 1 on success.
  12010. * @return 0 on error.
  12011. */
  12012. int wolfSSL_ECDSA_sign(int type, const unsigned char *digest, int digestSz,
  12013. unsigned char *sig, unsigned int *sigSz, WOLFSSL_EC_KEY *key)
  12014. {
  12015. int ret = 1;
  12016. WC_RNG* rng = NULL;
  12017. #ifdef WOLFSSL_SMALL_STACK
  12018. WC_RNG* tmpRng = NULL;
  12019. #else
  12020. WC_RNG tmpRng[1];
  12021. #endif
  12022. int initTmpRng = 0;
  12023. WOLFSSL_ENTER("wolfSSL_ECDSA_sign");
  12024. /* Digest algorithm not used in DER encoding. */
  12025. (void)type;
  12026. /* Validate parameters. */
  12027. if (key == NULL) {
  12028. ret = 0;
  12029. }
  12030. if (ret == 1) {
  12031. /* Make an RNG - create local or get global. */
  12032. rng = wolfssl_make_rng(tmpRng, &initTmpRng);
  12033. if (rng == NULL) {
  12034. ret = 0;
  12035. }
  12036. }
  12037. /* Sign the digest with the key using the RNG and put signature into buffer
  12038. * update sigSz to be actual length.
  12039. */
  12040. if ((ret == 1) && (wc_ecc_sign_hash(digest, digestSz, sig, sigSz, rng,
  12041. (ecc_key*)key->internal) != 0)) {
  12042. ret = 0;
  12043. }
  12044. if (initTmpRng) {
  12045. wc_FreeRng(rng);
  12046. #ifdef WOLFSSL_SMALL_STACK
  12047. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  12048. #endif
  12049. }
  12050. return ret;
  12051. }
  12052. /* Verify the signature with the digest and key.
  12053. *
  12054. * @param [in] type Digest algorithm used to create digest. Unused.
  12055. * @param [in] digest Digest of the message to verify.
  12056. * @param [in] digestSz Size of the digest in bytes.
  12057. * @param [in] sig Buffer holding signature.
  12058. * @param [in] sigSz Size of signature data in bytes.
  12059. * @param [in] key EC key containing public key.
  12060. * @return 1 when signature is valid.
  12061. * @return 0 when signature is invalid or error.
  12062. */
  12063. int wolfSSL_ECDSA_verify(int type, const unsigned char *digest, int digestSz,
  12064. const unsigned char *sig, int sigSz, WOLFSSL_EC_KEY *key)
  12065. {
  12066. int ret = 1;
  12067. int verify = 0;
  12068. WOLFSSL_ENTER("wolfSSL_ECDSA_verify");
  12069. /* Digest algorithm not used in DER encoding. */
  12070. (void)type;
  12071. /* Validate parameters. */
  12072. if (key == NULL) {
  12073. ret = 0;
  12074. }
  12075. /* Verify signature using digest and key. */
  12076. if ((ret == 1) && (wc_ecc_verify_hash(sig, sigSz, digest, digestSz, &verify,
  12077. (ecc_key*)key->internal) != 0)) {
  12078. ret = 0;
  12079. }
  12080. /* When no error, verification may still have failed - check now. */
  12081. if ((ret == 1) && (verify != 1)) {
  12082. WOLFSSL_MSG("wolfSSL_ECDSA_verify failed");
  12083. ret = 0;
  12084. }
  12085. return ret;
  12086. }
  12087. /* End ECDSA */
  12088. /* Start ECDH */
  12089. #ifndef WOLF_CRYPTO_CB_ONLY_ECC
  12090. /* Compute the shared secret (key) using ECDH.
  12091. *
  12092. * KDF not supported.
  12093. *
  12094. * Return code compliant with OpenSSL.
  12095. *
  12096. * @param [out] out Buffer to hold key.
  12097. * @param [in] outLen Length of buffer in bytes.
  12098. * @param [in] pubKey Public key as an EC point.
  12099. * @param [in] privKey EC key holding a private key.
  12100. * @param [in] kdf Key derivation function to apply to secret.
  12101. * @return Length of computed key on success
  12102. * @return 0 on error.
  12103. */
  12104. int wolfSSL_ECDH_compute_key(void *out, size_t outLen,
  12105. const WOLFSSL_EC_POINT *pubKey, WOLFSSL_EC_KEY *privKey,
  12106. void *(*kdf) (const void *in, size_t inlen, void *out, size_t *outLen))
  12107. {
  12108. int err = 0;
  12109. word32 len = 0;
  12110. ecc_key* key = NULL;
  12111. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12112. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12113. int setGlobalRNG = 0;
  12114. #endif
  12115. /* TODO: support using the KDF. */
  12116. (void)kdf;
  12117. WOLFSSL_ENTER("wolfSSL_ECDH_compute_key");
  12118. /* Validate parameters. */
  12119. if ((out == NULL) || (pubKey == NULL) || (pubKey->internal == NULL) ||
  12120. (privKey == NULL) || (privKey->internal == NULL)) {
  12121. WOLFSSL_MSG("Bad function arguments");
  12122. err = 1;
  12123. }
  12124. /* Ensure internal EC key is set from external. */
  12125. if ((!err) && (privKey->inSet == 0)) {
  12126. WOLFSSL_MSG("No EC key internal set, do it");
  12127. if (SetECKeyInternal(privKey) != 1) {
  12128. WOLFSSL_MSG("SetECKeyInternal failed");
  12129. err = 1;
  12130. }
  12131. }
  12132. if (!err) {
  12133. int ret;
  12134. /* Get the internal key. */
  12135. key = (ecc_key*)privKey->internal;
  12136. /* Set length into variable of type suitable for wolfSSL API. */
  12137. len = (word32)outLen;
  12138. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12139. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12140. /* An RNG is needed. */
  12141. if (key->rng == NULL) {
  12142. key->rng = wolfssl_make_global_rng();
  12143. /* RNG set and needs to be unset. */
  12144. setGlobalRNG = 1;
  12145. }
  12146. #endif
  12147. PRIVATE_KEY_UNLOCK();
  12148. /* Create secret using wolfSSL. */
  12149. ret = wc_ecc_shared_secret_ex(key, (ecc_point*)pubKey->internal,
  12150. (byte *)out, &len);
  12151. PRIVATE_KEY_LOCK();
  12152. if (ret != MP_OKAY) {
  12153. WOLFSSL_MSG("wc_ecc_shared_secret failed");
  12154. err = 1;
  12155. }
  12156. }
  12157. #if defined(ECC_TIMING_RESISTANT) && !defined(HAVE_SELFTEST) && \
  12158. (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5,0))
  12159. /* Remove global from key. */
  12160. if (setGlobalRNG) {
  12161. key->rng = NULL;
  12162. }
  12163. #endif
  12164. if (err) {
  12165. /* Make returned value zero. */
  12166. len = 0;
  12167. }
  12168. return (int)len;
  12169. }
  12170. #endif /* WOLF_CRYPTO_CB_ONLY_ECC */
  12171. /* End ECDH */
  12172. #endif /* OPENSSL_EXTRA */
  12173. #endif /* HAVE_ECC */
  12174. /*******************************************************************************
  12175. * END OF EC API
  12176. ******************************************************************************/
  12177. #endif /* !WOLFSSL_PK_INCLUDED */