integer.c 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509
  1. /* integer.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. * Based on public domain LibTomMath 0.38 by Tom St Denis, tomstdenis@iahu.ca,
  23. * http://math.libtomcrypt.com
  24. */
  25. #ifdef HAVE_CONFIG_H
  26. #include <config.h>
  27. #endif
  28. /* in case user set USE_FAST_MATH there */
  29. #include <wolfssl/wolfcrypt/settings.h>
  30. #ifndef NO_BIG_INT
  31. #if !defined(USE_FAST_MATH) && defined(USE_INTEGER_HEAP_MATH)
  32. #ifndef WOLFSSL_SP_MATH
  33. #ifdef NO_INLINE
  34. #include <wolfssl/wolfcrypt/misc.h>
  35. #else
  36. #define WOLFSSL_MISC_INCLUDED
  37. #include <wolfcrypt/src/misc.c>
  38. #endif
  39. #include <wolfssl/wolfcrypt/wolfmath.h>
  40. #if defined(FREESCALE_LTC_TFM)
  41. #include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h>
  42. #endif
  43. #ifdef WOLFSSL_DEBUG_MATH
  44. #include <stdio.h>
  45. #endif
  46. #ifdef SHOW_GEN
  47. #ifndef NO_STDIO_FILESYSTEM
  48. #include <stdio.h>
  49. #endif
  50. #endif
  51. #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
  52. #ifdef __cplusplus
  53. extern "C" {
  54. #endif
  55. WOLFSSL_LOCAL int sp_ModExp_1024(mp_int* base, mp_int* exp, mp_int* mod,
  56. mp_int* res);
  57. WOLFSSL_LOCAL int sp_ModExp_1536(mp_int* base, mp_int* exp, mp_int* mod,
  58. mp_int* res);
  59. WOLFSSL_LOCAL int sp_ModExp_2048(mp_int* base, mp_int* exp, mp_int* mod,
  60. mp_int* res);
  61. WOLFSSL_LOCAL int sp_ModExp_3072(mp_int* base, mp_int* exp, mp_int* mod,
  62. mp_int* res);
  63. WOLFSSL_LOCAL int sp_ModExp_4096(mp_int* base, mp_int* exp, mp_int* mod,
  64. mp_int* res);
  65. #ifdef __cplusplus
  66. } /* extern "C" */
  67. #endif
  68. #endif
  69. /* reverse an array, used for radix code */
  70. static void
  71. bn_reverse (unsigned char *s, int len)
  72. {
  73. int ix, iy;
  74. unsigned char t;
  75. ix = 0;
  76. iy = len - 1;
  77. while (ix < iy) {
  78. t = s[ix];
  79. s[ix] = s[iy];
  80. s[iy] = t;
  81. ++ix;
  82. --iy;
  83. }
  84. }
  85. /* math settings check */
  86. word32 CheckRunTimeSettings(void)
  87. {
  88. return CTC_SETTINGS;
  89. }
  90. /* handle up to 6 inits */
  91. int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d, mp_int* e,
  92. mp_int* f)
  93. {
  94. int res = MP_OKAY;
  95. if (a) XMEMSET(a, 0, sizeof(mp_int));
  96. if (b) XMEMSET(b, 0, sizeof(mp_int));
  97. if (c) XMEMSET(c, 0, sizeof(mp_int));
  98. if (d) XMEMSET(d, 0, sizeof(mp_int));
  99. if (e) XMEMSET(e, 0, sizeof(mp_int));
  100. if (f) XMEMSET(f, 0, sizeof(mp_int));
  101. if (a && ((res = mp_init(a)) != MP_OKAY))
  102. return res;
  103. if (b && ((res = mp_init(b)) != MP_OKAY)) {
  104. mp_clear(a);
  105. return res;
  106. }
  107. if (c && ((res = mp_init(c)) != MP_OKAY)) {
  108. mp_clear(a); mp_clear(b);
  109. return res;
  110. }
  111. if (d && ((res = mp_init(d)) != MP_OKAY)) {
  112. mp_clear(a); mp_clear(b); mp_clear(c);
  113. return res;
  114. }
  115. if (e && ((res = mp_init(e)) != MP_OKAY)) {
  116. mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d);
  117. return res;
  118. }
  119. if (f && ((res = mp_init(f)) != MP_OKAY)) {
  120. mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d); mp_clear(e);
  121. return res;
  122. }
  123. return res;
  124. }
  125. /* init a new mp_int */
  126. int mp_init (mp_int * a)
  127. {
  128. /* Safeguard against passing in a null pointer */
  129. if (a == NULL)
  130. return MP_VAL;
  131. /* defer allocation until mp_grow */
  132. a->dp = NULL;
  133. /* set the used to zero, allocated digits to the default precision
  134. * and sign to positive */
  135. a->used = 0;
  136. a->alloc = 0;
  137. a->sign = MP_ZPOS;
  138. #ifdef HAVE_WOLF_BIGINT
  139. wc_bigint_init(&a->raw);
  140. #endif
  141. return MP_OKAY;
  142. }
  143. /* clear one (frees) */
  144. void mp_clear (mp_int * a)
  145. {
  146. int i;
  147. if (a == NULL)
  148. return;
  149. /* only do anything if a hasn't been freed previously */
  150. #ifndef HAVE_WOLF_BIGINT
  151. /* When HAVE_WOLF_BIGINT then mp_free -> wc_bigint_free needs to be called
  152. * because a->raw->buf may be allocated even when a->dp == NULL. This is the
  153. * case for when a zero is loaded into the mp_int. */
  154. if (a->dp != NULL)
  155. #endif
  156. {
  157. /* first zero the digits */
  158. for (i = 0; i < a->used; i++) {
  159. a->dp[i] = 0;
  160. }
  161. /* free ram */
  162. mp_free(a);
  163. /* reset members to make debugging easier */
  164. a->alloc = a->used = 0;
  165. a->sign = MP_ZPOS;
  166. }
  167. }
  168. void mp_free (mp_int * a)
  169. {
  170. /* only do anything if a hasn't been freed previously */
  171. if (a->dp != NULL) {
  172. /* free ram */
  173. XFREE(a->dp, 0, DYNAMIC_TYPE_BIGINT);
  174. a->dp = NULL;
  175. }
  176. #ifdef HAVE_WOLF_BIGINT
  177. wc_bigint_free(&a->raw);
  178. #endif
  179. }
  180. void mp_forcezero(mp_int * a)
  181. {
  182. if (a == NULL)
  183. return;
  184. /* only do anything if a hasn't been freed previously */
  185. if (a->dp != NULL) {
  186. /* force zero the used digits */
  187. ForceZero(a->dp, a->used * sizeof(mp_digit));
  188. #ifdef HAVE_WOLF_BIGINT
  189. wc_bigint_zero(&a->raw);
  190. #endif
  191. /* free ram */
  192. mp_free(a);
  193. /* reset members to make debugging easier */
  194. a->alloc = a->used = 0;
  195. a->sign = MP_ZPOS;
  196. }
  197. a->sign = MP_ZPOS;
  198. a->used = 0;
  199. }
  200. /* get the size for an unsigned equivalent */
  201. int mp_unsigned_bin_size (const mp_int * a)
  202. {
  203. int size = mp_count_bits (a);
  204. return (size / 8 + ((size & 7) != 0 ? 1 : 0));
  205. }
  206. /* returns the number of bits in an int */
  207. int mp_count_bits (const mp_int * a)
  208. {
  209. int r;
  210. mp_digit q;
  211. /* shortcut */
  212. if (a->used == 0) {
  213. return 0;
  214. }
  215. /* get number of digits and add that */
  216. r = (a->used - 1) * DIGIT_BIT;
  217. /* take the last digit and count the bits in it */
  218. q = a->dp[a->used - 1];
  219. while (q > ((mp_digit) 0)) {
  220. ++r;
  221. q >>= ((mp_digit) 1);
  222. }
  223. return r;
  224. }
  225. int mp_leading_bit (mp_int * a)
  226. {
  227. int c = mp_count_bits(a);
  228. if (c == 0) return 0;
  229. return (c % 8) == 0;
  230. }
  231. int mp_to_unsigned_bin_at_pos(int x, mp_int *t, unsigned char *b)
  232. {
  233. int res = 0;
  234. while (mp_iszero(t) == MP_NO) {
  235. #ifndef MP_8BIT
  236. b[x++] = (unsigned char) (t->dp[0] & 255);
  237. #else
  238. b[x++] = (unsigned char) (t->dp[0] | ((t->dp[1] & 0x01) << 7));
  239. #endif
  240. if ((res = mp_div_2d (t, 8, t, NULL)) != MP_OKAY) {
  241. return res;
  242. }
  243. res = x;
  244. }
  245. return res;
  246. }
  247. /* store in unsigned [big endian] format */
  248. int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
  249. {
  250. int x, res;
  251. mp_int t;
  252. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  253. return res;
  254. }
  255. x = mp_to_unsigned_bin_at_pos(0, &t, b);
  256. if (x < 0) {
  257. mp_clear(&t);
  258. return x;
  259. }
  260. bn_reverse (b, x);
  261. mp_clear (&t);
  262. return res;
  263. }
  264. int mp_to_unsigned_bin_len(mp_int * a, unsigned char *b, int c)
  265. {
  266. int i, len;
  267. len = mp_unsigned_bin_size(a);
  268. if (len > c) {
  269. return MP_VAL;
  270. }
  271. /* pad front w/ zeros to match length */
  272. for (i = 0; i < c - len; i++) {
  273. b[i] = 0x00;
  274. }
  275. return mp_to_unsigned_bin(a, b + i);
  276. }
  277. /* creates "a" then copies b into it */
  278. int mp_init_copy (mp_int * a, mp_int * b)
  279. {
  280. int res;
  281. if ((res = mp_init_size (a, b->used)) != MP_OKAY) {
  282. return res;
  283. }
  284. if((res = mp_copy (b, a)) != MP_OKAY) {
  285. mp_clear(a);
  286. }
  287. return res;
  288. }
  289. /* copy, b = a */
  290. int mp_copy (const mp_int * a, mp_int * b)
  291. {
  292. int res, n;
  293. /* Safeguard against passing in a null pointer */
  294. if (a == NULL || b == NULL)
  295. return MP_VAL;
  296. /* if dst == src do nothing */
  297. if (a == b) {
  298. return MP_OKAY;
  299. }
  300. /* grow dest */
  301. if (b->alloc < a->used || b->alloc == 0) {
  302. if ((res = mp_grow (b, a->used)) != MP_OKAY) {
  303. return res;
  304. }
  305. }
  306. /* zero b and copy the parameters over */
  307. {
  308. mp_digit *tmpa, *tmpb;
  309. /* pointer aliases */
  310. /* source */
  311. tmpa = a->dp;
  312. /* destination */
  313. tmpb = b->dp;
  314. /* copy all the digits */
  315. for (n = 0; n < a->used; n++) {
  316. *tmpb++ = *tmpa++;
  317. }
  318. /* clear high digits */
  319. for (; n < b->used && b->dp; n++) {
  320. *tmpb++ = 0;
  321. }
  322. }
  323. /* copy used count and sign */
  324. b->used = a->used;
  325. b->sign = a->sign;
  326. return MP_OKAY;
  327. }
  328. /* grow as required */
  329. int mp_grow (mp_int * a, int size)
  330. {
  331. int i;
  332. mp_digit *tmp;
  333. /* if the alloc size is smaller alloc more ram */
  334. if (a->alloc < size || size == 0) {
  335. /* ensure there are always at least MP_PREC digits extra on top */
  336. size += (MP_PREC * 2) - (size % MP_PREC);
  337. /* reallocate the array a->dp
  338. *
  339. * We store the return in a temporary variable
  340. * in case the operation failed we don't want
  341. * to overwrite the dp member of a.
  342. */
  343. tmp = (mp_digit *)XREALLOC (a->dp, sizeof (mp_digit) * size, NULL,
  344. DYNAMIC_TYPE_BIGINT);
  345. if (tmp == NULL) {
  346. /* reallocation failed but "a" is still valid [can be freed] */
  347. return MP_MEM;
  348. }
  349. /* reallocation succeeded so set a->dp */
  350. a->dp = tmp;
  351. /* zero excess digits */
  352. i = a->alloc;
  353. a->alloc = size;
  354. for (; i < a->alloc; i++) {
  355. a->dp[i] = 0;
  356. }
  357. }
  358. return MP_OKAY;
  359. }
  360. /* shift right by a certain bit count (store quotient in c, optional
  361. remainder in d) */
  362. int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
  363. {
  364. int D, res;
  365. mp_int t;
  366. /* if the shift count is <= 0 then we do no work */
  367. if (b <= 0) {
  368. res = mp_copy (a, c);
  369. if (d != NULL) {
  370. mp_zero (d);
  371. }
  372. return res;
  373. }
  374. if ((res = mp_init (&t)) != MP_OKAY) {
  375. return res;
  376. }
  377. /* get the remainder */
  378. if (d != NULL) {
  379. if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
  380. mp_clear (&t);
  381. return res;
  382. }
  383. }
  384. /* copy */
  385. if ((res = mp_copy (a, c)) != MP_OKAY) {
  386. mp_clear (&t);
  387. return res;
  388. }
  389. /* shift by as many digits in the bit count */
  390. if (b >= (int)DIGIT_BIT) {
  391. mp_rshd (c, b / DIGIT_BIT);
  392. }
  393. /* shift any bit count < DIGIT_BIT */
  394. D = (b % DIGIT_BIT);
  395. if (D != 0) {
  396. mp_rshb(c, D);
  397. }
  398. mp_clamp (c);
  399. if (d != NULL) {
  400. mp_exch (&t, d);
  401. }
  402. mp_clear (&t);
  403. return MP_OKAY;
  404. }
  405. /* set to zero */
  406. void mp_zero (mp_int * a)
  407. {
  408. int n;
  409. mp_digit *tmp;
  410. if (a == NULL)
  411. return;
  412. a->sign = MP_ZPOS;
  413. a->used = 0;
  414. tmp = a->dp;
  415. for (n = 0; tmp != NULL && n < a->alloc; n++) {
  416. *tmp++ = 0;
  417. }
  418. }
  419. /* trim unused digits
  420. *
  421. * This is used to ensure that leading zero digits are
  422. * trimmed and the leading "used" digit will be non-zero
  423. * Typically very fast. Also fixes the sign if there
  424. * are no more leading digits
  425. */
  426. void mp_clamp (mp_int * a)
  427. {
  428. /* decrease used while the most significant digit is
  429. * zero.
  430. */
  431. while (a->used > 0 && a->dp[a->used - 1] == 0) {
  432. --(a->used);
  433. }
  434. /* reset the sign flag if used == 0 */
  435. if (a->used == 0) {
  436. a->sign = MP_ZPOS;
  437. }
  438. }
  439. /* swap the elements of two integers, for cases where you can't simply swap the
  440. * mp_int pointers around
  441. */
  442. int mp_exch (mp_int * a, mp_int * b)
  443. {
  444. mp_int t;
  445. t = *a;
  446. *a = *b;
  447. *b = t;
  448. return MP_OKAY;
  449. }
  450. int mp_cond_swap_ct_ex (mp_int * a, mp_int * b, int c, int m, mp_int * t)
  451. {
  452. (void)c;
  453. (void)t;
  454. if (m == 1)
  455. mp_exch(a, b);
  456. return MP_OKAY;
  457. }
  458. int mp_cond_swap_ct (mp_int * a, mp_int * b, int c, int m)
  459. {
  460. (void)c;
  461. if (m == 1)
  462. mp_exch(a, b);
  463. return MP_OKAY;
  464. }
  465. /* shift right a certain number of bits */
  466. void mp_rshb (mp_int *c, int x)
  467. {
  468. mp_digit *tmpc, mask, shift;
  469. mp_digit r, rr;
  470. mp_digit D = x;
  471. /* shifting by a negative number not supported, and shifting by
  472. * zero changes nothing.
  473. */
  474. if (x <= 0) return;
  475. /* shift digits first if needed */
  476. if (x >= DIGIT_BIT) {
  477. mp_rshd(c, x / DIGIT_BIT);
  478. /* recalculate number of bits to shift */
  479. D = x % DIGIT_BIT;
  480. /* check if any more shifting needed */
  481. if (D == 0) return;
  482. }
  483. /* zero shifted is always zero */
  484. if (mp_iszero(c)) return;
  485. /* mask */
  486. mask = (((mp_digit)1) << D) - 1;
  487. /* shift for lsb */
  488. shift = DIGIT_BIT - D;
  489. /* alias */
  490. tmpc = c->dp + (c->used - 1);
  491. /* carry */
  492. r = 0;
  493. for (x = c->used - 1; x >= 0; x--) {
  494. /* get the lower bits of this word in a temp */
  495. rr = *tmpc & mask;
  496. /* shift the current word and mix in the carry bits from previous word */
  497. *tmpc = (*tmpc >> D) | (r << shift);
  498. --tmpc;
  499. /* set the carry to the carry bits of the current word found above */
  500. r = rr;
  501. }
  502. mp_clamp(c);
  503. }
  504. /* shift right a certain amount of digits */
  505. void mp_rshd (mp_int * a, int b)
  506. {
  507. int x;
  508. /* if b <= 0 then ignore it */
  509. if (b <= 0) {
  510. return;
  511. }
  512. /* if b > used then simply zero it and return */
  513. if (a->used <= b) {
  514. mp_zero (a);
  515. return;
  516. }
  517. {
  518. mp_digit *bottom, *top;
  519. /* shift the digits down */
  520. /* bottom */
  521. bottom = a->dp;
  522. /* top [offset into digits] */
  523. top = a->dp + b;
  524. /* this is implemented as a sliding window where
  525. * the window is b-digits long and digits from
  526. * the top of the window are copied to the bottom
  527. *
  528. * e.g.
  529. b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
  530. /\ | ---->
  531. \-------------------/ ---->
  532. */
  533. for (x = 0; x < (a->used - b); x++) {
  534. *bottom++ = *top++;
  535. }
  536. /* zero the top digits */
  537. for (; x < a->used; x++) {
  538. *bottom++ = 0;
  539. }
  540. }
  541. /* remove excess digits */
  542. a->used -= b;
  543. }
  544. /* calc a value mod 2**b */
  545. int mp_mod_2d (mp_int * a, int b, mp_int * c)
  546. {
  547. int x, res, bmax;
  548. /* if b is <= 0 then zero the int */
  549. if (b <= 0) {
  550. mp_zero (c);
  551. return MP_OKAY;
  552. }
  553. /* if the modulus is larger than the value than return */
  554. if (a->sign == MP_ZPOS && b >= (int) (a->used * DIGIT_BIT)) {
  555. res = mp_copy (a, c);
  556. return res;
  557. }
  558. /* copy */
  559. if ((res = mp_copy (a, c)) != MP_OKAY) {
  560. return res;
  561. }
  562. /* calculate number of digits in mod value */
  563. bmax = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1);
  564. /* zero digits above the last digit of the modulus */
  565. for (x = bmax; x < c->used; x++) {
  566. c->dp[x] = 0;
  567. }
  568. if (c->sign == MP_NEG) {
  569. mp_digit carry = 0;
  570. /* grow result to size of modulus */
  571. if ((res = mp_grow(c, bmax)) != MP_OKAY) {
  572. return res;
  573. }
  574. /* negate value */
  575. for (x = 0; x < c->used; x++) {
  576. mp_digit next = c->dp[x] > 0;
  577. c->dp[x] = ((mp_digit)0 - c->dp[x] - carry) & MP_MASK;
  578. carry |= next;
  579. }
  580. for (; x < bmax; x++) {
  581. c->dp[x] = ((mp_digit)0 - carry) & MP_MASK;
  582. }
  583. c->used = bmax;
  584. c->sign = MP_ZPOS;
  585. }
  586. /* clear the digit that is not completely outside/inside the modulus */
  587. x = DIGIT_BIT - (b % DIGIT_BIT);
  588. if (x != DIGIT_BIT) {
  589. c->dp[bmax - 1] &=
  590. ((mp_digit)~((mp_digit)0)) >> (x + ((sizeof(mp_digit)*8) - DIGIT_BIT));
  591. }
  592. mp_clamp (c);
  593. return MP_OKAY;
  594. }
  595. /* reads a unsigned char array, assumes the msb is stored first [big endian] */
  596. int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
  597. {
  598. int res;
  599. int digits_needed;
  600. while (c > 0 && b[0] == 0) {
  601. c--;
  602. b++;
  603. }
  604. digits_needed = ((c * CHAR_BIT) + DIGIT_BIT - 1) / DIGIT_BIT;
  605. /* make sure there are enough digits available */
  606. if (a->alloc < digits_needed) {
  607. if ((res = mp_grow(a, digits_needed)) != MP_OKAY) {
  608. return res;
  609. }
  610. }
  611. /* zero the int */
  612. mp_zero (a);
  613. /* read the bytes in */
  614. while (c-- > 0) {
  615. if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
  616. return res;
  617. }
  618. #ifndef MP_8BIT
  619. a->dp[0] |= *b++;
  620. if (a->used == 0)
  621. a->used = 1;
  622. #else
  623. a->dp[0] = (*b & MP_MASK);
  624. a->dp[1] |= ((*b++ >> 7U) & 1);
  625. if (a->used == 0)
  626. a->used = 2;
  627. #endif
  628. }
  629. mp_clamp (a);
  630. return MP_OKAY;
  631. }
  632. /* shift left by a certain bit count */
  633. int mp_mul_2d (mp_int * a, int b, mp_int * c)
  634. {
  635. mp_digit d;
  636. int res;
  637. /* copy */
  638. if (a != c) {
  639. if ((res = mp_copy (a, c)) != MP_OKAY) {
  640. return res;
  641. }
  642. }
  643. if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
  644. if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
  645. return res;
  646. }
  647. }
  648. /* shift by as many digits in the bit count */
  649. if (b >= (int)DIGIT_BIT) {
  650. if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
  651. return res;
  652. }
  653. }
  654. /* shift any bit count < DIGIT_BIT */
  655. d = (mp_digit) (b % DIGIT_BIT);
  656. if (d != 0) {
  657. mp_digit *tmpc, shift, mask, r, rr;
  658. int x;
  659. /* bitmask for carries */
  660. mask = (((mp_digit)1) << d) - 1;
  661. /* shift for msbs */
  662. shift = DIGIT_BIT - d;
  663. /* alias */
  664. tmpc = c->dp;
  665. /* carry */
  666. r = 0;
  667. for (x = 0; x < c->used; x++) {
  668. /* get the higher bits of the current word */
  669. rr = (*tmpc >> shift) & mask;
  670. /* shift the current word and OR in the carry */
  671. *tmpc = (mp_digit)(((*tmpc << d) | r) & MP_MASK);
  672. ++tmpc;
  673. /* set the carry to the carry bits of the current word */
  674. r = rr;
  675. }
  676. /* set final carry */
  677. if (r != 0) {
  678. c->dp[(c->used)++] = r;
  679. }
  680. }
  681. mp_clamp (c);
  682. return MP_OKAY;
  683. }
  684. /* shift left a certain amount of digits */
  685. int mp_lshd (mp_int * a, int b)
  686. {
  687. int x, res;
  688. /* if its less than zero return */
  689. if (b <= 0) {
  690. return MP_OKAY;
  691. }
  692. /* grow to fit the new digits */
  693. if (a->alloc < a->used + b) {
  694. if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
  695. return res;
  696. }
  697. }
  698. {
  699. mp_digit *top, *bottom;
  700. /* increment the used by the shift amount then copy upwards */
  701. a->used += b;
  702. /* top */
  703. top = a->dp + a->used - 1;
  704. /* base */
  705. bottom = a->dp + a->used - 1 - b;
  706. /* much like mp_rshd this is implemented using a sliding window
  707. * except the window goes the other way around. Copying from
  708. * the bottom to the top. see bn_mp_rshd.c for more info.
  709. */
  710. for (x = a->used - 1; x >= b; x--) {
  711. *top-- = *bottom--;
  712. }
  713. /* zero the lower digits */
  714. top = a->dp;
  715. for (x = 0; x < b; x++) {
  716. *top++ = 0;
  717. }
  718. }
  719. return MP_OKAY;
  720. }
  721. /* this is a shell function that calls either the normal or Montgomery
  722. * exptmod functions. Originally the call to the montgomery code was
  723. * embedded in the normal function but that wasted a lot of stack space
  724. * for nothing (since 99% of the time the Montgomery code would be called)
  725. */
  726. #if defined(FREESCALE_LTC_TFM)
  727. int wolfcrypt_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
  728. #else
  729. int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) /* //NOLINT(misc-no-recursion) */
  730. #endif
  731. {
  732. int dr;
  733. /* modulus P must be positive */
  734. if (mp_iszero(P) || P->sign == MP_NEG) {
  735. return MP_VAL;
  736. }
  737. if (mp_isone(P)) {
  738. return mp_set(Y, 0);
  739. }
  740. if (mp_iszero(X)) {
  741. return mp_set(Y, 1);
  742. }
  743. if (mp_iszero(G)) {
  744. return mp_set(Y, 0);
  745. }
  746. /* if exponent X is negative we have to recurse */
  747. if (X->sign == MP_NEG) {
  748. #ifdef BN_MP_INVMOD_C
  749. mp_int tmpG, tmpX;
  750. int err;
  751. /* first compute 1/G mod P */
  752. if ((err = mp_init(&tmpG)) != MP_OKAY) {
  753. return err;
  754. }
  755. if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
  756. mp_clear(&tmpG);
  757. return err;
  758. }
  759. /* now get |X| */
  760. if ((err = mp_init(&tmpX)) != MP_OKAY) {
  761. mp_clear(&tmpG);
  762. return err;
  763. }
  764. if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
  765. mp_clear(&tmpG);
  766. mp_clear(&tmpX);
  767. return err;
  768. }
  769. /* and now compute (1/G)**|X| instead of G**X [X < 0] */
  770. err = mp_exptmod(&tmpG, &tmpX, P, Y);
  771. mp_clear(&tmpG);
  772. mp_clear(&tmpX);
  773. return err;
  774. #else
  775. /* no invmod */
  776. return MP_VAL;
  777. #endif
  778. }
  779. #ifdef BN_MP_EXPTMOD_BASE_2
  780. if (G->used == 1 && G->dp[0] == 2) {
  781. return mp_exptmod_base_2(X, P, Y);
  782. }
  783. #endif
  784. /* modified diminished radix reduction */
  785. #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && \
  786. defined(BN_S_MP_EXPTMOD_C)
  787. if (mp_reduce_is_2k_l(P) == MP_YES) {
  788. return s_mp_exptmod(G, X, P, Y, 1);
  789. }
  790. #endif
  791. #ifdef BN_MP_DR_IS_MODULUS_C
  792. /* is it a DR modulus? */
  793. dr = mp_dr_is_modulus(P);
  794. #else
  795. /* default to no */
  796. dr = 0;
  797. #endif
  798. (void)dr;
  799. #ifdef BN_MP_REDUCE_IS_2K_C
  800. /* if not, is it a unrestricted DR modulus? */
  801. if (dr == 0) {
  802. dr = mp_reduce_is_2k(P) << 1;
  803. }
  804. #endif
  805. /* if the modulus is odd or dr != 0 use the montgomery method */
  806. #ifdef BN_MP_EXPTMOD_FAST_C
  807. if (mp_isodd (P) == MP_YES || dr != 0) {
  808. return mp_exptmod_fast (G, X, P, Y, dr);
  809. } else {
  810. #endif
  811. #ifdef BN_S_MP_EXPTMOD_C
  812. /* otherwise use the generic Barrett reduction technique */
  813. return s_mp_exptmod (G, X, P, Y, 0);
  814. #else
  815. /* no exptmod for evens */
  816. return MP_VAL;
  817. #endif
  818. #ifdef BN_MP_EXPTMOD_FAST_C
  819. }
  820. #endif
  821. }
  822. int mp_exptmod_ex (mp_int * G, mp_int * X, int digits, mp_int * P, mp_int * Y)
  823. {
  824. (void)digits;
  825. return mp_exptmod(G, X, P, Y);
  826. }
  827. /* b = |a|
  828. *
  829. * Simple function copies the input and fixes the sign to positive
  830. */
  831. int mp_abs (mp_int * a, mp_int * b)
  832. {
  833. int res;
  834. /* copy a to b */
  835. if (a != b) {
  836. if ((res = mp_copy (a, b)) != MP_OKAY) {
  837. return res;
  838. }
  839. }
  840. /* force the sign of b to positive */
  841. b->sign = MP_ZPOS;
  842. return MP_OKAY;
  843. }
  844. /* hac 14.61, pp608 */
  845. #if defined(FREESCALE_LTC_TFM)
  846. int wolfcrypt_mp_invmod(mp_int * a, mp_int * b, mp_int * c)
  847. #else
  848. int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
  849. #endif
  850. {
  851. /* b cannot be negative or zero, and can not divide by 0 (1/a mod b) */
  852. if (b->sign == MP_NEG || mp_iszero(b) == MP_YES || mp_iszero(a) == MP_YES) {
  853. return MP_VAL;
  854. }
  855. #ifdef BN_FAST_MP_INVMOD_C
  856. /* if the modulus is odd we can use a faster routine instead */
  857. if ((mp_isodd(b) == MP_YES) && (mp_cmp_d(b, 1) != MP_EQ)) {
  858. return fast_mp_invmod (a, b, c);
  859. }
  860. #endif
  861. #ifdef BN_MP_INVMOD_SLOW_C
  862. return mp_invmod_slow(a, b, c);
  863. #else
  864. return MP_VAL;
  865. #endif
  866. }
  867. /* computes the modular inverse via binary extended euclidean algorithm,
  868. * that is c = 1/a mod b
  869. *
  870. * Based on slow invmod except this is optimized for the case where b is
  871. * odd as per HAC Note 14.64 on pp. 610
  872. */
  873. int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c)
  874. {
  875. mp_int x, y, u, v, B, D;
  876. int res, loop_check = 0;
  877. /* 2. [modified] b must be odd */
  878. if (mp_iseven (b) == MP_YES) {
  879. return MP_VAL;
  880. }
  881. /* init all our temps */
  882. if ((res = mp_init_multi(&x, &y, &u, &v, &B, &D)) != MP_OKAY) {
  883. return res;
  884. }
  885. /* x == modulus, y == value to invert */
  886. if ((res = mp_copy (b, &x)) != MP_OKAY) {
  887. goto LBL_ERR;
  888. }
  889. /* we need y = |a| */
  890. if ((res = mp_mod (a, b, &y)) != MP_OKAY) {
  891. goto LBL_ERR;
  892. }
  893. if (mp_iszero (&y) == MP_YES) {
  894. /* invmod doesn't exist for this a and b */
  895. res = MP_VAL;
  896. goto LBL_ERR;
  897. }
  898. /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
  899. if ((res = mp_copy (&x, &u)) != MP_OKAY) {
  900. goto LBL_ERR;
  901. }
  902. if ((res = mp_copy (&y, &v)) != MP_OKAY) {
  903. goto LBL_ERR;
  904. }
  905. if ((res = mp_set (&D, 1)) != MP_OKAY) {
  906. goto LBL_ERR;
  907. }
  908. top:
  909. /* 4. while u is even do */
  910. while (mp_iseven (&u) == MP_YES) {
  911. /* 4.1 u = u/2 */
  912. if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
  913. goto LBL_ERR;
  914. }
  915. /* 4.2 if B is odd then */
  916. if (mp_isodd (&B) == MP_YES) {
  917. if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
  918. goto LBL_ERR;
  919. }
  920. }
  921. /* B = B/2 */
  922. if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
  923. goto LBL_ERR;
  924. }
  925. }
  926. /* 5. while v is even do */
  927. while (mp_iseven (&v) == MP_YES) {
  928. /* 5.1 v = v/2 */
  929. if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
  930. goto LBL_ERR;
  931. }
  932. /* 5.2 if D is odd then */
  933. if (mp_isodd (&D) == MP_YES) {
  934. /* D = (D-x)/2 */
  935. if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
  936. goto LBL_ERR;
  937. }
  938. }
  939. /* D = D/2 */
  940. if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
  941. goto LBL_ERR;
  942. }
  943. }
  944. /* 6. if u >= v then */
  945. if (mp_cmp (&u, &v) != MP_LT) {
  946. /* u = u - v, B = B - D */
  947. if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
  948. goto LBL_ERR;
  949. }
  950. if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
  951. goto LBL_ERR;
  952. }
  953. } else {
  954. /* v - v - u, D = D - B */
  955. if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
  956. goto LBL_ERR;
  957. }
  958. if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
  959. goto LBL_ERR;
  960. }
  961. }
  962. /* if not zero goto step 4 */
  963. if (mp_iszero (&u) == MP_NO) {
  964. if (++loop_check > MAX_INVMOD_SZ) {
  965. res = MP_VAL;
  966. goto LBL_ERR;
  967. }
  968. goto top;
  969. }
  970. /* now a = C, b = D, gcd == g*v */
  971. /* if v != 1 then there is no inverse */
  972. if (mp_cmp_d (&v, 1) != MP_EQ) {
  973. res = MP_VAL;
  974. goto LBL_ERR;
  975. }
  976. /* b is now the inverse */
  977. while (D.sign == MP_NEG) {
  978. if ((res = mp_add (&D, b, &D)) != MP_OKAY) {
  979. goto LBL_ERR;
  980. }
  981. }
  982. /* too big */
  983. while (mp_cmp_mag(&D, b) != MP_LT) {
  984. if ((res = mp_sub(&D, b, &D)) != MP_OKAY) {
  985. goto LBL_ERR;
  986. }
  987. }
  988. mp_exch (&D, c);
  989. res = MP_OKAY;
  990. LBL_ERR:mp_clear(&x);
  991. mp_clear(&y);
  992. mp_clear(&u);
  993. mp_clear(&v);
  994. mp_clear(&B);
  995. mp_clear(&D);
  996. return res;
  997. }
  998. /* hac 14.61, pp608 */
  999. int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
  1000. {
  1001. mp_int x, y, u, v, A, B, C, D;
  1002. int res;
  1003. /* b cannot be negative */
  1004. if (b->sign == MP_NEG || mp_iszero(b) == MP_YES) {
  1005. return MP_VAL;
  1006. }
  1007. /* init temps */
  1008. if ((res = mp_init_multi(&x, &y, &u, &v,
  1009. &A, &B)) != MP_OKAY) {
  1010. return res;
  1011. }
  1012. /* init rest of tmps temps */
  1013. if ((res = mp_init_multi(&C, &D, 0, 0, 0, 0)) != MP_OKAY) {
  1014. mp_clear(&x);
  1015. mp_clear(&y);
  1016. mp_clear(&u);
  1017. mp_clear(&v);
  1018. mp_clear(&A);
  1019. mp_clear(&B);
  1020. return res;
  1021. }
  1022. /* x = a, y = b */
  1023. if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
  1024. goto LBL_ERR;
  1025. }
  1026. if (mp_iszero (&x) == MP_YES) {
  1027. /* invmod doesn't exist for this a and b */
  1028. res = MP_VAL;
  1029. goto LBL_ERR;
  1030. }
  1031. if (mp_isone(&x)) {
  1032. res = mp_set(c, 1);
  1033. goto LBL_ERR;
  1034. }
  1035. if ((res = mp_copy (b, &y)) != MP_OKAY) {
  1036. goto LBL_ERR;
  1037. }
  1038. /* 2. [modified] if x,y are both even then return an error! */
  1039. if (mp_iseven (&x) == MP_YES && mp_iseven (&y) == MP_YES) {
  1040. res = MP_VAL;
  1041. goto LBL_ERR;
  1042. }
  1043. /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
  1044. if ((res = mp_copy (&x, &u)) != MP_OKAY) {
  1045. goto LBL_ERR;
  1046. }
  1047. if ((res = mp_copy (&y, &v)) != MP_OKAY) {
  1048. goto LBL_ERR;
  1049. }
  1050. if ((res = mp_set (&A, 1)) != MP_OKAY) {
  1051. goto LBL_ERR;
  1052. }
  1053. if ((res = mp_set (&D, 1)) != MP_OKAY) {
  1054. goto LBL_ERR;
  1055. }
  1056. top:
  1057. /* 4. while u is even do */
  1058. while (mp_iseven (&u) == MP_YES) {
  1059. /* 4.1 u = u/2 */
  1060. if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
  1061. goto LBL_ERR;
  1062. }
  1063. /* 4.2 if A or B is odd then */
  1064. if (mp_isodd (&A) == MP_YES || mp_isodd (&B) == MP_YES) {
  1065. /* A = (A+y)/2, B = (B-x)/2 */
  1066. if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
  1067. goto LBL_ERR;
  1068. }
  1069. if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
  1070. goto LBL_ERR;
  1071. }
  1072. }
  1073. /* A = A/2, B = B/2 */
  1074. if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
  1075. goto LBL_ERR;
  1076. }
  1077. if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
  1078. goto LBL_ERR;
  1079. }
  1080. }
  1081. /* 5. while v is even do */
  1082. while (mp_iseven (&v) == MP_YES) {
  1083. /* 5.1 v = v/2 */
  1084. if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
  1085. goto LBL_ERR;
  1086. }
  1087. /* 5.2 if C or D is odd then */
  1088. if (mp_isodd (&C) == MP_YES || mp_isodd (&D) == MP_YES) {
  1089. /* C = (C+y)/2, D = (D-x)/2 */
  1090. if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
  1091. goto LBL_ERR;
  1092. }
  1093. if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
  1094. goto LBL_ERR;
  1095. }
  1096. }
  1097. /* C = C/2, D = D/2 */
  1098. if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
  1099. goto LBL_ERR;
  1100. }
  1101. if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
  1102. goto LBL_ERR;
  1103. }
  1104. }
  1105. /* 6. if u >= v then */
  1106. if (mp_cmp (&u, &v) != MP_LT) {
  1107. /* u = u - v, A = A - C, B = B - D */
  1108. if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
  1109. goto LBL_ERR;
  1110. }
  1111. if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
  1112. goto LBL_ERR;
  1113. }
  1114. if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
  1115. goto LBL_ERR;
  1116. }
  1117. } else {
  1118. /* v - v - u, C = C - A, D = D - B */
  1119. if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
  1120. goto LBL_ERR;
  1121. }
  1122. if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
  1123. goto LBL_ERR;
  1124. }
  1125. if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
  1126. goto LBL_ERR;
  1127. }
  1128. }
  1129. /* if not zero goto step 4 */
  1130. if (mp_iszero (&u) == MP_NO)
  1131. goto top;
  1132. /* now a = C, b = D, gcd == g*v */
  1133. /* if v != 1 then there is no inverse */
  1134. if (mp_cmp_d (&v, 1) != MP_EQ) {
  1135. res = MP_VAL;
  1136. goto LBL_ERR;
  1137. }
  1138. /* if its too low */
  1139. while (mp_cmp_d(&C, 0) == MP_LT) {
  1140. if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
  1141. goto LBL_ERR;
  1142. }
  1143. }
  1144. /* too big */
  1145. while (mp_cmp_mag(&C, b) != MP_LT) {
  1146. if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
  1147. goto LBL_ERR;
  1148. }
  1149. }
  1150. /* C is now the inverse */
  1151. mp_exch (&C, c);
  1152. res = MP_OKAY;
  1153. LBL_ERR:mp_clear(&x);
  1154. mp_clear(&y);
  1155. mp_clear(&u);
  1156. mp_clear(&v);
  1157. mp_clear(&A);
  1158. mp_clear(&B);
  1159. mp_clear(&C);
  1160. mp_clear(&D);
  1161. return res;
  1162. }
  1163. /* compare magnitude of two ints (unsigned) */
  1164. int mp_cmp_mag (mp_int * a, mp_int * b)
  1165. {
  1166. int n;
  1167. mp_digit *tmpa, *tmpb;
  1168. /* compare based on # of non-zero digits */
  1169. if (a->used > b->used) {
  1170. return MP_GT;
  1171. }
  1172. if (a->used < b->used) {
  1173. return MP_LT;
  1174. }
  1175. if (a->used == 0)
  1176. return MP_EQ;
  1177. /* alias for a */
  1178. tmpa = a->dp + (a->used - 1);
  1179. /* alias for b */
  1180. tmpb = b->dp + (a->used - 1);
  1181. /* compare based on digits */
  1182. for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
  1183. if (*tmpa > *tmpb) {
  1184. return MP_GT;
  1185. }
  1186. if (*tmpa < *tmpb) {
  1187. return MP_LT;
  1188. }
  1189. }
  1190. return MP_EQ;
  1191. }
  1192. /* compare two ints (signed)*/
  1193. int mp_cmp (mp_int * a, mp_int * b)
  1194. {
  1195. /* compare based on sign */
  1196. if (a->sign != b->sign) {
  1197. if (a->sign == MP_NEG) {
  1198. return MP_LT;
  1199. } else {
  1200. return MP_GT;
  1201. }
  1202. }
  1203. /* compare digits */
  1204. if (a->sign == MP_NEG) {
  1205. /* if negative compare opposite direction */
  1206. return mp_cmp_mag(b, a);
  1207. } else {
  1208. return mp_cmp_mag(a, b);
  1209. }
  1210. }
  1211. /* compare a digit */
  1212. int mp_cmp_d(mp_int * a, mp_digit b)
  1213. {
  1214. /* special case for zero*/
  1215. if (a->used == 0 && b == 0)
  1216. return MP_EQ;
  1217. /* compare based on sign */
  1218. if ((b && a->used == 0) || a->sign == MP_NEG) {
  1219. return MP_LT;
  1220. }
  1221. /* compare based on magnitude */
  1222. if (a->used > 1) {
  1223. return MP_GT;
  1224. }
  1225. /* compare the only digit of a to b */
  1226. if (a->dp[0] > b) {
  1227. return MP_GT;
  1228. } else if (a->dp[0] < b) {
  1229. return MP_LT;
  1230. } else {
  1231. return MP_EQ;
  1232. }
  1233. }
  1234. /* set to a digit */
  1235. int mp_set (mp_int * a, mp_digit b)
  1236. {
  1237. int res;
  1238. mp_zero (a);
  1239. res = mp_grow (a, 1);
  1240. if (res == MP_OKAY) {
  1241. a->dp[0] = (mp_digit)(b & MP_MASK);
  1242. a->used = (a->dp[0] != 0) ? 1 : 0;
  1243. }
  1244. return res;
  1245. }
  1246. /* check if a bit is set */
  1247. int mp_is_bit_set (mp_int *a, mp_digit b)
  1248. {
  1249. mp_digit i = b / DIGIT_BIT; /* word index */
  1250. mp_digit s = b % DIGIT_BIT; /* bit index */
  1251. if ((mp_digit)a->used <= i) {
  1252. /* no words available at that bit count */
  1253. return 0;
  1254. }
  1255. /* get word and shift bit to check down to index 0 */
  1256. return (int)((a->dp[i] >> s) & (mp_digit)1);
  1257. }
  1258. /* c = a mod b, 0 <= c < b */
  1259. #if defined(FREESCALE_LTC_TFM)
  1260. int wolfcrypt_mp_mod(mp_int * a, mp_int * b, mp_int * c)
  1261. #else
  1262. int mp_mod (mp_int * a, mp_int * b, mp_int * c)
  1263. #endif
  1264. {
  1265. mp_int t;
  1266. int res;
  1267. if ((res = mp_init_size (&t, b->used)) != MP_OKAY) {
  1268. return res;
  1269. }
  1270. if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
  1271. mp_clear (&t);
  1272. return res;
  1273. }
  1274. if ((mp_iszero(&t) != MP_NO) || (t.sign == b->sign)) {
  1275. res = MP_OKAY;
  1276. mp_exch (&t, c);
  1277. } else {
  1278. res = mp_add (b, &t, c);
  1279. }
  1280. mp_clear (&t);
  1281. return res;
  1282. }
  1283. /* slower bit-bang division... also smaller */
  1284. int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
  1285. {
  1286. mp_int ta, tb, tq, q;
  1287. int res, n, n2;
  1288. /* is divisor zero ? */
  1289. if (mp_iszero (b) == MP_YES) {
  1290. return MP_VAL;
  1291. }
  1292. /* if a < b then q=0, r = a */
  1293. if (mp_cmp_mag (a, b) == MP_LT) {
  1294. if (d != NULL) {
  1295. res = mp_copy (a, d);
  1296. } else {
  1297. res = MP_OKAY;
  1298. }
  1299. if (c != NULL) {
  1300. mp_zero (c);
  1301. }
  1302. return res;
  1303. }
  1304. /* init our temps */
  1305. if ((res = mp_init_multi(&ta, &tb, &tq, &q, 0, 0)) != MP_OKAY) {
  1306. return res;
  1307. }
  1308. if ((res = mp_set(&tq, 1)) != MP_OKAY) {
  1309. return res;
  1310. }
  1311. n = mp_count_bits(a) - mp_count_bits(b);
  1312. if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
  1313. ((res = mp_abs(b, &tb)) != MP_OKAY) ||
  1314. ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
  1315. ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
  1316. goto LBL_ERR;
  1317. }
  1318. while (n-- >= 0) {
  1319. if (mp_cmp(&tb, &ta) != MP_GT) {
  1320. if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
  1321. ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
  1322. goto LBL_ERR;
  1323. }
  1324. }
  1325. if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
  1326. ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
  1327. goto LBL_ERR;
  1328. }
  1329. }
  1330. /* now q == quotient and ta == remainder */
  1331. n = a->sign;
  1332. n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
  1333. if (c != NULL) {
  1334. mp_exch(c, &q);
  1335. c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
  1336. }
  1337. if (d != NULL) {
  1338. mp_exch(d, &ta);
  1339. d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
  1340. }
  1341. LBL_ERR:
  1342. mp_clear(&ta);
  1343. mp_clear(&tb);
  1344. mp_clear(&tq);
  1345. mp_clear(&q);
  1346. return res;
  1347. }
  1348. /* b = a/2 */
  1349. int mp_div_2(mp_int * a, mp_int * b)
  1350. {
  1351. int x, res, oldused;
  1352. /* copy */
  1353. if (b->alloc < a->used) {
  1354. if ((res = mp_grow (b, a->used)) != MP_OKAY) {
  1355. return res;
  1356. }
  1357. }
  1358. oldused = b->used;
  1359. b->used = a->used;
  1360. {
  1361. mp_digit r, rr, *tmpa, *tmpb;
  1362. /* source alias */
  1363. tmpa = a->dp + b->used - 1;
  1364. /* dest alias */
  1365. tmpb = b->dp + b->used - 1;
  1366. /* carry */
  1367. r = 0;
  1368. for (x = b->used - 1; x >= 0; x--) {
  1369. /* get the carry for the next iteration */
  1370. rr = *tmpa & 1;
  1371. /* shift the current digit, add in carry and store */
  1372. *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
  1373. /* forward carry to next iteration */
  1374. r = rr;
  1375. }
  1376. /* zero excess digits */
  1377. tmpb = b->dp + b->used;
  1378. for (x = b->used; x < oldused; x++) {
  1379. *tmpb++ = 0;
  1380. }
  1381. }
  1382. b->sign = a->sign;
  1383. mp_clamp (b);
  1384. return MP_OKAY;
  1385. }
  1386. /* c = a / 2 (mod b) - constant time (a < b and positive) */
  1387. int mp_div_2_mod_ct(mp_int *a, mp_int *b, mp_int *c)
  1388. {
  1389. int res;
  1390. if (mp_isodd(a)) {
  1391. res = mp_add(a, b, c);
  1392. if (res == MP_OKAY) {
  1393. res = mp_div_2(c, c);
  1394. }
  1395. }
  1396. else {
  1397. res = mp_div_2(a, c);
  1398. }
  1399. return res;
  1400. }
  1401. /* high level addition (handles signs) */
  1402. int mp_add (mp_int * a, mp_int * b, mp_int * c)
  1403. {
  1404. int sa, sb, res;
  1405. /* get sign of both inputs */
  1406. sa = a->sign;
  1407. sb = b->sign;
  1408. /* handle two cases, not four */
  1409. if (sa == sb) {
  1410. /* both positive or both negative */
  1411. /* add their magnitudes, copy the sign */
  1412. c->sign = sa;
  1413. res = s_mp_add (a, b, c);
  1414. } else {
  1415. /* one positive, the other negative */
  1416. /* subtract the one with the greater magnitude from */
  1417. /* the one of the lesser magnitude. The result gets */
  1418. /* the sign of the one with the greater magnitude. */
  1419. if (mp_cmp_mag (a, b) == MP_LT) {
  1420. c->sign = sb;
  1421. res = s_mp_sub (b, a, c);
  1422. } else {
  1423. c->sign = sa;
  1424. res = s_mp_sub (a, b, c);
  1425. }
  1426. }
  1427. return res;
  1428. }
  1429. /* low level addition, based on HAC pp.594, Algorithm 14.7 */
  1430. int s_mp_add (mp_int * a, mp_int * b, mp_int * c)
  1431. {
  1432. mp_int *x;
  1433. int olduse, res, min_ab, max_ab;
  1434. /* find sizes, we let |a| <= |b| which means we have to sort
  1435. * them. "x" will point to the input with the most digits
  1436. */
  1437. if (a->used > b->used) {
  1438. min_ab = b->used;
  1439. max_ab = a->used;
  1440. x = a;
  1441. } else {
  1442. min_ab = a->used;
  1443. max_ab = b->used;
  1444. x = b;
  1445. }
  1446. /* init result */
  1447. if (c->dp == NULL || c->alloc < max_ab + 1) {
  1448. if ((res = mp_grow (c, max_ab + 1)) != MP_OKAY) {
  1449. return res;
  1450. }
  1451. }
  1452. /* get old used digit count and set new one */
  1453. olduse = c->used;
  1454. c->used = max_ab + 1;
  1455. {
  1456. mp_digit u, *tmpa, *tmpb, *tmpc;
  1457. int i;
  1458. /* alias for digit pointers */
  1459. /* first input */
  1460. tmpa = a->dp;
  1461. /* second input */
  1462. tmpb = b->dp;
  1463. /* destination */
  1464. tmpc = c->dp;
  1465. /* zero the carry */
  1466. u = 0;
  1467. for (i = 0; i < min_ab; i++) {
  1468. /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
  1469. *tmpc = *tmpa++ + *tmpb++ + u;
  1470. /* U = carry bit of T[i] */
  1471. u = *tmpc >> ((mp_digit)DIGIT_BIT);
  1472. /* take away carry bit from T[i] */
  1473. *tmpc++ &= MP_MASK;
  1474. }
  1475. /* now copy higher words if any, that is in A+B
  1476. * if A or B has more digits add those in
  1477. */
  1478. if (min_ab != max_ab) {
  1479. for (; i < max_ab; i++) {
  1480. /* T[i] = X[i] + U */
  1481. *tmpc = x->dp[i] + u;
  1482. /* U = carry bit of T[i] */
  1483. u = *tmpc >> ((mp_digit)DIGIT_BIT);
  1484. /* take away carry bit from T[i] */
  1485. *tmpc++ &= MP_MASK;
  1486. }
  1487. }
  1488. /* add carry */
  1489. *tmpc++ = u;
  1490. /* clear digits above olduse */
  1491. for (i = c->used; i < olduse; i++) {
  1492. *tmpc++ = 0;
  1493. }
  1494. }
  1495. mp_clamp (c);
  1496. return MP_OKAY;
  1497. }
  1498. /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
  1499. int s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
  1500. {
  1501. int olduse, res, min_b, max_a;
  1502. /* find sizes */
  1503. min_b = b->used;
  1504. max_a = a->used;
  1505. /* init result */
  1506. if (c->alloc < max_a) {
  1507. if ((res = mp_grow (c, max_a)) != MP_OKAY) {
  1508. return res;
  1509. }
  1510. }
  1511. /* sanity check on destination */
  1512. if (c->dp == NULL)
  1513. return MP_VAL;
  1514. olduse = c->used;
  1515. c->used = max_a;
  1516. {
  1517. mp_digit u, *tmpa, *tmpb, *tmpc;
  1518. int i;
  1519. /* alias for digit pointers */
  1520. tmpa = a->dp;
  1521. tmpb = b->dp;
  1522. tmpc = c->dp;
  1523. /* set carry to zero */
  1524. u = 0;
  1525. for (i = 0; i < min_b; i++) {
  1526. /* T[i] = A[i] - B[i] - U */
  1527. *tmpc = *tmpa++ - *tmpb++ - u;
  1528. /* U = carry bit of T[i]
  1529. * Note this saves performing an AND operation since
  1530. * if a carry does occur it will propagate all the way to the
  1531. * MSB. As a result a single shift is enough to get the carry
  1532. */
  1533. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  1534. /* Clear carry from T[i] */
  1535. *tmpc++ &= MP_MASK;
  1536. }
  1537. /* now copy higher words if any, e.g. if A has more digits than B */
  1538. for (; i < max_a; i++) {
  1539. /* T[i] = A[i] - U */
  1540. *tmpc = *tmpa++ - u;
  1541. /* U = carry bit of T[i] */
  1542. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  1543. /* Clear carry from T[i] */
  1544. *tmpc++ &= MP_MASK;
  1545. }
  1546. /* clear digits above used (since we may not have grown result above) */
  1547. for (i = c->used; i < olduse; i++) {
  1548. *tmpc++ = 0;
  1549. }
  1550. }
  1551. mp_clamp (c);
  1552. return MP_OKAY;
  1553. }
  1554. /* high level subtraction (handles signs) */
  1555. int mp_sub (mp_int * a, mp_int * b, mp_int * c)
  1556. {
  1557. int sa, sb, res;
  1558. sa = a->sign;
  1559. sb = b->sign;
  1560. if (sa != sb) {
  1561. /* subtract a negative from a positive, OR */
  1562. /* subtract a positive from a negative. */
  1563. /* In either case, ADD their magnitudes, */
  1564. /* and use the sign of the first number. */
  1565. c->sign = sa;
  1566. res = s_mp_add (a, b, c);
  1567. } else {
  1568. /* subtract a positive from a positive, OR */
  1569. /* subtract a negative from a negative. */
  1570. /* First, take the difference between their */
  1571. /* magnitudes, then... */
  1572. if (mp_cmp_mag (a, b) != MP_LT) {
  1573. /* Copy the sign from the first */
  1574. c->sign = sa;
  1575. /* The first has a larger or equal magnitude */
  1576. res = s_mp_sub (a, b, c);
  1577. } else {
  1578. /* The result has the *opposite* sign from */
  1579. /* the first number. */
  1580. c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
  1581. /* The second has a larger magnitude */
  1582. res = s_mp_sub (b, a, c);
  1583. }
  1584. }
  1585. return res;
  1586. }
  1587. /* determines if reduce_2k_l can be used */
  1588. int mp_reduce_is_2k_l(mp_int *a)
  1589. {
  1590. int ix, iy;
  1591. if (a->used == 0) {
  1592. return MP_NO;
  1593. } else if (a->used == 1) {
  1594. return MP_YES;
  1595. } else if (a->used > 1) {
  1596. /* if more than half of the digits are -1 we're sold */
  1597. for (iy = ix = 0; ix < a->used; ix++) {
  1598. if (a->dp[ix] == MP_MASK) {
  1599. ++iy;
  1600. }
  1601. }
  1602. return (iy >= (a->used/2)) ? MP_YES : MP_NO;
  1603. }
  1604. return MP_NO;
  1605. }
  1606. /* determines if mp_reduce_2k can be used */
  1607. int mp_reduce_is_2k(mp_int *a)
  1608. {
  1609. int ix, iy, iw;
  1610. mp_digit iz;
  1611. if (a->used == 0) {
  1612. return MP_NO;
  1613. } else if (a->used == 1) {
  1614. return MP_YES;
  1615. } else if (a->used > 1) {
  1616. iy = mp_count_bits(a);
  1617. iz = 1;
  1618. iw = 1;
  1619. /* Test every bit from the second digit up, must be 1 */
  1620. for (ix = DIGIT_BIT; ix < iy; ix++) {
  1621. if ((a->dp[iw] & iz) == 0) {
  1622. return MP_NO;
  1623. }
  1624. iz <<= 1;
  1625. if (iz > (mp_digit)MP_MASK) {
  1626. ++iw;
  1627. iz = 1;
  1628. }
  1629. }
  1630. }
  1631. return MP_YES;
  1632. }
  1633. /* determines if a number is a valid DR modulus */
  1634. int mp_dr_is_modulus(mp_int *a)
  1635. {
  1636. int ix;
  1637. /* must be at least two digits */
  1638. if (a->used < 2) {
  1639. return 0;
  1640. }
  1641. /* must be of the form b**k - a [a <= b] so all
  1642. * but the first digit must be equal to -1 (mod b).
  1643. */
  1644. for (ix = 1; ix < a->used; ix++) {
  1645. if (a->dp[ix] != MP_MASK) {
  1646. return 0;
  1647. }
  1648. }
  1649. return 1;
  1650. }
  1651. /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
  1652. *
  1653. * Uses a left-to-right k-ary sliding window to compute the modular
  1654. * exponentiation.
  1655. * The value of k changes based on the size of the exponent.
  1656. *
  1657. * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
  1658. */
  1659. #ifdef MP_LOW_MEM
  1660. #define TAB_SIZE 32
  1661. #else
  1662. #define TAB_SIZE 256
  1663. #endif
  1664. int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y,
  1665. int redmode)
  1666. {
  1667. mp_int res;
  1668. mp_digit buf, mp;
  1669. int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
  1670. #ifdef WOLFSSL_SMALL_STACK
  1671. mp_int* M;
  1672. #else
  1673. mp_int M[TAB_SIZE];
  1674. #endif
  1675. /* use a pointer to the reduction algorithm. This allows us to use
  1676. * one of many reduction algorithms without modding the guts of
  1677. * the code with if statements everywhere.
  1678. */
  1679. int (*redux)(mp_int*,mp_int*,mp_digit) = NULL;
  1680. #ifdef WOLFSSL_SMALL_STACK
  1681. M = (mp_int*) XMALLOC(sizeof(mp_int) * TAB_SIZE, NULL,
  1682. DYNAMIC_TYPE_BIGINT);
  1683. if (M == NULL)
  1684. return MP_MEM;
  1685. #endif
  1686. /* find window size */
  1687. x = mp_count_bits (X);
  1688. if (x <= 7) {
  1689. winsize = 2;
  1690. } else if (x <= 36) {
  1691. winsize = 3;
  1692. } else if (x <= 140) {
  1693. winsize = 4;
  1694. } else if (x <= 450) {
  1695. winsize = 5;
  1696. } else if (x <= 1303) {
  1697. winsize = 6;
  1698. } else if (x <= 3529) {
  1699. winsize = 7;
  1700. } else {
  1701. winsize = 8;
  1702. }
  1703. #ifdef MP_LOW_MEM
  1704. if (winsize > 5) {
  1705. winsize = 5;
  1706. }
  1707. #endif
  1708. /* init M array */
  1709. /* init first cell */
  1710. if ((err = mp_init_size(&M[1], P->alloc)) != MP_OKAY) {
  1711. #ifdef WOLFSSL_SMALL_STACK
  1712. XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
  1713. #endif
  1714. return err;
  1715. }
  1716. /* now init the second half of the array */
  1717. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  1718. if ((err = mp_init_size(&M[x], P->alloc)) != MP_OKAY) {
  1719. for (y = 1<<(winsize-1); y < x; y++) {
  1720. mp_clear (&M[y]);
  1721. }
  1722. mp_clear(&M[1]);
  1723. #ifdef WOLFSSL_SMALL_STACK
  1724. XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
  1725. #endif
  1726. return err;
  1727. }
  1728. }
  1729. /* determine and setup reduction code */
  1730. if (redmode == 0) {
  1731. #ifdef BN_MP_MONTGOMERY_SETUP_C
  1732. /* now setup montgomery */
  1733. if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
  1734. goto LBL_M;
  1735. }
  1736. #else
  1737. err = MP_VAL;
  1738. goto LBL_M;
  1739. #endif
  1740. /* automatically pick the comba one if available (saves quite a few
  1741. calls/ifs) */
  1742. #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
  1743. if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
  1744. P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  1745. redux = fast_mp_montgomery_reduce;
  1746. } else
  1747. #endif
  1748. {
  1749. #ifdef BN_MP_MONTGOMERY_REDUCE_C
  1750. /* use slower baseline Montgomery method */
  1751. redux = mp_montgomery_reduce;
  1752. #endif
  1753. }
  1754. } else if (redmode == 1) {
  1755. #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
  1756. /* setup DR reduction for moduli of the form B**k - b */
  1757. mp_dr_setup(P, &mp);
  1758. redux = mp_dr_reduce;
  1759. #endif
  1760. } else {
  1761. #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
  1762. /* setup DR reduction for moduli of the form 2**k - b */
  1763. if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
  1764. goto LBL_M;
  1765. }
  1766. redux = mp_reduce_2k;
  1767. #endif
  1768. }
  1769. if (redux == NULL) {
  1770. err = MP_VAL;
  1771. goto LBL_M;
  1772. }
  1773. /* setup result */
  1774. if ((err = mp_init_size (&res, P->alloc)) != MP_OKAY) {
  1775. goto LBL_M;
  1776. }
  1777. /* create M table
  1778. *
  1779. *
  1780. * The first half of the table is not computed though accept for M[0] and M[1]
  1781. */
  1782. if (redmode == 0) {
  1783. #ifdef BN_MP_MONTGOMERY_CALC_NORMALIZATION_C
  1784. /* now we need R mod m */
  1785. if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
  1786. goto LBL_RES;
  1787. }
  1788. /* now set M[1] to G * R mod m */
  1789. if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
  1790. goto LBL_RES;
  1791. }
  1792. #else
  1793. err = MP_VAL;
  1794. goto LBL_RES;
  1795. #endif
  1796. } else {
  1797. if ((err = mp_set(&res, 1)) != MP_OKAY) {
  1798. goto LBL_RES;
  1799. }
  1800. if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
  1801. goto LBL_RES;
  1802. }
  1803. }
  1804. /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times*/
  1805. if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  1806. goto LBL_RES;
  1807. }
  1808. for (x = 0; x < (winsize - 1); x++) {
  1809. if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))],
  1810. &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  1811. goto LBL_RES;
  1812. }
  1813. if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, mp)) != MP_OKAY) {
  1814. goto LBL_RES;
  1815. }
  1816. }
  1817. /* create upper table */
  1818. for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
  1819. if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
  1820. goto LBL_RES;
  1821. }
  1822. if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
  1823. goto LBL_RES;
  1824. }
  1825. }
  1826. /* set initial mode and bit cnt */
  1827. mode = 0;
  1828. bitcnt = 1;
  1829. buf = 0;
  1830. digidx = X->used - 1;
  1831. bitcpy = 0;
  1832. bitbuf = 0;
  1833. for (;;) {
  1834. /* grab next digit as required */
  1835. if (--bitcnt == 0) {
  1836. /* if digidx == -1 we are out of digits so break */
  1837. if (digidx == -1) {
  1838. break;
  1839. }
  1840. /* read next digit and reset bitcnt */
  1841. buf = X->dp[digidx--];
  1842. bitcnt = (int)DIGIT_BIT;
  1843. }
  1844. /* grab the next msb from the exponent */
  1845. y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
  1846. buf <<= (mp_digit)1;
  1847. /* if the bit is zero and mode == 0 then we ignore it
  1848. * These represent the leading zero bits before the first 1 bit
  1849. * in the exponent. Technically this opt is not required but it
  1850. * does lower the # of trivial squaring/reductions used
  1851. */
  1852. if (mode == 0 && y == 0) {
  1853. continue;
  1854. }
  1855. /* if the bit is zero and mode == 1 then we square */
  1856. if (mode == 1 && y == 0) {
  1857. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1858. goto LBL_RES;
  1859. }
  1860. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1861. goto LBL_RES;
  1862. }
  1863. continue;
  1864. }
  1865. /* else we add it to the window */
  1866. bitbuf |= (y << (winsize - ++bitcpy));
  1867. mode = 2;
  1868. if (bitcpy == winsize) {
  1869. /* ok window is filled so square as required and multiply */
  1870. /* square first */
  1871. for (x = 0; x < winsize; x++) {
  1872. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1873. goto LBL_RES;
  1874. }
  1875. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1876. goto LBL_RES;
  1877. }
  1878. }
  1879. /* then multiply */
  1880. if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
  1881. goto LBL_RES;
  1882. }
  1883. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1884. goto LBL_RES;
  1885. }
  1886. /* empty window and reset */
  1887. bitcpy = 0;
  1888. bitbuf = 0;
  1889. mode = 1;
  1890. }
  1891. }
  1892. /* if bits remain then square/multiply */
  1893. if (mode == 2 && bitcpy > 0) {
  1894. /* square then multiply if the bit is set */
  1895. for (x = 0; x < bitcpy; x++) {
  1896. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1897. goto LBL_RES;
  1898. }
  1899. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1900. goto LBL_RES;
  1901. }
  1902. /* get next bit of the window */
  1903. bitbuf <<= 1;
  1904. if ((bitbuf & (1 << winsize)) != 0) {
  1905. /* then multiply */
  1906. if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
  1907. goto LBL_RES;
  1908. }
  1909. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1910. goto LBL_RES;
  1911. }
  1912. }
  1913. }
  1914. }
  1915. if (redmode == 0) {
  1916. /* fixup result if Montgomery reduction is used
  1917. * recall that any value in a Montgomery system is
  1918. * actually multiplied by R mod n. So we have
  1919. * to reduce one more time to cancel out the factor
  1920. * of R.
  1921. */
  1922. if ((err = redux(&res, P, mp)) != MP_OKAY) {
  1923. goto LBL_RES;
  1924. }
  1925. }
  1926. /* swap res with Y */
  1927. mp_exch (&res, Y);
  1928. err = MP_OKAY;
  1929. LBL_RES:mp_clear (&res);
  1930. LBL_M:
  1931. mp_clear(&M[1]);
  1932. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  1933. mp_clear (&M[x]);
  1934. }
  1935. #ifdef WOLFSSL_SMALL_STACK
  1936. XFREE(M, NULL, DYNAMIC_TYPE_BIGINT);
  1937. #endif
  1938. return err;
  1939. }
  1940. #ifdef BN_MP_EXPTMOD_BASE_2
  1941. #if DIGIT_BIT < 16
  1942. #define WINSIZE 3
  1943. #elif DIGIT_BIT < 32
  1944. #define WINSIZE 4
  1945. #elif DIGIT_BIT < 64
  1946. #define WINSIZE 5
  1947. #elif DIGIT_BIT < 128
  1948. #define WINSIZE 6
  1949. #endif
  1950. int mp_exptmod_base_2(mp_int * X, mp_int * P, mp_int * Y)
  1951. {
  1952. mp_digit buf, mp;
  1953. int err = MP_OKAY, bitbuf, bitcpy, bitcnt, digidx, x, y;
  1954. mp_int res[1];
  1955. int (*redux)(mp_int*,mp_int*,mp_digit) = NULL;
  1956. /* automatically pick the comba one if available (saves quite a few
  1957. calls/ifs) */
  1958. #ifdef BN_FAST_MP_MONTGOMERY_REDUCE_C
  1959. if (((P->used * 2 + 1) < (int)MP_WARRAY) &&
  1960. P->used < (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  1961. redux = fast_mp_montgomery_reduce;
  1962. } else
  1963. #endif
  1964. #ifdef BN_MP_MONTGOMERY_REDUCE_C
  1965. {
  1966. /* use slower baseline Montgomery method */
  1967. redux = mp_montgomery_reduce;
  1968. }
  1969. #endif
  1970. if (redux == NULL) {
  1971. return MP_VAL;
  1972. }
  1973. /* now setup montgomery */
  1974. if ((err = mp_montgomery_setup(P, &mp)) != MP_OKAY) {
  1975. goto LBL_M;
  1976. }
  1977. /* setup result */
  1978. if ((err = mp_init(res)) != MP_OKAY) {
  1979. goto LBL_M;
  1980. }
  1981. /* now we need R mod m */
  1982. if ((err = mp_montgomery_calc_normalization(res, P)) != MP_OKAY) {
  1983. goto LBL_RES;
  1984. }
  1985. /* Get the top bits left over after taking WINSIZE bits starting at the
  1986. * least-significant.
  1987. */
  1988. digidx = X->used - 1;
  1989. bitcpy = (X->used * DIGIT_BIT) % WINSIZE;
  1990. if (bitcpy > 0) {
  1991. bitcnt = (int)DIGIT_BIT - bitcpy;
  1992. buf = X->dp[digidx--];
  1993. bitbuf = (int)(buf >> bitcnt);
  1994. /* Multiply montgomery representation of 1 by 2 ^ top */
  1995. err = mp_mul_2d(res, bitbuf, res);
  1996. if (err != MP_OKAY) {
  1997. goto LBL_RES;
  1998. }
  1999. err = mp_mod(res, P, res);
  2000. if (err != MP_OKAY) {
  2001. goto LBL_RES;
  2002. }
  2003. /* Move out bits used */
  2004. buf <<= bitcpy;
  2005. bitcnt++;
  2006. }
  2007. else {
  2008. bitcnt = 1;
  2009. buf = 0;
  2010. }
  2011. /* empty window and reset */
  2012. bitbuf = 0;
  2013. bitcpy = 0;
  2014. for (;;) {
  2015. /* grab next digit as required */
  2016. if (--bitcnt == 0) {
  2017. /* if digidx == -1 we are out of digits so break */
  2018. if (digidx == -1) {
  2019. break;
  2020. }
  2021. /* read next digit and reset bitcnt */
  2022. buf = X->dp[digidx--];
  2023. bitcnt = (int)DIGIT_BIT;
  2024. }
  2025. /* grab the next msb from the exponent */
  2026. y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
  2027. buf <<= (mp_digit)1;
  2028. /* add bit to the window */
  2029. bitbuf |= (y << (WINSIZE - ++bitcpy));
  2030. if (bitcpy == WINSIZE) {
  2031. /* ok window is filled so square as required and multiply */
  2032. /* square first */
  2033. for (x = 0; x < WINSIZE; x++) {
  2034. err = mp_sqr(res, res);
  2035. if (err != MP_OKAY) {
  2036. goto LBL_RES;
  2037. }
  2038. err = (*redux)(res, P, mp);
  2039. if (err != MP_OKAY) {
  2040. goto LBL_RES;
  2041. }
  2042. }
  2043. /* then multiply by 2^bitbuf */
  2044. err = mp_mul_2d(res, bitbuf, res);
  2045. if (err != MP_OKAY) {
  2046. goto LBL_RES;
  2047. }
  2048. err = mp_mod(res, P, res);
  2049. if (err != MP_OKAY) {
  2050. goto LBL_RES;
  2051. }
  2052. /* empty window and reset */
  2053. bitcpy = 0;
  2054. bitbuf = 0;
  2055. }
  2056. }
  2057. /* fixup result if Montgomery reduction is used
  2058. * recall that any value in a Montgomery system is
  2059. * actually multiplied by R mod n. So we have
  2060. * to reduce one more time to cancel out the factor
  2061. * of R.
  2062. */
  2063. err = (*redux)(res, P, mp);
  2064. if (err != MP_OKAY) {
  2065. goto LBL_RES;
  2066. }
  2067. /* swap res with Y */
  2068. err = mp_copy(res, Y);
  2069. LBL_RES:mp_clear (res);
  2070. LBL_M:
  2071. return err;
  2072. }
  2073. #undef WINSIZE
  2074. #endif /* BN_MP_EXPTMOD_BASE_2 */
  2075. /* setups the montgomery reduction stuff */
  2076. int mp_montgomery_setup (mp_int * n, mp_digit * rho)
  2077. {
  2078. mp_digit x, b;
  2079. /* fast inversion mod 2**k
  2080. *
  2081. * Based on the fact that
  2082. *
  2083. * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
  2084. * => 2*X*A - X*X*A*A = 1
  2085. * => 2*(1) - (1) = 1
  2086. */
  2087. b = n->dp[0];
  2088. if ((b & 1) == 0) {
  2089. return MP_VAL;
  2090. }
  2091. x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
  2092. x *= 2 - b * x; /* here x*a==1 mod 2**8 */
  2093. #if !defined(MP_8BIT)
  2094. x *= 2 - b * x; /* here x*a==1 mod 2**16 */
  2095. #endif
  2096. #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
  2097. x *= 2 - b * x; /* here x*a==1 mod 2**32 */
  2098. #endif
  2099. #ifdef MP_64BIT
  2100. x *= 2 - b * x; /* here x*a==1 mod 2**64 */
  2101. #endif
  2102. /* rho = -1/m mod b */
  2103. /* TAO, switched mp_word casts to mp_digit to shut up compiler */
  2104. *rho = (mp_digit)((((mp_digit)1 << ((mp_digit) DIGIT_BIT)) - x) & MP_MASK);
  2105. return MP_OKAY;
  2106. }
  2107. /* computes xR**-1 == x (mod N) via Montgomery Reduction
  2108. *
  2109. * This is an optimized implementation of montgomery_reduce
  2110. * which uses the comba method to quickly calculate the columns of the
  2111. * reduction.
  2112. *
  2113. * Based on Algorithm 14.32 on pp.601 of HAC.
  2114. */
  2115. int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
  2116. {
  2117. int ix, res, olduse;
  2118. #ifdef WOLFSSL_SMALL_STACK
  2119. mp_word* W; /* uses dynamic memory and slower */
  2120. #else
  2121. mp_word W[MP_WARRAY];
  2122. #endif
  2123. /* get old used count */
  2124. olduse = x->used;
  2125. /* grow a as required */
  2126. if (x->alloc < n->used + 1) {
  2127. if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
  2128. return res;
  2129. }
  2130. }
  2131. #ifdef WOLFSSL_SMALL_STACK
  2132. W = (mp_word*)XMALLOC(sizeof(mp_word) * (n->used * 2 + 2), NULL,
  2133. DYNAMIC_TYPE_BIGINT);
  2134. if (W == NULL)
  2135. return MP_MEM;
  2136. #endif
  2137. XMEMSET(W, 0, sizeof(mp_word) * (n->used * 2 + 2));
  2138. /* first we have to get the digits of the input into
  2139. * an array of double precision words W[...]
  2140. */
  2141. {
  2142. mp_word *_W;
  2143. mp_digit *tmpx;
  2144. /* alias for the W[] array */
  2145. _W = W;
  2146. /* alias for the digits of x*/
  2147. tmpx = x->dp;
  2148. /* copy the digits of a into W[0..a->used-1] */
  2149. for (ix = 0; ix < x->used; ix++) {
  2150. *_W++ = *tmpx++;
  2151. }
  2152. }
  2153. /* now we proceed to zero successive digits
  2154. * from the least significant upwards
  2155. */
  2156. for (ix = 0; ix < n->used; ix++) {
  2157. /* mu = ai * m' mod b
  2158. *
  2159. * We avoid a double precision multiplication (which isn't required)
  2160. * by casting the value down to a mp_digit. Note this requires
  2161. * that W[ix-1] have the carry cleared (see after the inner loop)
  2162. */
  2163. mp_digit mu;
  2164. mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
  2165. /* a = a + mu * m * b**i
  2166. *
  2167. * This is computed in place and on the fly. The multiplication
  2168. * by b**i is handled by offsetting which columns the results
  2169. * are added to.
  2170. *
  2171. * Note the comba method normally doesn't handle carries in the
  2172. * inner loop In this case we fix the carry from the previous
  2173. * column since the Montgomery reduction requires digits of the
  2174. * result (so far) [see above] to work. This is
  2175. * handled by fixing up one carry after the inner loop. The
  2176. * carry fixups are done in order so after these loops the
  2177. * first m->used words of W[] have the carries fixed
  2178. */
  2179. {
  2180. int iy;
  2181. mp_digit *tmpn;
  2182. mp_word *_W;
  2183. /* alias for the digits of the modulus */
  2184. tmpn = n->dp;
  2185. /* Alias for the columns set by an offset of ix */
  2186. _W = W + ix;
  2187. /* inner loop */
  2188. for (iy = 0; iy < n->used; iy++) {
  2189. *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
  2190. }
  2191. }
  2192. /* now fix carry for next digit, W[ix+1] */
  2193. W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
  2194. }
  2195. /* now we have to propagate the carries and
  2196. * shift the words downward [all those least
  2197. * significant digits we zeroed].
  2198. */
  2199. {
  2200. mp_digit *tmpx;
  2201. mp_word *_W, *_W1;
  2202. /* nox fix rest of carries */
  2203. /* alias for current word */
  2204. _W1 = W + ix;
  2205. /* alias for next word, where the carry goes */
  2206. _W = W + ++ix;
  2207. for (; ix <= n->used * 2 + 1; ix++) {
  2208. *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
  2209. }
  2210. /* copy out, A = A/b**n
  2211. *
  2212. * The result is A/b**n but instead of converting from an
  2213. * array of mp_word to mp_digit than calling mp_rshd
  2214. * we just copy them in the right order
  2215. */
  2216. /* alias for destination word */
  2217. tmpx = x->dp;
  2218. /* alias for shifted double precision result */
  2219. _W = W + n->used;
  2220. for (ix = 0; ix < n->used + 1; ix++) {
  2221. *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
  2222. }
  2223. /* zero olduse digits, if the input a was larger than
  2224. * m->used+1 we'll have to clear the digits
  2225. */
  2226. for (; ix < olduse; ix++) {
  2227. *tmpx++ = 0;
  2228. }
  2229. }
  2230. /* set the max used and clamp */
  2231. x->used = n->used + 1;
  2232. mp_clamp (x);
  2233. #ifdef WOLFSSL_SMALL_STACK
  2234. XFREE(W, NULL, DYNAMIC_TYPE_BIGINT);
  2235. #endif
  2236. /* if A >= m then A = A - m */
  2237. if (mp_cmp_mag (x, n) != MP_LT) {
  2238. return s_mp_sub (x, n, x);
  2239. }
  2240. return MP_OKAY;
  2241. }
  2242. /* computes xR**-1 == x (mod N) via Montgomery Reduction */
  2243. int mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
  2244. {
  2245. int ix, res, digs;
  2246. mp_digit mu;
  2247. /* can the fast reduction [comba] method be used?
  2248. *
  2249. * Note that unlike in mul you're safely allowed *less*
  2250. * than the available columns [255 per default] since carries
  2251. * are fixed up in the inner loop.
  2252. */
  2253. digs = n->used * 2 + 1;
  2254. if ((digs < (int)MP_WARRAY) &&
  2255. n->used <
  2256. (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  2257. return fast_mp_montgomery_reduce (x, n, rho);
  2258. }
  2259. /* grow the input as required */
  2260. if (x->alloc < digs) {
  2261. if ((res = mp_grow (x, digs)) != MP_OKAY) {
  2262. return res;
  2263. }
  2264. }
  2265. x->used = digs;
  2266. for (ix = 0; ix < n->used; ix++) {
  2267. /* mu = ai * rho mod b
  2268. *
  2269. * The value of rho must be precalculated via
  2270. * montgomery_setup() such that
  2271. * it equals -1/n0 mod b this allows the
  2272. * following inner loop to reduce the
  2273. * input one digit at a time
  2274. */
  2275. mu = (mp_digit) (((mp_word)x->dp[ix]) * ((mp_word)rho) & MP_MASK);
  2276. /* a = a + mu * m * b**i */
  2277. {
  2278. int iy;
  2279. mp_digit *tmpn, *tmpx, u;
  2280. mp_word r;
  2281. /* alias for digits of the modulus */
  2282. tmpn = n->dp;
  2283. /* alias for the digits of x [the input] */
  2284. tmpx = x->dp + ix;
  2285. /* set the carry to zero */
  2286. u = 0;
  2287. /* Multiply and add in place */
  2288. for (iy = 0; iy < n->used; iy++) {
  2289. /* compute product and sum */
  2290. r = ((mp_word)mu) * ((mp_word)*tmpn++) +
  2291. ((mp_word) u) + ((mp_word) * tmpx);
  2292. /* get carry */
  2293. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2294. /* fix digit */
  2295. *tmpx++ = (mp_digit)(r & ((mp_word) MP_MASK));
  2296. }
  2297. /* At this point the ix'th digit of x should be zero */
  2298. /* propagate carries upwards as required*/
  2299. while (u) {
  2300. *tmpx += u;
  2301. u = *tmpx >> DIGIT_BIT;
  2302. *tmpx++ &= MP_MASK;
  2303. }
  2304. }
  2305. }
  2306. /* at this point the n.used'th least
  2307. * significant digits of x are all zero
  2308. * which means we can shift x to the
  2309. * right by n.used digits and the
  2310. * residue is unchanged.
  2311. */
  2312. /* x = x/b**n.used */
  2313. mp_clamp(x);
  2314. mp_rshd (x, n->used);
  2315. /* if x >= n then x = x - n */
  2316. if (mp_cmp_mag (x, n) != MP_LT) {
  2317. return s_mp_sub (x, n, x);
  2318. }
  2319. return MP_OKAY;
  2320. }
  2321. /* determines the setup value */
  2322. void mp_dr_setup(mp_int *a, mp_digit *d)
  2323. {
  2324. /* the casts are required if DIGIT_BIT is one less than
  2325. * the number of bits in a mp_digit [e.g. DIGIT_BIT==31]
  2326. */
  2327. *d = (mp_digit)((((mp_word)1) << ((mp_word)DIGIT_BIT)) -
  2328. ((mp_word)a->dp[0]));
  2329. }
  2330. /* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
  2331. *
  2332. * Based on algorithm from the paper
  2333. *
  2334. * "Generating Efficient Primes for Discrete Log Cryptosystems"
  2335. * Chae Hoon Lim, Pil Joong Lee,
  2336. * POSTECH Information Research Laboratories
  2337. *
  2338. * The modulus must be of a special format [see manual]
  2339. *
  2340. * Has been modified to use algorithm 7.10 from the LTM book instead
  2341. *
  2342. * Input x must be in the range 0 <= x <= (n-1)**2
  2343. */
  2344. int mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k)
  2345. {
  2346. int err, i, m;
  2347. mp_word r;
  2348. mp_digit mu, *tmpx1, *tmpx2;
  2349. /* m = digits in modulus */
  2350. m = n->used;
  2351. /* ensure that "x" has at least 2m digits */
  2352. if (x->alloc < m + m) {
  2353. if ((err = mp_grow (x, m + m)) != MP_OKAY) {
  2354. return err;
  2355. }
  2356. }
  2357. /* top of loop, this is where the code resumes if
  2358. * another reduction pass is required.
  2359. */
  2360. top:
  2361. /* aliases for digits */
  2362. /* alias for lower half of x */
  2363. tmpx1 = x->dp;
  2364. /* alias for upper half of x, or x/B**m */
  2365. tmpx2 = x->dp + m;
  2366. /* set carry to zero */
  2367. mu = 0;
  2368. /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
  2369. for (i = 0; i < m; i++) {
  2370. r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu;
  2371. *tmpx1++ = (mp_digit)(r & MP_MASK);
  2372. mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT));
  2373. }
  2374. /* set final carry */
  2375. *tmpx1++ = mu;
  2376. /* zero words above m */
  2377. for (i = m + 1; i < x->used; i++) {
  2378. *tmpx1++ = 0;
  2379. }
  2380. /* clamp, sub and return */
  2381. mp_clamp (x);
  2382. /* if x >= n then subtract and reduce again
  2383. * Each successive "recursion" makes the input smaller and smaller.
  2384. */
  2385. if (mp_cmp_mag (x, n) != MP_LT) {
  2386. if ((err = s_mp_sub(x, n, x)) != MP_OKAY) {
  2387. return err;
  2388. }
  2389. goto top;
  2390. }
  2391. return MP_OKAY;
  2392. }
  2393. /* reduces a modulo n where n is of the form 2**p - d */
  2394. int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d)
  2395. {
  2396. mp_int q;
  2397. int p, res;
  2398. if ((res = mp_init(&q)) != MP_OKAY) {
  2399. return res;
  2400. }
  2401. p = mp_count_bits(n);
  2402. top:
  2403. /* q = a/2**p, a = a mod 2**p */
  2404. if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  2405. goto ERR;
  2406. }
  2407. if (d != 1) {
  2408. /* q = q * d */
  2409. if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) {
  2410. goto ERR;
  2411. }
  2412. }
  2413. /* a = a + q */
  2414. if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
  2415. goto ERR;
  2416. }
  2417. if (mp_cmp_mag(a, n) != MP_LT) {
  2418. if ((res = s_mp_sub(a, n, a)) != MP_OKAY) {
  2419. goto ERR;
  2420. }
  2421. goto top;
  2422. }
  2423. ERR:
  2424. mp_clear(&q);
  2425. return res;
  2426. }
  2427. /* determines the setup value */
  2428. int mp_reduce_2k_setup(mp_int *a, mp_digit *d)
  2429. {
  2430. int res, p;
  2431. mp_int tmp;
  2432. if ((res = mp_init(&tmp)) != MP_OKAY) {
  2433. return res;
  2434. }
  2435. p = mp_count_bits(a);
  2436. if ((res = mp_2expt(&tmp, p)) != MP_OKAY) {
  2437. mp_clear(&tmp);
  2438. return res;
  2439. }
  2440. if ((res = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) {
  2441. mp_clear(&tmp);
  2442. return res;
  2443. }
  2444. *d = tmp.dp[0];
  2445. mp_clear(&tmp);
  2446. return MP_OKAY;
  2447. }
  2448. /* set the b bit of a */
  2449. int mp_set_bit (mp_int * a, int b)
  2450. {
  2451. int i = b / DIGIT_BIT, res;
  2452. /*
  2453. * Require:
  2454. * bit index b >= 0
  2455. * a->alloc == a->used == 0 if a->dp == NULL
  2456. */
  2457. if (b < 0 || (a->dp == NULL && (a->alloc != 0 || a->used != 0)))
  2458. return MP_VAL;
  2459. if (a->dp == NULL || a->used < (int)(i + 1)) {
  2460. /* grow a to accommodate the single bit */
  2461. if ((res = mp_grow (a, i + 1)) != MP_OKAY) {
  2462. return res;
  2463. }
  2464. /* set the used count of where the bit will go */
  2465. a->used = (int)(i + 1);
  2466. }
  2467. /* put the single bit in its place */
  2468. a->dp[i] |= ((mp_digit)1) << (b % DIGIT_BIT);
  2469. return MP_OKAY;
  2470. }
  2471. /* computes a = 2**b
  2472. *
  2473. * Simple algorithm which zeros the int, set the required bit
  2474. */
  2475. int mp_2expt (mp_int * a, int b)
  2476. {
  2477. /* zero a as per default */
  2478. mp_zero (a);
  2479. return mp_set_bit(a, b);
  2480. }
  2481. /* multiply by a digit */
  2482. int mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
  2483. {
  2484. mp_digit u, *tmpa, *tmpc;
  2485. mp_word r;
  2486. int ix, res, olduse;
  2487. /* make sure c is big enough to hold a*b */
  2488. if (c->dp == NULL || c->alloc < a->used + 1) {
  2489. if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) {
  2490. return res;
  2491. }
  2492. }
  2493. /* get the original destinations used count */
  2494. olduse = c->used;
  2495. /* set the sign */
  2496. c->sign = a->sign;
  2497. /* alias for a->dp [source] */
  2498. tmpa = a->dp;
  2499. /* alias for c->dp [dest] */
  2500. tmpc = c->dp;
  2501. /* zero carry */
  2502. u = 0;
  2503. /* compute columns */
  2504. for (ix = 0; ix < a->used; ix++) {
  2505. /* compute product and carry sum for this term */
  2506. r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b);
  2507. /* mask off higher bits to get a single digit */
  2508. *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2509. /* send carry into next iteration */
  2510. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  2511. }
  2512. /* store final carry [if any] and increment ix offset */
  2513. *tmpc++ = u;
  2514. ++ix;
  2515. /* now zero digits above the top */
  2516. while (ix++ < olduse) {
  2517. *tmpc++ = 0;
  2518. }
  2519. /* set used count */
  2520. c->used = a->used + 1;
  2521. mp_clamp(c);
  2522. return MP_OKAY;
  2523. }
  2524. /* d = a * b (mod c) */
  2525. #if defined(FREESCALE_LTC_TFM)
  2526. int wolfcrypt_mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d)
  2527. #else
  2528. int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
  2529. #endif
  2530. {
  2531. int res;
  2532. mp_int t;
  2533. if ((res = mp_init_size (&t, c->used)) != MP_OKAY) {
  2534. return res;
  2535. }
  2536. res = mp_mul (a, b, &t);
  2537. if (res == MP_OKAY) {
  2538. res = mp_mod (&t, c, d);
  2539. }
  2540. mp_clear (&t);
  2541. return res;
  2542. }
  2543. /* d = a - b (mod c) */
  2544. int mp_submod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
  2545. {
  2546. int res;
  2547. mp_int t;
  2548. if ((res = mp_init (&t)) != MP_OKAY) {
  2549. return res;
  2550. }
  2551. res = mp_sub (a, b, &t);
  2552. if (res == MP_OKAY) {
  2553. res = mp_mod (&t, c, d);
  2554. }
  2555. mp_clear (&t);
  2556. return res;
  2557. }
  2558. /* d = a + b (mod c) */
  2559. int mp_addmod(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
  2560. {
  2561. int res;
  2562. mp_int t;
  2563. if ((res = mp_init (&t)) != MP_OKAY) {
  2564. return res;
  2565. }
  2566. res = mp_add (a, b, &t);
  2567. if (res == MP_OKAY) {
  2568. res = mp_mod (&t, c, d);
  2569. }
  2570. mp_clear (&t);
  2571. return res;
  2572. }
  2573. /* d = a - b (mod c) - a < c and b < c and positive */
  2574. int mp_submod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
  2575. {
  2576. int res;
  2577. res = mp_sub(a, b, d);
  2578. if (res == MP_OKAY && mp_isneg(d)) {
  2579. res = mp_add(d, c, d);
  2580. }
  2581. return res;
  2582. }
  2583. /* d = a + b (mod c) - a < c and b < c and positive */
  2584. int mp_addmod_ct(mp_int* a, mp_int* b, mp_int* c, mp_int* d)
  2585. {
  2586. int res;
  2587. res = mp_add(a, b, d);
  2588. if (res == MP_OKAY && mp_cmp(d, c) != MP_LT) {
  2589. res = mp_sub(d, c, d);
  2590. }
  2591. return res;
  2592. }
  2593. /* computes b = a*a */
  2594. int mp_sqr (mp_int * a, mp_int * b)
  2595. {
  2596. int res;
  2597. {
  2598. #ifdef BN_FAST_S_MP_SQR_C
  2599. /* can we use the fast comba multiplier? */
  2600. if ((a->used * 2 + 1) < (int)MP_WARRAY &&
  2601. a->used <
  2602. (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
  2603. res = fast_s_mp_sqr (a, b);
  2604. } else
  2605. #endif
  2606. #ifdef BN_S_MP_SQR_C
  2607. res = s_mp_sqr (a, b);
  2608. #else
  2609. res = MP_VAL;
  2610. #endif
  2611. }
  2612. b->sign = MP_ZPOS;
  2613. return res;
  2614. }
  2615. /* high level multiplication (handles sign) */
  2616. #if defined(FREESCALE_LTC_TFM)
  2617. int wolfcrypt_mp_mul(mp_int *a, mp_int *b, mp_int *c)
  2618. #else
  2619. int mp_mul (mp_int * a, mp_int * b, mp_int * c)
  2620. #endif
  2621. {
  2622. int res, neg;
  2623. neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
  2624. {
  2625. #ifdef BN_FAST_S_MP_MUL_DIGS_C
  2626. /* can we use the fast multiplier?
  2627. *
  2628. * The fast multiplier can be used if the output will
  2629. * have less than MP_WARRAY digits and the number of
  2630. * digits won't affect carry propagation
  2631. */
  2632. int digs = a->used + b->used + 1;
  2633. if ((digs < (int)MP_WARRAY) &&
  2634. MIN(a->used, b->used) <=
  2635. (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  2636. res = fast_s_mp_mul_digs (a, b, c, digs);
  2637. } else
  2638. #endif
  2639. #ifdef BN_S_MP_MUL_DIGS_C
  2640. res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
  2641. #else
  2642. res = MP_VAL;
  2643. #endif
  2644. }
  2645. c->sign = (c->used > 0) ? neg : MP_ZPOS;
  2646. return res;
  2647. }
  2648. /* b = a*2 */
  2649. int mp_mul_2(mp_int * a, mp_int * b)
  2650. {
  2651. int x, res, oldused;
  2652. /* grow to accommodate result */
  2653. if (b->alloc < a->used + 1) {
  2654. if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
  2655. return res;
  2656. }
  2657. }
  2658. oldused = b->used;
  2659. b->used = a->used;
  2660. {
  2661. mp_digit r, rr, *tmpa, *tmpb;
  2662. /* alias for source */
  2663. tmpa = a->dp;
  2664. /* alias for dest */
  2665. tmpb = b->dp;
  2666. /* carry */
  2667. r = 0;
  2668. for (x = 0; x < a->used; x++) {
  2669. /* get what will be the *next* carry bit from the
  2670. * MSB of the current digit
  2671. */
  2672. rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
  2673. /* now shift up this digit, add in the carry [from the previous] */
  2674. *tmpb++ = (mp_digit)(((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK);
  2675. /* copy the carry that would be from the source
  2676. * digit into the next iteration
  2677. */
  2678. r = rr;
  2679. }
  2680. /* new leading digit? */
  2681. if (r != 0) {
  2682. /* add a MSB which is always 1 at this point */
  2683. *tmpb = 1;
  2684. ++(b->used);
  2685. }
  2686. /* now zero any excess digits on the destination
  2687. * that we didn't write to
  2688. */
  2689. tmpb = b->dp + b->used;
  2690. for (x = b->used; x < oldused; x++) {
  2691. *tmpb++ = 0;
  2692. }
  2693. }
  2694. b->sign = a->sign;
  2695. return MP_OKAY;
  2696. }
  2697. /* divide by three (based on routine from MPI and the GMP manual) */
  2698. int mp_div_3 (mp_int * a, mp_int *c, mp_digit * d)
  2699. {
  2700. mp_int q;
  2701. mp_word w, t;
  2702. mp_digit b;
  2703. int res, ix;
  2704. /* b = 2**DIGIT_BIT / 3 */
  2705. b = (mp_digit) ( (((mp_word)1) << ((mp_word)DIGIT_BIT)) / ((mp_word)3) );
  2706. if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
  2707. return res;
  2708. }
  2709. q.used = a->used;
  2710. q.sign = a->sign;
  2711. w = 0;
  2712. for (ix = a->used - 1; ix >= 0; ix--) {
  2713. w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
  2714. if (w >= 3) {
  2715. /* multiply w by [1/3] */
  2716. t = (w * ((mp_word)b)) >> ((mp_word)DIGIT_BIT);
  2717. /* now subtract 3 * [w/3] from w, to get the remainder */
  2718. w -= t+t+t;
  2719. /* fixup the remainder as required since
  2720. * the optimization is not exact.
  2721. */
  2722. while (w >= 3) {
  2723. t += 1;
  2724. w -= 3;
  2725. }
  2726. } else {
  2727. t = 0;
  2728. }
  2729. q.dp[ix] = (mp_digit)t;
  2730. }
  2731. /* [optional] store the remainder */
  2732. if (d != NULL) {
  2733. *d = (mp_digit)w;
  2734. }
  2735. /* [optional] store the quotient */
  2736. if (c != NULL) {
  2737. mp_clamp(&q);
  2738. mp_exch(&q, c);
  2739. }
  2740. mp_clear(&q);
  2741. return res;
  2742. }
  2743. /* init an mp_init for a given size */
  2744. int mp_init_size (mp_int * a, int size)
  2745. {
  2746. int x;
  2747. /* pad size so there are always extra digits */
  2748. size += (MP_PREC * 2) - (size % MP_PREC);
  2749. /* alloc mem */
  2750. a->dp = (mp_digit *)XMALLOC (sizeof (mp_digit) * size, NULL,
  2751. DYNAMIC_TYPE_BIGINT);
  2752. if (a->dp == NULL) {
  2753. return MP_MEM;
  2754. }
  2755. /* set the members */
  2756. a->used = 0;
  2757. a->alloc = size;
  2758. a->sign = MP_ZPOS;
  2759. #ifdef HAVE_WOLF_BIGINT
  2760. wc_bigint_init(&a->raw);
  2761. #endif
  2762. /* zero the digits */
  2763. for (x = 0; x < size; x++) {
  2764. a->dp[x] = 0;
  2765. }
  2766. return MP_OKAY;
  2767. }
  2768. /* the jist of squaring...
  2769. * you do like mult except the offset of the tmpx [one that
  2770. * starts closer to zero] can't equal the offset of tmpy.
  2771. * So basically you set up iy like before then you min it with
  2772. * (ty-tx) so that it never happens. You double all those
  2773. * you add in the inner loop
  2774. After that loop you do the squares and add them in.
  2775. */
  2776. int fast_s_mp_sqr (mp_int * a, mp_int * b)
  2777. {
  2778. int olduse, res, pa, ix, iz;
  2779. #ifdef WOLFSSL_SMALL_STACK
  2780. mp_digit* W; /* uses dynamic memory and slower */
  2781. #else
  2782. mp_digit W[MP_WARRAY];
  2783. #endif
  2784. mp_digit *tmpx;
  2785. mp_word W1;
  2786. /* grow the destination as required */
  2787. pa = a->used + a->used;
  2788. if (b->alloc < pa) {
  2789. if ((res = mp_grow (b, pa)) != MP_OKAY) {
  2790. return res;
  2791. }
  2792. }
  2793. if (pa > (int)MP_WARRAY)
  2794. return MP_RANGE; /* TAO range check */
  2795. if (pa == 0) {
  2796. /* Nothing to do. Zero result and return. */
  2797. mp_zero(b);
  2798. return MP_OKAY;
  2799. }
  2800. #ifdef WOLFSSL_SMALL_STACK
  2801. W = (mp_digit*)XMALLOC(sizeof(mp_digit) * pa, NULL, DYNAMIC_TYPE_BIGINT);
  2802. if (W == NULL)
  2803. return MP_MEM;
  2804. #endif
  2805. /* number of output digits to produce */
  2806. W1 = 0;
  2807. for (ix = 0; ix < pa; ix++) {
  2808. int tx, ty, iy;
  2809. mp_word _W;
  2810. mp_digit *tmpy;
  2811. /* clear counter */
  2812. _W = 0;
  2813. /* get offsets into the two bignums */
  2814. ty = MIN(a->used-1, ix);
  2815. tx = ix - ty;
  2816. /* setup temp aliases */
  2817. tmpx = a->dp + tx;
  2818. tmpy = a->dp + ty;
  2819. /* this is the number of times the loop will iterate, essentially
  2820. while (tx++ < a->used && ty-- >= 0) { ... }
  2821. */
  2822. iy = MIN(a->used-tx, ty+1);
  2823. /* now for squaring tx can never equal ty
  2824. * we halve the distance since they approach at a rate of 2x
  2825. * and we have to round because odd cases need to be executed
  2826. */
  2827. iy = MIN(iy, (ty-tx+1)>>1);
  2828. /* execute loop */
  2829. for (iz = 0; iz < iy; iz++) {
  2830. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  2831. }
  2832. /* double the inner product and add carry */
  2833. _W = _W + _W + W1;
  2834. /* even columns have the square term in them */
  2835. if ((ix&1) == 0) {
  2836. _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
  2837. }
  2838. /* store it */
  2839. W[ix] = (mp_digit)(_W & MP_MASK);
  2840. /* make next carry */
  2841. W1 = _W >> ((mp_word)DIGIT_BIT);
  2842. }
  2843. /* setup dest */
  2844. olduse = b->used;
  2845. b->used = a->used+a->used;
  2846. {
  2847. mp_digit *tmpb;
  2848. tmpb = b->dp;
  2849. for (ix = 0; ix < pa; ix++) {
  2850. *tmpb++ = (mp_digit)(W[ix] & MP_MASK);
  2851. }
  2852. /* clear unused digits [that existed in the old copy of c] */
  2853. for (; ix < olduse; ix++) {
  2854. *tmpb++ = 0;
  2855. }
  2856. }
  2857. mp_clamp (b);
  2858. #ifdef WOLFSSL_SMALL_STACK
  2859. XFREE(W, NULL, DYNAMIC_TYPE_BIGINT);
  2860. #endif
  2861. return MP_OKAY;
  2862. }
  2863. /* Fast (comba) multiplier
  2864. *
  2865. * This is the fast column-array [comba] multiplier. It is
  2866. * designed to compute the columns of the product first
  2867. * then handle the carries afterwards. This has the effect
  2868. * of making the nested loops that compute the columns very
  2869. * simple and schedulable on super-scalar processors.
  2870. *
  2871. * This has been modified to produce a variable number of
  2872. * digits of output so if say only a half-product is required
  2873. * you don't have to compute the upper half (a feature
  2874. * required for fast Barrett reduction).
  2875. *
  2876. * Based on Algorithm 14.12 on pp.595 of HAC.
  2877. *
  2878. */
  2879. int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  2880. {
  2881. int olduse, res, pa, ix, iz;
  2882. #ifdef WOLFSSL_SMALL_STACK
  2883. mp_digit* W; /* uses dynamic memory and slower */
  2884. #else
  2885. mp_digit W[MP_WARRAY];
  2886. #endif
  2887. mp_word _W;
  2888. /* grow the destination as required */
  2889. if (c->alloc < digs) {
  2890. if ((res = mp_grow (c, digs)) != MP_OKAY) {
  2891. return res;
  2892. }
  2893. }
  2894. /* number of output digits to produce */
  2895. pa = MIN(digs, a->used + b->used);
  2896. if (pa > (int)MP_WARRAY)
  2897. return MP_RANGE; /* TAO range check */
  2898. if (pa == 0) {
  2899. /* Nothing to do. Zero result and return. */
  2900. mp_zero(c);
  2901. return MP_OKAY;
  2902. }
  2903. #ifdef WOLFSSL_SMALL_STACK
  2904. W = (mp_digit*)XMALLOC(sizeof(mp_digit) * pa, NULL, DYNAMIC_TYPE_BIGINT);
  2905. if (W == NULL)
  2906. return MP_MEM;
  2907. #endif
  2908. /* clear the carry */
  2909. _W = 0;
  2910. for (ix = 0; ix < pa; ix++) {
  2911. int tx, ty;
  2912. int iy;
  2913. mp_digit *tmpx, *tmpy;
  2914. if ((a->used > 0) && (b->used > 0)) {
  2915. /* get offsets into the two bignums */
  2916. ty = MIN(b->used-1, ix);
  2917. tx = ix - ty;
  2918. /* setup temp aliases */
  2919. tmpx = a->dp + tx;
  2920. tmpy = b->dp + ty;
  2921. /* this is the number of times the loop will iterate, essentially
  2922. while (tx++ < a->used && ty-- >= 0) { ... }
  2923. */
  2924. iy = MIN(a->used-tx, ty+1);
  2925. /* execute loop */
  2926. for (iz = 0; iz < iy; ++iz) {
  2927. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  2928. }
  2929. }
  2930. /* store term */
  2931. W[ix] = (mp_digit)(((mp_digit)_W) & MP_MASK);
  2932. /* make next carry */
  2933. _W = _W >> ((mp_word)DIGIT_BIT);
  2934. }
  2935. /* setup dest */
  2936. olduse = c->used;
  2937. c->used = pa;
  2938. {
  2939. mp_digit *tmpc;
  2940. tmpc = c->dp;
  2941. for (ix = 0; ix < pa; ix++) { /* JRB, +1 could read uninitialized data */
  2942. /* now extract the previous digit [below the carry] */
  2943. *tmpc++ = W[ix];
  2944. }
  2945. /* clear unused digits [that existed in the old copy of c] */
  2946. for (; ix < olduse; ix++) {
  2947. *tmpc++ = 0;
  2948. }
  2949. }
  2950. mp_clamp (c);
  2951. #ifdef WOLFSSL_SMALL_STACK
  2952. XFREE(W, NULL, DYNAMIC_TYPE_BIGINT);
  2953. #endif
  2954. return MP_OKAY;
  2955. }
  2956. /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
  2957. int s_mp_sqr (mp_int * a, mp_int * b)
  2958. {
  2959. mp_int t;
  2960. int res, ix, iy, pa;
  2961. mp_word r;
  2962. mp_digit u, tmpx, *tmpt;
  2963. pa = a->used;
  2964. if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
  2965. return res;
  2966. }
  2967. /* default used is maximum possible size */
  2968. t.used = 2*pa + 1;
  2969. for (ix = 0; ix < pa; ix++) {
  2970. /* first calculate the digit at 2*ix */
  2971. /* calculate double precision result */
  2972. r = ((mp_word) t.dp[2*ix]) +
  2973. ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
  2974. /* store lower part in result */
  2975. t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
  2976. /* get the carry */
  2977. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2978. /* left hand side of A[ix] * A[iy] */
  2979. tmpx = a->dp[ix];
  2980. /* alias for where to store the results */
  2981. tmpt = t.dp + (2*ix + 1);
  2982. for (iy = ix + 1; iy < pa; iy++) {
  2983. /* first calculate the product */
  2984. r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
  2985. /* now calculate the double precision result, note we use
  2986. * addition instead of *2 since it's easier to optimize
  2987. */
  2988. r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
  2989. /* store lower part */
  2990. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2991. /* get carry */
  2992. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2993. }
  2994. /* propagate upwards */
  2995. while (u != ((mp_digit) 0)) {
  2996. r = ((mp_word) *tmpt) + ((mp_word) u);
  2997. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2998. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2999. }
  3000. }
  3001. mp_clamp (&t);
  3002. mp_exch (&t, b);
  3003. mp_clear (&t);
  3004. return MP_OKAY;
  3005. }
  3006. /* multiplies |a| * |b| and only computes up to digs digits of result
  3007. * HAC pp. 595, Algorithm 14.12 Modified so you can control how
  3008. * many digits of output are created.
  3009. */
  3010. int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  3011. {
  3012. mp_int t;
  3013. int res, pa, pb, ix, iy;
  3014. mp_digit u;
  3015. mp_word r;
  3016. mp_digit tmpx, *tmpt, *tmpy;
  3017. /* can we use the fast multiplier? */
  3018. if ((digs < (int)MP_WARRAY) &&
  3019. MIN (a->used, b->used) <
  3020. (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  3021. return fast_s_mp_mul_digs (a, b, c, digs);
  3022. }
  3023. if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
  3024. return res;
  3025. }
  3026. t.used = digs;
  3027. /* compute the digits of the product directly */
  3028. pa = a->used;
  3029. for (ix = 0; ix < pa; ix++) {
  3030. /* set the carry to zero */
  3031. u = 0;
  3032. /* limit ourselves to making digs digits of output */
  3033. pb = MIN (b->used, digs - ix);
  3034. /* setup some aliases */
  3035. /* copy of the digit from a used within the nested loop */
  3036. tmpx = a->dp[ix];
  3037. /* an alias for the destination shifted ix places */
  3038. tmpt = t.dp + ix;
  3039. /* an alias for the digits of b */
  3040. tmpy = b->dp;
  3041. /* compute the columns of the output and propagate the carry */
  3042. for (iy = 0; iy < pb; iy++) {
  3043. /* compute the column as a mp_word */
  3044. r = ((mp_word)*tmpt) +
  3045. ((mp_word)tmpx) * ((mp_word)*tmpy++) +
  3046. ((mp_word) u);
  3047. /* the new column is the lower part of the result */
  3048. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  3049. /* get the carry word from the result */
  3050. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  3051. }
  3052. /* set carry if it is placed below digs */
  3053. if (ix + iy < digs) {
  3054. *tmpt = u;
  3055. }
  3056. }
  3057. mp_clamp (&t);
  3058. mp_exch (&t, c);
  3059. mp_clear (&t);
  3060. return MP_OKAY;
  3061. }
  3062. /*
  3063. * shifts with subtractions when the result is greater than b.
  3064. *
  3065. * The method is slightly modified to shift B unconditionally up to just under
  3066. * the leading bit of b. This saves a lot of multiple precision shifting.
  3067. */
  3068. int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
  3069. {
  3070. int x, bits, res;
  3071. /* how many bits of last digit does b use */
  3072. bits = mp_count_bits (b) % DIGIT_BIT;
  3073. if (b->used > 1) {
  3074. if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1))
  3075. != MP_OKAY) {
  3076. return res;
  3077. }
  3078. } else {
  3079. if ((res = mp_set(a, 1)) != MP_OKAY) {
  3080. return res;
  3081. }
  3082. bits = 1;
  3083. }
  3084. /* now compute C = A * B mod b */
  3085. for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
  3086. if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
  3087. return res;
  3088. }
  3089. if (mp_cmp_mag (a, b) != MP_LT) {
  3090. if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
  3091. return res;
  3092. }
  3093. }
  3094. }
  3095. return MP_OKAY;
  3096. }
  3097. #ifdef MP_LOW_MEM
  3098. #define TAB_SIZE 32
  3099. #else
  3100. #define TAB_SIZE 256
  3101. #endif
  3102. int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
  3103. {
  3104. mp_int M[TAB_SIZE], res, mu;
  3105. mp_digit buf;
  3106. int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
  3107. int (*redux)(mp_int*,mp_int*,mp_int*);
  3108. /* find window size */
  3109. x = mp_count_bits (X);
  3110. if (x <= 7) {
  3111. winsize = 2;
  3112. } else if (x <= 36) {
  3113. winsize = 3;
  3114. } else if (x <= 140) {
  3115. winsize = 4;
  3116. } else if (x <= 450) {
  3117. winsize = 5;
  3118. } else if (x <= 1303) {
  3119. winsize = 6;
  3120. } else if (x <= 3529) {
  3121. winsize = 7;
  3122. } else {
  3123. winsize = 8;
  3124. }
  3125. #ifdef MP_LOW_MEM
  3126. if (winsize > 5) {
  3127. winsize = 5;
  3128. }
  3129. #endif
  3130. /* init M array */
  3131. /* init first cell */
  3132. if ((err = mp_init(&M[1])) != MP_OKAY) {
  3133. return err;
  3134. }
  3135. /* now init the second half of the array */
  3136. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  3137. if ((err = mp_init(&M[x])) != MP_OKAY) {
  3138. for (y = 1<<(winsize-1); y < x; y++) {
  3139. mp_clear (&M[y]);
  3140. }
  3141. mp_clear(&M[1]);
  3142. return err;
  3143. }
  3144. }
  3145. /* create mu, used for Barrett reduction */
  3146. if ((err = mp_init (&mu)) != MP_OKAY) {
  3147. goto LBL_M;
  3148. }
  3149. if (redmode == 0) {
  3150. if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
  3151. goto LBL_MU;
  3152. }
  3153. redux = mp_reduce;
  3154. } else {
  3155. if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
  3156. goto LBL_MU;
  3157. }
  3158. redux = mp_reduce_2k_l;
  3159. }
  3160. /* create M table
  3161. *
  3162. * The M table contains powers of the base,
  3163. * e.g. M[x] = G**x mod P
  3164. *
  3165. * The first half of the table is not
  3166. * computed though accept for M[0] and M[1]
  3167. */
  3168. if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
  3169. goto LBL_MU;
  3170. }
  3171. /* compute the value at M[1<<(winsize-1)] by squaring
  3172. * M[1] (winsize-1) times
  3173. */
  3174. if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  3175. goto LBL_MU;
  3176. }
  3177. for (x = 0; x < (winsize - 1); x++) {
  3178. /* square it */
  3179. if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))],
  3180. &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  3181. goto LBL_MU;
  3182. }
  3183. /* reduce modulo P */
  3184. if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, &mu)) != MP_OKAY) {
  3185. goto LBL_MU;
  3186. }
  3187. }
  3188. /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
  3189. * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
  3190. */
  3191. for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
  3192. if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
  3193. goto LBL_MU;
  3194. }
  3195. if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
  3196. goto LBL_MU;
  3197. }
  3198. }
  3199. /* setup result */
  3200. if ((err = mp_init (&res)) != MP_OKAY) {
  3201. goto LBL_MU;
  3202. }
  3203. if ((err = mp_set (&res, 1)) != MP_OKAY) {
  3204. goto LBL_MU;
  3205. }
  3206. /* set initial mode and bit cnt */
  3207. mode = 0;
  3208. bitcnt = 1;
  3209. buf = 0;
  3210. digidx = X->used - 1;
  3211. bitcpy = 0;
  3212. bitbuf = 0;
  3213. for (;;) {
  3214. /* grab next digit as required */
  3215. if (--bitcnt == 0) {
  3216. /* if digidx == -1 we are out of digits */
  3217. if (digidx == -1) {
  3218. break;
  3219. }
  3220. /* read next digit and reset the bitcnt */
  3221. buf = X->dp[digidx--];
  3222. bitcnt = (int) DIGIT_BIT;
  3223. }
  3224. /* grab the next msb from the exponent */
  3225. y = (int)(buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
  3226. buf <<= (mp_digit)1;
  3227. /* if the bit is zero and mode == 0 then we ignore it
  3228. * These represent the leading zero bits before the first 1 bit
  3229. * in the exponent. Technically this opt is not required but it
  3230. * does lower the # of trivial squaring/reductions used
  3231. */
  3232. if (mode == 0 && y == 0) {
  3233. continue;
  3234. }
  3235. /* if the bit is zero and mode == 1 then we square */
  3236. if (mode == 1 && y == 0) {
  3237. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  3238. goto LBL_RES;
  3239. }
  3240. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  3241. goto LBL_RES;
  3242. }
  3243. continue;
  3244. }
  3245. /* else we add it to the window */
  3246. bitbuf |= (y << (winsize - ++bitcpy));
  3247. mode = 2;
  3248. if (bitcpy == winsize) {
  3249. /* ok window is filled so square as required and multiply */
  3250. /* square first */
  3251. for (x = 0; x < winsize; x++) {
  3252. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  3253. goto LBL_RES;
  3254. }
  3255. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  3256. goto LBL_RES;
  3257. }
  3258. }
  3259. /* then multiply */
  3260. if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
  3261. goto LBL_RES;
  3262. }
  3263. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  3264. goto LBL_RES;
  3265. }
  3266. /* empty window and reset */
  3267. bitcpy = 0;
  3268. bitbuf = 0;
  3269. mode = 1;
  3270. }
  3271. }
  3272. /* if bits remain then square/multiply */
  3273. if (mode == 2 && bitcpy > 0) {
  3274. /* square then multiply if the bit is set */
  3275. for (x = 0; x < bitcpy; x++) {
  3276. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  3277. goto LBL_RES;
  3278. }
  3279. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  3280. goto LBL_RES;
  3281. }
  3282. bitbuf <<= 1;
  3283. if ((bitbuf & (1 << winsize)) != 0) {
  3284. /* then multiply */
  3285. if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
  3286. goto LBL_RES;
  3287. }
  3288. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  3289. goto LBL_RES;
  3290. }
  3291. }
  3292. }
  3293. }
  3294. mp_exch (&res, Y);
  3295. err = MP_OKAY;
  3296. LBL_RES:mp_clear (&res);
  3297. LBL_MU:mp_clear (&mu);
  3298. LBL_M:
  3299. mp_clear(&M[1]);
  3300. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  3301. mp_clear (&M[x]);
  3302. }
  3303. return err;
  3304. }
  3305. /* pre-calculate the value required for Barrett reduction
  3306. * For a given modulus "b" it calculates the value required in "a"
  3307. */
  3308. int mp_reduce_setup (mp_int * a, mp_int * b)
  3309. {
  3310. int res;
  3311. if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
  3312. return res;
  3313. }
  3314. return mp_div (a, b, a, NULL);
  3315. }
  3316. /* reduces x mod m, assumes 0 < x < m**2, mu is
  3317. * precomputed via mp_reduce_setup.
  3318. * From HAC pp.604 Algorithm 14.42
  3319. */
  3320. int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
  3321. {
  3322. mp_int q;
  3323. int res, um = m->used;
  3324. /* q = x */
  3325. if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
  3326. return res;
  3327. }
  3328. /* q1 = x / b**(k-1) */
  3329. mp_rshd (&q, um - 1);
  3330. /* according to HAC this optimization is ok */
  3331. if (((mp_word) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
  3332. if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
  3333. goto CLEANUP;
  3334. }
  3335. } else {
  3336. #ifdef BN_S_MP_MUL_HIGH_DIGS_C
  3337. if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
  3338. goto CLEANUP;
  3339. }
  3340. #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C)
  3341. if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
  3342. goto CLEANUP;
  3343. }
  3344. #else
  3345. {
  3346. res = MP_VAL;
  3347. goto CLEANUP;
  3348. }
  3349. #endif
  3350. }
  3351. /* q3 = q2 / b**(k+1) */
  3352. mp_rshd (&q, um + 1);
  3353. /* x = x mod b**(k+1), quick (no division) */
  3354. if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
  3355. goto CLEANUP;
  3356. }
  3357. /* q = q * m mod b**(k+1), quick (no division) */
  3358. if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
  3359. goto CLEANUP;
  3360. }
  3361. /* x = x - q */
  3362. if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
  3363. goto CLEANUP;
  3364. }
  3365. /* If x < 0, add b**(k+1) to it */
  3366. if (mp_cmp_d (x, 0) == MP_LT) {
  3367. if ((res = mp_set (&q, 1)) != MP_OKAY)
  3368. goto CLEANUP;
  3369. if ((res = mp_lshd (&q, um + 1)) != MP_OKAY)
  3370. goto CLEANUP;
  3371. if ((res = mp_add (x, &q, x)) != MP_OKAY)
  3372. goto CLEANUP;
  3373. }
  3374. /* Back off if it's too big */
  3375. while (mp_cmp (x, m) != MP_LT) {
  3376. if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
  3377. goto CLEANUP;
  3378. }
  3379. }
  3380. CLEANUP:
  3381. mp_clear (&q);
  3382. return res;
  3383. }
  3384. /* reduces a modulo n where n is of the form 2**p - d
  3385. This differs from reduce_2k since "d" can be larger
  3386. than a single digit.
  3387. */
  3388. int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
  3389. {
  3390. mp_int q;
  3391. int p, res;
  3392. if ((res = mp_init(&q)) != MP_OKAY) {
  3393. return res;
  3394. }
  3395. p = mp_count_bits(n);
  3396. top:
  3397. /* q = a/2**p, a = a mod 2**p */
  3398. if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  3399. goto ERR;
  3400. }
  3401. /* q = q * d */
  3402. if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
  3403. goto ERR;
  3404. }
  3405. /* a = a + q */
  3406. if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
  3407. goto ERR;
  3408. }
  3409. if (mp_cmp_mag(a, n) != MP_LT) {
  3410. if ((res = s_mp_sub(a, n, a)) != MP_OKAY) {
  3411. goto ERR;
  3412. }
  3413. goto top;
  3414. }
  3415. ERR:
  3416. mp_clear(&q);
  3417. return res;
  3418. }
  3419. /* determines the setup value */
  3420. int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
  3421. {
  3422. int res;
  3423. mp_int tmp;
  3424. if ((res = mp_init(&tmp)) != MP_OKAY) {
  3425. return res;
  3426. }
  3427. if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
  3428. goto ERR;
  3429. }
  3430. if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
  3431. goto ERR;
  3432. }
  3433. ERR:
  3434. mp_clear(&tmp);
  3435. return res;
  3436. }
  3437. /* multiplies |a| * |b| and does not compute the lower digs digits
  3438. * [meant to get the higher part of the product]
  3439. */
  3440. int s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  3441. {
  3442. mp_int t;
  3443. int res, pa, pb, ix, iy;
  3444. mp_digit u;
  3445. mp_word r;
  3446. mp_digit tmpx, *tmpt, *tmpy;
  3447. /* can we use the fast multiplier? */
  3448. #ifdef BN_FAST_S_MP_MUL_HIGH_DIGS_C
  3449. if (((a->used + b->used + 1) < (int)MP_WARRAY)
  3450. && MIN (a->used, b->used) <
  3451. (1L << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  3452. return fast_s_mp_mul_high_digs (a, b, c, digs);
  3453. }
  3454. #endif
  3455. if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
  3456. return res;
  3457. }
  3458. t.used = a->used + b->used + 1;
  3459. pa = a->used;
  3460. pb = b->used;
  3461. for (ix = 0; ix < pa && a->dp; ix++) {
  3462. /* clear the carry */
  3463. u = 0;
  3464. /* left hand side of A[ix] * B[iy] */
  3465. tmpx = a->dp[ix];
  3466. /* alias to the address of where the digits will be stored */
  3467. tmpt = &(t.dp[digs]);
  3468. /* alias for where to read the right hand side from */
  3469. tmpy = b->dp + (digs - ix);
  3470. for (iy = digs - ix; iy < pb; iy++) {
  3471. /* calculate the double precision result */
  3472. r = ((mp_word)*tmpt) +
  3473. ((mp_word)tmpx) * ((mp_word)*tmpy++) +
  3474. ((mp_word) u);
  3475. /* get the lower part */
  3476. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  3477. /* carry the carry */
  3478. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  3479. }
  3480. *tmpt = u;
  3481. }
  3482. mp_clamp (&t);
  3483. mp_exch (&t, c);
  3484. mp_clear (&t);
  3485. return MP_OKAY;
  3486. }
  3487. /* this is a modified version of fast_s_mul_digs that only produces
  3488. * output digits *above* digs. See the comments for fast_s_mul_digs
  3489. * to see how it works.
  3490. *
  3491. * This is used in the Barrett reduction since for one of the multiplications
  3492. * only the higher digits were needed. This essentially halves the work.
  3493. *
  3494. * Based on Algorithm 14.12 on pp.595 of HAC.
  3495. */
  3496. int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  3497. {
  3498. int olduse, res, pa, ix, iz;
  3499. #ifdef WOLFSSL_SMALL_STACK
  3500. mp_digit* W; /* uses dynamic memory and slower */
  3501. #else
  3502. mp_digit W[MP_WARRAY];
  3503. #endif
  3504. mp_word _W;
  3505. if (a->dp == NULL) { /* JRB, avoid reading uninitialized values */
  3506. return MP_VAL;
  3507. }
  3508. /* grow the destination as required */
  3509. pa = a->used + b->used;
  3510. if (c->alloc < pa) {
  3511. if ((res = mp_grow (c, pa)) != MP_OKAY) {
  3512. return res;
  3513. }
  3514. }
  3515. if (pa > (int)MP_WARRAY)
  3516. return MP_RANGE; /* TAO range check */
  3517. #ifdef WOLFSSL_SMALL_STACK
  3518. W = (mp_digit*)XMALLOC(sizeof(mp_digit) * pa, NULL, DYNAMIC_TYPE_BIGINT);
  3519. if (W == NULL)
  3520. return MP_MEM;
  3521. #endif
  3522. /* number of output digits to produce */
  3523. _W = 0;
  3524. for (ix = digs; ix < pa; ix++) { /* JRB, have a->dp check at top of function*/
  3525. int tx, ty, iy;
  3526. mp_digit *tmpx, *tmpy;
  3527. /* get offsets into the two bignums */
  3528. ty = MIN(b->used-1, ix);
  3529. tx = ix - ty;
  3530. /* setup temp aliases */
  3531. tmpx = a->dp + tx;
  3532. tmpy = b->dp + ty;
  3533. /* this is the number of times the loop will iterate, essentially its
  3534. while (tx++ < a->used && ty-- >= 0) { ... }
  3535. */
  3536. iy = MIN(a->used-tx, ty+1);
  3537. /* execute loop */
  3538. for (iz = 0; iz < iy; iz++) {
  3539. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  3540. }
  3541. /* store term */
  3542. W[ix] = (mp_digit)(((mp_digit)_W) & MP_MASK);
  3543. /* make next carry */
  3544. _W = _W >> ((mp_word)DIGIT_BIT);
  3545. }
  3546. /* setup dest */
  3547. olduse = c->used;
  3548. c->used = pa;
  3549. {
  3550. mp_digit *tmpc;
  3551. tmpc = c->dp + digs;
  3552. for (ix = digs; ix < pa; ix++) { /* TAO, <= could potentially overwrite */
  3553. /* now extract the previous digit [below the carry] */
  3554. *tmpc++ = W[ix];
  3555. }
  3556. /* clear unused digits [that existed in the old copy of c] */
  3557. for (; ix < olduse; ix++) {
  3558. *tmpc++ = 0;
  3559. }
  3560. }
  3561. mp_clamp (c);
  3562. #ifdef WOLFSSL_SMALL_STACK
  3563. XFREE(W, NULL, DYNAMIC_TYPE_BIGINT);
  3564. #endif
  3565. return MP_OKAY;
  3566. }
  3567. #ifndef MP_SET_CHUNK_BITS
  3568. #define MP_SET_CHUNK_BITS 4
  3569. #endif
  3570. int mp_set_int (mp_int * a, unsigned long b)
  3571. {
  3572. int x, res;
  3573. /* use direct mp_set if b is less than mp_digit max */
  3574. if (b < MP_DIGIT_MAX) {
  3575. return mp_set (a, (mp_digit)b);
  3576. }
  3577. mp_zero (a);
  3578. /* set chunk bits at a time */
  3579. for (x = 0; x < (int)(sizeof(b) * 8) / MP_SET_CHUNK_BITS; x++) {
  3580. /* shift the number up chunk bits */
  3581. if ((res = mp_mul_2d (a, MP_SET_CHUNK_BITS, a)) != MP_OKAY) {
  3582. return res;
  3583. }
  3584. /* OR in the top bits of the source */
  3585. a->dp[0] |= (b >> ((sizeof(b) * 8) - MP_SET_CHUNK_BITS)) &
  3586. ((1 << MP_SET_CHUNK_BITS) - 1);
  3587. /* shift the source up to the next chunk bits */
  3588. b <<= MP_SET_CHUNK_BITS;
  3589. /* ensure that digits are not clamped off */
  3590. a->used += 1;
  3591. }
  3592. mp_clamp (a);
  3593. return MP_OKAY;
  3594. }
  3595. #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_ECC) || !defined(NO_RSA) || \
  3596. !defined(NO_DSA) | !defined(NO_DH)
  3597. /* c = a * a (mod b) */
  3598. int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c)
  3599. {
  3600. int res;
  3601. mp_int t;
  3602. if ((res = mp_init (&t)) != MP_OKAY) {
  3603. return res;
  3604. }
  3605. if ((res = mp_sqr (a, &t)) != MP_OKAY) {
  3606. mp_clear (&t);
  3607. return res;
  3608. }
  3609. res = mp_mod (&t, b, c);
  3610. mp_clear (&t);
  3611. return res;
  3612. }
  3613. #endif
  3614. #if defined(HAVE_ECC) || !defined(NO_PWDBASED) || defined(WOLFSSL_SNIFFER) || \
  3615. defined(WOLFSSL_HAVE_WOLFSCEP) || defined(WOLFSSL_KEY_GEN) || \
  3616. defined(OPENSSL_EXTRA) || defined(WC_RSA_BLINDING) || \
  3617. (!defined(NO_RSA) && !defined(NO_RSA_BOUNDS_CHECK))
  3618. /* single digit addition */
  3619. int mp_add_d (mp_int* a, mp_digit b, mp_int* c) /* //NOLINT(misc-no-recursion) */
  3620. {
  3621. int res, ix, oldused;
  3622. mp_digit *tmpa, *tmpc, mu;
  3623. if (b > MP_DIGIT_MAX) return MP_VAL;
  3624. /* grow c as required */
  3625. if (c->alloc < a->used + 1) {
  3626. if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
  3627. return res;
  3628. }
  3629. }
  3630. /* if a is negative and |a| >= b, call c = |a| - b */
  3631. if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) {
  3632. /* temporarily fix sign of a */
  3633. a->sign = MP_ZPOS;
  3634. /* c = |a| - b */
  3635. res = mp_sub_d(a, b, c);
  3636. /* fix sign */
  3637. a->sign = c->sign = MP_NEG;
  3638. /* clamp */
  3639. mp_clamp(c);
  3640. return res;
  3641. }
  3642. /* old number of used digits in c */
  3643. oldused = c->used;
  3644. /* sign always positive */
  3645. c->sign = MP_ZPOS;
  3646. /* source alias */
  3647. tmpa = a->dp;
  3648. /* destination alias */
  3649. tmpc = c->dp;
  3650. if (tmpa == NULL || tmpc == NULL) {
  3651. return MP_MEM;
  3652. }
  3653. /* if a is positive */
  3654. if (a->sign == MP_ZPOS) {
  3655. /* add digit, after this we're propagating
  3656. * the carry.
  3657. */
  3658. *tmpc = *tmpa++ + b;
  3659. mu = *tmpc >> DIGIT_BIT;
  3660. *tmpc++ &= MP_MASK;
  3661. /* now handle rest of the digits */
  3662. for (ix = 1; ix < a->used; ix++) {
  3663. *tmpc = *tmpa++ + mu;
  3664. mu = *tmpc >> DIGIT_BIT;
  3665. *tmpc++ &= MP_MASK;
  3666. }
  3667. /* set final carry */
  3668. if (ix < c->alloc) {
  3669. ix++;
  3670. *tmpc++ = mu;
  3671. }
  3672. /* setup size */
  3673. c->used = a->used + 1;
  3674. } else {
  3675. /* a was negative and |a| < b */
  3676. c->used = 1;
  3677. /* the result is a single digit */
  3678. if (a->used == 1) {
  3679. *tmpc++ = b - a->dp[0];
  3680. } else {
  3681. *tmpc++ = b;
  3682. }
  3683. /* setup count so the clearing of oldused
  3684. * can fall through correctly
  3685. */
  3686. ix = 1;
  3687. }
  3688. /* now zero to oldused */
  3689. while (ix++ < oldused) {
  3690. *tmpc++ = 0;
  3691. }
  3692. mp_clamp(c);
  3693. return MP_OKAY;
  3694. }
  3695. /* single digit subtraction */
  3696. int mp_sub_d (mp_int * a, mp_digit b, mp_int * c) /* //NOLINT(misc-no-recursion) */
  3697. {
  3698. mp_digit *tmpa, *tmpc, mu;
  3699. int res, ix, oldused;
  3700. if (b > MP_MASK) return MP_VAL;
  3701. /* grow c as required */
  3702. if (c->alloc < a->used + 1) {
  3703. if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
  3704. return res;
  3705. }
  3706. }
  3707. /* if a is negative just do an unsigned
  3708. * addition [with fudged signs]
  3709. */
  3710. if (a->sign == MP_NEG) {
  3711. a->sign = MP_ZPOS;
  3712. res = mp_add_d(a, b, c);
  3713. a->sign = c->sign = MP_NEG;
  3714. /* clamp */
  3715. mp_clamp(c);
  3716. return res;
  3717. }
  3718. /* setup regs */
  3719. oldused = c->used;
  3720. tmpa = a->dp;
  3721. tmpc = c->dp;
  3722. if (tmpa == NULL || tmpc == NULL) {
  3723. return MP_MEM;
  3724. }
  3725. /* if a <= b simply fix the single digit */
  3726. if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) {
  3727. if (a->used == 1) {
  3728. *tmpc++ = b - *tmpa;
  3729. } else {
  3730. *tmpc++ = b;
  3731. }
  3732. ix = 1;
  3733. /* negative/1digit */
  3734. c->sign = MP_NEG;
  3735. c->used = 1;
  3736. } else {
  3737. /* positive/size */
  3738. c->sign = MP_ZPOS;
  3739. c->used = a->used;
  3740. /* subtract first digit */
  3741. *tmpc = *tmpa++ - b;
  3742. mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
  3743. *tmpc++ &= MP_MASK;
  3744. /* handle rest of the digits */
  3745. for (ix = 1; ix < a->used; ix++) {
  3746. *tmpc = *tmpa++ - mu;
  3747. mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
  3748. *tmpc++ &= MP_MASK;
  3749. }
  3750. }
  3751. /* zero excess digits */
  3752. while (ix++ < oldused) {
  3753. *tmpc++ = 0;
  3754. }
  3755. mp_clamp(c);
  3756. return MP_OKAY;
  3757. }
  3758. #endif /* defined(HAVE_ECC) || !defined(NO_PWDBASED) */
  3759. #if defined(WOLFSSL_KEY_GEN) || defined(HAVE_COMP_KEY) || defined(HAVE_ECC) || \
  3760. defined(DEBUG_WOLFSSL) || !defined(NO_RSA) || !defined(NO_DSA) || \
  3761. !defined(NO_DH) || defined(WC_MP_TO_RADIX)
  3762. static const int lnz[16] = {
  3763. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
  3764. };
  3765. /* Counts the number of lsbs which are zero before the first zero bit */
  3766. int mp_cnt_lsb(mp_int *a)
  3767. {
  3768. int x;
  3769. mp_digit q = 0, qq;
  3770. /* easy out */
  3771. if (mp_iszero(a) == MP_YES) {
  3772. return 0;
  3773. }
  3774. /* scan lower digits until non-zero */
  3775. for (x = 0; x < a->used && a->dp[x] == 0; x++) {}
  3776. if (a->dp)
  3777. q = a->dp[x];
  3778. x *= DIGIT_BIT;
  3779. /* now scan this digit until a 1 is found */
  3780. if ((q & 1) == 0) {
  3781. do {
  3782. qq = q & 15;
  3783. x += lnz[qq];
  3784. q >>= 4;
  3785. } while (qq == 0);
  3786. }
  3787. return x;
  3788. }
  3789. static int s_is_power_of_two(mp_digit b, int *p)
  3790. {
  3791. int x;
  3792. /* fast return if no power of two */
  3793. if ((b==0) || (b & (b-1))) {
  3794. return 0;
  3795. }
  3796. for (x = 0; x < DIGIT_BIT; x++) {
  3797. if (b == (((mp_digit)1)<<x)) {
  3798. *p = x;
  3799. return 1;
  3800. }
  3801. }
  3802. return 0;
  3803. }
  3804. /* single digit division (based on routine from MPI) */
  3805. static int mp_div_d (mp_int * a, mp_digit b, mp_int * c, mp_digit * d)
  3806. {
  3807. mp_int q;
  3808. mp_word w;
  3809. mp_digit t;
  3810. int res = MP_OKAY, ix;
  3811. /* cannot divide by zero */
  3812. if (b == 0) {
  3813. return MP_VAL;
  3814. }
  3815. /* quick outs */
  3816. if (b == 1 || mp_iszero(a) == MP_YES) {
  3817. if (d != NULL) {
  3818. *d = 0;
  3819. }
  3820. if (c != NULL) {
  3821. return mp_copy(a, c);
  3822. }
  3823. return MP_OKAY;
  3824. }
  3825. /* power of two ? */
  3826. if (s_is_power_of_two(b, &ix) == 1) {
  3827. if (d != NULL) {
  3828. *d = a->dp[0] & ((((mp_digit)1)<<ix) - 1);
  3829. }
  3830. if (c != NULL) {
  3831. return mp_div_2d(a, ix, c, NULL);
  3832. }
  3833. return MP_OKAY;
  3834. }
  3835. #ifdef BN_MP_DIV_3_C
  3836. /* three? */
  3837. if (b == 3) {
  3838. return mp_div_3(a, c, d);
  3839. }
  3840. #endif
  3841. /* no easy answer [c'est la vie]. Just division */
  3842. if (c != NULL) {
  3843. if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
  3844. return res;
  3845. }
  3846. q.used = a->used;
  3847. q.sign = a->sign;
  3848. }
  3849. else {
  3850. if ((res = mp_init(&q)) != MP_OKAY) {
  3851. return res;
  3852. }
  3853. }
  3854. w = 0;
  3855. for (ix = a->used - 1; ix >= 0; ix--) {
  3856. w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
  3857. if (w >= b) {
  3858. #ifdef WOLFSSL_LINUXKM
  3859. t = (mp_digit)w;
  3860. /* Linux kernel macro for in-place 64 bit integer division. */
  3861. do_div(t, b);
  3862. #else
  3863. t = (mp_digit)(w / b);
  3864. #endif
  3865. w -= ((mp_word)t) * ((mp_word)b);
  3866. } else {
  3867. t = 0;
  3868. }
  3869. if (c != NULL)
  3870. q.dp[ix] = (mp_digit)t;
  3871. }
  3872. if (d != NULL) {
  3873. *d = (mp_digit)w;
  3874. }
  3875. if (c != NULL) {
  3876. mp_clamp(&q);
  3877. mp_exch(&q, c);
  3878. }
  3879. mp_clear(&q);
  3880. return res;
  3881. }
  3882. int mp_mod_d (mp_int * a, mp_digit b, mp_digit * c)
  3883. {
  3884. return mp_div_d(a, b, NULL, c);
  3885. }
  3886. #endif /* WOLFSSL_KEY_GEN || HAVE_COMP_KEY || HAVE_ECC || DEBUG_WOLFSSL */
  3887. #if (defined(WOLFSSL_KEY_GEN) && !defined(NO_RSA)) || !defined(NO_DH) || !defined(NO_DSA)
  3888. const FLASH_QUALIFIER mp_digit ltm_prime_tab[PRIME_SIZE] = {
  3889. 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
  3890. 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
  3891. 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
  3892. 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F,
  3893. #ifndef MP_8BIT
  3894. 0x0083,
  3895. 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
  3896. 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
  3897. 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
  3898. 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
  3899. 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
  3900. 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
  3901. 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
  3902. 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
  3903. 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
  3904. 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
  3905. 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
  3906. 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
  3907. 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
  3908. 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
  3909. 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
  3910. 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
  3911. 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
  3912. 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
  3913. 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
  3914. 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
  3915. 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
  3916. 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
  3917. 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
  3918. 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
  3919. 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
  3920. 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
  3921. 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
  3922. 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
  3923. #endif
  3924. };
  3925. /* Miller-Rabin test of "a" to the base of "b" as described in
  3926. * HAC pp. 139 Algorithm 4.24
  3927. *
  3928. * Sets result to 0 if definitely composite or 1 if probably prime.
  3929. * Randomly the chance of error is no more than 1/4 and often
  3930. * very much lower.
  3931. */
  3932. static int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
  3933. {
  3934. mp_int n1, y, r;
  3935. int s, j, err;
  3936. /* default */
  3937. *result = MP_NO;
  3938. /* ensure b > 1 */
  3939. if (mp_cmp_d(b, 1) != MP_GT) {
  3940. return MP_VAL;
  3941. }
  3942. /* get n1 = a - 1 */
  3943. if ((err = mp_init_copy (&n1, a)) != MP_OKAY) {
  3944. return err;
  3945. }
  3946. if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) {
  3947. goto LBL_N1;
  3948. }
  3949. /* set 2**s * r = n1 */
  3950. if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) {
  3951. goto LBL_N1;
  3952. }
  3953. /* count the number of least significant bits
  3954. * which are zero
  3955. */
  3956. s = mp_cnt_lsb(&r);
  3957. /* now divide n - 1 by 2**s */
  3958. if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) {
  3959. goto LBL_R;
  3960. }
  3961. /* compute y = b**r mod a */
  3962. if ((err = mp_init (&y)) != MP_OKAY) {
  3963. goto LBL_R;
  3964. }
  3965. #if defined(WOLFSSL_HAVE_SP_RSA) || defined(WOLFSSL_HAVE_SP_DH)
  3966. #ifndef WOLFSSL_SP_NO_2048
  3967. if (mp_count_bits(a) == 1024 && mp_isodd(a))
  3968. err = sp_ModExp_1024(b, &r, a, &y);
  3969. else if (mp_count_bits(a) == 2048 && mp_isodd(a))
  3970. err = sp_ModExp_2048(b, &r, a, &y);
  3971. else
  3972. #endif
  3973. #ifndef WOLFSSL_SP_NO_3072
  3974. if (mp_count_bits(a) == 1536 && mp_isodd(a))
  3975. err = sp_ModExp_1536(b, &r, a, &y);
  3976. else if (mp_count_bits(a) == 3072 && mp_isodd(a))
  3977. err = sp_ModExp_3072(b, &r, a, &y);
  3978. else
  3979. #endif
  3980. #ifdef WOLFSSL_SP_4096
  3981. if (mp_count_bits(a) == 4096 && mp_isodd(a))
  3982. err = sp_ModExp_4096(b, &r, a, &y);
  3983. else
  3984. #endif
  3985. #endif
  3986. err = mp_exptmod (b, &r, a, &y);
  3987. if (err != MP_OKAY)
  3988. goto LBL_Y;
  3989. /* if y != 1 and y != n1 do */
  3990. if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) {
  3991. j = 1;
  3992. /* while j <= s-1 and y != n1 */
  3993. while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) {
  3994. if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) {
  3995. goto LBL_Y;
  3996. }
  3997. /* if y == 1 then composite */
  3998. if (mp_cmp_d (&y, 1) == MP_EQ) {
  3999. goto LBL_Y;
  4000. }
  4001. ++j;
  4002. }
  4003. /* if y != n1 then composite */
  4004. if (mp_cmp (&y, &n1) != MP_EQ) {
  4005. goto LBL_Y;
  4006. }
  4007. }
  4008. /* probably prime now */
  4009. *result = MP_YES;
  4010. LBL_Y:mp_clear (&y);
  4011. LBL_R:mp_clear (&r);
  4012. LBL_N1:mp_clear (&n1);
  4013. return err;
  4014. }
  4015. /* determines if an integers is divisible by one
  4016. * of the first PRIME_SIZE primes or not
  4017. *
  4018. * sets result to 0 if not, 1 if yes
  4019. */
  4020. static int mp_prime_is_divisible (mp_int * a, int *result)
  4021. {
  4022. int err, ix;
  4023. mp_digit res;
  4024. /* default to not */
  4025. *result = MP_NO;
  4026. for (ix = 0; ix < PRIME_SIZE; ix++) {
  4027. /* what is a mod LBL_prime_tab[ix] */
  4028. if ((err = mp_mod_d (a, ltm_prime_tab[ix], &res)) != MP_OKAY) {
  4029. return err;
  4030. }
  4031. /* is the residue zero? */
  4032. if (res == 0) {
  4033. *result = MP_YES;
  4034. return MP_OKAY;
  4035. }
  4036. }
  4037. return MP_OKAY;
  4038. }
  4039. /*
  4040. * Sets result to 1 if probably prime, 0 otherwise
  4041. */
  4042. int mp_prime_is_prime (mp_int * a, int t, int *result)
  4043. {
  4044. mp_int b;
  4045. int ix, err, res;
  4046. /* default to no */
  4047. *result = MP_NO;
  4048. /* valid value of t? */
  4049. if (t <= 0 || t > PRIME_SIZE) {
  4050. return MP_VAL;
  4051. }
  4052. if (mp_isone(a)) {
  4053. *result = MP_NO;
  4054. return MP_OKAY;
  4055. }
  4056. /* is the input equal to one of the primes in the table? */
  4057. for (ix = 0; ix < PRIME_SIZE; ix++) {
  4058. if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
  4059. *result = MP_YES;
  4060. return MP_OKAY;
  4061. }
  4062. }
  4063. /* first perform trial division */
  4064. if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
  4065. return err;
  4066. }
  4067. /* return if it was trivially divisible */
  4068. if (res == MP_YES) {
  4069. return MP_OKAY;
  4070. }
  4071. /* now perform the miller-rabin rounds */
  4072. if ((err = mp_init (&b)) != MP_OKAY) {
  4073. return err;
  4074. }
  4075. for (ix = 0; ix < t; ix++) {
  4076. /* set the prime */
  4077. if ((err = mp_set (&b, ltm_prime_tab[ix])) != MP_OKAY) {
  4078. goto LBL_B;
  4079. }
  4080. if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
  4081. goto LBL_B;
  4082. }
  4083. if (res == MP_NO) {
  4084. goto LBL_B;
  4085. }
  4086. }
  4087. /* passed the test */
  4088. *result = MP_YES;
  4089. LBL_B:mp_clear (&b);
  4090. return err;
  4091. }
  4092. /*
  4093. * Sets result to 1 if probably prime, 0 otherwise
  4094. */
  4095. int mp_prime_is_prime_ex (mp_int * a, int t, int *result, WC_RNG *rng)
  4096. {
  4097. mp_int b, c;
  4098. int ix, err, res;
  4099. byte* base = NULL;
  4100. word32 bitSz = 0;
  4101. word32 baseSz = 0;
  4102. /* default to no */
  4103. *result = MP_NO;
  4104. /* valid value of t? */
  4105. if (t <= 0 || t > PRIME_SIZE) {
  4106. return MP_VAL;
  4107. }
  4108. if (a->sign == MP_NEG) {
  4109. return MP_VAL;
  4110. }
  4111. if (mp_isone(a)) {
  4112. *result = MP_NO;
  4113. return MP_OKAY;
  4114. }
  4115. /* is the input equal to one of the primes in the table? */
  4116. for (ix = 0; ix < PRIME_SIZE; ix++) {
  4117. if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
  4118. *result = MP_YES;
  4119. return MP_OKAY;
  4120. }
  4121. }
  4122. /* first perform trial division */
  4123. if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
  4124. return err;
  4125. }
  4126. /* return if it was trivially divisible */
  4127. if (res == MP_YES) {
  4128. return MP_OKAY;
  4129. }
  4130. /* now perform the miller-rabin rounds */
  4131. if ((err = mp_init (&b)) != MP_OKAY) {
  4132. return err;
  4133. }
  4134. if ((err = mp_init (&c)) != MP_OKAY) {
  4135. mp_clear(&b);
  4136. return err;
  4137. }
  4138. bitSz = mp_count_bits(a);
  4139. baseSz = (bitSz / 8) + ((bitSz % 8) ? 1 : 0);
  4140. bitSz %= 8;
  4141. base = (byte*)XMALLOC(baseSz, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4142. if (base == NULL) {
  4143. err = MP_MEM;
  4144. goto LBL_B;
  4145. }
  4146. if ((err = mp_sub_d(a, 2, &c)) != MP_OKAY) {
  4147. goto LBL_B;
  4148. }
  4149. /* now do a miller rabin with up to t random numbers, this should
  4150. * give a (1/4)^t chance of a false prime. */
  4151. for (ix = 0; ix < t; ix++) {
  4152. /* Set a test candidate. */
  4153. if ((err = wc_RNG_GenerateBlock(rng, base, baseSz)) != 0) {
  4154. goto LBL_B;
  4155. }
  4156. /* Clear bits higher than those in a. */
  4157. if (bitSz > 0) {
  4158. base[0] &= (1 << bitSz) - 1;
  4159. }
  4160. if ((err = mp_read_unsigned_bin(&b, base, baseSz)) != MP_OKAY) {
  4161. goto LBL_B;
  4162. }
  4163. if (mp_cmp_d(&b, 2) != MP_GT || mp_cmp(&b, &c) != MP_LT) {
  4164. ix--;
  4165. continue;
  4166. }
  4167. if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
  4168. goto LBL_B;
  4169. }
  4170. if (res == MP_NO) {
  4171. goto LBL_B;
  4172. }
  4173. }
  4174. /* passed the test */
  4175. *result = MP_YES;
  4176. LBL_B:mp_clear (&b);
  4177. mp_clear (&c);
  4178. XFREE(base, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4179. return err;
  4180. }
  4181. #endif /* (WOLFSSL_KEY_GEN && !NO_RSA) || !NO_DH || !NO_DSA */
  4182. #if defined(WOLFSSL_KEY_GEN) && (!defined(NO_DH) || !defined(NO_DSA))
  4183. static const int USE_BBS = 1;
  4184. int mp_rand_prime(mp_int* a, int len, WC_RNG* rng, void* heap)
  4185. {
  4186. int err, res, type;
  4187. byte* buf;
  4188. if (a == NULL || rng == NULL)
  4189. return MP_VAL;
  4190. /* get type */
  4191. if (len < 0) {
  4192. type = USE_BBS;
  4193. len = -len;
  4194. } else {
  4195. type = 0;
  4196. }
  4197. /* allow sizes between 2 and 512 bytes for a prime size */
  4198. if (len < 2 || len > 512) {
  4199. return MP_VAL;
  4200. }
  4201. /* allocate buffer to work with */
  4202. buf = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_RSA);
  4203. if (buf == NULL) {
  4204. return MP_MEM;
  4205. }
  4206. XMEMSET(buf, 0, len);
  4207. do {
  4208. #ifdef SHOW_GEN
  4209. printf(".");
  4210. fflush(stdout);
  4211. #endif
  4212. /* generate value */
  4213. err = wc_RNG_GenerateBlock(rng, buf, len);
  4214. if (err != 0) {
  4215. XFREE(buf, heap, DYNAMIC_TYPE_RSA);
  4216. return err;
  4217. }
  4218. /* munge bits */
  4219. buf[0] |= 0x80 | 0x40;
  4220. buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00);
  4221. /* load value */
  4222. if ((err = mp_read_unsigned_bin(a, buf, len)) != MP_OKAY) {
  4223. XFREE(buf, heap, DYNAMIC_TYPE_RSA);
  4224. return err;
  4225. }
  4226. /* test */
  4227. /* Running Miller-Rabin up to 3 times gives us a 2^{-80} chance
  4228. * of a 1024-bit candidate being a false positive, when it is our
  4229. * prime candidate. (Note 4.49 of Handbook of Applied Cryptography.)
  4230. * Using 8 because we've always used 8. */
  4231. if ((err = mp_prime_is_prime_ex(a, 8, &res, rng)) != MP_OKAY) {
  4232. XFREE(buf, heap, DYNAMIC_TYPE_RSA);
  4233. return err;
  4234. }
  4235. } while (res == MP_NO);
  4236. XMEMSET(buf, 0, len);
  4237. XFREE(buf, heap, DYNAMIC_TYPE_RSA);
  4238. return MP_OKAY;
  4239. }
  4240. #endif
  4241. #if defined(WOLFSSL_KEY_GEN)
  4242. /* computes least common multiple as |a*b|/(a, b) */
  4243. int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
  4244. {
  4245. int res;
  4246. mp_int t1, t2;
  4247. /* LCM of 0 and any number is undefined as 0 is not in the set of values
  4248. * being used. */
  4249. if (mp_iszero (a) == MP_YES || mp_iszero (b) == MP_YES) {
  4250. return MP_VAL;
  4251. }
  4252. if ((res = mp_init_multi (&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  4253. return res;
  4254. }
  4255. /* t1 = get the GCD of the two inputs */
  4256. if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) {
  4257. goto LBL_T;
  4258. }
  4259. /* divide the smallest by the GCD */
  4260. if (mp_cmp_mag(a, b) == MP_LT) {
  4261. /* store quotient in t2 such that t2 * b is the LCM */
  4262. if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
  4263. goto LBL_T;
  4264. }
  4265. res = mp_mul(b, &t2, c);
  4266. } else {
  4267. /* store quotient in t2 such that t2 * a is the LCM */
  4268. if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
  4269. goto LBL_T;
  4270. }
  4271. res = mp_mul(a, &t2, c);
  4272. }
  4273. /* fix the sign to positive */
  4274. c->sign = MP_ZPOS;
  4275. LBL_T:
  4276. mp_clear(&t1);
  4277. mp_clear(&t2);
  4278. return res;
  4279. }
  4280. /* Greatest Common Divisor using the binary method */
  4281. int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
  4282. {
  4283. mp_int u, v;
  4284. int k, u_lsb, v_lsb, res;
  4285. /* either zero than gcd is the largest */
  4286. if (mp_iszero (a) == MP_YES) {
  4287. /* GCD of 0 and 0 is undefined as all integers divide 0. */
  4288. if (mp_iszero (b) == MP_YES) {
  4289. return MP_VAL;
  4290. }
  4291. return mp_abs (b, c);
  4292. }
  4293. if (mp_iszero (b) == MP_YES) {
  4294. return mp_abs (a, c);
  4295. }
  4296. /* get copies of a and b we can modify */
  4297. if ((res = mp_init_copy (&u, a)) != MP_OKAY) {
  4298. return res;
  4299. }
  4300. if ((res = mp_init_copy (&v, b)) != MP_OKAY) {
  4301. goto LBL_U;
  4302. }
  4303. /* must be positive for the remainder of the algorithm */
  4304. u.sign = v.sign = MP_ZPOS;
  4305. /* B1. Find the common power of two for u and v */
  4306. u_lsb = mp_cnt_lsb(&u);
  4307. v_lsb = mp_cnt_lsb(&v);
  4308. k = MIN(u_lsb, v_lsb);
  4309. if (k > 0) {
  4310. /* divide the power of two out */
  4311. if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
  4312. goto LBL_V;
  4313. }
  4314. if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
  4315. goto LBL_V;
  4316. }
  4317. }
  4318. /* divide any remaining factors of two out */
  4319. if (u_lsb != k) {
  4320. if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
  4321. goto LBL_V;
  4322. }
  4323. }
  4324. if (v_lsb != k) {
  4325. if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
  4326. goto LBL_V;
  4327. }
  4328. }
  4329. while (mp_iszero(&v) == MP_NO) {
  4330. /* make sure v is the largest */
  4331. if (mp_cmp_mag(&u, &v) == MP_GT) {
  4332. /* swap u and v to make sure v is >= u */
  4333. mp_exch(&u, &v);
  4334. }
  4335. /* subtract smallest from largest */
  4336. if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
  4337. goto LBL_V;
  4338. }
  4339. /* Divide out all factors of two */
  4340. if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
  4341. goto LBL_V;
  4342. }
  4343. }
  4344. /* multiply by 2**k which we divided out at the beginning */
  4345. if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) {
  4346. goto LBL_V;
  4347. }
  4348. c->sign = MP_ZPOS;
  4349. res = MP_OKAY;
  4350. LBL_V:mp_clear (&v);
  4351. LBL_U:mp_clear (&u);
  4352. return res;
  4353. }
  4354. #endif /* WOLFSSL_KEY_GEN */
  4355. #if !defined(NO_DSA) || defined(HAVE_ECC) || defined(WOLFSSL_KEY_GEN) || \
  4356. defined(HAVE_COMP_KEY) || defined(WOLFSSL_DEBUG_MATH) || \
  4357. defined(DEBUG_WOLFSSL) || defined(OPENSSL_EXTRA) || defined(WC_MP_TO_RADIX)
  4358. /* chars used in radix conversions */
  4359. const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  4360. "abcdefghijklmnopqrstuvwxyz+/";
  4361. #endif
  4362. #if !defined(NO_DSA) || defined(HAVE_ECC) || defined(OPENSSL_EXTRA)
  4363. /* read a string [ASCII] in a given radix */
  4364. int mp_read_radix (mp_int * a, const char *str, int radix)
  4365. {
  4366. int y, res, neg;
  4367. char ch;
  4368. /* zero the digit bignum */
  4369. mp_zero(a);
  4370. /* make sure the radix is ok */
  4371. if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
  4372. return MP_VAL;
  4373. }
  4374. /* if the leading digit is a
  4375. * minus set the sign to negative.
  4376. */
  4377. if (*str == '-') {
  4378. ++str;
  4379. neg = MP_NEG;
  4380. } else {
  4381. neg = MP_ZPOS;
  4382. }
  4383. /* set the integer to the default of zero */
  4384. mp_zero (a);
  4385. /* process each digit of the string */
  4386. while (*str != '\0') {
  4387. /* if the radix <= 36 the conversion is case insensitive
  4388. * this allows numbers like 1AB and 1ab to represent the same value
  4389. * [e.g. in hex]
  4390. */
  4391. ch = (radix <= 36) ? (char)XTOUPPER((unsigned char)*str) : *str;
  4392. for (y = 0; y < 64; y++) {
  4393. if (ch == mp_s_rmap[y]) {
  4394. break;
  4395. }
  4396. }
  4397. /* if the char was found in the map
  4398. * and is less than the given radix add it
  4399. * to the number, otherwise exit the loop.
  4400. */
  4401. if (y < radix) {
  4402. if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
  4403. mp_zero(a);
  4404. return res;
  4405. }
  4406. if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
  4407. mp_zero(a);
  4408. return res;
  4409. }
  4410. } else {
  4411. break;
  4412. }
  4413. ++str;
  4414. }
  4415. /* if digit in isn't null term, then invalid character was found */
  4416. if (*str != '\0') {
  4417. mp_zero (a);
  4418. return MP_VAL;
  4419. }
  4420. /* set the sign only if a != 0 */
  4421. if (mp_iszero(a) != MP_YES) {
  4422. a->sign = neg;
  4423. }
  4424. return MP_OKAY;
  4425. }
  4426. #endif /* !defined(NO_DSA) || defined(HAVE_ECC) */
  4427. #ifdef WC_MP_TO_RADIX
  4428. /* returns size of ASCII representation */
  4429. int mp_radix_size (mp_int *a, int radix, int *size)
  4430. {
  4431. int res, digs;
  4432. mp_int t;
  4433. mp_digit d;
  4434. *size = 0;
  4435. /* special case for binary */
  4436. if (radix == MP_RADIX_BIN) {
  4437. *size = mp_count_bits(a);
  4438. if (*size == 0)
  4439. *size = 1;
  4440. *size += (a->sign == MP_NEG ? 1 : 0) + 1; /* "-" sign + null term */
  4441. return MP_OKAY;
  4442. }
  4443. /* make sure the radix is in range */
  4444. if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
  4445. return MP_VAL;
  4446. }
  4447. if (mp_iszero(a) == MP_YES) {
  4448. #ifndef WC_DISABLE_RADIX_ZERO_PAD
  4449. if (radix == 16)
  4450. *size = 3;
  4451. else
  4452. #endif
  4453. *size = 2;
  4454. return MP_OKAY;
  4455. }
  4456. /* digs is the digit count */
  4457. digs = 0;
  4458. /* init a copy of the input */
  4459. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  4460. return res;
  4461. }
  4462. /* force temp to positive */
  4463. t.sign = MP_ZPOS;
  4464. /* fetch out all of the digits */
  4465. while (mp_iszero (&t) == MP_NO) {
  4466. if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
  4467. mp_clear (&t);
  4468. return res;
  4469. }
  4470. ++digs;
  4471. }
  4472. mp_clear (&t);
  4473. #ifndef WC_DISABLE_RADIX_ZERO_PAD
  4474. /* For hexadecimal output, add zero padding when number of digits is odd */
  4475. if ((digs & 1) && (radix == 16)) {
  4476. ++digs;
  4477. }
  4478. #endif
  4479. /* if it's negative add one for the sign */
  4480. if (a->sign == MP_NEG) {
  4481. ++digs;
  4482. }
  4483. /* return digs + 1, the 1 is for the NULL byte that would be required. */
  4484. *size = digs + 1;
  4485. return MP_OKAY;
  4486. }
  4487. /* stores a bignum as a ASCII string in a given radix (2..64) */
  4488. int mp_toradix (mp_int *a, char *str, int radix)
  4489. {
  4490. int res, digs;
  4491. mp_int t;
  4492. mp_digit d;
  4493. char *_s = str;
  4494. /* check range of the radix */
  4495. if (radix < MP_RADIX_BIN || radix > MP_RADIX_MAX) {
  4496. return MP_VAL;
  4497. }
  4498. /* quick out if its zero */
  4499. if (mp_iszero(a) == MP_YES) {
  4500. #ifndef WC_DISABLE_RADIX_ZERO_PAD
  4501. if (radix == 16) {
  4502. *str++ = '0';
  4503. }
  4504. #endif
  4505. *str++ = '0';
  4506. *str = '\0';
  4507. return MP_OKAY;
  4508. }
  4509. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  4510. return res;
  4511. }
  4512. /* if it is negative output a - */
  4513. if (t.sign == MP_NEG) {
  4514. ++_s;
  4515. *str++ = '-';
  4516. t.sign = MP_ZPOS;
  4517. }
  4518. digs = 0;
  4519. while (mp_iszero (&t) == MP_NO) {
  4520. if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
  4521. mp_clear (&t);
  4522. return res;
  4523. }
  4524. *str++ = mp_s_rmap[d];
  4525. ++digs;
  4526. }
  4527. #ifndef WC_DISABLE_RADIX_ZERO_PAD
  4528. /* For hexadecimal output, add zero padding when number of digits is odd */
  4529. if ((digs & 1) && (radix == 16)) {
  4530. *str++ = mp_s_rmap[0];
  4531. ++digs;
  4532. }
  4533. #endif
  4534. /* reverse the digits of the string. In this case _s points
  4535. * to the first digit [excluding the sign] of the number]
  4536. */
  4537. bn_reverse ((unsigned char *)_s, digs);
  4538. /* append a NULL so the string is properly terminated */
  4539. *str = '\0';
  4540. mp_clear (&t);
  4541. return MP_OKAY;
  4542. }
  4543. #ifdef WOLFSSL_DEBUG_MATH
  4544. void mp_dump(const char* desc, mp_int* a, byte verbose)
  4545. {
  4546. char *buffer;
  4547. int size = a->alloc;
  4548. buffer = (char*)XMALLOC(size * sizeof(mp_digit) * 2, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4549. if (buffer == NULL) {
  4550. return;
  4551. }
  4552. printf("%s: ptr=%p, used=%d, sign=%d, size=%d, mpd=%d\n",
  4553. desc, a, a->used, a->sign, size, (int)sizeof(mp_digit));
  4554. mp_tohex(a, buffer);
  4555. printf(" %s\n ", buffer);
  4556. if (verbose) {
  4557. int i;
  4558. for(i=0; i<a->alloc * (int)sizeof(mp_digit); i++) {
  4559. printf("%02x ", *(((byte*)a->dp) + i));
  4560. }
  4561. printf("\n");
  4562. }
  4563. XFREE(buffer, NULL, DYNAMIC_TYPE_TMP_BUFFER);
  4564. }
  4565. #endif /* WOLFSSL_DEBUG_MATH */
  4566. #endif /* WC_MP_TO_RADIX */
  4567. #endif /* WOLFSSL_SP_MATH */
  4568. #endif /* !USE_FAST_MATH && USE_INTEGER_HEAP_MATH */
  4569. #endif /* NO_BIG_INT */