rsa.c 152 KB

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