rsa.c 136 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716
  1. /* rsa.c
  2. *
  3. * Copyright (C) 2006-2021 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. /*
  22. DESCRIPTION
  23. This library provides the interface to the RSA.
  24. RSA keys can be used to encrypt, decrypt, sign and verify data.
  25. */
  26. #ifdef HAVE_CONFIG_H
  27. #include <config.h>
  28. #endif
  29. #include <wolfssl/wolfcrypt/settings.h>
  30. #include <wolfssl/wolfcrypt/error-crypt.h>
  31. #ifndef NO_RSA
  32. #if defined(HAVE_FIPS) && \
  33. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2)
  34. /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
  35. #define FIPS_NO_WRAPPERS
  36. #ifdef USE_WINDOWS_API
  37. #pragma code_seg(".fipsA$e")
  38. #pragma const_seg(".fipsB$e")
  39. #endif
  40. #endif
  41. #include <wolfssl/wolfcrypt/rsa.h>
  42. #ifdef WOLFSSL_AFALG_XILINX_RSA
  43. #include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
  44. #endif
  45. #ifdef WOLFSSL_HAVE_SP_RSA
  46. #include <wolfssl/wolfcrypt/sp.h>
  47. #endif
  48. /*
  49. Possible RSA enable options:
  50. * NO_RSA: Overall control of RSA default: on (not defined)
  51. * WC_RSA_BLINDING: Uses Blinding w/ Private Ops default: off
  52. Note: slower by ~20%
  53. * WOLFSSL_KEY_GEN: Allows Private Key Generation default: off
  54. * RSA_LOW_MEM: NON CRT Private Operations, less memory default: off
  55. * WC_NO_RSA_OAEP: Disables RSA OAEP padding default: on (not defined)
  56. * WC_RSA_NONBLOCK: Enables support for RSA non-blocking default: off
  57. * WC_RSA_NONBLOCK_TIME:Enables support for time based blocking default: off
  58. * time calculation.
  59. */
  60. /*
  61. RSA Key Size Configuration:
  62. * FP_MAX_BITS: With USE_FAST_MATH only default: 4096
  63. If USE_FAST_MATH then use this to override default.
  64. Value is key size * 2. Example: RSA 3072 = 6144
  65. */
  66. /* If building for old FIPS. */
  67. #if defined(HAVE_FIPS) && \
  68. (!defined(HAVE_FIPS_VERSION) || (HAVE_FIPS_VERSION < 2))
  69. int wc_InitRsaKey(RsaKey* key, void* ptr)
  70. {
  71. if (key == NULL) {
  72. return BAD_FUNC_ARG;
  73. }
  74. return InitRsaKey_fips(key, ptr);
  75. }
  76. int wc_InitRsaKey_ex(RsaKey* key, void* ptr, int devId)
  77. {
  78. (void)devId;
  79. if (key == NULL) {
  80. return BAD_FUNC_ARG;
  81. }
  82. return InitRsaKey_fips(key, ptr);
  83. }
  84. int wc_FreeRsaKey(RsaKey* key)
  85. {
  86. return FreeRsaKey_fips(key);
  87. }
  88. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  89. int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
  90. word32 outLen, RsaKey* key, WC_RNG* rng)
  91. {
  92. if (in == NULL || out == NULL || key == NULL || rng == NULL) {
  93. return BAD_FUNC_ARG;
  94. }
  95. return RsaPublicEncrypt_fips(in, inLen, out, outLen, key, rng);
  96. }
  97. #endif
  98. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  99. int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out,
  100. RsaKey* key)
  101. {
  102. if (in == NULL || out == NULL || key == NULL) {
  103. return BAD_FUNC_ARG;
  104. }
  105. return RsaPrivateDecryptInline_fips(in, inLen, out, key);
  106. }
  107. int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
  108. word32 outLen, RsaKey* key)
  109. {
  110. if (in == NULL || out == NULL || key == NULL) {
  111. return BAD_FUNC_ARG;
  112. }
  113. return RsaPrivateDecrypt_fips(in, inLen, out, outLen, key);
  114. }
  115. int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
  116. word32 outLen, RsaKey* key, WC_RNG* rng)
  117. {
  118. if (in == NULL || out == NULL || key == NULL || inLen == 0) {
  119. return BAD_FUNC_ARG;
  120. }
  121. return RsaSSL_Sign_fips(in, inLen, out, outLen, key, rng);
  122. }
  123. #endif
  124. int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
  125. {
  126. if (in == NULL || out == NULL || key == NULL) {
  127. return BAD_FUNC_ARG;
  128. }
  129. return RsaSSL_VerifyInline_fips(in, inLen, out, key);
  130. }
  131. int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out,
  132. word32 outLen, RsaKey* key)
  133. {
  134. if (in == NULL || out == NULL || key == NULL || inLen == 0) {
  135. return BAD_FUNC_ARG;
  136. }
  137. return RsaSSL_Verify_fips(in, inLen, out, outLen, key);
  138. }
  139. int wc_RsaEncryptSize(const RsaKey* key)
  140. {
  141. if (key == NULL) {
  142. return BAD_FUNC_ARG;
  143. }
  144. return RsaEncryptSize_fips((RsaKey*)key);
  145. }
  146. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  147. int wc_RsaFlattenPublicKey(RsaKey* key, byte* a, word32* aSz, byte* b,
  148. word32* bSz)
  149. {
  150. /* not specified as fips so not needing _fips */
  151. return RsaFlattenPublicKey(key, a, aSz, b, bSz);
  152. }
  153. #endif
  154. #ifdef WOLFSSL_KEY_GEN
  155. int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
  156. {
  157. return MakeRsaKey(key, size, e, rng);
  158. }
  159. #endif
  160. /* these are functions in asn and are routed to wolfssl/wolfcrypt/asn.c
  161. * wc_RsaPrivateKeyDecode
  162. * wc_RsaPublicKeyDecode
  163. */
  164. #else /* else build without fips, or for new fips */
  165. #include <wolfssl/wolfcrypt/random.h>
  166. #include <wolfssl/wolfcrypt/logging.h>
  167. #ifdef WOLF_CRYPTO_CB
  168. #include <wolfssl/wolfcrypt/cryptocb.h>
  169. #endif
  170. #ifdef NO_INLINE
  171. #include <wolfssl/wolfcrypt/misc.h>
  172. #else
  173. #define WOLFSSL_MISC_INCLUDED
  174. #include <wolfcrypt/src/misc.c>
  175. #endif
  176. enum {
  177. RSA_STATE_NONE = 0,
  178. RSA_STATE_ENCRYPT_PAD,
  179. RSA_STATE_ENCRYPT_EXPTMOD,
  180. RSA_STATE_ENCRYPT_RES,
  181. RSA_STATE_DECRYPT_EXPTMOD,
  182. RSA_STATE_DECRYPT_UNPAD,
  183. RSA_STATE_DECRYPT_RES,
  184. };
  185. static void wc_RsaCleanup(RsaKey* key)
  186. {
  187. #ifndef WOLFSSL_RSA_VERIFY_INLINE
  188. if (key && key->data) {
  189. /* make sure any allocated memory is free'd */
  190. if (key->dataIsAlloc) {
  191. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  192. if (key->type == RSA_PRIVATE_DECRYPT ||
  193. key->type == RSA_PRIVATE_ENCRYPT) {
  194. ForceZero(key->data, key->dataLen);
  195. }
  196. #endif
  197. XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
  198. key->dataIsAlloc = 0;
  199. }
  200. key->data = NULL;
  201. key->dataLen = 0;
  202. }
  203. #else
  204. (void)key;
  205. #endif
  206. }
  207. int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
  208. {
  209. int ret = 0;
  210. if (key == NULL) {
  211. return BAD_FUNC_ARG;
  212. }
  213. XMEMSET(key, 0, sizeof(RsaKey));
  214. key->type = RSA_TYPE_UNKNOWN;
  215. key->state = RSA_STATE_NONE;
  216. key->heap = heap;
  217. #ifndef WOLFSSL_RSA_VERIFY_INLINE
  218. key->dataIsAlloc = 0;
  219. key->data = NULL;
  220. #endif
  221. key->dataLen = 0;
  222. #ifdef WC_RSA_BLINDING
  223. key->rng = NULL;
  224. #endif
  225. #ifdef WOLF_CRYPTO_CB
  226. key->devId = devId;
  227. #else
  228. (void)devId;
  229. #endif
  230. #ifdef WOLFSSL_ASYNC_CRYPT
  231. #ifdef WOLFSSL_CERT_GEN
  232. XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
  233. #endif
  234. #ifdef WC_ASYNC_ENABLE_RSA
  235. /* handle as async */
  236. ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA,
  237. key->heap, devId);
  238. if (ret != 0)
  239. return ret;
  240. #endif /* WC_ASYNC_ENABLE_RSA */
  241. #endif /* WOLFSSL_ASYNC_CRYPT */
  242. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  243. ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
  244. if (ret != MP_OKAY)
  245. return ret;
  246. #if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
  247. ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
  248. #else
  249. ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
  250. #endif
  251. if (ret != MP_OKAY) {
  252. mp_clear(&key->n);
  253. mp_clear(&key->e);
  254. return ret;
  255. }
  256. #else
  257. ret = mp_init(&key->n);
  258. if (ret != MP_OKAY)
  259. return ret;
  260. ret = mp_init(&key->e);
  261. if (ret != MP_OKAY) {
  262. mp_clear(&key->n);
  263. return ret;
  264. }
  265. #endif
  266. #ifdef WOLFSSL_XILINX_CRYPT
  267. key->pubExp = 0;
  268. key->mod = NULL;
  269. #endif
  270. #ifdef WOLFSSL_AFALG_XILINX_RSA
  271. key->alFd = WC_SOCK_NOTSET;
  272. key->rdFd = WC_SOCK_NOTSET;
  273. #endif
  274. #ifdef WOLFSSL_KCAPI_RSA
  275. key->handle = NULL;
  276. #endif
  277. return ret;
  278. }
  279. int wc_InitRsaKey(RsaKey* key, void* heap)
  280. {
  281. return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
  282. }
  283. #ifdef WOLF_CRYPTO_CB
  284. int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
  285. int devId)
  286. {
  287. int ret = 0;
  288. if (key == NULL)
  289. ret = BAD_FUNC_ARG;
  290. if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
  291. ret = BUFFER_E;
  292. if (ret == 0)
  293. ret = wc_InitRsaKey_ex(key, heap, devId);
  294. if (ret == 0 && id != NULL && len != 0) {
  295. XMEMCPY(key->id, id, len);
  296. key->idLen = len;
  297. }
  298. return ret;
  299. }
  300. int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId)
  301. {
  302. int ret = 0;
  303. int labelLen = 0;
  304. if (key == NULL || label == NULL)
  305. ret = BAD_FUNC_ARG;
  306. if (ret == 0) {
  307. labelLen = (int)XSTRLEN(label);
  308. if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN)
  309. ret = BUFFER_E;
  310. }
  311. if (ret == 0)
  312. ret = wc_InitRsaKey_ex(key, heap, devId);
  313. if (ret == 0) {
  314. XMEMCPY(key->label, label, labelLen);
  315. key->labelLen = labelLen;
  316. }
  317. return ret;
  318. }
  319. #endif
  320. #ifdef WOLFSSL_XILINX_CRYPT
  321. #define MAX_E_SIZE 4
  322. /* Used to setup hardware state
  323. *
  324. * key the RSA key to setup
  325. *
  326. * returns 0 on success
  327. */
  328. int wc_InitRsaHw(RsaKey* key)
  329. {
  330. unsigned char* m; /* RSA modulus */
  331. word32 e = 0; /* RSA public exponent */
  332. int mSz;
  333. int eSz;
  334. if (key == NULL) {
  335. return BAD_FUNC_ARG;
  336. }
  337. mSz = mp_unsigned_bin_size(&(key->n));
  338. m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
  339. if (m == NULL) {
  340. return MEMORY_E;
  341. }
  342. if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
  343. WOLFSSL_MSG("Unable to get RSA key modulus");
  344. XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
  345. return MP_READ_E;
  346. }
  347. eSz = mp_unsigned_bin_size(&(key->e));
  348. if (eSz > MAX_E_SIZE) {
  349. WOLFSSL_MSG("Exponent of size 4 bytes expected");
  350. XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
  351. return BAD_FUNC_ARG;
  352. }
  353. if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
  354. != MP_OKAY) {
  355. XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
  356. WOLFSSL_MSG("Unable to get RSA key exponent");
  357. return MP_READ_E;
  358. }
  359. /* check for existing mod buffer to avoid memory leak */
  360. if (key->mod != NULL) {
  361. XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
  362. }
  363. key->pubExp = e;
  364. key->mod = m;
  365. if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
  366. (byte*)&(key->pubExp)) != XST_SUCCESS) {
  367. WOLFSSL_MSG("Unable to initialize RSA on hardware");
  368. XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
  369. return BAD_STATE_E;
  370. }
  371. #ifdef WOLFSSL_XILINX_PATCH
  372. /* currently a patch of xsecure_rsa.c for 2048 bit keys */
  373. if (wc_RsaEncryptSize(key) == 256) {
  374. if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
  375. WOLFSSL_MSG("Unable to set RSA key size on hardware");
  376. XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
  377. return BAD_STATE_E;
  378. }
  379. }
  380. #endif
  381. return 0;
  382. } /* WOLFSSL_XILINX_CRYPT*/
  383. #elif defined(WOLFSSL_CRYPTOCELL)
  384. int wc_InitRsaHw(RsaKey* key)
  385. {
  386. CRYSError_t ret = 0;
  387. byte e[3];
  388. word32 eSz = sizeof(e);
  389. byte n[256];
  390. word32 nSz = sizeof(n);
  391. byte d[256];
  392. word32 dSz = sizeof(d);
  393. byte p[128];
  394. word32 pSz = sizeof(p);
  395. byte q[128];
  396. word32 qSz = sizeof(q);
  397. if (key == NULL) {
  398. return BAD_FUNC_ARG;
  399. }
  400. ret = wc_RsaExportKey(key, e, &eSz, n, &nSz, d, &dSz, p, &pSz, q, &qSz);
  401. if (ret != 0)
  402. return MP_READ_E;
  403. ret = CRYS_RSA_Build_PubKey(&key->ctx.pubKey, e, eSz, n, nSz);
  404. if (ret != SA_SILIB_RET_OK){
  405. WOLFSSL_MSG("CRYS_RSA_Build_PubKey failed");
  406. return ret;
  407. }
  408. ret = CRYS_RSA_Build_PrivKey(&key->ctx.privKey, d, dSz, e, eSz, n, nSz);
  409. if (ret != SA_SILIB_RET_OK){
  410. WOLFSSL_MSG("CRYS_RSA_Build_PrivKey failed");
  411. return ret;
  412. }
  413. key->type = RSA_PRIVATE;
  414. return 0;
  415. }
  416. static int cc310_RSA_GenerateKeyPair(RsaKey* key, int size, long e)
  417. {
  418. CRYSError_t ret = 0;
  419. CRYS_RSAKGData_t KeyGenData;
  420. CRYS_RSAKGFipsContext_t FipsCtx;
  421. byte ex[3];
  422. word16 eSz = sizeof(ex);
  423. byte n[256];
  424. word16 nSz = sizeof(n);
  425. ret = CRYS_RSA_KG_GenerateKeyPair(&wc_rndState,
  426. wc_rndGenVectFunc,
  427. (byte*)&e,
  428. 3*sizeof(byte),
  429. size,
  430. &key->ctx.privKey,
  431. &key->ctx.pubKey,
  432. &KeyGenData,
  433. &FipsCtx);
  434. if (ret != SA_SILIB_RET_OK){
  435. WOLFSSL_MSG("CRYS_RSA_KG_GenerateKeyPair failed");
  436. return ret;
  437. }
  438. ret = CRYS_RSA_Get_PubKey(&key->ctx.pubKey, ex, &eSz, n, &nSz);
  439. if (ret != SA_SILIB_RET_OK){
  440. WOLFSSL_MSG("CRYS_RSA_Get_PubKey failed");
  441. return ret;
  442. }
  443. ret = wc_RsaPublicKeyDecodeRaw(n, nSz, ex, eSz, key);
  444. key->type = RSA_PRIVATE;
  445. return ret;
  446. }
  447. #endif /* WOLFSSL_CRYPTOCELL */
  448. int wc_FreeRsaKey(RsaKey* key)
  449. {
  450. int ret = 0;
  451. if (key == NULL) {
  452. return BAD_FUNC_ARG;
  453. }
  454. wc_RsaCleanup(key);
  455. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
  456. wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
  457. #endif
  458. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  459. if (key->type == RSA_PRIVATE) {
  460. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  461. mp_forcezero(&key->u);
  462. mp_forcezero(&key->dQ);
  463. mp_forcezero(&key->dP);
  464. #endif
  465. mp_forcezero(&key->q);
  466. mp_forcezero(&key->p);
  467. mp_forcezero(&key->d);
  468. }
  469. /* private part */
  470. #if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
  471. mp_clear(&key->u);
  472. mp_clear(&key->dQ);
  473. mp_clear(&key->dP);
  474. #endif
  475. mp_clear(&key->q);
  476. mp_clear(&key->p);
  477. mp_clear(&key->d);
  478. #endif /* WOLFSSL_RSA_PUBLIC_ONLY */
  479. /* public part */
  480. mp_clear(&key->e);
  481. mp_clear(&key->n);
  482. #ifdef WOLFSSL_XILINX_CRYPT
  483. XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
  484. key->mod = NULL;
  485. #endif
  486. #ifdef WOLFSSL_AFALG_XILINX_RSA
  487. /* make sure that sockets are closed on cleanup */
  488. if (key->alFd > 0) {
  489. close(key->alFd);
  490. key->alFd = WC_SOCK_NOTSET;
  491. }
  492. if (key->rdFd > 0) {
  493. close(key->rdFd);
  494. key->rdFd = WC_SOCK_NOTSET;
  495. }
  496. #endif
  497. #ifdef WOLFSSL_KCAPI_RSA
  498. KcapiRsa_Free(key);
  499. #endif
  500. return ret;
  501. }
  502. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  503. #if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_NO_RSA_KEY_CHECK)
  504. /* Check the pair-wise consistency of the RSA key. */
  505. static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng)
  506. {
  507. const char* msg = "Everyone gets Friday off.";
  508. byte* sig;
  509. byte* plain;
  510. int ret = 0;
  511. word32 msgLen, plainLen, sigLen;
  512. msgLen = (word32)XSTRLEN(msg);
  513. sigLen = wc_RsaEncryptSize(key);
  514. /* Sign and verify. */
  515. sig = (byte*)XMALLOC(sigLen, NULL, DYNAMIC_TYPE_RSA);
  516. if (sig == NULL) {
  517. return MEMORY_E;
  518. }
  519. XMEMSET(sig, 0, sigLen);
  520. plain = sig;
  521. #ifdef WOLFSSL_ASYNC_CRYPT
  522. /* Do blocking async calls here, caller does not support WC_PENDING_E */
  523. do {
  524. if (ret == WC_PENDING_E)
  525. ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  526. if (ret >= 0)
  527. #endif
  528. ret = wc_RsaSSL_Sign((const byte*)msg, msgLen, sig, sigLen, key, rng);
  529. #ifdef WOLFSSL_ASYNC_CRYPT
  530. } while (ret == WC_PENDING_E);
  531. #endif
  532. if (ret > 0) {
  533. sigLen = (word32)ret;
  534. #ifdef WOLFSSL_ASYNC_CRYPT
  535. /* Do blocking async calls here, caller does not support WC_PENDING_E */
  536. do {
  537. if (ret == WC_PENDING_E)
  538. ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
  539. if (ret >= 0)
  540. #endif
  541. ret = wc_RsaSSL_VerifyInline(sig, sigLen, &plain, key);
  542. #ifdef WOLFSSL_ASYNC_CRYPT
  543. } while (ret == WC_PENDING_E);
  544. #endif
  545. }
  546. if (ret > 0) {
  547. plainLen = (word32)ret;
  548. ret = (msgLen != plainLen) || (XMEMCMP(plain, msg, msgLen) != 0);
  549. }
  550. if (ret != 0)
  551. ret = RSA_KEY_PAIR_E;
  552. ForceZero(sig, sigLen);
  553. XFREE(sig, NULL, DYNAMIC_TYPE_RSA);
  554. return ret;
  555. }
  556. int wc_CheckRsaKey(RsaKey* key)
  557. {
  558. #if defined(WOLFSSL_CRYPTOCELL)
  559. return 0;
  560. #endif
  561. #ifdef WOLFSSL_SMALL_STACK
  562. mp_int *tmp = NULL;
  563. WC_RNG *rng = NULL;
  564. #else
  565. mp_int tmp[1];
  566. WC_RNG rng[1];
  567. #endif
  568. int ret = 0;
  569. #ifdef WOLFSSL_SMALL_STACK
  570. rng = (WC_RNG*)XMALLOC(sizeof(WC_RNG), NULL, DYNAMIC_TYPE_RNG);
  571. if (rng != NULL)
  572. tmp = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_RSA);
  573. if (rng == NULL || tmp == NULL) {
  574. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  575. XFREE(tmp, NULL, DYNAMIC_TYPE_RSA);
  576. return MEMORY_E;
  577. }
  578. #endif
  579. ret = wc_InitRng(rng);
  580. if (ret == 0)
  581. SAVE_VECTOR_REGISTERS(ret = _svr_ret;);
  582. if (ret == 0) {
  583. if (mp_init(tmp) != MP_OKAY)
  584. ret = MP_INIT_E;
  585. }
  586. if (ret == 0) {
  587. if (key == NULL)
  588. ret = BAD_FUNC_ARG;
  589. }
  590. if (ret == 0)
  591. ret = _ifc_pairwise_consistency_test(key, rng);
  592. /* Check d is less than n. */
  593. if (ret == 0 ) {
  594. if (mp_cmp(&key->d, &key->n) != MP_LT) {
  595. ret = MP_EXPTMOD_E;
  596. }
  597. }
  598. /* Check p*q = n. */
  599. if (ret == 0 ) {
  600. if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
  601. ret = MP_EXPTMOD_E;
  602. }
  603. }
  604. if (ret == 0 ) {
  605. if (mp_cmp(&key->n, tmp) != MP_EQ) {
  606. ret = MP_EXPTMOD_E;
  607. }
  608. }
  609. /* Check dP, dQ and u if they exist */
  610. if (ret == 0 && !mp_iszero(&key->dP)) {
  611. if (mp_sub_d(&key->p, 1, tmp) != MP_OKAY) {
  612. ret = MP_EXPTMOD_E;
  613. }
  614. /* Check dP <= p-1. */
  615. if (ret == 0) {
  616. if (mp_cmp(&key->dP, tmp) != MP_LT) {
  617. ret = MP_EXPTMOD_E;
  618. }
  619. }
  620. /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
  621. if (ret == 0) {
  622. if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
  623. ret = MP_EXPTMOD_E;
  624. }
  625. }
  626. if (ret == 0 ) {
  627. if (!mp_isone(tmp)) {
  628. ret = MP_EXPTMOD_E;
  629. }
  630. }
  631. if (ret == 0) {
  632. if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
  633. ret = MP_EXPTMOD_E;
  634. }
  635. }
  636. /* Check dQ <= q-1. */
  637. if (ret == 0) {
  638. if (mp_cmp(&key->dQ, tmp) != MP_LT) {
  639. ret = MP_EXPTMOD_E;
  640. }
  641. }
  642. /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
  643. if (ret == 0) {
  644. if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
  645. ret = MP_EXPTMOD_E;
  646. }
  647. }
  648. if (ret == 0 ) {
  649. if (!mp_isone(tmp)) {
  650. ret = MP_EXPTMOD_E;
  651. }
  652. }
  653. /* Check u <= p. */
  654. if (ret == 0) {
  655. if (mp_cmp(&key->u, &key->p) != MP_LT) {
  656. ret = MP_EXPTMOD_E;
  657. }
  658. }
  659. /* Check u*q mod p = 1. (u = 1/q mod p) */
  660. if (ret == 0) {
  661. if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
  662. ret = MP_EXPTMOD_E;
  663. }
  664. }
  665. if (ret == 0 ) {
  666. if (!mp_isone(tmp)) {
  667. ret = MP_EXPTMOD_E;
  668. }
  669. }
  670. }
  671. mp_forcezero(tmp);
  672. mp_clear(tmp);
  673. RESTORE_VECTOR_REGISTERS();
  674. wc_FreeRng(rng);
  675. #ifdef WOLFSSL_SMALL_STACK
  676. XFREE(tmp, NULL, DYNAMIC_TYPE_RSA);
  677. XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
  678. #endif
  679. return ret;
  680. }
  681. #endif /* WOLFSSL_KEY_GEN && !WOLFSSL_NO_RSA_KEY_CHECK */
  682. #endif /* WOLFSSL_RSA_PUBLIC_ONLY */
  683. #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)
  684. /* Uses MGF1 standard as a mask generation function
  685. hType: hash type used
  686. seed: seed to use for generating mask
  687. seedSz: size of seed buffer
  688. out: mask output after generation
  689. outSz: size of output buffer
  690. */
  691. #if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
  692. static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
  693. byte* out, word32 outSz, void* heap)
  694. {
  695. byte* tmp;
  696. /* needs to be large enough for seed size plus counter(4) */
  697. byte tmpA[WC_MAX_DIGEST_SIZE + 4];
  698. byte tmpF; /* 1 if dynamic memory needs freed */
  699. word32 tmpSz;
  700. int hLen;
  701. int ret;
  702. word32 counter;
  703. word32 idx;
  704. #ifdef WOLFSSL_SMALL_STACK_CACHE
  705. wc_HashAlg *hash;
  706. #endif
  707. hLen = wc_HashGetDigestSize(hType);
  708. counter = 0;
  709. idx = 0;
  710. (void)heap;
  711. /* check error return of wc_HashGetDigestSize */
  712. if (hLen < 0) {
  713. return hLen;
  714. }
  715. /* if tmp is not large enough than use some dynamic memory */
  716. if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
  717. /* find largest amount of memory needed which will be the max of
  718. * hLen and (seedSz + 4) since tmp is used to store the hash digest */
  719. tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
  720. tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
  721. if (tmp == NULL) {
  722. return MEMORY_E;
  723. }
  724. tmpF = 1; /* make sure to free memory when done */
  725. }
  726. else {
  727. /* use array on the stack */
  728. #ifndef WOLFSSL_SMALL_STACK_CACHE
  729. tmpSz = sizeof(tmpA);
  730. #endif
  731. tmp = tmpA;
  732. tmpF = 0; /* no need to free memory at end */
  733. }
  734. #ifdef WOLFSSL_SMALL_STACK_CACHE
  735. hash = (wc_HashAlg*)XMALLOC(sizeof(*hash), heap, DYNAMIC_TYPE_DIGEST);
  736. if (hash == NULL) {
  737. if (tmpF) {
  738. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  739. }
  740. return MEMORY_E;
  741. }
  742. ret = wc_HashInit_ex(hash, hType, heap, INVALID_DEVID);
  743. if (ret != 0) {
  744. XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
  745. if (tmpF) {
  746. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  747. }
  748. return ret;
  749. }
  750. #endif
  751. do {
  752. int i = 0;
  753. XMEMCPY(tmp, seed, seedSz);
  754. /* counter to byte array appended to tmp */
  755. tmp[seedSz] = (byte)((counter >> 24) & 0xFF);
  756. tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
  757. tmp[seedSz + 2] = (byte)((counter >> 8) & 0xFF);
  758. tmp[seedSz + 3] = (byte)((counter) & 0xFF);
  759. /* hash and append to existing output */
  760. #ifdef WOLFSSL_SMALL_STACK_CACHE
  761. ret = wc_HashUpdate(hash, hType, tmp, (seedSz + 4));
  762. if (ret == 0) {
  763. ret = wc_HashFinal(hash, hType, tmp);
  764. }
  765. #else
  766. ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz);
  767. #endif
  768. if (ret != 0) {
  769. /* check for if dynamic memory was needed, then free */
  770. if (tmpF) {
  771. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  772. }
  773. return ret;
  774. }
  775. for (i = 0; i < hLen && idx < outSz; i++) {
  776. out[idx++] = tmp[i];
  777. }
  778. counter++;
  779. } while (idx < outSz);
  780. /* check for if dynamic memory was needed, then free */
  781. if (tmpF) {
  782. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  783. }
  784. #ifdef WOLFSSL_SMALL_STACK_CACHE
  785. wc_HashFree(hash, hType);
  786. XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
  787. #endif
  788. return 0;
  789. }
  790. #endif /* SHA2 Hashes */
  791. /* helper function to direct which mask generation function is used
  792. switched on type input
  793. */
  794. static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
  795. word32 outSz, void* heap)
  796. {
  797. int ret;
  798. switch(type) {
  799. #ifndef NO_SHA
  800. case WC_MGF1SHA1:
  801. ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
  802. break;
  803. #endif
  804. #ifndef NO_SHA256
  805. #ifdef WOLFSSL_SHA224
  806. case WC_MGF1SHA224:
  807. ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
  808. break;
  809. #endif
  810. case WC_MGF1SHA256:
  811. ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
  812. break;
  813. #endif
  814. #ifdef WOLFSSL_SHA384
  815. case WC_MGF1SHA384:
  816. ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
  817. break;
  818. #endif
  819. #ifdef WOLFSSL_SHA512
  820. case WC_MGF1SHA512:
  821. ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
  822. break;
  823. #endif
  824. default:
  825. WOLFSSL_MSG("Unknown MGF type: check build options");
  826. ret = BAD_FUNC_ARG;
  827. }
  828. /* in case of default avoid unused warning */
  829. (void)seed;
  830. (void)seedSz;
  831. (void)out;
  832. (void)outSz;
  833. (void)heap;
  834. return ret;
  835. }
  836. #endif /* !WC_NO_RSA_OAEP || WC_RSA_PSS */
  837. /* Padding */
  838. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  839. #ifndef WC_NO_RNG
  840. #ifndef WC_NO_RSA_OAEP
  841. static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
  842. word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
  843. enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
  844. void* heap)
  845. {
  846. int ret;
  847. int hLen;
  848. int psLen;
  849. int i;
  850. word32 idx;
  851. byte* dbMask;
  852. #ifdef WOLFSSL_SMALL_STACK
  853. byte* lHash = NULL;
  854. byte* seed = NULL;
  855. #else
  856. /* must be large enough to contain largest hash */
  857. byte lHash[WC_MAX_DIGEST_SIZE];
  858. byte seed[ WC_MAX_DIGEST_SIZE];
  859. #endif
  860. /* no label is allowed, but catch if no label provided and length > 0 */
  861. if (optLabel == NULL && labelLen > 0) {
  862. return BUFFER_E;
  863. }
  864. /* limit of label is the same as limit of hash function which is massive */
  865. hLen = wc_HashGetDigestSize(hType);
  866. if (hLen < 0) {
  867. return hLen;
  868. }
  869. #ifdef WOLFSSL_SMALL_STACK
  870. lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
  871. if (lHash == NULL) {
  872. return MEMORY_E;
  873. }
  874. seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
  875. if (seed == NULL) {
  876. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  877. return MEMORY_E;
  878. }
  879. #else
  880. /* hLen should never be larger than lHash since size is max digest size,
  881. but check before blindly calling wc_Hash */
  882. if ((word32)hLen > sizeof(lHash)) {
  883. WOLFSSL_MSG("OAEP lHash to small for digest!!");
  884. return MEMORY_E;
  885. }
  886. #endif
  887. if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
  888. WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
  889. #ifdef WOLFSSL_SMALL_STACK
  890. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  891. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  892. #endif
  893. return ret;
  894. }
  895. /* handles check of location for idx as well as psLen, cast to int to check
  896. for pkcsBlockLen(k) - 2 * hLen - 2 being negative
  897. This check is similar to decryption where k > 2 * hLen + 2 as msg
  898. size approaches 0. In decryption if k is less than or equal -- then there
  899. is no possible room for msg.
  900. k = RSA key size
  901. hLen = hash digest size -- will always be >= 0 at this point
  902. */
  903. if ((word32)(2 * hLen + 2) > pkcsBlockLen) {
  904. WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
  905. #ifdef WOLFSSL_SMALL_STACK
  906. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  907. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  908. #endif
  909. return BAD_FUNC_ARG;
  910. }
  911. if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
  912. WOLFSSL_MSG("OAEP pad error message too long");
  913. #ifdef WOLFSSL_SMALL_STACK
  914. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  915. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  916. #endif
  917. return BAD_FUNC_ARG;
  918. }
  919. /* concatenate lHash || PS || 0x01 || msg */
  920. idx = pkcsBlockLen - 1 - inputLen;
  921. psLen = pkcsBlockLen - inputLen - 2 * hLen - 2;
  922. if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
  923. #ifdef WOLFSSL_SMALL_STACK
  924. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  925. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  926. #endif
  927. return BUFFER_E;
  928. }
  929. XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
  930. pkcsBlock[idx--] = 0x01; /* PS and M separator */
  931. while (psLen > 0 && idx > 0) {
  932. pkcsBlock[idx--] = 0x00;
  933. psLen--;
  934. }
  935. idx = idx - hLen + 1;
  936. XMEMCPY(pkcsBlock + idx, lHash, hLen);
  937. /* generate random seed */
  938. if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
  939. #ifdef WOLFSSL_SMALL_STACK
  940. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  941. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  942. #endif
  943. return ret;
  944. }
  945. /* create maskedDB from dbMask */
  946. dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
  947. if (dbMask == NULL) {
  948. #ifdef WOLFSSL_SMALL_STACK
  949. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  950. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  951. #endif
  952. return MEMORY_E;
  953. }
  954. XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
  955. ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
  956. if (ret != 0) {
  957. XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
  958. #ifdef WOLFSSL_SMALL_STACK
  959. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  960. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  961. #endif
  962. return ret;
  963. }
  964. i = 0;
  965. idx = hLen + 1;
  966. while (idx < pkcsBlockLen && (word32)i < (pkcsBlockLen - hLen -1)) {
  967. pkcsBlock[idx] = dbMask[i++] ^ pkcsBlock[idx];
  968. idx++;
  969. }
  970. XFREE(dbMask, heap, DYNAMIC_TYPE_RSA);
  971. /* create maskedSeed from seedMask */
  972. idx = 0;
  973. pkcsBlock[idx++] = 0x00;
  974. /* create seedMask inline */
  975. if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
  976. pkcsBlock + 1, hLen, heap)) != 0) {
  977. #ifdef WOLFSSL_SMALL_STACK
  978. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  979. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  980. #endif
  981. return ret;
  982. }
  983. /* xor created seedMask with seed to make maskedSeed */
  984. i = 0;
  985. while (idx < (word32)(hLen + 1) && i < hLen) {
  986. pkcsBlock[idx] = pkcsBlock[idx] ^ seed[i++];
  987. idx++;
  988. }
  989. #ifdef WOLFSSL_SMALL_STACK
  990. XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
  991. XFREE(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
  992. #endif
  993. (void)padValue;
  994. return 0;
  995. }
  996. #endif /* !WC_NO_RSA_OAEP */
  997. #ifdef WC_RSA_PSS
  998. /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
  999. * XOR MGF over all bytes down to end of Salt
  1000. * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
  1001. *
  1002. * input Digest of the message.
  1003. * inputLen Length of digest.
  1004. * pkcsBlock Buffer to write to.
  1005. * pkcsBlockLen Length of buffer to write to.
  1006. * rng Random number generator (for salt).
  1007. * htype Hash function to use.
  1008. * mgf Mask generation function.
  1009. * saltLen Length of salt to put in padding.
  1010. * bits Length of key in bits.
  1011. * heap Used for dynamic memory allocation.
  1012. * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
  1013. * and other negative values on error.
  1014. */
  1015. static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
  1016. word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
  1017. int saltLen, int bits, void* heap)
  1018. {
  1019. int ret = 0;
  1020. int hLen, i, o, maskLen, hiBits;
  1021. byte* m;
  1022. byte* s;
  1023. #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
  1024. byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
  1025. #else
  1026. byte* msg = NULL;
  1027. #endif
  1028. #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
  1029. byte* salt;
  1030. #else
  1031. byte salt[WC_MAX_DIGEST_SIZE];
  1032. #endif
  1033. #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
  1034. if (pkcsBlockLen > RSA_MAX_SIZE/8) {
  1035. return MEMORY_E;
  1036. }
  1037. #endif
  1038. hLen = wc_HashGetDigestSize(hType);
  1039. if (hLen < 0)
  1040. return hLen;
  1041. if ((int)inputLen != hLen) {
  1042. return BAD_FUNC_ARG;
  1043. }
  1044. hiBits = (bits - 1) & 0x7;
  1045. if (hiBits == 0) {
  1046. /* Per RFC8017, set the leftmost 8emLen - emBits bits of the
  1047. leftmost octet in DB to zero.
  1048. */
  1049. *(pkcsBlock++) = 0;
  1050. pkcsBlockLen--;
  1051. }
  1052. if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
  1053. saltLen = hLen;
  1054. #ifdef WOLFSSL_SHA512
  1055. /* See FIPS 186-4 section 5.5 item (e). */
  1056. if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
  1057. saltLen = RSA_PSS_SALT_MAX_SZ;
  1058. }
  1059. #endif
  1060. }
  1061. #ifndef WOLFSSL_PSS_LONG_SALT
  1062. else if (saltLen > hLen) {
  1063. return PSS_SALTLEN_E;
  1064. }
  1065. #endif
  1066. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  1067. else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
  1068. return PSS_SALTLEN_E;
  1069. }
  1070. #else
  1071. else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
  1072. saltLen = (int)pkcsBlockLen - hLen - 2;
  1073. if (saltLen < 0) {
  1074. return PSS_SALTLEN_E;
  1075. }
  1076. }
  1077. else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
  1078. return PSS_SALTLEN_E;
  1079. }
  1080. #endif
  1081. if ((int)pkcsBlockLen - hLen < saltLen + 2) {
  1082. return PSS_SALTLEN_E;
  1083. }
  1084. maskLen = pkcsBlockLen - 1 - hLen;
  1085. #if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
  1086. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1087. msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
  1088. DYNAMIC_TYPE_RSA_BUFFER);
  1089. if (msg == NULL) {
  1090. return MEMORY_E;
  1091. }
  1092. #endif
  1093. salt = s = m = msg;
  1094. XMEMSET(m, 0, RSA_PSS_PAD_SZ);
  1095. m += RSA_PSS_PAD_SZ;
  1096. XMEMCPY(m, input, inputLen);
  1097. m += inputLen;
  1098. o = (int)(m - s);
  1099. if (saltLen > 0) {
  1100. ret = wc_RNG_GenerateBlock(rng, m, saltLen);
  1101. if (ret == 0) {
  1102. m += saltLen;
  1103. }
  1104. }
  1105. #else
  1106. if (pkcsBlockLen < RSA_PSS_PAD_SZ + inputLen + saltLen) {
  1107. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1108. msg = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inputLen + saltLen, heap,
  1109. DYNAMIC_TYPE_RSA_BUFFER);
  1110. if (msg == NULL) {
  1111. return MEMORY_E;
  1112. }
  1113. #endif
  1114. m = msg;
  1115. }
  1116. else {
  1117. m = pkcsBlock;
  1118. }
  1119. s = m;
  1120. XMEMSET(m, 0, RSA_PSS_PAD_SZ);
  1121. m += RSA_PSS_PAD_SZ;
  1122. XMEMCPY(m, input, inputLen);
  1123. m += inputLen;
  1124. o = 0;
  1125. if (saltLen > 0) {
  1126. ret = wc_RNG_GenerateBlock(rng, salt, saltLen);
  1127. if (ret == 0) {
  1128. XMEMCPY(m, salt, saltLen);
  1129. m += saltLen;
  1130. }
  1131. }
  1132. #endif
  1133. if (ret == 0) {
  1134. /* Put Hash at end of pkcsBlock - 1 */
  1135. ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, hLen);
  1136. }
  1137. if (ret == 0) {
  1138. /* Set the last eight bits or trailer field to the octet 0xbc */
  1139. pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
  1140. ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, pkcsBlock, maskLen, heap);
  1141. }
  1142. if (ret == 0) {
  1143. /* Clear the first high bit when "8emLen - emBits" is non-zero.
  1144. where emBits = n modBits - 1 */
  1145. if (hiBits)
  1146. pkcsBlock[0] &= (1 << hiBits) - 1;
  1147. m = pkcsBlock + maskLen - saltLen - 1;
  1148. *(m++) ^= 0x01;
  1149. for (i = 0; i < saltLen; i++) {
  1150. m[i] ^= salt[o + i];
  1151. }
  1152. }
  1153. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1154. /* msg is always not NULL as we bail on allocation failure */
  1155. XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1156. #endif
  1157. return ret;
  1158. }
  1159. #endif /* WC_RSA_PSS */
  1160. #endif /* !WC_NO_RNG */
  1161. static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
  1162. word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
  1163. {
  1164. if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
  1165. pkcsBlockLen == 0) {
  1166. return BAD_FUNC_ARG;
  1167. }
  1168. if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
  1169. WOLFSSL_MSG("RsaPad error, invalid length");
  1170. return RSA_PAD_E;
  1171. }
  1172. pkcsBlock[0] = 0x0; /* set first byte to zero and advance */
  1173. pkcsBlock++; pkcsBlockLen--;
  1174. pkcsBlock[0] = padValue; /* insert padValue */
  1175. if (padValue == RSA_BLOCK_TYPE_1) {
  1176. /* pad with 0xff bytes */
  1177. XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
  1178. }
  1179. else {
  1180. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
  1181. /* pad with non-zero random bytes */
  1182. word32 padLen, i;
  1183. int ret;
  1184. padLen = pkcsBlockLen - inputLen - 1;
  1185. ret = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
  1186. if (ret != 0) {
  1187. return ret;
  1188. }
  1189. /* remove zeros */
  1190. for (i = 1; i < padLen; i++) {
  1191. if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
  1192. }
  1193. #else
  1194. (void)rng;
  1195. return RSA_WRONG_TYPE_E;
  1196. #endif
  1197. }
  1198. pkcsBlock[pkcsBlockLen-inputLen-1] = 0; /* separator */
  1199. XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
  1200. return 0;
  1201. }
  1202. /* helper function to direct which padding is used */
  1203. int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
  1204. word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
  1205. enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
  1206. int saltLen, int bits, void* heap)
  1207. {
  1208. int ret;
  1209. switch (padType)
  1210. {
  1211. case WC_RSA_PKCSV15_PAD:
  1212. /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
  1213. ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
  1214. padValue, rng);
  1215. break;
  1216. #ifndef WC_NO_RNG
  1217. #ifndef WC_NO_RSA_OAEP
  1218. case WC_RSA_OAEP_PAD:
  1219. WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
  1220. ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
  1221. padValue, rng, hType, mgf, optLabel, labelLen, heap);
  1222. break;
  1223. #endif
  1224. #ifdef WC_RSA_PSS
  1225. case WC_RSA_PSS_PAD:
  1226. WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
  1227. ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
  1228. hType, mgf, saltLen, bits, heap);
  1229. break;
  1230. #endif
  1231. #endif /* !WC_NO_RNG */
  1232. #ifdef WC_RSA_NO_PADDING
  1233. case WC_RSA_NO_PAD:
  1234. WOLFSSL_MSG("wolfSSL Using NO padding");
  1235. /* In the case of no padding being used check that input is exactly
  1236. * the RSA key length */
  1237. if (bits <= 0 || inputLen != ((word32)bits/WOLFSSL_BIT_SIZE)) {
  1238. WOLFSSL_MSG("Bad input size");
  1239. ret = RSA_PAD_E;
  1240. }
  1241. else {
  1242. XMEMCPY(pkcsBlock, input, inputLen);
  1243. ret = 0;
  1244. }
  1245. break;
  1246. #endif
  1247. default:
  1248. WOLFSSL_MSG("Unknown RSA Pad Type");
  1249. ret = RSA_PAD_E;
  1250. }
  1251. /* silence warning if not used with padding scheme */
  1252. (void)input;
  1253. (void)inputLen;
  1254. (void)pkcsBlock;
  1255. (void)pkcsBlockLen;
  1256. (void)padValue;
  1257. (void)rng;
  1258. (void)padType;
  1259. (void)hType;
  1260. (void)mgf;
  1261. (void)optLabel;
  1262. (void)labelLen;
  1263. (void)saltLen;
  1264. (void)bits;
  1265. (void)heap;
  1266. return ret;
  1267. }
  1268. #endif /* WOLFSSL_RSA_VERIFY_ONLY */
  1269. /* UnPadding */
  1270. #ifndef WC_NO_RSA_OAEP
  1271. /* UnPad plaintext, set start to *output, return length of plaintext,
  1272. * < 0 on error */
  1273. static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
  1274. byte **output, enum wc_HashType hType, int mgf,
  1275. byte* optLabel, word32 labelLen, void* heap)
  1276. {
  1277. int hLen;
  1278. int ret;
  1279. byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
  1280. byte* tmp;
  1281. word32 idx;
  1282. /* no label is allowed, but catch if no label provided and length > 0 */
  1283. if (optLabel == NULL && labelLen > 0) {
  1284. return BUFFER_E;
  1285. }
  1286. hLen = wc_HashGetDigestSize(hType);
  1287. if ((hLen < 0) || (pkcsBlockLen < (2 * (word32)hLen + 2))) {
  1288. return BAD_FUNC_ARG;
  1289. }
  1290. tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1291. if (tmp == NULL) {
  1292. return MEMORY_E;
  1293. }
  1294. XMEMSET(tmp, 0, pkcsBlockLen);
  1295. /* find seedMask value */
  1296. if ((ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
  1297. pkcsBlockLen - hLen - 1, tmp, hLen, heap)) != 0) {
  1298. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1299. return ret;
  1300. }
  1301. /* xor seedMask value with maskedSeed to get seed value */
  1302. for (idx = 0; idx < (word32)hLen; idx++) {
  1303. tmp[idx] = tmp[idx] ^ pkcsBlock[1 + idx];
  1304. }
  1305. /* get dbMask value */
  1306. if ((ret = RsaMGF(mgf, tmp, hLen, tmp + hLen,
  1307. pkcsBlockLen - hLen - 1, heap)) != 0) {
  1308. XFREE(tmp, NULL, DYNAMIC_TYPE_RSA_BUFFER);
  1309. return ret;
  1310. }
  1311. /* get DB value by doing maskedDB xor dbMask */
  1312. for (idx = 0; idx < (pkcsBlockLen - hLen - 1); idx++) {
  1313. pkcsBlock[hLen + 1 + idx] = pkcsBlock[hLen + 1 + idx] ^ tmp[idx + hLen];
  1314. }
  1315. /* done with use of tmp buffer */
  1316. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1317. /* advance idx to index of PS and msg separator, account for PS size of 0*/
  1318. idx = hLen + 1 + hLen;
  1319. while (idx < pkcsBlockLen && pkcsBlock[idx] == 0) {idx++;}
  1320. /* create hash of label for comparison with hash sent */
  1321. if ((ret = wc_Hash(hType, optLabel, labelLen, h, hLen)) != 0) {
  1322. return ret;
  1323. }
  1324. /* say no to chosen ciphertext attack.
  1325. Comparison of lHash, Y, and separator value needs to all happen in
  1326. constant time.
  1327. Attackers should not be able to get error condition from the timing of
  1328. these checks.
  1329. */
  1330. ret = 0;
  1331. ret |= ConstantCompare(pkcsBlock + hLen + 1, h, hLen);
  1332. ret += pkcsBlock[idx++] ^ 0x01; /* separator value is 0x01 */
  1333. ret += pkcsBlock[0] ^ 0x00; /* Y, the first value, should be 0 */
  1334. /* Return 0 data length on error. */
  1335. idx = ctMaskSelInt(ctMaskEq(ret, 0), idx, pkcsBlockLen);
  1336. /* adjust pointer to correct location in array and return size of M */
  1337. *output = (byte*)(pkcsBlock + idx);
  1338. return pkcsBlockLen - idx;
  1339. }
  1340. #endif /* WC_NO_RSA_OAEP */
  1341. #ifdef WC_RSA_PSS
  1342. /* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
  1343. * MGF over all bytes down to end of Salt
  1344. *
  1345. * pkcsBlock Buffer holding decrypted data.
  1346. * pkcsBlockLen Length of buffer.
  1347. * htype Hash function to use.
  1348. * mgf Mask generation function.
  1349. * saltLen Length of salt to put in padding.
  1350. * bits Length of key in bits.
  1351. * heap Used for dynamic memory allocation.
  1352. * returns the sum of salt length and SHA-256 digest size on success.
  1353. * Otherwise, PSS_SALTLEN_E for an incorrect salt length,
  1354. * WC_KEY_SIZE_E for an incorrect encoded message (EM) size
  1355. and other negative values on error.
  1356. */
  1357. static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
  1358. byte **output, enum wc_HashType hType, int mgf,
  1359. int saltLen, int bits, void* heap)
  1360. {
  1361. int ret;
  1362. byte* tmp;
  1363. int hLen, i, maskLen;
  1364. #ifdef WOLFSSL_SHA512
  1365. int orig_bits = bits;
  1366. #endif
  1367. #if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
  1368. byte tmp_buf[RSA_MAX_SIZE/8];
  1369. tmp = tmp_buf;
  1370. if (pkcsBlockLen > RSA_MAX_SIZE/8) {
  1371. return MEMORY_E;
  1372. }
  1373. #endif
  1374. hLen = wc_HashGetDigestSize(hType);
  1375. if (hLen < 0)
  1376. return hLen;
  1377. bits = (bits - 1) & 0x7;
  1378. if ((pkcsBlock[0] & (0xff << bits)) != 0) {
  1379. return BAD_PADDING_E;
  1380. }
  1381. if (bits == 0) {
  1382. pkcsBlock++;
  1383. pkcsBlockLen--;
  1384. }
  1385. maskLen = (int)pkcsBlockLen - 1 - hLen;
  1386. if (maskLen < 0) {
  1387. WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
  1388. return WC_KEY_SIZE_E;
  1389. }
  1390. if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
  1391. saltLen = hLen;
  1392. #ifdef WOLFSSL_SHA512
  1393. /* See FIPS 186-4 section 5.5 item (e). */
  1394. if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
  1395. saltLen = RSA_PSS_SALT_MAX_SZ;
  1396. #endif
  1397. }
  1398. #ifndef WOLFSSL_PSS_LONG_SALT
  1399. else if (saltLen > hLen)
  1400. return PSS_SALTLEN_E;
  1401. #endif
  1402. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  1403. else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
  1404. return PSS_SALTLEN_E;
  1405. if (maskLen < saltLen + 1) {
  1406. return PSS_SALTLEN_E;
  1407. }
  1408. #else
  1409. else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
  1410. return PSS_SALTLEN_E;
  1411. if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
  1412. return WC_KEY_SIZE_E;
  1413. }
  1414. #endif
  1415. if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
  1416. WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
  1417. return BAD_PADDING_E;
  1418. }
  1419. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1420. tmp = (byte*)XMALLOC(maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1421. if (tmp == NULL) {
  1422. return MEMORY_E;
  1423. }
  1424. #endif
  1425. if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, hLen, tmp, maskLen,
  1426. heap)) != 0) {
  1427. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1428. return ret;
  1429. }
  1430. tmp[0] &= (1 << bits) - 1;
  1431. pkcsBlock[0] &= (1 << bits) - 1;
  1432. #ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
  1433. if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
  1434. for (i = 0; i < maskLen - 1; i++) {
  1435. if (tmp[i] != pkcsBlock[i]) {
  1436. break;
  1437. }
  1438. }
  1439. if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
  1440. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1441. WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
  1442. return PSS_SALTLEN_RECOVER_E;
  1443. }
  1444. saltLen = maskLen - (i + 1);
  1445. }
  1446. else
  1447. #endif
  1448. {
  1449. for (i = 0; i < maskLen - 1 - saltLen; i++) {
  1450. if (tmp[i] != pkcsBlock[i]) {
  1451. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1452. WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
  1453. return PSS_SALTLEN_E;
  1454. }
  1455. }
  1456. if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
  1457. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1458. WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
  1459. return PSS_SALTLEN_E;
  1460. }
  1461. }
  1462. for (i++; i < maskLen; i++)
  1463. pkcsBlock[i] ^= tmp[i];
  1464. #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
  1465. XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
  1466. #endif
  1467. *output = pkcsBlock + maskLen - saltLen;
  1468. return saltLen + hLen;
  1469. }
  1470. #endif
  1471. /* UnPad plaintext, set start to *output, return length of plaintext,
  1472. * < 0 on error */
  1473. static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
  1474. byte **output, byte padValue)
  1475. {
  1476. int ret = BAD_FUNC_ARG;
  1477. word16 i;
  1478. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  1479. byte invalid = 0;
  1480. #endif
  1481. if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
  1482. return BAD_FUNC_ARG;
  1483. }
  1484. if (padValue == RSA_BLOCK_TYPE_1) {
  1485. /* First byte must be 0x00 and Second byte, block type, 0x01 */
  1486. if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
  1487. WOLFSSL_MSG("RsaUnPad error, invalid formatting");
  1488. return RSA_PAD_E;
  1489. }
  1490. /* check the padding until we find the separator */
  1491. for (i = 2; i < pkcsBlockLen; ) {
  1492. if (pkcsBlock[i++] != 0xFF) {
  1493. break;
  1494. }
  1495. }
  1496. /* Minimum of 11 bytes of pre-message data and must have separator. */
  1497. if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
  1498. WOLFSSL_MSG("RsaUnPad error, bad formatting");
  1499. return RSA_PAD_E;
  1500. }
  1501. *output = (byte *)(pkcsBlock + i);
  1502. ret = pkcsBlockLen - i;
  1503. }
  1504. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  1505. else {
  1506. word16 j;
  1507. word16 pastSep = 0;
  1508. i = 0;
  1509. /* Decrypted with private key - unpad must be constant time. */
  1510. for (j = 2; j < pkcsBlockLen; j++) {
  1511. /* Update i if not passed the separator and at separator. */
  1512. i |= (~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) & (j + 1);
  1513. pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
  1514. }
  1515. /* Minimum of 11 bytes of pre-message data - including leading 0x00. */
  1516. invalid |= ctMaskLT(i, RSA_MIN_PAD_SZ);
  1517. /* Must have seen separator. */
  1518. invalid |= ~pastSep;
  1519. /* First byte must be 0x00. */
  1520. invalid |= ctMaskNotEq(pkcsBlock[0], 0x00);
  1521. /* Check against expected block type: padValue */
  1522. invalid |= ctMaskNotEq(pkcsBlock[1], padValue);
  1523. *output = (byte *)(pkcsBlock + i);
  1524. ret = ((int)(byte)~invalid) & (pkcsBlockLen - i);
  1525. }
  1526. #endif
  1527. return ret;
  1528. }
  1529. /* helper function to direct unpadding
  1530. *
  1531. * bits is the key modulus size in bits
  1532. */
  1533. int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
  1534. byte padValue, int padType, enum wc_HashType hType,
  1535. int mgf, byte* optLabel, word32 labelLen, int saltLen,
  1536. int bits, void* heap)
  1537. {
  1538. int ret;
  1539. switch (padType) {
  1540. case WC_RSA_PKCSV15_PAD:
  1541. /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
  1542. ret = RsaUnPad(pkcsBlock, pkcsBlockLen, out, padValue);
  1543. break;
  1544. #ifndef WC_NO_RSA_OAEP
  1545. case WC_RSA_OAEP_PAD:
  1546. WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
  1547. ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
  1548. hType, mgf, optLabel, labelLen, heap);
  1549. break;
  1550. #endif
  1551. #ifdef WC_RSA_PSS
  1552. case WC_RSA_PSS_PAD:
  1553. WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
  1554. ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
  1555. saltLen, bits, heap);
  1556. break;
  1557. #endif
  1558. #ifdef WC_RSA_NO_PADDING
  1559. case WC_RSA_NO_PAD:
  1560. WOLFSSL_MSG("wolfSSL Using NO un-padding");
  1561. /* In the case of no padding being used check that input is exactly
  1562. * the RSA key length */
  1563. if (bits <= 0 || pkcsBlockLen !=
  1564. ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
  1565. WOLFSSL_MSG("Bad input size");
  1566. ret = RSA_PAD_E;
  1567. }
  1568. else {
  1569. if (out != NULL) {
  1570. *out = pkcsBlock;
  1571. }
  1572. ret = pkcsBlockLen;
  1573. }
  1574. break;
  1575. #endif /* WC_RSA_NO_PADDING */
  1576. default:
  1577. WOLFSSL_MSG("Unknown RSA UnPad Type");
  1578. ret = RSA_PAD_E;
  1579. }
  1580. /* silence warning if not used with padding scheme */
  1581. (void)hType;
  1582. (void)mgf;
  1583. (void)optLabel;
  1584. (void)labelLen;
  1585. (void)saltLen;
  1586. (void)bits;
  1587. (void)heap;
  1588. return ret;
  1589. }
  1590. int wc_hash2mgf(enum wc_HashType hType)
  1591. {
  1592. switch (hType) {
  1593. case WC_HASH_TYPE_NONE:
  1594. return WC_MGF1NONE;
  1595. case WC_HASH_TYPE_SHA:
  1596. #ifndef NO_SHA
  1597. return WC_MGF1SHA1;
  1598. #else
  1599. break;
  1600. #endif
  1601. case WC_HASH_TYPE_SHA224:
  1602. #ifdef WOLFSSL_SHA224
  1603. return WC_MGF1SHA224;
  1604. #else
  1605. break;
  1606. #endif
  1607. case WC_HASH_TYPE_SHA256:
  1608. #ifndef NO_SHA256
  1609. return WC_MGF1SHA256;
  1610. #else
  1611. break;
  1612. #endif
  1613. case WC_HASH_TYPE_SHA384:
  1614. #ifdef WOLFSSL_SHA384
  1615. return WC_MGF1SHA384;
  1616. #else
  1617. break;
  1618. #endif
  1619. case WC_HASH_TYPE_SHA512:
  1620. #ifdef WOLFSSL_SHA512
  1621. return WC_MGF1SHA512;
  1622. #else
  1623. break;
  1624. #endif
  1625. case WC_HASH_TYPE_MD2:
  1626. case WC_HASH_TYPE_MD4:
  1627. case WC_HASH_TYPE_MD5:
  1628. case WC_HASH_TYPE_MD5_SHA:
  1629. #ifndef WOLFSSL_NOSHA512_224
  1630. case WC_HASH_TYPE_SHA512_224:
  1631. #endif
  1632. #ifndef WOLFSSL_NOSHA512_256
  1633. case WC_HASH_TYPE_SHA512_256:
  1634. #endif
  1635. case WC_HASH_TYPE_SHA3_224:
  1636. case WC_HASH_TYPE_SHA3_256:
  1637. case WC_HASH_TYPE_SHA3_384:
  1638. case WC_HASH_TYPE_SHA3_512:
  1639. case WC_HASH_TYPE_BLAKE2B:
  1640. case WC_HASH_TYPE_BLAKE2S:
  1641. #ifndef WOLFSSL_NO_SHAKE256
  1642. case WC_HASH_TYPE_SHAKE128:
  1643. case WC_HASH_TYPE_SHAKE256:
  1644. #endif
  1645. default:
  1646. break;
  1647. }
  1648. WOLFSSL_MSG("Unrecognized or unsupported hash function");
  1649. return WC_MGF1NONE;
  1650. }
  1651. #ifdef WC_RSA_NONBLOCK
  1652. static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
  1653. word32* outLen, int type, RsaKey* key)
  1654. {
  1655. int ret = 0;
  1656. word32 keyLen, len;
  1657. if (key == NULL || key->nb == NULL) {
  1658. return BAD_FUNC_ARG;
  1659. }
  1660. if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
  1661. if (mp_init(&key->nb->tmp) != MP_OKAY) {
  1662. ret = MP_INIT_E;
  1663. }
  1664. if (ret == 0) {
  1665. if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
  1666. ret = MP_READ_E;
  1667. }
  1668. }
  1669. }
  1670. if (ret == 0) {
  1671. switch(type) {
  1672. case RSA_PRIVATE_DECRYPT:
  1673. case RSA_PRIVATE_ENCRYPT:
  1674. ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
  1675. &key->n, &key->nb->tmp);
  1676. if (ret == FP_WOULDBLOCK)
  1677. return ret;
  1678. if (ret != MP_OKAY)
  1679. ret = MP_EXPTMOD_E;
  1680. break;
  1681. case RSA_PUBLIC_ENCRYPT:
  1682. case RSA_PUBLIC_DECRYPT:
  1683. ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
  1684. &key->n, &key->nb->tmp);
  1685. if (ret == FP_WOULDBLOCK)
  1686. return ret;
  1687. if (ret != MP_OKAY)
  1688. ret = MP_EXPTMOD_E;
  1689. break;
  1690. default:
  1691. ret = RSA_WRONG_TYPE_E;
  1692. break;
  1693. }
  1694. }
  1695. if (ret == 0) {
  1696. keyLen = wc_RsaEncryptSize(key);
  1697. if (keyLen > *outLen)
  1698. ret = RSA_BUFFER_E;
  1699. }
  1700. if (ret == 0) {
  1701. len = mp_unsigned_bin_size(&key->nb->tmp);
  1702. /* pad front w/ zeros to match key length */
  1703. while (len < keyLen) {
  1704. *out++ = 0x00;
  1705. len++;
  1706. }
  1707. *outLen = keyLen;
  1708. /* convert */
  1709. if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
  1710. ret = MP_TO_E;
  1711. }
  1712. }
  1713. mp_clear(&key->nb->tmp);
  1714. return ret;
  1715. }
  1716. #endif /* WC_RSA_NONBLOCK */
  1717. #ifdef WOLFSSL_XILINX_CRYPT
  1718. /*
  1719. * Xilinx hardened crypto acceleration.
  1720. *
  1721. * Returns 0 on success and negative values on error.
  1722. */
  1723. static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
  1724. word32* outLen, int type, RsaKey* key, WC_RNG* rng)
  1725. {
  1726. int ret = 0;
  1727. word32 keyLen;
  1728. (void)rng;
  1729. keyLen = wc_RsaEncryptSize(key);
  1730. if (keyLen > *outLen) {
  1731. WOLFSSL_MSG("Output buffer is not big enough");
  1732. return BAD_FUNC_ARG;
  1733. }
  1734. if (inLen != keyLen) {
  1735. WOLFSSL_MSG("Expected that inLen equals RSA key length");
  1736. return BAD_FUNC_ARG;
  1737. }
  1738. switch(type) {
  1739. case RSA_PRIVATE_DECRYPT:
  1740. case RSA_PRIVATE_ENCRYPT:
  1741. #ifdef WOLFSSL_XILINX_CRYPTO_OLD
  1742. /* Currently public exponent is loaded by default.
  1743. * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
  1744. * leading to private key operations with Xsecure_RsaDecrypt not being
  1745. * supported */
  1746. ret = RSA_WRONG_TYPE_E;
  1747. #else
  1748. {
  1749. byte *d;
  1750. int dSz;
  1751. XSecure_Rsa rsa;
  1752. dSz = mp_unsigned_bin_size(&key->d);
  1753. d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  1754. if (d == NULL) {
  1755. ret = MEMORY_E;
  1756. }
  1757. else {
  1758. ret = mp_to_unsigned_bin(&key->d, d);
  1759. XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
  1760. }
  1761. if (ret == 0) {
  1762. if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
  1763. XST_SUCCESS) {
  1764. ret = BAD_STATE_E;
  1765. }
  1766. }
  1767. if (d != NULL) {
  1768. XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
  1769. }
  1770. }
  1771. #endif
  1772. break;
  1773. case RSA_PUBLIC_ENCRYPT:
  1774. case RSA_PUBLIC_DECRYPT:
  1775. #ifdef WOLFSSL_XILINX_CRYPTO_OLD
  1776. if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
  1777. ret = BAD_STATE_E;
  1778. }
  1779. #else
  1780. /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
  1781. if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
  1782. WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
  1783. ret = BAD_STATE_E;
  1784. }
  1785. #endif
  1786. break;
  1787. default:
  1788. ret = RSA_WRONG_TYPE_E;
  1789. }
  1790. *outLen = keyLen;
  1791. return ret;
  1792. }
  1793. #elif defined(WOLFSSL_AFALG_XILINX_RSA)
  1794. #ifndef ERROR_OUT
  1795. #define ERROR_OUT(x) ret = (x); goto done
  1796. #endif
  1797. static const char WC_TYPE_ASYMKEY[] = "skcipher";
  1798. static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
  1799. #ifndef MAX_XILINX_RSA_KEY
  1800. /* max key size of 4096 bits / 512 bytes */
  1801. #define MAX_XILINX_RSA_KEY 512
  1802. #endif
  1803. static const byte XILINX_RSA_FLAG[] = {0x1};
  1804. /* AF_ALG implementation of RSA */
  1805. static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
  1806. word32* outLen, int type, RsaKey* key, WC_RNG* rng)
  1807. {
  1808. struct msghdr msg;
  1809. struct cmsghdr* cmsg;
  1810. struct iovec iov;
  1811. byte* keyBuf = NULL;
  1812. word32 keyBufSz = 0;
  1813. char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
  1814. int ret = 0;
  1815. int op = 0; /* decryption vs encryption flag */
  1816. word32 keyLen;
  1817. /* input and output buffer need to be aligned */
  1818. ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
  1819. ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
  1820. XMEMSET(&msg, 0, sizeof(struct msghdr));
  1821. (void)rng;
  1822. keyLen = wc_RsaEncryptSize(key);
  1823. if (keyLen > *outLen) {
  1824. ERROR_OUT(RSA_BUFFER_E);
  1825. }
  1826. if (keyLen > MAX_XILINX_RSA_KEY) {
  1827. WOLFSSL_MSG("RSA key size larger than supported");
  1828. ERROR_OUT(BAD_FUNC_ARG);
  1829. }
  1830. if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
  1831. == NULL) {
  1832. ERROR_OUT(MEMORY_E);
  1833. }
  1834. if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
  1835. ERROR_OUT(MP_TO_E);
  1836. }
  1837. switch(type) {
  1838. case RSA_PRIVATE_DECRYPT:
  1839. case RSA_PRIVATE_ENCRYPT:
  1840. op = 1; /* set as decrypt */
  1841. {
  1842. keyBufSz = mp_unsigned_bin_size(&(key->d));
  1843. if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
  1844. != MP_OKAY) {
  1845. ERROR_OUT(MP_TO_E);
  1846. }
  1847. }
  1848. break;
  1849. case RSA_PUBLIC_DECRYPT:
  1850. case RSA_PUBLIC_ENCRYPT: {
  1851. word32 exp = 0;
  1852. word32 eSz = mp_unsigned_bin_size(&(key->e));
  1853. if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
  1854. (sizeof(word32) - eSz))) != MP_OKAY) {
  1855. ERROR_OUT(MP_TO_E);
  1856. }
  1857. keyBufSz = sizeof(word32);
  1858. XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
  1859. break;
  1860. }
  1861. default:
  1862. ERROR_OUT(RSA_WRONG_TYPE_E);
  1863. }
  1864. keyBufSz += keyLen; /* add size of modulus */
  1865. /* check for existing sockets before creating new ones */
  1866. if (key->alFd > 0) {
  1867. close(key->alFd);
  1868. key->alFd = WC_SOCK_NOTSET;
  1869. }
  1870. if (key->rdFd > 0) {
  1871. close(key->rdFd);
  1872. key->rdFd = WC_SOCK_NOTSET;
  1873. }
  1874. /* create new sockets and set the key to use */
  1875. if ((key->alFd = wc_Afalg_Socket()) < 0) {
  1876. WOLFSSL_MSG("Unable to create socket");
  1877. ERROR_OUT(key->alFd);
  1878. }
  1879. if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
  1880. WC_NAME_RSA)) < 0) {
  1881. WOLFSSL_MSG("Unable to bind and create read/send socket");
  1882. ERROR_OUT(key->rdFd);
  1883. }
  1884. if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
  1885. keyBufSz)) < 0) {
  1886. WOLFSSL_MSG("Error setting RSA key");
  1887. ERROR_OUT(ret);
  1888. }
  1889. msg.msg_control = cbuf;
  1890. msg.msg_controllen = sizeof(cbuf);
  1891. cmsg = CMSG_FIRSTHDR(&msg);
  1892. if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
  1893. ERROR_OUT(ret);
  1894. }
  1895. /* set flag in IV spot, needed for Xilinx hardware acceleration use */
  1896. cmsg = CMSG_NXTHDR(&msg, cmsg);
  1897. if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
  1898. sizeof(XILINX_RSA_FLAG))) != 0) {
  1899. ERROR_OUT(ret);
  1900. }
  1901. /* compose and send msg */
  1902. XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
  1903. iov.iov_base = inBuf;
  1904. iov.iov_len = inLen;
  1905. msg.msg_iov = &iov;
  1906. msg.msg_iovlen = 1;
  1907. if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
  1908. ERROR_OUT(WC_AFALG_SOCK_E);
  1909. }
  1910. if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
  1911. ERROR_OUT(WC_AFALG_SOCK_E);
  1912. }
  1913. XMEMCPY(out, outBuf, ret);
  1914. *outLen = keyLen;
  1915. done:
  1916. /* clear key data and free buffer */
  1917. if (keyBuf != NULL) {
  1918. ForceZero(keyBuf, keyBufSz);
  1919. }
  1920. XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
  1921. if (key->alFd > 0) {
  1922. close(key->alFd);
  1923. key->alFd = WC_SOCK_NOTSET;
  1924. }
  1925. if (key->rdFd > 0) {
  1926. close(key->rdFd);
  1927. key->rdFd = WC_SOCK_NOTSET;
  1928. }
  1929. return ret;
  1930. }
  1931. #elif defined(WOLFSSL_KCAPI_RSA)
  1932. static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
  1933. word32* outLen, int type, RsaKey* key,
  1934. WC_RNG* rng)
  1935. {
  1936. int ret;
  1937. (void)rng;
  1938. switch(type) {
  1939. case RSA_PRIVATE_DECRYPT:
  1940. case RSA_PRIVATE_ENCRYPT:
  1941. ret = KcapiRsa_Decrypt(key, in, inLen, out, outLen);
  1942. break;
  1943. case RSA_PUBLIC_DECRYPT:
  1944. case RSA_PUBLIC_ENCRYPT:
  1945. ret = KcapiRsa_Encrypt(key, in, inLen, out, outLen);
  1946. break;
  1947. default:
  1948. ret = RSA_WRONG_TYPE_E;
  1949. }
  1950. return ret;
  1951. }
  1952. #else
  1953. static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
  1954. word32* outLen, int type, RsaKey* key, WC_RNG* rng)
  1955. {
  1956. #if !defined(WOLFSSL_SP_MATH)
  1957. #ifdef WOLFSSL_SMALL_STACK
  1958. mp_int* tmp;
  1959. #ifdef WC_RSA_BLINDING
  1960. mp_int* rnd;
  1961. mp_int* rndi;
  1962. #endif
  1963. #else
  1964. mp_int tmp[1];
  1965. #ifdef WC_RSA_BLINDING
  1966. mp_int rnd[1], rndi[1];
  1967. #endif
  1968. #endif
  1969. int ret = 0;
  1970. word32 keyLen = 0;
  1971. #endif
  1972. #ifdef WOLFSSL_HAVE_SP_RSA
  1973. #ifndef WOLFSSL_SP_NO_2048
  1974. if (mp_count_bits(&key->n) == 2048) {
  1975. switch(type) {
  1976. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  1977. case RSA_PRIVATE_DECRYPT:
  1978. case RSA_PRIVATE_ENCRYPT:
  1979. #ifdef WC_RSA_BLINDING
  1980. if (rng == NULL)
  1981. return MISSING_RNG_E;
  1982. #endif
  1983. #ifndef RSA_LOW_MEM
  1984. if ((mp_count_bits(&key->p) == 1024) &&
  1985. (mp_count_bits(&key->q) == 1024)) {
  1986. return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
  1987. &key->dP, &key->dQ, &key->u, &key->n,
  1988. out, outLen);
  1989. }
  1990. break;
  1991. #else
  1992. return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
  1993. NULL, NULL, &key->n, out, outLen);
  1994. #endif
  1995. #endif
  1996. case RSA_PUBLIC_ENCRYPT:
  1997. case RSA_PUBLIC_DECRYPT:
  1998. return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
  1999. default:
  2000. break;
  2001. }
  2002. }
  2003. #endif
  2004. #ifndef WOLFSSL_SP_NO_3072
  2005. if (mp_count_bits(&key->n) == 3072) {
  2006. switch(type) {
  2007. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2008. case RSA_PRIVATE_DECRYPT:
  2009. case RSA_PRIVATE_ENCRYPT:
  2010. #ifdef WC_RSA_BLINDING
  2011. if (rng == NULL)
  2012. return MISSING_RNG_E;
  2013. #endif
  2014. #ifndef RSA_LOW_MEM
  2015. if ((mp_count_bits(&key->p) == 1536) &&
  2016. (mp_count_bits(&key->q) == 1536)) {
  2017. return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
  2018. &key->dP, &key->dQ, &key->u, &key->n,
  2019. out, outLen);
  2020. }
  2021. break;
  2022. #else
  2023. return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
  2024. NULL, NULL, &key->n, out, outLen);
  2025. #endif
  2026. #endif
  2027. case RSA_PUBLIC_ENCRYPT:
  2028. case RSA_PUBLIC_DECRYPT:
  2029. return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
  2030. default:
  2031. break;
  2032. }
  2033. }
  2034. #endif
  2035. #ifdef WOLFSSL_SP_4096
  2036. if (mp_count_bits(&key->n) == 4096) {
  2037. switch(type) {
  2038. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2039. case RSA_PRIVATE_DECRYPT:
  2040. case RSA_PRIVATE_ENCRYPT:
  2041. #ifdef WC_RSA_BLINDING
  2042. if (rng == NULL)
  2043. return MISSING_RNG_E;
  2044. #endif
  2045. #ifndef RSA_LOW_MEM
  2046. if ((mp_count_bits(&key->p) == 2048) &&
  2047. (mp_count_bits(&key->q) == 2048)) {
  2048. return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
  2049. &key->dP, &key->dQ, &key->u, &key->n,
  2050. out, outLen);
  2051. }
  2052. break;
  2053. #else
  2054. return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
  2055. NULL, NULL, &key->n, out, outLen);
  2056. #endif
  2057. #endif
  2058. case RSA_PUBLIC_ENCRYPT:
  2059. case RSA_PUBLIC_DECRYPT:
  2060. return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
  2061. default:
  2062. break;
  2063. }
  2064. }
  2065. #endif
  2066. #endif /* WOLFSSL_HAVE_SP_RSA */
  2067. #if defined(WOLFSSL_SP_MATH)
  2068. (void)rng;
  2069. WOLFSSL_MSG("SP Key Size Error");
  2070. return WC_KEY_SIZE_E;
  2071. #else
  2072. (void)rng;
  2073. #ifdef WOLFSSL_SMALL_STACK
  2074. tmp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
  2075. if (tmp == NULL)
  2076. return MEMORY_E;
  2077. #ifdef WC_RSA_BLINDING
  2078. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
  2079. rnd = (mp_int*)XMALLOC(sizeof(mp_int) * 2, key->heap, DYNAMIC_TYPE_RSA);
  2080. if (rnd == NULL) {
  2081. XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
  2082. return MEMORY_E;
  2083. }
  2084. rndi = rnd + 1;
  2085. #else
  2086. rnd = NULL;
  2087. rndi = NULL;
  2088. #endif
  2089. #endif /* WC_RSA_BLINDING */
  2090. #endif /* WOLFSSL_SMALL_STACK */
  2091. if (mp_init(tmp) != MP_OKAY)
  2092. ret = MP_INIT_E;
  2093. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
  2094. #ifdef WC_RSA_BLINDING
  2095. if (ret == 0) {
  2096. if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
  2097. if (mp_init_multi(rnd, rndi, NULL, NULL, NULL, NULL) != MP_OKAY) {
  2098. mp_clear(tmp);
  2099. ret = MP_INIT_E;
  2100. }
  2101. }
  2102. }
  2103. #endif
  2104. #endif
  2105. #ifndef TEST_UNPAD_CONSTANT_TIME
  2106. if (ret == 0 && mp_read_unsigned_bin(tmp, in, inLen) != MP_OKAY)
  2107. ret = MP_READ_E;
  2108. if (ret == 0) {
  2109. switch(type) {
  2110. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
  2111. case RSA_PRIVATE_DECRYPT:
  2112. case RSA_PRIVATE_ENCRYPT:
  2113. {
  2114. #if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
  2115. /* blind */
  2116. ret = mp_rand(rnd, get_digit_count(&key->n), rng);
  2117. /* rndi = 1/rnd mod n */
  2118. if (ret == 0 && mp_invmod(rnd, &key->n, rndi) != MP_OKAY)
  2119. ret = MP_INVMOD_E;
  2120. /* rnd = rnd^e */
  2121. #ifndef WOLFSSL_SP_MATH_ALL
  2122. if (ret == 0 && mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY)
  2123. ret = MP_EXPTMOD_E;
  2124. #else
  2125. if (ret == 0 && mp_exptmod_nct(rnd, &key->e, &key->n,
  2126. rnd) != MP_OKAY) {
  2127. ret = MP_EXPTMOD_E;
  2128. }
  2129. #endif
  2130. /* tmp = tmp*rnd mod n */
  2131. if (ret == 0 && mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY)
  2132. ret = MP_MULMOD_E;
  2133. #endif /* WC_RSA_BLINDING && !WC_NO_RNG */
  2134. #ifdef RSA_LOW_MEM /* half as much memory but twice as slow */
  2135. if (ret == 0 && mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY)
  2136. ret = MP_EXPTMOD_E;
  2137. #else
  2138. if (ret == 0) {
  2139. #ifdef WOLFSSL_SMALL_STACK
  2140. mp_int* tmpa;
  2141. mp_int* tmpb = NULL;
  2142. #else
  2143. mp_int tmpa[1], tmpb[1];
  2144. #endif
  2145. int cleara = 0, clearb = 0;
  2146. #ifdef WOLFSSL_SMALL_STACK
  2147. tmpa = (mp_int*)XMALLOC(sizeof(mp_int) * 2,
  2148. key->heap, DYNAMIC_TYPE_RSA);
  2149. if (tmpa != NULL)
  2150. tmpb = tmpa + 1;
  2151. else
  2152. ret = MEMORY_E;
  2153. #endif
  2154. if (ret == 0) {
  2155. if (mp_init(tmpa) != MP_OKAY)
  2156. ret = MP_INIT_E;
  2157. else
  2158. cleara = 1;
  2159. }
  2160. if (ret == 0) {
  2161. if (mp_init(tmpb) != MP_OKAY)
  2162. ret = MP_INIT_E;
  2163. else
  2164. clearb = 1;
  2165. }
  2166. /* tmpa = tmp^dP mod p */
  2167. if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p,
  2168. tmpa) != MP_OKAY)
  2169. ret = MP_EXPTMOD_E;
  2170. /* tmpb = tmp^dQ mod q */
  2171. if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q,
  2172. tmpb) != MP_OKAY)
  2173. ret = MP_EXPTMOD_E;
  2174. /* tmp = (tmpa - tmpb) * qInv (mod p) */
  2175. #if defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL) && \
  2176. !defined(WOLFSSL_SP_INT_NEGATIVE))
  2177. if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY)
  2178. ret = MP_SUB_E;
  2179. #else
  2180. if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
  2181. ret = MP_SUB_E;
  2182. #endif
  2183. if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p,
  2184. tmp) != MP_OKAY)
  2185. ret = MP_MULMOD_E;
  2186. /* tmp = tmpb + q * tmp */
  2187. if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
  2188. ret = MP_MUL_E;
  2189. if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
  2190. ret = MP_ADD_E;
  2191. #ifdef WOLFSSL_SMALL_STACK
  2192. if (tmpa != NULL)
  2193. #endif
  2194. {
  2195. if (cleara)
  2196. mp_clear(tmpa);
  2197. if (clearb)
  2198. mp_clear(tmpb);
  2199. #ifdef WOLFSSL_SMALL_STACK
  2200. XFREE(tmpa, key->heap, DYNAMIC_TYPE_RSA);
  2201. #endif
  2202. }
  2203. } /* tmpa/b scope */
  2204. #endif /* RSA_LOW_MEM */
  2205. #ifdef WC_RSA_BLINDING
  2206. /* unblind */
  2207. if (ret == 0 && mp_mulmod(tmp, rndi, &key->n, tmp) != MP_OKAY)
  2208. ret = MP_MULMOD_E;
  2209. #endif /* WC_RSA_BLINDING */
  2210. break;
  2211. }
  2212. #endif
  2213. case RSA_PUBLIC_ENCRYPT:
  2214. case RSA_PUBLIC_DECRYPT:
  2215. if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY)
  2216. ret = MP_EXPTMOD_E;
  2217. break;
  2218. default:
  2219. ret = RSA_WRONG_TYPE_E;
  2220. break;
  2221. }
  2222. }
  2223. if (ret == 0) {
  2224. keyLen = wc_RsaEncryptSize(key);
  2225. if (keyLen > *outLen)
  2226. ret = RSA_BUFFER_E;
  2227. }
  2228. #ifndef WOLFSSL_XILINX_CRYPT
  2229. if (ret == 0) {
  2230. *outLen = keyLen;
  2231. if (mp_to_unsigned_bin_len(tmp, out, keyLen) != MP_OKAY)
  2232. ret = MP_TO_E;
  2233. }
  2234. #endif
  2235. #else
  2236. (void)type;
  2237. (void)key;
  2238. (void)keyLen;
  2239. XMEMCPY(out, in, inLen);
  2240. *outLen = inLen;
  2241. #endif
  2242. mp_clear(tmp);
  2243. #ifdef WOLFSSL_SMALL_STACK
  2244. XFREE(tmp, key->heap, DYNAMIC_TYPE_RSA);
  2245. #endif
  2246. #ifdef WC_RSA_BLINDING
  2247. if (type == RSA_PRIVATE_DECRYPT || type == RSA_PRIVATE_ENCRYPT) {
  2248. mp_clear(rndi);
  2249. mp_clear(rnd);
  2250. }
  2251. #ifdef WOLFSSL_SMALL_STACK
  2252. XFREE(rnd, key->heap, DYNAMIC_TYPE_RSA);
  2253. #endif
  2254. #endif /* WC_RSA_BLINDING */
  2255. return ret;
  2256. #endif /* WOLFSSL_SP_MATH */
  2257. }
  2258. #endif
  2259. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
  2260. static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
  2261. word32* outLen, int type, RsaKey* key, WC_RNG* rng)
  2262. {
  2263. int ret = 0;
  2264. (void)rng;
  2265. #ifdef WOLFSSL_ASYNC_CRYPT_TEST
  2266. if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_FUNC)) {
  2267. WC_ASYNC_TEST* testDev = &key->asyncDev.test;
  2268. testDev->rsaFunc.in = in;
  2269. testDev->rsaFunc.inSz = inLen;
  2270. testDev->rsaFunc.out = out;
  2271. testDev->rsaFunc.outSz = outLen;
  2272. testDev->rsaFunc.type = type;
  2273. testDev->rsaFunc.key = key;
  2274. testDev->rsaFunc.rng = rng;
  2275. return WC_PENDING_E;
  2276. }
  2277. #endif /* WOLFSSL_ASYNC_CRYPT_TEST */
  2278. switch(type) {
  2279. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2280. case RSA_PRIVATE_DECRYPT:
  2281. case RSA_PRIVATE_ENCRYPT:
  2282. #ifdef HAVE_CAVIUM
  2283. key->dataLen = key->n.raw.len;
  2284. ret = NitroxRsaExptMod(in, inLen,
  2285. key->d.raw.buf, key->d.raw.len,
  2286. key->n.raw.buf, key->n.raw.len,
  2287. out, outLen, key);
  2288. #elif defined(HAVE_INTEL_QA)
  2289. #ifdef RSA_LOW_MEM
  2290. ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
  2291. &key->d.raw, &key->n.raw,
  2292. out, outLen);
  2293. #else
  2294. ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
  2295. &key->p.raw, &key->q.raw,
  2296. &key->dP.raw, &key->dQ.raw,
  2297. &key->u.raw,
  2298. out, outLen);
  2299. #endif
  2300. #else /* WOLFSSL_ASYNC_CRYPT_TEST */
  2301. ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
  2302. #endif
  2303. break;
  2304. #endif
  2305. case RSA_PUBLIC_ENCRYPT:
  2306. case RSA_PUBLIC_DECRYPT:
  2307. #ifdef HAVE_CAVIUM
  2308. key->dataLen = key->n.raw.len;
  2309. ret = NitroxRsaExptMod(in, inLen,
  2310. key->e.raw.buf, key->e.raw.len,
  2311. key->n.raw.buf, key->n.raw.len,
  2312. out, outLen, key);
  2313. #elif defined(HAVE_INTEL_QA)
  2314. ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
  2315. &key->e.raw, &key->n.raw,
  2316. out, outLen);
  2317. #else /* WOLFSSL_ASYNC_CRYPT_TEST */
  2318. ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
  2319. #endif
  2320. break;
  2321. default:
  2322. ret = RSA_WRONG_TYPE_E;
  2323. }
  2324. return ret;
  2325. }
  2326. #endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
  2327. #if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING)
  2328. /* Function that does the RSA operation directly with no padding.
  2329. *
  2330. * in buffer to do operation on
  2331. * inLen length of input buffer
  2332. * out buffer to hold results
  2333. * outSz gets set to size of result buffer. Should be passed in as length
  2334. * of out buffer. If the pointer "out" is null then outSz gets set to
  2335. * the expected buffer size needed and LENGTH_ONLY_E gets returned.
  2336. * key RSA key to use for encrypt/decrypt
  2337. * type if using private or public key {RSA_PUBLIC_ENCRYPT,
  2338. * RSA_PUBLIC_DECRYPT, RSA_PRIVATE_ENCRYPT, RSA_PRIVATE_DECRYPT}
  2339. * rng wolfSSL RNG to use if needed
  2340. *
  2341. * returns size of result on success
  2342. */
  2343. int wc_RsaDirect(byte* in, word32 inLen, byte* out, word32* outSz,
  2344. RsaKey* key, int type, WC_RNG* rng)
  2345. {
  2346. int ret;
  2347. if (in == NULL || outSz == NULL || key == NULL) {
  2348. return BAD_FUNC_ARG;
  2349. }
  2350. /* sanity check on type of RSA operation */
  2351. switch (type) {
  2352. case RSA_PUBLIC_ENCRYPT:
  2353. case RSA_PUBLIC_DECRYPT:
  2354. case RSA_PRIVATE_ENCRYPT:
  2355. case RSA_PRIVATE_DECRYPT:
  2356. break;
  2357. default:
  2358. WOLFSSL_MSG("Bad RSA type");
  2359. return BAD_FUNC_ARG;
  2360. }
  2361. if ((ret = wc_RsaEncryptSize(key)) < 0) {
  2362. return BAD_FUNC_ARG;
  2363. }
  2364. if (inLen != (word32)ret) {
  2365. WOLFSSL_MSG("Bad input length. Should be RSA key size");
  2366. return BAD_FUNC_ARG;
  2367. }
  2368. if (out == NULL) {
  2369. *outSz = inLen;
  2370. return LENGTH_ONLY_E;
  2371. }
  2372. switch (key->state) {
  2373. case RSA_STATE_NONE:
  2374. case RSA_STATE_ENCRYPT_PAD:
  2375. case RSA_STATE_ENCRYPT_EXPTMOD:
  2376. case RSA_STATE_DECRYPT_EXPTMOD:
  2377. case RSA_STATE_DECRYPT_UNPAD:
  2378. key->state = (type == RSA_PRIVATE_ENCRYPT ||
  2379. type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
  2380. RSA_STATE_DECRYPT_EXPTMOD;
  2381. key->dataLen = *outSz;
  2382. ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
  2383. if (ret >= 0 || ret == WC_PENDING_E) {
  2384. key->state = (type == RSA_PRIVATE_ENCRYPT ||
  2385. type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
  2386. RSA_STATE_DECRYPT_RES;
  2387. }
  2388. if (ret < 0) {
  2389. break;
  2390. }
  2391. FALL_THROUGH;
  2392. case RSA_STATE_ENCRYPT_RES:
  2393. case RSA_STATE_DECRYPT_RES:
  2394. ret = key->dataLen;
  2395. break;
  2396. default:
  2397. ret = BAD_STATE_E;
  2398. }
  2399. /* if async pending then skip cleanup*/
  2400. if (ret == WC_PENDING_E
  2401. #ifdef WC_RSA_NONBLOCK
  2402. || ret == FP_WOULDBLOCK
  2403. #endif
  2404. ) {
  2405. return ret;
  2406. }
  2407. key->state = RSA_STATE_NONE;
  2408. wc_RsaCleanup(key);
  2409. return ret;
  2410. }
  2411. #endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING */
  2412. #if defined(WOLFSSL_CRYPTOCELL)
  2413. static int cc310_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out,
  2414. word32 outLen, RsaKey* key)
  2415. {
  2416. CRYSError_t ret = 0;
  2417. CRYS_RSAPrimeData_t primeData;
  2418. int modulusSize = wc_RsaEncryptSize(key);
  2419. /* The out buffer must be at least modulus size bytes long. */
  2420. if (outLen < modulusSize)
  2421. return BAD_FUNC_ARG;
  2422. ret = CRYS_RSA_PKCS1v15_Encrypt(&wc_rndState,
  2423. wc_rndGenVectFunc,
  2424. &key->ctx.pubKey,
  2425. &primeData,
  2426. (byte*)in,
  2427. inLen,
  2428. out);
  2429. if (ret != SA_SILIB_RET_OK){
  2430. WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Encrypt failed");
  2431. return -1;
  2432. }
  2433. return modulusSize;
  2434. }
  2435. static int cc310_RsaPublicDecrypt(const byte* in, word32 inLen, byte* out,
  2436. word32 outLen, RsaKey* key)
  2437. {
  2438. CRYSError_t ret = 0;
  2439. CRYS_RSAPrimeData_t primeData;
  2440. word16 actualOutLen = outLen;
  2441. ret = CRYS_RSA_PKCS1v15_Decrypt(&key->ctx.privKey,
  2442. &primeData,
  2443. (byte*)in,
  2444. inLen,
  2445. out,
  2446. &actualOutLen);
  2447. if (ret != SA_SILIB_RET_OK){
  2448. WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Decrypt failed");
  2449. return -1;
  2450. }
  2451. return actualOutLen;
  2452. }
  2453. int cc310_RsaSSL_Sign(const byte* in, word32 inLen, byte* out,
  2454. word32 outLen, RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
  2455. {
  2456. CRYSError_t ret = 0;
  2457. word16 actualOutLen = outLen*sizeof(byte);
  2458. CRYS_RSAPrivUserContext_t contextPrivate;
  2459. ret = CRYS_RSA_PKCS1v15_Sign(&wc_rndState,
  2460. wc_rndGenVectFunc,
  2461. &contextPrivate,
  2462. &key->ctx.privKey,
  2463. mode,
  2464. (byte*)in,
  2465. inLen,
  2466. out,
  2467. &actualOutLen);
  2468. if (ret != SA_SILIB_RET_OK){
  2469. WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Sign failed");
  2470. return -1;
  2471. }
  2472. return actualOutLen;
  2473. }
  2474. int cc310_RsaSSL_Verify(const byte* in, word32 inLen, byte* sig,
  2475. RsaKey* key, CRYS_RSA_HASH_OpMode_t mode)
  2476. {
  2477. CRYSError_t ret = 0;
  2478. CRYS_RSAPubUserContext_t contextPub;
  2479. /* verify the signature in the sig pointer */
  2480. ret = CRYS_RSA_PKCS1v15_Verify(&contextPub,
  2481. &key->ctx.pubKey,
  2482. mode,
  2483. (byte*)in,
  2484. inLen,
  2485. sig);
  2486. if (ret != SA_SILIB_RET_OK){
  2487. WOLFSSL_MSG("CRYS_RSA_PKCS1v15_Verify failed");
  2488. return -1;
  2489. }
  2490. return ret;
  2491. }
  2492. #endif /* WOLFSSL_CRYPTOCELL */
  2493. int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
  2494. word32* outLen, int type, RsaKey* key, WC_RNG* rng)
  2495. {
  2496. int ret = 0;
  2497. if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
  2498. outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
  2499. return BAD_FUNC_ARG;
  2500. }
  2501. #ifdef WOLF_CRYPTO_CB
  2502. if (key->devId != INVALID_DEVID) {
  2503. ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
  2504. if (ret != CRYPTOCB_UNAVAILABLE)
  2505. return ret;
  2506. /* fall-through when unavailable */
  2507. ret = 0; /* reset error code and try using software */
  2508. }
  2509. #endif
  2510. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2511. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  2512. #ifndef TEST_UNPAD_CONSTANT_TIME
  2513. #ifndef NO_RSA_BOUNDS_CHECK
  2514. if (type == RSA_PRIVATE_DECRYPT &&
  2515. key->state == RSA_STATE_DECRYPT_EXPTMOD) {
  2516. /* Check that 1 < in < n-1. (Requirement of 800-56B.) */
  2517. #ifdef WOLFSSL_SMALL_STACK
  2518. mp_int* c;
  2519. #else
  2520. mp_int c[1];
  2521. #endif
  2522. #ifdef WOLFSSL_SMALL_STACK
  2523. c = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_RSA);
  2524. if (c == NULL)
  2525. ret = MEMORY_E;
  2526. #endif
  2527. if (ret == 0 && mp_init(c) != MP_OKAY)
  2528. ret = MP_INIT_E;
  2529. if (ret == 0) {
  2530. if (mp_read_unsigned_bin(c, in, inLen) != 0)
  2531. ret = MP_READ_E;
  2532. }
  2533. if (ret == 0) {
  2534. /* check c > 1 */
  2535. if (mp_cmp_d(c, 1) != MP_GT)
  2536. ret = RSA_OUT_OF_RANGE_E;
  2537. }
  2538. if (ret == 0) {
  2539. /* add c+1 */
  2540. if (mp_add_d(c, 1, c) != MP_OKAY)
  2541. ret = MP_ADD_E;
  2542. }
  2543. if (ret == 0) {
  2544. /* check c+1 < n */
  2545. if (mp_cmp(c, &key->n) != MP_LT)
  2546. ret = RSA_OUT_OF_RANGE_E;
  2547. }
  2548. mp_clear(c);
  2549. #ifdef WOLFSSL_SMALL_STACK
  2550. if (c != NULL)
  2551. XFREE(c, key->heap, DYNAMIC_TYPE_RSA);
  2552. #endif
  2553. if (ret != 0) {
  2554. RESTORE_VECTOR_REGISTERS();
  2555. return ret;
  2556. }
  2557. }
  2558. #endif /* NO_RSA_BOUNDS_CHECK */
  2559. #endif
  2560. #endif
  2561. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
  2562. if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
  2563. key->n.raw.len > 0) {
  2564. ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
  2565. }
  2566. else
  2567. #endif
  2568. #ifdef WC_RSA_NONBLOCK
  2569. if (key->nb) {
  2570. ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
  2571. }
  2572. else
  2573. #endif
  2574. {
  2575. ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
  2576. }
  2577. RESTORE_VECTOR_REGISTERS();
  2578. /* handle error */
  2579. if (ret < 0 && ret != WC_PENDING_E
  2580. #ifdef WC_RSA_NONBLOCK
  2581. && ret != FP_WOULDBLOCK
  2582. #endif
  2583. ) {
  2584. if (ret == MP_EXPTMOD_E) {
  2585. /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
  2586. WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
  2587. }
  2588. key->state = RSA_STATE_NONE;
  2589. wc_RsaCleanup(key);
  2590. }
  2591. return ret;
  2592. }
  2593. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  2594. /* Internal Wrappers */
  2595. /* Gives the option of choosing padding type
  2596. in : input to be encrypted
  2597. inLen: length of input buffer
  2598. out: encrypted output
  2599. outLen: length of encrypted output buffer
  2600. key : wolfSSL initialized RSA key struct
  2601. rng : wolfSSL initialized random number struct
  2602. rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
  2603. RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
  2604. pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
  2605. pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
  2606. WC_RSA_NO_PAD or WC_RSA_PSS_PAD
  2607. hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
  2608. mgf : type of mask generation function to use
  2609. label : optional label
  2610. labelSz : size of optional label buffer
  2611. saltLen : Length of salt used in PSS
  2612. rng : random number generator */
  2613. static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
  2614. word32 outLen, RsaKey* key, int rsa_type,
  2615. byte pad_value, int pad_type,
  2616. enum wc_HashType hash, int mgf,
  2617. byte* label, word32 labelSz, int saltLen,
  2618. WC_RNG* rng)
  2619. {
  2620. int ret, sz, state;
  2621. if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
  2622. return BAD_FUNC_ARG;
  2623. }
  2624. sz = wc_RsaEncryptSize(key);
  2625. if (sz > (int)outLen) {
  2626. return RSA_BUFFER_E;
  2627. }
  2628. if (sz < RSA_MIN_PAD_SZ) {
  2629. return WC_KEY_SIZE_E;
  2630. }
  2631. if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
  2632. #ifdef WC_RSA_NO_PADDING
  2633. /* In the case that no padding is used the input length can and should
  2634. * be the same size as the RSA key. */
  2635. if (pad_type != WC_RSA_NO_PAD)
  2636. #endif
  2637. return RSA_BUFFER_E;
  2638. }
  2639. #ifndef WOLFSSL_BIND
  2640. state = key->state;
  2641. #else
  2642. /* Bind9 shares the EVP_PKEY struct across multiple threads so let's just
  2643. * force a restart on each RsaPublicEncryptEx call for it. */
  2644. state = RSA_STATE_NONE;
  2645. #ifdef WOLFSSL_ASYNC_CRYPT
  2646. #error wolfSSL does not handle building bind support with async crypto
  2647. #endif
  2648. #endif
  2649. switch (state) {
  2650. case RSA_STATE_NONE:
  2651. case RSA_STATE_ENCRYPT_PAD:
  2652. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
  2653. defined(HAVE_CAVIUM)
  2654. if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
  2655. pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
  2656. /* Async operations that include padding */
  2657. if (rsa_type == RSA_PUBLIC_ENCRYPT &&
  2658. pad_value == RSA_BLOCK_TYPE_2) {
  2659. key->state = RSA_STATE_ENCRYPT_RES;
  2660. key->dataLen = key->n.raw.len;
  2661. return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
  2662. }
  2663. else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
  2664. pad_value == RSA_BLOCK_TYPE_1) {
  2665. key->state = RSA_STATE_ENCRYPT_RES;
  2666. key->dataLen = key->n.raw.len;
  2667. return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
  2668. }
  2669. }
  2670. #elif defined(WOLFSSL_CRYPTOCELL)
  2671. if (rsa_type == RSA_PUBLIC_ENCRYPT &&
  2672. pad_value == RSA_BLOCK_TYPE_2) {
  2673. return cc310_RsaPublicEncrypt(in, inLen, out, outLen, key);
  2674. }
  2675. else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
  2676. pad_value == RSA_BLOCK_TYPE_1) {
  2677. return cc310_RsaSSL_Sign(in, inLen, out, outLen, key,
  2678. cc310_hashModeRSA(hash, 0));
  2679. }
  2680. #endif /* WOLFSSL_CRYPTOCELL */
  2681. key->state = RSA_STATE_ENCRYPT_PAD;
  2682. ret = wc_RsaPad_ex(in, inLen, out, sz, pad_value, rng, pad_type, hash,
  2683. mgf, label, labelSz, saltLen, mp_count_bits(&key->n),
  2684. key->heap);
  2685. if (ret < 0) {
  2686. break;
  2687. }
  2688. key->state = RSA_STATE_ENCRYPT_EXPTMOD;
  2689. FALL_THROUGH;
  2690. case RSA_STATE_ENCRYPT_EXPTMOD:
  2691. key->dataLen = outLen;
  2692. ret = wc_RsaFunction(out, sz, out, &key->dataLen, rsa_type, key, rng);
  2693. if (ret >= 0 || ret == WC_PENDING_E) {
  2694. key->state = RSA_STATE_ENCRYPT_RES;
  2695. }
  2696. if (ret < 0) {
  2697. break;
  2698. }
  2699. FALL_THROUGH;
  2700. case RSA_STATE_ENCRYPT_RES:
  2701. ret = key->dataLen;
  2702. break;
  2703. default:
  2704. ret = BAD_STATE_E;
  2705. break;
  2706. }
  2707. /* if async pending then return and skip done cleanup below */
  2708. if (ret == WC_PENDING_E
  2709. #ifdef WC_RSA_NONBLOCK
  2710. || ret == FP_WOULDBLOCK
  2711. #endif
  2712. ) {
  2713. return ret;
  2714. }
  2715. key->state = RSA_STATE_NONE;
  2716. wc_RsaCleanup(key);
  2717. return ret;
  2718. }
  2719. #endif
  2720. /* Gives the option of choosing padding type
  2721. in : input to be decrypted
  2722. inLen: length of input buffer
  2723. out: decrypted message
  2724. outLen: length of decrypted message in bytes
  2725. outPtr: optional inline output pointer (if provided doing inline)
  2726. key : wolfSSL initialized RSA key struct
  2727. rsa_type : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
  2728. RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
  2729. pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
  2730. pad_type : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
  2731. WC_RSA_NO_PAD, WC_RSA_PSS_PAD
  2732. hash : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
  2733. mgf : type of mask generation function to use
  2734. label : optional label
  2735. labelSz : size of optional label buffer
  2736. saltLen : Length of salt used in PSS
  2737. rng : random number generator */
  2738. static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
  2739. word32 outLen, byte** outPtr, RsaKey* key,
  2740. int rsa_type, byte pad_value, int pad_type,
  2741. enum wc_HashType hash, int mgf,
  2742. byte* label, word32 labelSz, int saltLen,
  2743. WC_RNG* rng)
  2744. {
  2745. int ret = RSA_WRONG_TYPE_E;
  2746. byte* pad = NULL;
  2747. if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
  2748. return BAD_FUNC_ARG;
  2749. }
  2750. switch (key->state) {
  2751. case RSA_STATE_NONE:
  2752. key->dataLen = inLen;
  2753. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
  2754. defined(HAVE_CAVIUM)
  2755. /* Async operations that include padding */
  2756. if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
  2757. pad_type != WC_RSA_PSS_PAD) {
  2758. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2759. if (rsa_type == RSA_PRIVATE_DECRYPT &&
  2760. pad_value == RSA_BLOCK_TYPE_2) {
  2761. key->state = RSA_STATE_DECRYPT_RES;
  2762. key->data = NULL;
  2763. return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
  2764. key);
  2765. #endif
  2766. }
  2767. else if (rsa_type == RSA_PUBLIC_DECRYPT &&
  2768. pad_value == RSA_BLOCK_TYPE_1) {
  2769. key->state = RSA_STATE_DECRYPT_RES;
  2770. key->data = NULL;
  2771. return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
  2772. }
  2773. }
  2774. #elif defined(WOLFSSL_CRYPTOCELL)
  2775. if (rsa_type == RSA_PRIVATE_DECRYPT &&
  2776. pad_value == RSA_BLOCK_TYPE_2) {
  2777. ret = cc310_RsaPublicDecrypt(in, inLen, out, outLen, key);
  2778. if (outPtr != NULL)
  2779. *outPtr = out; /* for inline */
  2780. return ret;
  2781. }
  2782. else if (rsa_type == RSA_PUBLIC_DECRYPT &&
  2783. pad_value == RSA_BLOCK_TYPE_1) {
  2784. return cc310_RsaSSL_Verify(in, inLen, out, key,
  2785. cc310_hashModeRSA(hash, 0));
  2786. }
  2787. #endif /* WOLFSSL_CRYPTOCELL */
  2788. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
  2789. /* verify the tmp ptr is NULL, otherwise indicates bad state */
  2790. if (key->data != NULL) {
  2791. ret = BAD_STATE_E;
  2792. break;
  2793. }
  2794. /* if not doing this inline then allocate a buffer for it */
  2795. if (outPtr == NULL) {
  2796. key->data = (byte*)XMALLOC(inLen, key->heap,
  2797. DYNAMIC_TYPE_WOLF_BIGINT);
  2798. key->dataIsAlloc = 1;
  2799. if (key->data == NULL) {
  2800. ret = MEMORY_E;
  2801. break;
  2802. }
  2803. XMEMCPY(key->data, in, inLen);
  2804. }
  2805. else {
  2806. key->data = out;
  2807. }
  2808. #endif
  2809. key->state = RSA_STATE_DECRYPT_EXPTMOD;
  2810. FALL_THROUGH;
  2811. case RSA_STATE_DECRYPT_EXPTMOD:
  2812. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
  2813. ret = wc_RsaFunction(key->data, inLen, key->data, &key->dataLen,
  2814. rsa_type, key, rng);
  2815. #else
  2816. ret = wc_RsaFunction(in, inLen, out, &key->dataLen, rsa_type, key, rng);
  2817. #endif
  2818. if (ret >= 0 || ret == WC_PENDING_E) {
  2819. key->state = RSA_STATE_DECRYPT_UNPAD;
  2820. }
  2821. if (ret < 0) {
  2822. break;
  2823. }
  2824. FALL_THROUGH;
  2825. case RSA_STATE_DECRYPT_UNPAD:
  2826. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
  2827. ret = wc_RsaUnPad_ex(key->data, key->dataLen, &pad, pad_value, pad_type,
  2828. hash, mgf, label, labelSz, saltLen,
  2829. mp_count_bits(&key->n), key->heap);
  2830. #else
  2831. ret = wc_RsaUnPad_ex(out, key->dataLen, &pad, pad_value, pad_type, hash,
  2832. mgf, label, labelSz, saltLen,
  2833. mp_count_bits(&key->n), key->heap);
  2834. #endif
  2835. if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen)
  2836. ret = RSA_BUFFER_E;
  2837. else if (ret >= 0 && pad != NULL) {
  2838. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
  2839. signed char c;
  2840. #endif
  2841. /* only copy output if not inline */
  2842. if (outPtr == NULL) {
  2843. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)
  2844. if (rsa_type == RSA_PRIVATE_DECRYPT) {
  2845. word32 i = 0;
  2846. word32 j;
  2847. int start = (int)((size_t)pad - (size_t)key->data);
  2848. for (j = 0; j < key->dataLen; j++) {
  2849. out[i] = key->data[j];
  2850. c = ctMaskGTE(j, start);
  2851. c &= ctMaskLT(i, outLen);
  2852. /* 0 - no add, -1 add */
  2853. i += (word32)((byte)(-c));
  2854. }
  2855. }
  2856. else
  2857. #endif
  2858. {
  2859. XMEMCPY(out, pad, ret);
  2860. }
  2861. }
  2862. else
  2863. *outPtr = pad;
  2864. #if !defined(WOLFSSL_RSA_VERIFY_ONLY)
  2865. ret = ctMaskSelInt(ctMaskLTE(ret, outLen), ret, RSA_BUFFER_E);
  2866. ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret, RSA_BUFFER_E);
  2867. #else
  2868. if (outLen < (word32)ret)
  2869. ret = RSA_BUFFER_E;
  2870. #endif
  2871. }
  2872. key->state = RSA_STATE_DECRYPT_RES;
  2873. FALL_THROUGH;
  2874. case RSA_STATE_DECRYPT_RES:
  2875. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
  2876. defined(HAVE_CAVIUM)
  2877. if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
  2878. pad_type != WC_RSA_PSS_PAD) {
  2879. ret = key->asyncDev.event.ret;
  2880. if (ret >= 0) {
  2881. /* convert result */
  2882. byte* dataLen = (byte*)&key->dataLen;
  2883. ret = (dataLen[0] << 8) | (dataLen[1]);
  2884. if (outPtr)
  2885. *outPtr = in;
  2886. }
  2887. }
  2888. #endif
  2889. break;
  2890. default:
  2891. ret = BAD_STATE_E;
  2892. break;
  2893. }
  2894. /* if async pending then return and skip done cleanup below */
  2895. if (ret == WC_PENDING_E
  2896. #ifdef WC_RSA_NONBLOCK
  2897. || ret == FP_WOULDBLOCK
  2898. #endif
  2899. ) {
  2900. return ret;
  2901. }
  2902. key->state = RSA_STATE_NONE;
  2903. wc_RsaCleanup(key);
  2904. return ret;
  2905. }
  2906. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  2907. /* Public RSA Functions */
  2908. int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
  2909. RsaKey* key, WC_RNG* rng)
  2910. {
  2911. int ret;
  2912. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2913. ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
  2914. RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
  2915. WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
  2916. RESTORE_VECTOR_REGISTERS();
  2917. return ret;
  2918. }
  2919. #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
  2920. int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
  2921. word32 outLen, RsaKey* key, WC_RNG* rng, int type,
  2922. enum wc_HashType hash, int mgf, byte* label,
  2923. word32 labelSz)
  2924. {
  2925. int ret;
  2926. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2927. ret = RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
  2928. RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
  2929. RESTORE_VECTOR_REGISTERS();
  2930. return ret;
  2931. }
  2932. #endif /* WC_NO_RSA_OAEP */
  2933. #endif
  2934. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  2935. int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
  2936. {
  2937. WC_RNG* rng;
  2938. int ret;
  2939. #ifdef WC_RSA_BLINDING
  2940. rng = key->rng;
  2941. #else
  2942. rng = NULL;
  2943. #endif
  2944. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2945. ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
  2946. RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
  2947. WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
  2948. RESTORE_VECTOR_REGISTERS();
  2949. return ret;
  2950. }
  2951. #ifndef WC_NO_RSA_OAEP
  2952. int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
  2953. RsaKey* key, int type, enum wc_HashType hash,
  2954. int mgf, byte* label, word32 labelSz)
  2955. {
  2956. WC_RNG* rng;
  2957. int ret;
  2958. #ifdef WC_RSA_BLINDING
  2959. rng = key->rng;
  2960. #else
  2961. rng = NULL;
  2962. #endif
  2963. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2964. ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
  2965. RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
  2966. mgf, label, labelSz, 0, rng);
  2967. RESTORE_VECTOR_REGISTERS();
  2968. return ret;
  2969. }
  2970. #endif /* WC_NO_RSA_OAEP */
  2971. int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
  2972. word32 outLen, RsaKey* key)
  2973. {
  2974. WC_RNG* rng;
  2975. int ret;
  2976. #ifdef WC_RSA_BLINDING
  2977. rng = key->rng;
  2978. #else
  2979. rng = NULL;
  2980. #endif
  2981. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  2982. ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
  2983. RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
  2984. WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
  2985. RESTORE_VECTOR_REGISTERS();
  2986. return ret;
  2987. }
  2988. #if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
  2989. int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
  2990. word32 outLen, RsaKey* key, int type,
  2991. enum wc_HashType hash, int mgf, byte* label,
  2992. word32 labelSz)
  2993. {
  2994. WC_RNG* rng;
  2995. int ret;
  2996. #ifdef WC_RSA_BLINDING
  2997. rng = key->rng;
  2998. #else
  2999. rng = NULL;
  3000. #endif
  3001. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3002. ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
  3003. RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
  3004. labelSz, 0, rng);
  3005. RESTORE_VECTOR_REGISTERS();
  3006. return ret;
  3007. }
  3008. #endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
  3009. #endif /* WOLFSSL_RSA_PUBLIC_ONLY */
  3010. #if !defined(WOLFSSL_CRYPTOCELL)
  3011. int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
  3012. {
  3013. WC_RNG* rng;
  3014. int ret;
  3015. #ifdef WC_RSA_BLINDING
  3016. rng = key->rng;
  3017. #else
  3018. rng = NULL;
  3019. #endif
  3020. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3021. ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
  3022. RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
  3023. WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
  3024. RESTORE_VECTOR_REGISTERS();
  3025. return ret;
  3026. }
  3027. #endif
  3028. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  3029. int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
  3030. RsaKey* key)
  3031. {
  3032. return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key, WC_RSA_PKCSV15_PAD);
  3033. }
  3034. int wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
  3035. RsaKey* key, int pad_type)
  3036. {
  3037. int ret;
  3038. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3039. ret = wc_RsaSSL_Verify_ex2(in, inLen, out, outLen, key, pad_type,
  3040. WC_HASH_TYPE_NONE);
  3041. RESTORE_VECTOR_REGISTERS();
  3042. return ret;
  3043. }
  3044. int wc_RsaSSL_Verify_ex2(const byte* in, word32 inLen, byte* out, word32 outLen,
  3045. RsaKey* key, int pad_type, enum wc_HashType hash)
  3046. {
  3047. WC_RNG* rng;
  3048. int ret;
  3049. if (key == NULL) {
  3050. return BAD_FUNC_ARG;
  3051. }
  3052. #ifdef WC_RSA_BLINDING
  3053. rng = key->rng;
  3054. #else
  3055. rng = NULL;
  3056. #endif
  3057. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3058. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3059. ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
  3060. RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
  3061. hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DEFAULT, rng);
  3062. #else
  3063. ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
  3064. RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
  3065. hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DISCOVER, rng);
  3066. #endif
  3067. RESTORE_VECTOR_REGISTERS();
  3068. return ret;
  3069. }
  3070. #endif
  3071. #ifdef WC_RSA_PSS
  3072. /* Verify the message signed with RSA-PSS.
  3073. * The input buffer is reused for the output buffer.
  3074. * Salt length is equal to hash length.
  3075. *
  3076. * in Buffer holding encrypted data.
  3077. * inLen Length of data in buffer.
  3078. * out Pointer to address containing the PSS data.
  3079. * hash Hash algorithm.
  3080. * mgf Mask generation function.
  3081. * key Public RSA key.
  3082. * returns the length of the PSS data on success and negative indicates failure.
  3083. */
  3084. int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
  3085. enum wc_HashType hash, int mgf, RsaKey* key)
  3086. {
  3087. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3088. return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
  3089. RSA_PSS_SALT_LEN_DEFAULT, key);
  3090. #else
  3091. return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
  3092. RSA_PSS_SALT_LEN_DISCOVER, key);
  3093. #endif
  3094. }
  3095. /* Verify the message signed with RSA-PSS.
  3096. * The input buffer is reused for the output buffer.
  3097. *
  3098. * in Buffer holding encrypted data.
  3099. * inLen Length of data in buffer.
  3100. * out Pointer to address containing the PSS data.
  3101. * hash Hash algorithm.
  3102. * mgf Mask generation function.
  3103. * key Public RSA key.
  3104. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
  3105. * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
  3106. * indicates salt length is determined from the data.
  3107. * returns the length of the PSS data on success and negative indicates failure.
  3108. */
  3109. int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
  3110. enum wc_HashType hash, int mgf, int saltLen,
  3111. RsaKey* key)
  3112. {
  3113. WC_RNG* rng;
  3114. int ret;
  3115. #ifdef WC_RSA_BLINDING
  3116. rng = key->rng;
  3117. #else
  3118. rng = NULL;
  3119. #endif
  3120. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3121. ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
  3122. RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
  3123. hash, mgf, NULL, 0, saltLen, rng);
  3124. RESTORE_VECTOR_REGISTERS();
  3125. return ret;
  3126. }
  3127. /* Verify the message signed with RSA-PSS.
  3128. * Salt length is equal to hash length.
  3129. *
  3130. * in Buffer holding encrypted data.
  3131. * inLen Length of data in buffer.
  3132. * out Pointer to address containing the PSS data.
  3133. * hash Hash algorithm.
  3134. * mgf Mask generation function.
  3135. * key Public RSA key.
  3136. * returns the length of the PSS data on success and negative indicates failure.
  3137. */
  3138. int wc_RsaPSS_Verify(byte* in, word32 inLen, byte* out, word32 outLen,
  3139. enum wc_HashType hash, int mgf, RsaKey* key)
  3140. {
  3141. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3142. return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
  3143. RSA_PSS_SALT_LEN_DEFAULT, key);
  3144. #else
  3145. return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
  3146. RSA_PSS_SALT_LEN_DISCOVER, key);
  3147. #endif
  3148. }
  3149. /* Verify the message signed with RSA-PSS.
  3150. *
  3151. * in Buffer holding encrypted data.
  3152. * inLen Length of data in buffer.
  3153. * out Pointer to address containing the PSS data.
  3154. * hash Hash algorithm.
  3155. * mgf Mask generation function.
  3156. * key Public RSA key.
  3157. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
  3158. * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
  3159. * indicates salt length is determined from the data.
  3160. * returns the length of the PSS data on success and negative indicates failure.
  3161. */
  3162. int wc_RsaPSS_Verify_ex(byte* in, word32 inLen, byte* out, word32 outLen,
  3163. enum wc_HashType hash, int mgf, int saltLen,
  3164. RsaKey* key)
  3165. {
  3166. WC_RNG* rng;
  3167. int ret;
  3168. #ifdef WC_RSA_BLINDING
  3169. rng = key->rng;
  3170. #else
  3171. rng = NULL;
  3172. #endif
  3173. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3174. ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
  3175. RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
  3176. hash, mgf, NULL, 0, saltLen, rng);
  3177. RESTORE_VECTOR_REGISTERS();
  3178. return ret;
  3179. }
  3180. /* Checks the PSS data to ensure that the signature matches.
  3181. * Salt length is equal to hash length.
  3182. *
  3183. * in Hash of the data that is being verified.
  3184. * inSz Length of hash.
  3185. * sig Buffer holding PSS data.
  3186. * sigSz Size of PSS data.
  3187. * hashType Hash algorithm.
  3188. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
  3189. * NULL is passed in to in or sig or inSz is not the same as the hash
  3190. * algorithm length and 0 on success.
  3191. */
  3192. int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, byte* sig,
  3193. word32 sigSz, enum wc_HashType hashType)
  3194. {
  3195. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3196. return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DEFAULT, 0);
  3197. #else
  3198. return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DISCOVER, 0);
  3199. #endif
  3200. }
  3201. /* Checks the PSS data to ensure that the signature matches.
  3202. *
  3203. * in Hash of the data that is being verified.
  3204. * inSz Length of hash.
  3205. * sig Buffer holding PSS data.
  3206. * sigSz Size of PSS data.
  3207. * hashType Hash algorithm.
  3208. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
  3209. * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
  3210. * indicates salt length is determined from the data.
  3211. * bits Can be used to calculate salt size in FIPS case
  3212. * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
  3213. * NULL is passed in to in or sig or inSz is not the same as the hash
  3214. * algorithm length and 0 on success.
  3215. */
  3216. int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, byte* sig,
  3217. word32 sigSz, enum wc_HashType hashType,
  3218. int saltLen, int bits, void* heap)
  3219. {
  3220. int ret = 0;
  3221. byte sigCheckBuf[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
  3222. byte *sigCheck = sigCheckBuf;
  3223. (void)bits;
  3224. if (in == NULL || sig == NULL ||
  3225. inSz != (word32)wc_HashGetDigestSize(hashType)) {
  3226. ret = BAD_FUNC_ARG;
  3227. }
  3228. if (ret == 0) {
  3229. if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
  3230. saltLen = inSz;
  3231. #ifdef WOLFSSL_SHA512
  3232. /* See FIPS 186-4 section 5.5 item (e). */
  3233. if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
  3234. saltLen = RSA_PSS_SALT_MAX_SZ;
  3235. }
  3236. #endif
  3237. }
  3238. #ifndef WOLFSSL_PSS_LONG_SALT
  3239. else if (saltLen > (int)inSz) {
  3240. ret = PSS_SALTLEN_E;
  3241. }
  3242. #endif
  3243. #ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
  3244. else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
  3245. ret = PSS_SALTLEN_E;
  3246. }
  3247. #else
  3248. else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
  3249. saltLen = sigSz - inSz;
  3250. if (saltLen < 0) {
  3251. ret = PSS_SALTLEN_E;
  3252. }
  3253. }
  3254. else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
  3255. ret = PSS_SALTLEN_E;
  3256. }
  3257. #endif
  3258. }
  3259. /* Sig = Salt | Exp Hash */
  3260. if (ret == 0) {
  3261. if (sigSz != inSz + saltLen) {
  3262. ret = PSS_SALTLEN_E;
  3263. }
  3264. }
  3265. #ifdef WOLFSSL_PSS_LONG_SALT
  3266. /* if long salt is larger then default maximum buffer then allocate a buffer */
  3267. if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + saltLen)) {
  3268. sigCheck = (byte*)XMALLOC(RSA_PSS_PAD_SZ + inSz + saltLen, heap,
  3269. DYNAMIC_TYPE_RSA_BUFFER);
  3270. if (sigCheck == NULL) {
  3271. ret = MEMORY_E;
  3272. }
  3273. }
  3274. #endif
  3275. /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
  3276. if (ret == 0) {
  3277. XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
  3278. XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
  3279. XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, saltLen);
  3280. ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + saltLen,
  3281. sigCheck, inSz);
  3282. }
  3283. if (ret == 0) {
  3284. if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
  3285. WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
  3286. ret = BAD_PADDING_E;
  3287. }
  3288. }
  3289. #ifdef WOLFSSL_PSS_LONG_SALT
  3290. if (sigCheck != NULL && sigCheck != sigCheckBuf) {
  3291. XFREE(sigCheck, heap, DYNAMIC_TYPE_RSA_BUFFER);
  3292. }
  3293. #endif
  3294. (void)heap; /* unused if memory is disabled */
  3295. return ret;
  3296. }
  3297. int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, byte* sig,
  3298. word32 sigSz, enum wc_HashType hashType,
  3299. int saltLen, int bits)
  3300. {
  3301. return wc_RsaPSS_CheckPadding_ex2(in, inSz, sig, sigSz, hashType, saltLen,
  3302. bits, NULL);
  3303. }
  3304. /* Verify the message signed with RSA-PSS.
  3305. * The input buffer is reused for the output buffer.
  3306. * Salt length is equal to hash length.
  3307. *
  3308. * in Buffer holding encrypted data.
  3309. * inLen Length of data in buffer.
  3310. * out Pointer to address containing the PSS data.
  3311. * digest Hash of the data that is being verified.
  3312. * digestLen Length of hash.
  3313. * hash Hash algorithm.
  3314. * mgf Mask generation function.
  3315. * key Public RSA key.
  3316. * returns the length of the PSS data on success and negative indicates failure.
  3317. */
  3318. int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
  3319. const byte* digest, word32 digestLen,
  3320. enum wc_HashType hash, int mgf, RsaKey* key)
  3321. {
  3322. int ret = 0, verify, saltLen, hLen, bits = 0;
  3323. hLen = wc_HashGetDigestSize(hash);
  3324. if (hLen < 0)
  3325. return BAD_FUNC_ARG;
  3326. if ((word32)hLen != digestLen)
  3327. return BAD_FUNC_ARG;
  3328. saltLen = hLen;
  3329. #ifdef WOLFSSL_SHA512
  3330. /* See FIPS 186-4 section 5.5 item (e). */
  3331. bits = mp_count_bits(&key->n);
  3332. if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
  3333. saltLen = RSA_PSS_SALT_MAX_SZ;
  3334. #endif
  3335. verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
  3336. if (verify > 0)
  3337. ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, verify,
  3338. hash, saltLen, bits);
  3339. if (ret == 0)
  3340. ret = verify;
  3341. return ret;
  3342. }
  3343. /* Verify the message signed with RSA-PSS.
  3344. * Salt length is equal to hash length.
  3345. *
  3346. * in Buffer holding encrypted data.
  3347. * inLen Length of data in buffer.
  3348. * out Pointer to address containing the PSS data.
  3349. * outLen Length of the output.
  3350. * digest Hash of the data that is being verified.
  3351. * digestLen Length of hash.
  3352. * hash Hash algorithm.
  3353. * mgf Mask generation function.
  3354. * key Public RSA key.
  3355. * returns the length of the PSS data on success and negative indicates failure.
  3356. */
  3357. int wc_RsaPSS_VerifyCheck(byte* in, word32 inLen, byte* out, word32 outLen,
  3358. const byte* digest, word32 digestLen,
  3359. enum wc_HashType hash, int mgf,
  3360. RsaKey* key)
  3361. {
  3362. int ret = 0, verify, saltLen, hLen, bits = 0;
  3363. hLen = wc_HashGetDigestSize(hash);
  3364. if (hLen < 0)
  3365. return hLen;
  3366. if ((word32)hLen != digestLen)
  3367. return BAD_FUNC_ARG;
  3368. saltLen = hLen;
  3369. #ifdef WOLFSSL_SHA512
  3370. /* See FIPS 186-4 section 5.5 item (e). */
  3371. bits = mp_count_bits(&key->n);
  3372. if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
  3373. saltLen = RSA_PSS_SALT_MAX_SZ;
  3374. #endif
  3375. verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
  3376. mgf, saltLen, key);
  3377. if (verify > 0)
  3378. ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, verify,
  3379. hash, saltLen, bits);
  3380. if (ret == 0)
  3381. ret = verify;
  3382. return ret;
  3383. }
  3384. #endif
  3385. #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
  3386. int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
  3387. RsaKey* key, WC_RNG* rng)
  3388. {
  3389. int ret;
  3390. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3391. ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
  3392. RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
  3393. WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
  3394. RESTORE_VECTOR_REGISTERS();
  3395. return ret;
  3396. }
  3397. #ifdef WC_RSA_PSS
  3398. /* Sign the hash of a message using RSA-PSS.
  3399. * Salt length is equal to hash length.
  3400. *
  3401. * in Buffer holding hash of message.
  3402. * inLen Length of data in buffer (hash length).
  3403. * out Buffer to write encrypted signature into.
  3404. * outLen Size of buffer to write to.
  3405. * hash Hash algorithm.
  3406. * mgf Mask generation function.
  3407. * key Public RSA key.
  3408. * rng Random number generator.
  3409. * returns the length of the encrypted signature on success, a negative value
  3410. * indicates failure.
  3411. */
  3412. int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
  3413. enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
  3414. {
  3415. return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
  3416. RSA_PSS_SALT_LEN_DEFAULT, key, rng);
  3417. }
  3418. /* Sign the hash of a message using RSA-PSS.
  3419. *
  3420. * in Buffer holding hash of message.
  3421. * inLen Length of data in buffer (hash length).
  3422. * out Buffer to write encrypted signature into.
  3423. * outLen Size of buffer to write to.
  3424. * hash Hash algorithm.
  3425. * mgf Mask generation function.
  3426. * saltLen Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
  3427. * length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
  3428. * indicates salt length is determined from the data.
  3429. * key Public RSA key.
  3430. * rng Random number generator.
  3431. * returns the length of the encrypted signature on success, a negative value
  3432. * indicates failure.
  3433. */
  3434. int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
  3435. enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
  3436. WC_RNG* rng)
  3437. {
  3438. int ret;
  3439. SAVE_VECTOR_REGISTERS(return _svr_ret;);
  3440. ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
  3441. RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
  3442. hash, mgf, NULL, 0, saltLen, rng);
  3443. RESTORE_VECTOR_REGISTERS();
  3444. return ret;
  3445. }
  3446. #endif
  3447. #endif
  3448. #if !defined(WOLFSSL_RSA_VERIFY_ONLY) || !defined(WOLFSSL_SP_MATH) || \
  3449. defined(WC_RSA_PSS)
  3450. int wc_RsaEncryptSize(const RsaKey* key)
  3451. {
  3452. int ret;
  3453. if (key == NULL) {
  3454. return BAD_FUNC_ARG;
  3455. }
  3456. ret = mp_unsigned_bin_size(&key->n);
  3457. #ifdef WOLF_CRYPTO_CB
  3458. if (ret == 0 && key->devId != INVALID_DEVID) {
  3459. ret = 2048/8; /* hardware handles, use 2048-bit as default */
  3460. }
  3461. #endif
  3462. return ret;
  3463. }
  3464. #endif
  3465. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  3466. /* flatten RsaKey structure into individual elements (e, n) */
  3467. int wc_RsaFlattenPublicKey(RsaKey* key, byte* e, word32* eSz, byte* n,
  3468. word32* nSz)
  3469. {
  3470. int sz, ret;
  3471. if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
  3472. return BAD_FUNC_ARG;
  3473. }
  3474. sz = mp_unsigned_bin_size(&key->e);
  3475. if ((word32)sz > *eSz)
  3476. return RSA_BUFFER_E;
  3477. ret = mp_to_unsigned_bin(&key->e, e);
  3478. if (ret != MP_OKAY)
  3479. return ret;
  3480. *eSz = (word32)sz;
  3481. sz = wc_RsaEncryptSize(key);
  3482. if ((word32)sz > *nSz)
  3483. return RSA_BUFFER_E;
  3484. ret = mp_to_unsigned_bin(&key->n, n);
  3485. if (ret != MP_OKAY)
  3486. return ret;
  3487. *nSz = (word32)sz;
  3488. return 0;
  3489. }
  3490. #endif
  3491. #endif /* HAVE_FIPS */
  3492. #ifndef WOLFSSL_RSA_VERIFY_ONLY
  3493. static int RsaGetValue(mp_int* in, byte* out, word32* outSz)
  3494. {
  3495. word32 sz;
  3496. int ret = 0;
  3497. /* Parameters ensured by calling function. */
  3498. sz = (word32)mp_unsigned_bin_size(in);
  3499. if (sz > *outSz)
  3500. ret = RSA_BUFFER_E;
  3501. if (ret == 0)
  3502. ret = mp_to_unsigned_bin(in, out);
  3503. if (ret == MP_OKAY)
  3504. *outSz = sz;
  3505. return ret;
  3506. }
  3507. int wc_RsaExportKey(RsaKey* key,
  3508. byte* e, word32* eSz, byte* n, word32* nSz,
  3509. byte* d, word32* dSz, byte* p, word32* pSz,
  3510. byte* q, word32* qSz)
  3511. {
  3512. int ret = BAD_FUNC_ARG;
  3513. if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz)
  3514. ret = 0;
  3515. if (ret == 0)
  3516. ret = RsaGetValue(&key->e, e, eSz);
  3517. if (ret == 0)
  3518. ret = RsaGetValue(&key->n, n, nSz);
  3519. #ifndef WOLFSSL_RSA_PUBLIC_ONLY
  3520. if (ret == 0)
  3521. ret = RsaGetValue(&key->d, d, dSz);
  3522. if (ret == 0)
  3523. ret = RsaGetValue(&key->p, p, pSz);
  3524. if (ret == 0)
  3525. ret = RsaGetValue(&key->q, q, qSz);
  3526. #else
  3527. /* no private parts to key */
  3528. if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
  3529. || qSz == NULL) {
  3530. ret = BAD_FUNC_ARG;
  3531. }
  3532. else {
  3533. *dSz = 0;
  3534. *pSz = 0;
  3535. *qSz = 0;
  3536. }
  3537. #endif /* WOLFSSL_RSA_PUBLIC_ONLY */
  3538. return ret;
  3539. }
  3540. #endif
  3541. #ifdef WOLFSSL_KEY_GEN
  3542. /* Check that |p-q| > 2^((size/2)-100) */
  3543. static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size)
  3544. {
  3545. #ifdef WOLFSSL_SMALL_STACK
  3546. mp_int *c = NULL, *d = NULL;
  3547. #else
  3548. mp_int c[1], d[1];
  3549. #endif
  3550. int ret;
  3551. if (p == NULL || q == NULL)
  3552. return BAD_FUNC_ARG;
  3553. #ifdef WOLFSSL_SMALL_STACK
  3554. if (((c = (mp_int *)XMALLOC(sizeof(*c), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
  3555. ((d = (mp_int *)XMALLOC(sizeof(*d), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL))
  3556. ret = MEMORY_E;
  3557. else
  3558. ret = 0;
  3559. if (ret == 0)
  3560. #endif
  3561. ret = mp_init_multi(c, d, NULL, NULL, NULL, NULL);
  3562. /* c = 2^((size/2)-100) */
  3563. if (ret == 0)
  3564. ret = mp_2expt(c, (size/2)-100);
  3565. /* d = |p-q| */
  3566. if (ret == 0)
  3567. ret = mp_sub(p, q, d);
  3568. #if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \
  3569. defined(WOLFSSL_SP_INT_NEGATIVE))
  3570. if (ret == 0)
  3571. ret = mp_abs(d, d);
  3572. #endif
  3573. /* compare */
  3574. if (ret == 0)
  3575. ret = mp_cmp(d, c);
  3576. if (ret == MP_GT)
  3577. ret = MP_OKAY;
  3578. #ifdef WOLFSSL_SMALL_STACK
  3579. if (d != NULL) {
  3580. mp_clear(d);
  3581. XFREE(d, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
  3582. }
  3583. if (c != NULL) {
  3584. mp_clear(c);
  3585. XFREE(c, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
  3586. }
  3587. #else
  3588. mp_clear(d);
  3589. mp_clear(c);
  3590. #endif
  3591. return ret;
  3592. }
  3593. /* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
  3594. * This number was calculated using a small test tool written with a common
  3595. * large number math library. Other values of nlen may be checked with a subset
  3596. * of lower_bound. */
  3597. static const byte lower_bound[] = {
  3598. 0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
  3599. 0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
  3600. 0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
  3601. 0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
  3602. /* 512 */
  3603. 0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
  3604. 0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
  3605. 0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
  3606. 0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
  3607. /* 1024 */
  3608. 0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
  3609. 0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
  3610. 0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
  3611. 0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
  3612. 0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
  3613. 0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
  3614. 0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
  3615. 0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
  3616. /* 2048 */
  3617. 0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
  3618. 0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
  3619. 0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
  3620. 0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
  3621. 0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
  3622. 0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
  3623. 0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
  3624. 0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
  3625. /* 3072 */
  3626. 0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
  3627. 0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
  3628. 0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
  3629. 0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
  3630. 0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
  3631. 0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
  3632. 0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
  3633. 0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
  3634. /* 4096 */
  3635. };
  3636. /* returns 1 on key size ok and 0 if not ok */
  3637. static WC_INLINE int RsaSizeCheck(int size)
  3638. {
  3639. if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
  3640. return 0;
  3641. }
  3642. #ifdef HAVE_FIPS
  3643. /* Key size requirements for CAVP */
  3644. switch (size) {
  3645. case 1024:
  3646. case 2048:
  3647. case 3072:
  3648. case 4096:
  3649. return 1;
  3650. }
  3651. return 0;
  3652. #else
  3653. return 1; /* allow unusual key sizes in non FIPS mode */
  3654. #endif /* HAVE_FIPS */
  3655. }
  3656. static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
  3657. int* isPrime, WC_RNG* rng)
  3658. {
  3659. int ret;
  3660. #ifdef WOLFSSL_SMALL_STACK
  3661. mp_int *tmp1 = NULL, *tmp2 = NULL;
  3662. #else
  3663. mp_int tmp1[1], tmp2[2];
  3664. #endif
  3665. mp_int* prime;
  3666. if (p == NULL || e == NULL || isPrime == NULL)
  3667. return BAD_FUNC_ARG;
  3668. if (!RsaSizeCheck(nlen))
  3669. return BAD_FUNC_ARG;
  3670. *isPrime = MP_NO;
  3671. if (q != NULL) {
  3672. /* 5.4 - check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
  3673. ret = wc_CompareDiffPQ(p, q, nlen);
  3674. if (ret != MP_OKAY) goto notOkay;
  3675. prime = q;
  3676. }
  3677. else
  3678. prime = p;
  3679. #ifdef WOLFSSL_SMALL_STACK
  3680. if (((tmp1 = (mp_int *)XMALLOC(sizeof(*tmp1), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
  3681. ((tmp2 = (mp_int *)XMALLOC(sizeof(*tmp2), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL)) {
  3682. ret = MEMORY_E;
  3683. goto notOkay;
  3684. }
  3685. #endif
  3686. ret = mp_init_multi(tmp1, tmp2, NULL, NULL, NULL, NULL);
  3687. if (ret != MP_OKAY) goto notOkay;
  3688. /* 4.4,5.5 - Check that prime >= (2^(1/2))(2^((nlen/2)-1))
  3689. * This is a comparison against lowerBound */
  3690. ret = mp_read_unsigned_bin(tmp1, lower_bound, nlen/16);
  3691. if (ret != MP_OKAY) goto notOkay;
  3692. ret = mp_cmp(prime, tmp1);
  3693. if (ret == MP_LT) goto exit;
  3694. /* 4.5,5.6 - Check that GCD(p-1, e) == 1 */
  3695. ret = mp_sub_d(prime, 1, tmp1); /* tmp1 = prime-1 */
  3696. if (ret != MP_OKAY) goto notOkay;
  3697. ret = mp_gcd(tmp1, e, tmp2); /* tmp2 = gcd(prime-1, e) */
  3698. if (ret != MP_OKAY) goto notOkay;
  3699. ret = mp_cmp_d(tmp2, 1);
  3700. if (ret != MP_EQ) goto exit; /* e divides p-1 */
  3701. /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
  3702. * mp_prime_is_prime_ex() performs test divisions against the first 256
  3703. * prime numbers. After that it performs 8 rounds of M-R using random
  3704. * bases between 2 and n-2.
  3705. * mp_prime_is_prime() performs the same test divisions and then does
  3706. * M-R with the first 8 primes. Both functions set isPrime as a
  3707. * side-effect. */
  3708. if (rng != NULL)
  3709. ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
  3710. else
  3711. ret = mp_prime_is_prime(prime, 8, isPrime);
  3712. if (ret != MP_OKAY) goto notOkay;
  3713. exit:
  3714. ret = MP_OKAY;
  3715. notOkay:
  3716. #ifdef WOLFSSL_SMALL_STACK
  3717. if (tmp1 != NULL) {
  3718. mp_clear(tmp1);
  3719. XFREE(tmp1, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
  3720. }
  3721. if (tmp2 != NULL) {
  3722. mp_clear(tmp2);
  3723. XFREE(tmp2, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
  3724. }
  3725. #else
  3726. mp_clear(tmp1);
  3727. mp_clear(tmp2);
  3728. #endif
  3729. return ret;
  3730. }
  3731. int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
  3732. const byte* qRaw, word32 qRawSz,
  3733. const byte* eRaw, word32 eRawSz,
  3734. int nlen, int* isPrime, WC_RNG* rng)
  3735. {
  3736. #ifdef WOLFSSL_SMALL_STACK
  3737. mp_int *p = NULL, *q = NULL, *e = NULL;
  3738. #else
  3739. mp_int p[1], q[1], e[1];
  3740. #endif
  3741. mp_int* Q = NULL;
  3742. int ret;
  3743. if (pRaw == NULL || pRawSz == 0 ||
  3744. eRaw == NULL || eRawSz == 0 ||
  3745. isPrime == NULL) {
  3746. return BAD_FUNC_ARG;
  3747. }
  3748. if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
  3749. return BAD_FUNC_ARG;
  3750. #ifdef WOLFSSL_SMALL_STACK
  3751. if (((p = (mp_int *)XMALLOC(sizeof(*p), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
  3752. ((q = (mp_int *)XMALLOC(sizeof(*q), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
  3753. ((e = (mp_int *)XMALLOC(sizeof(*e), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL))
  3754. ret = MEMORY_E;
  3755. else
  3756. ret = 0;
  3757. if (ret == 0)
  3758. #endif
  3759. ret = mp_init_multi(p, q, e, NULL, NULL, NULL);
  3760. if (ret == MP_OKAY)
  3761. ret = mp_read_unsigned_bin(p, pRaw, pRawSz);
  3762. if (ret == MP_OKAY) {
  3763. if (qRaw != NULL) {
  3764. ret = mp_read_unsigned_bin(q, qRaw, qRawSz);
  3765. if (ret == MP_OKAY)
  3766. Q = q;
  3767. }
  3768. }
  3769. if (ret == MP_OKAY)
  3770. ret = mp_read_unsigned_bin(e, eRaw, eRawSz);
  3771. if (ret == MP_OKAY) {
  3772. SAVE_VECTOR_REGISTERS(ret = _svr_ret;);
  3773. if (ret == MP_OKAY)
  3774. ret = _CheckProbablePrime(p, Q, e, nlen, isPrime, rng);
  3775. RESTORE_VECTOR_REGISTERS();
  3776. }
  3777. ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
  3778. #ifdef WOLFSSL_SMALL_STACK
  3779. if (p != NULL) {
  3780. mp_clear(p);
  3781. XFREE(p, NULL, DYNAMIC_TYPE_RSA_BUFFER);
  3782. }
  3783. if (q != NULL) {
  3784. mp_clear(q);
  3785. XFREE(q, NULL, DYNAMIC_TYPE_RSA_BUFFER);
  3786. }
  3787. if (e != NULL) {
  3788. mp_clear(e);
  3789. XFREE(e, NULL, DYNAMIC_TYPE_RSA_BUFFER);
  3790. }
  3791. #else
  3792. mp_clear(p);
  3793. mp_clear(q);
  3794. mp_clear(e);
  3795. #endif
  3796. return ret;
  3797. }
  3798. int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
  3799. const byte* qRaw, word32 qRawSz,
  3800. const byte* eRaw, word32 eRawSz,
  3801. int nlen, int* isPrime)
  3802. {
  3803. return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
  3804. eRaw, eRawSz, nlen, isPrime, NULL);
  3805. }
  3806. #if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
  3807. defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
  3808. /* Make an RSA key for size bits, with e specified, 65537 is a good e */
  3809. int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
  3810. {
  3811. #ifndef WC_NO_RNG
  3812. #ifdef WOLFSSL_SMALL_STACK
  3813. mp_int *p = NULL;
  3814. mp_int *q = NULL;
  3815. mp_int *tmp1 = NULL;
  3816. mp_int *tmp2 = NULL;
  3817. mp_int *tmp3 = NULL;
  3818. #else
  3819. mp_int p_buf, *p = &p_buf;
  3820. mp_int q_buf, *q = &q_buf;
  3821. mp_int tmp1_buf, *tmp1 = &tmp1_buf;
  3822. mp_int tmp2_buf, *tmp2 = &tmp2_buf;
  3823. mp_int tmp3_buf, *tmp3 = &tmp3_buf;
  3824. #endif
  3825. int err, i, failCount, primeSz, isPrime = 0;
  3826. byte* buf = NULL;
  3827. if (key == NULL || rng == NULL) {
  3828. err = BAD_FUNC_ARG;
  3829. goto out;
  3830. }
  3831. #ifdef WOLFSSL_SMALL_STACK
  3832. p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
  3833. q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
  3834. tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
  3835. tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
  3836. tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
  3837. if ((p == NULL) ||
  3838. (q == NULL) ||
  3839. (tmp1 == NULL) ||
  3840. (tmp2 == NULL) ||
  3841. (tmp3 == NULL)) {
  3842. err = MEMORY_E;
  3843. goto out;
  3844. }
  3845. #endif
  3846. if (!RsaSizeCheck(size)) {
  3847. err = BAD_FUNC_ARG;
  3848. goto out;
  3849. }
  3850. if (e < 3 || (e & 1) == 0) {
  3851. err = BAD_FUNC_ARG;
  3852. goto out;
  3853. }
  3854. #if defined(WOLFSSL_CRYPTOCELL)
  3855. err = cc310_RSA_GenerateKeyPair(key, size, e);
  3856. goto out;
  3857. #endif /*WOLFSSL_CRYPTOCELL*/
  3858. #ifdef WOLF_CRYPTO_CB
  3859. if (key->devId != INVALID_DEVID) {
  3860. err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
  3861. if (err != CRYPTOCB_UNAVAILABLE)
  3862. goto out;
  3863. /* fall-through when unavailable */
  3864. }
  3865. #endif
  3866. #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
  3867. defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
  3868. if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
  3869. #ifdef HAVE_CAVIUM
  3870. /* TODO: Not implemented */
  3871. #elif defined(HAVE_INTEL_QA)
  3872. err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
  3873. goto out;
  3874. #else
  3875. if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_RSA_MAKE)) {
  3876. WC_ASYNC_TEST* testDev = &key->asyncDev.test;
  3877. testDev->rsaMake.rng = rng;
  3878. testDev->rsaMake.key = key;
  3879. testDev->rsaMake.size = size;
  3880. testDev->rsaMake.e = e;
  3881. err = WC_PENDING_E;
  3882. goto out;
  3883. }
  3884. #endif
  3885. }
  3886. #endif
  3887. err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
  3888. if (err == MP_OKAY)
  3889. err = mp_set_int(tmp3, e);
  3890. /* The failCount value comes from NIST FIPS 186-4, section B.3.3,
  3891. * process steps 4.7 and 5.8. */
  3892. failCount = 5 * (size / 2);
  3893. primeSz = size / 16; /* size is the size of n in bits.
  3894. primeSz is in bytes. */
  3895. /* allocate buffer to work with */
  3896. if (err == MP_OKAY) {
  3897. buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
  3898. if (buf == NULL)
  3899. err = MEMORY_E;
  3900. }
  3901. SAVE_VECTOR_REGISTERS(err = _svr_ret;);
  3902. /* make p */
  3903. if (err == MP_OKAY) {
  3904. isPrime = 0;
  3905. i = 0;
  3906. do {
  3907. #ifdef SHOW_GEN
  3908. printf(".");
  3909. fflush(stdout);
  3910. #endif
  3911. /* generate value */
  3912. err = wc_RNG_GenerateBlock(rng, buf, primeSz);
  3913. if (err == 0) {
  3914. /* prime lower bound has the MSB set, set it in candidate */
  3915. buf[0] |= 0x80;
  3916. /* make candidate odd */
  3917. buf[primeSz-1] |= 0x01;
  3918. /* load value */
  3919. err = mp_read_unsigned_bin(p, buf, primeSz);
  3920. }
  3921. if (err == MP_OKAY)
  3922. err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
  3923. #ifdef HAVE_FIPS
  3924. i++;
  3925. #else
  3926. /* Keep the old retry behavior in non-FIPS build. */
  3927. (void)i;
  3928. #endif
  3929. } while (err == MP_OKAY && !isPrime && i < failCount);
  3930. }
  3931. if (err == MP_OKAY && !isPrime)
  3932. err = PRIME_GEN_E;
  3933. /* make q */
  3934. if (err == MP_OKAY) {
  3935. isPrime = 0;
  3936. i = 0;
  3937. do {
  3938. #ifdef SHOW_GEN
  3939. printf(".");
  3940. fflush(stdout);
  3941. #endif
  3942. /* generate value */
  3943. err = wc_RNG_GenerateBlock(rng, buf, primeSz);
  3944. if (err == 0) {
  3945. /* prime lower bound has the MSB set, set it in candidate */
  3946. buf[0] |= 0x80;
  3947. /* make candidate odd */
  3948. buf[primeSz-1] |= 0x01;
  3949. /* load value */
  3950. err = mp_read_unsigned_bin(q, buf, primeSz);
  3951. }
  3952. if (err == MP_OKAY)
  3953. err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
  3954. #ifdef HAVE_FIPS
  3955. i++;
  3956. #else
  3957. /* Keep the old retry behavior in non-FIPS build. */
  3958. (void)i;
  3959. #endif
  3960. } while (err == MP_OKAY && !isPrime && i < failCount);
  3961. }
  3962. if (err == MP_OKAY && !isPrime)
  3963. err = PRIME_GEN_E;
  3964. if (buf) {
  3965. ForceZero(buf, primeSz);
  3966. XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
  3967. }
  3968. if (err == MP_OKAY && mp_cmp(p, q) < 0) {
  3969. err = mp_copy(p, tmp1);
  3970. if (err == MP_OKAY)
  3971. err = mp_copy(q, p);
  3972. if (err == MP_OKAY)
  3973. mp_copy(tmp1, q);
  3974. }
  3975. /* Setup RsaKey buffers */
  3976. if (err == MP_OKAY)
  3977. err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
  3978. if (err == MP_OKAY)
  3979. err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
  3980. /* Software Key Calculation */
  3981. if (err == MP_OKAY) /* tmp1 = p-1 */
  3982. err = mp_sub_d(p, 1, tmp1);
  3983. if (err == MP_OKAY) /* tmp2 = q-1 */
  3984. err = mp_sub_d(q, 1, tmp2);
  3985. #ifdef WC_RSA_BLINDING
  3986. if (err == MP_OKAY) /* tmp3 = order of n */
  3987. err = mp_mul(tmp1, tmp2, tmp3);
  3988. #else
  3989. if (err == MP_OKAY) /* tmp3 = lcm(p-1, q-1), last loop */
  3990. err = mp_lcm(tmp1, tmp2, tmp3);
  3991. #endif
  3992. /* make key */
  3993. if (err == MP_OKAY) /* key->e = e */
  3994. err = mp_set_int(&key->e, (mp_digit)e);
  3995. #ifdef WC_RSA_BLINDING
  3996. /* Blind the inverse operation with a value that is invertable */
  3997. if (err == MP_OKAY) {
  3998. do {
  3999. err = mp_rand(&key->p, get_digit_count(tmp3), rng);
  4000. if (err == MP_OKAY)
  4001. err = mp_set_bit(&key->p, 0);
  4002. if (err == MP_OKAY)
  4003. err = mp_set_bit(&key->p, size - 1);
  4004. if (err == MP_OKAY)
  4005. err = mp_gcd(&key->p, tmp3, &key->q);
  4006. }
  4007. while ((err == MP_OKAY) && !mp_isone(&key->q));
  4008. }
  4009. if (err == MP_OKAY)
  4010. err = mp_mul_d(&key->p, (mp_digit)e, &key->e);
  4011. #endif
  4012. if (err == MP_OKAY) /* key->d = 1/e mod lcm(p-1, q-1) */
  4013. err = mp_invmod(&key->e, tmp3, &key->d);
  4014. #ifdef WC_RSA_BLINDING
  4015. /* Take off blinding from d and reset e */
  4016. if (err == MP_OKAY)
  4017. err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
  4018. if (err == MP_OKAY)
  4019. err = mp_set_int(&key->e, (mp_digit)e);
  4020. #endif
  4021. if (err == MP_OKAY) /* key->n = pq */
  4022. err = mp_mul(p, q, &key->n);
  4023. if (err == MP_OKAY) /* key->dP = d mod(p-1) */
  4024. err = mp_mod(&key->d, tmp1, &key->dP);
  4025. if (err == MP_OKAY) /* key->dQ = d mod(q-1) */
  4026. err = mp_mod(&key->d, tmp2, &key->dQ);
  4027. #ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
  4028. if (err == MP_OKAY) /* key->u = 1/q mod p */
  4029. err = mp_invmod(q, p, &key->u);
  4030. #else
  4031. if (err == MP_OKAY)
  4032. err = mp_sub_d(p, 2, tmp3);
  4033. if (err == MP_OKAY) /* key->u = 1/q mod p = q^p-2 mod p */
  4034. err = mp_exptmod(q, tmp3 , p, &key->u);
  4035. #endif
  4036. if (err == MP_OKAY)
  4037. err = mp_copy(p, &key->p);
  4038. if (err == MP_OKAY)
  4039. err = mp_copy(q, &key->q);
  4040. #ifdef HAVE_WOLF_BIGINT
  4041. /* make sure raw unsigned bin version is available */
  4042. if (err == MP_OKAY)
  4043. err = wc_mp_to_bigint(&key->n, &key->n.raw);
  4044. if (err == MP_OKAY)
  4045. err = wc_mp_to_bigint(&key->e, &key->e.raw);
  4046. if (err == MP_OKAY)
  4047. err = wc_mp_to_bigint(&key->d, &key->d.raw);
  4048. if (err == MP_OKAY)
  4049. err = wc_mp_to_bigint(&key->p, &key->p.raw);
  4050. if (err == MP_OKAY)
  4051. err = wc_mp_to_bigint(&key->q, &key->q.raw);
  4052. if (err == MP_OKAY)
  4053. err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
  4054. if (err == MP_OKAY)
  4055. err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
  4056. if (err == MP_OKAY)
  4057. err = wc_mp_to_bigint(&key->u, &key->u.raw);
  4058. #endif
  4059. if (err == MP_OKAY)
  4060. key->type = RSA_PRIVATE;
  4061. RESTORE_VECTOR_REGISTERS();
  4062. mp_clear(tmp1);
  4063. mp_clear(tmp2);
  4064. mp_clear(tmp3);
  4065. mp_clear(p);
  4066. mp_clear(q);
  4067. #ifndef WOLFSSL_NO_RSA_KEY_CHECK
  4068. /* Perform the pair-wise consistency test on the new key. */
  4069. if (err == 0)
  4070. err = _ifc_pairwise_consistency_test(key, rng);
  4071. #endif
  4072. if (err != 0) {
  4073. wc_FreeRsaKey(key);
  4074. goto out;
  4075. }
  4076. #if defined(WOLFSSL_XILINX_CRYPT) || defined(WOLFSSL_CRYPTOCELL)
  4077. if (wc_InitRsaHw(key) != 0) {
  4078. return BAD_STATE_E;
  4079. }
  4080. #endif
  4081. err = 0;
  4082. out:
  4083. #ifdef WOLFSSL_SMALL_STACK
  4084. if (p)
  4085. XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
  4086. if (q)
  4087. XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
  4088. if (tmp1)
  4089. XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
  4090. if (tmp2)
  4091. XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
  4092. if (tmp3)
  4093. XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
  4094. #endif
  4095. return err;
  4096. #else
  4097. return NOT_COMPILED_IN;
  4098. #endif
  4099. }
  4100. #endif /* !FIPS || FIPS_VER >= 2 */
  4101. #endif /* WOLFSSL_KEY_GEN */
  4102. #ifdef WC_RSA_BLINDING
  4103. int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
  4104. {
  4105. if (key == NULL || rng == NULL)
  4106. return BAD_FUNC_ARG;
  4107. key->rng = rng;
  4108. return 0;
  4109. }
  4110. #endif /* WC_RSA_BLINDING */
  4111. #ifdef WC_RSA_NONBLOCK
  4112. int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
  4113. {
  4114. if (key == NULL)
  4115. return BAD_FUNC_ARG;
  4116. if (nb) {
  4117. XMEMSET(nb, 0, sizeof(RsaNb));
  4118. }
  4119. /* Allow nb == NULL to clear non-block mode */
  4120. key->nb = nb;
  4121. return 0;
  4122. }
  4123. #ifdef WC_RSA_NONBLOCK_TIME
  4124. int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
  4125. {
  4126. if (key == NULL || key->nb == NULL) {
  4127. return BAD_FUNC_ARG;
  4128. }
  4129. /* calculate maximum number of instructions to block */
  4130. key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
  4131. return 0;
  4132. }
  4133. #endif /* WC_RSA_NONBLOCK_TIME */
  4134. #endif /* WC_RSA_NONBLOCK */
  4135. #endif /* NO_RSA */