rsa.c 150 KB

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