integer.c 121 KB

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