integer.c 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312
  1. /* integer.c
  2. *
  3. * Copyright (C) 2006-2014 wolfSSL Inc.
  4. *
  5. * This file is part of CyaSSL.
  6. *
  7. * CyaSSL 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. * CyaSSL 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-1301, 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. #include <stddef.h>
  26. #include <stdint.h>
  27. #include "integer.h"
  28. void * malloc (int size);
  29. void free (void * mem);
  30. void * remalloc (const void * mem, int size);
  31. void memcpy(void *, void *, size_t);
  32. #define XMALLOC malloc
  33. #define XFREE free
  34. #define XREALLOC internal_realloc
  35. /* Implement realloc by ourselves, since the library doesn't provide realloc.
  36. */
  37. void * internal_realloc(void *old, int old_size, int new_size)
  38. {
  39. void *new = XMALLOC(new_size);
  40. if (new == NULL)
  41. return NULL;
  42. memcpy(new, old, old_size);
  43. XFREE(old);
  44. return new;
  45. }
  46. static inline int toupper (int c)
  47. {
  48. return ('a' <= c && c <= 'z') ? 'A' + (c - 'a') : c;
  49. }
  50. #define XTOUPPER toupper
  51. static void bn_reverse (unsigned char *s, int len);
  52. /* handle up to 6 inits */
  53. int mp_init_multi(mp_int* a, mp_int* b, mp_int* c, mp_int* d, mp_int* e,
  54. mp_int* f)
  55. {
  56. int res = MP_OKAY;
  57. if (a && ((res = mp_init(a)) != MP_OKAY))
  58. return res;
  59. if (b && ((res = mp_init(b)) != MP_OKAY)) {
  60. mp_clear(a);
  61. return res;
  62. }
  63. if (c && ((res = mp_init(c)) != MP_OKAY)) {
  64. mp_clear(a); mp_clear(b);
  65. return res;
  66. }
  67. if (d && ((res = mp_init(d)) != MP_OKAY)) {
  68. mp_clear(a); mp_clear(b); mp_clear(c);
  69. return res;
  70. }
  71. if (e && ((res = mp_init(e)) != MP_OKAY)) {
  72. mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d);
  73. return res;
  74. }
  75. if (f && ((res = mp_init(f)) != MP_OKAY)) {
  76. mp_clear(a); mp_clear(b); mp_clear(c); mp_clear(d); mp_clear(e);
  77. return res;
  78. }
  79. return res;
  80. }
  81. /* init a new mp_int */
  82. int mp_init (mp_int * a)
  83. {
  84. int i;
  85. /* allocate memory required and clear it */
  86. a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC);
  87. if (a->dp == NULL) {
  88. return MP_MEM;
  89. }
  90. /* set the digits to zero */
  91. for (i = 0; i < MP_PREC; i++) {
  92. a->dp[i] = 0;
  93. }
  94. /* set the used to zero, allocated digits to the default precision
  95. * and sign to positive */
  96. a->used = 0;
  97. a->alloc = MP_PREC;
  98. a->sign = MP_ZPOS;
  99. return MP_OKAY;
  100. }
  101. /* clear one (frees) */
  102. void
  103. mp_clear (mp_int * a)
  104. {
  105. int i;
  106. if (a == NULL)
  107. return;
  108. /* only do anything if a hasn't been freed previously */
  109. if (a->dp != NULL) {
  110. /* first zero the digits */
  111. for (i = 0; i < a->used; i++) {
  112. a->dp[i] = 0;
  113. }
  114. /* free ram */
  115. XFREE(a->dp);
  116. /* reset members to make debugging easier */
  117. a->dp = NULL;
  118. a->alloc = a->used = 0;
  119. a->sign = MP_ZPOS;
  120. }
  121. }
  122. /* get the size for an unsigned equivalent */
  123. int mp_unsigned_bin_size (mp_int * a)
  124. {
  125. int size = mp_count_bits (a);
  126. return (size / 8 + ((size & 7) != 0 ? 1 : 0));
  127. }
  128. /* returns the number of bits in an int */
  129. int
  130. mp_count_bits (mp_int * a)
  131. {
  132. int r;
  133. mp_digit q;
  134. /* shortcut */
  135. if (a->used == 0) {
  136. return 0;
  137. }
  138. /* get number of digits and add that */
  139. r = (a->used - 1) * DIGIT_BIT;
  140. /* take the last digit and count the bits in it */
  141. q = a->dp[a->used - 1];
  142. while (q > ((mp_digit) 0)) {
  143. ++r;
  144. q >>= ((mp_digit) 1);
  145. }
  146. return r;
  147. }
  148. int mp_leading_bit (mp_int * a)
  149. {
  150. int bit = 0;
  151. mp_int t;
  152. if (mp_init_copy(&t, a) != MP_OKAY)
  153. return 0;
  154. while (mp_iszero(&t) == 0) {
  155. #ifndef MP_8BIT
  156. bit = (t.dp[0] & 0x80) != 0;
  157. #else
  158. bit = (t.dp[0] | ((t.dp[1] & 0x01) << 7)) & 0x80 != 0;
  159. #endif
  160. if (mp_div_2d (&t, 8, &t, NULL) != MP_OKAY)
  161. break;
  162. }
  163. mp_clear(&t);
  164. return bit;
  165. }
  166. /* store in unsigned [big endian] format */
  167. int mp_to_unsigned_bin (mp_int * a, unsigned char *b)
  168. {
  169. int x, res;
  170. mp_int t;
  171. if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
  172. return res;
  173. }
  174. x = 0;
  175. while (mp_iszero (&t) == 0) {
  176. #ifndef MP_8BIT
  177. b[x++] = (unsigned char) (t.dp[0] & 255);
  178. #else
  179. b[x++] = (unsigned char) (t.dp[0] | ((t.dp[1] & 0x01) << 7));
  180. #endif
  181. if ((res = mp_div_2d (&t, 8, &t, NULL)) != MP_OKAY) {
  182. mp_clear (&t);
  183. return res;
  184. }
  185. }
  186. bn_reverse (b, x);
  187. mp_clear (&t);
  188. return MP_OKAY;
  189. }
  190. /* creates "a" then copies b into it */
  191. int mp_init_copy (mp_int * a, mp_int * b)
  192. {
  193. int res;
  194. if ((res = mp_init (a)) != MP_OKAY) {
  195. return res;
  196. }
  197. return mp_copy (b, a);
  198. }
  199. /* copy, b = a */
  200. int
  201. mp_copy (mp_int * a, mp_int * b)
  202. {
  203. int res, n;
  204. /* if dst == src do nothing */
  205. if (a == b) {
  206. return MP_OKAY;
  207. }
  208. /* grow dest */
  209. if (b->alloc < a->used) {
  210. if ((res = mp_grow (b, a->used)) != MP_OKAY) {
  211. return res;
  212. }
  213. }
  214. /* zero b and copy the parameters over */
  215. {
  216. register mp_digit *tmpa, *tmpb;
  217. /* pointer aliases */
  218. /* source */
  219. tmpa = a->dp;
  220. /* destination */
  221. tmpb = b->dp;
  222. /* copy all the digits */
  223. for (n = 0; n < a->used; n++) {
  224. *tmpb++ = *tmpa++;
  225. }
  226. /* clear high digits */
  227. for (; n < b->used; n++) {
  228. *tmpb++ = 0;
  229. }
  230. }
  231. /* copy used count and sign */
  232. b->used = a->used;
  233. b->sign = a->sign;
  234. return MP_OKAY;
  235. }
  236. /* grow as required */
  237. int mp_grow (mp_int * a, int size)
  238. {
  239. int i;
  240. mp_digit *tmp;
  241. /* if the alloc size is smaller alloc more ram */
  242. if (a->alloc < size) {
  243. /* ensure there are always at least MP_PREC digits extra on top */
  244. size += (MP_PREC * 2) - (size % MP_PREC);
  245. /* reallocate the array a->dp
  246. *
  247. * We store the return in a temporary variable
  248. * in case the operation failed we don't want
  249. * to overwrite the dp member of a.
  250. */
  251. //tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size);
  252. tmp = OPT_CAST(mp_digit) internal_realloc(a->dp,
  253. sizeof (mp_digit) * a->alloc,
  254. sizeof (mp_digit) * size);
  255. if (tmp == NULL) {
  256. /* reallocation failed but "a" is still valid [can be freed] */
  257. return MP_MEM;
  258. }
  259. /* reallocation succeeded so set a->dp */
  260. a->dp = tmp;
  261. /* zero excess digits */
  262. i = a->alloc;
  263. a->alloc = size;
  264. for (; i < a->alloc; i++) {
  265. a->dp[i] = 0;
  266. }
  267. }
  268. return MP_OKAY;
  269. }
  270. /* reverse an array, used for radix code */
  271. void
  272. bn_reverse (unsigned char *s, int len)
  273. {
  274. int ix, iy;
  275. unsigned char t;
  276. ix = 0;
  277. iy = len - 1;
  278. while (ix < iy) {
  279. t = s[ix];
  280. s[ix] = s[iy];
  281. s[iy] = t;
  282. ++ix;
  283. --iy;
  284. }
  285. }
  286. /* shift right by a certain bit count (store quotient in c, optional
  287. remainder in d) */
  288. int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d)
  289. {
  290. int D, res;
  291. mp_int t;
  292. /* if the shift count is <= 0 then we do no work */
  293. if (b <= 0) {
  294. res = mp_copy (a, c);
  295. if (d != NULL) {
  296. mp_zero (d);
  297. }
  298. return res;
  299. }
  300. if ((res = mp_init (&t)) != MP_OKAY) {
  301. return res;
  302. }
  303. /* get the remainder */
  304. if (d != NULL) {
  305. if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) {
  306. mp_clear (&t);
  307. return res;
  308. }
  309. }
  310. /* copy */
  311. if ((res = mp_copy (a, c)) != MP_OKAY) {
  312. mp_clear (&t);
  313. return res;
  314. }
  315. /* shift by as many digits in the bit count */
  316. if (b >= (int)DIGIT_BIT) {
  317. mp_rshd (c, b / DIGIT_BIT);
  318. }
  319. /* shift any bit count < DIGIT_BIT */
  320. D = (b % DIGIT_BIT);
  321. if (D != 0) {
  322. mp_rshb(c, D);
  323. }
  324. mp_clamp (c);
  325. if (d != NULL) {
  326. mp_exch (&t, d);
  327. }
  328. mp_clear (&t);
  329. return MP_OKAY;
  330. }
  331. /* set to zero */
  332. void mp_zero (mp_int * a)
  333. {
  334. int n;
  335. mp_digit *tmp;
  336. a->sign = MP_ZPOS;
  337. a->used = 0;
  338. tmp = a->dp;
  339. for (n = 0; n < a->alloc; n++) {
  340. *tmp++ = 0;
  341. }
  342. }
  343. /* trim unused digits
  344. *
  345. * This is used to ensure that leading zero digits are
  346. * trimed and the leading "used" digit will be non-zero
  347. * Typically very fast. Also fixes the sign if there
  348. * are no more leading digits
  349. */
  350. void
  351. mp_clamp (mp_int * a)
  352. {
  353. /* decrease used while the most significant digit is
  354. * zero.
  355. */
  356. while (a->used > 0 && a->dp[a->used - 1] == 0) {
  357. --(a->used);
  358. }
  359. /* reset the sign flag if used == 0 */
  360. if (a->used == 0) {
  361. a->sign = MP_ZPOS;
  362. }
  363. }
  364. /* swap the elements of two integers, for cases where you can't simply swap the
  365. * mp_int pointers around
  366. */
  367. void
  368. mp_exch (mp_int * a, mp_int * b)
  369. {
  370. mp_int t;
  371. t = *a;
  372. *a = *b;
  373. *b = t;
  374. }
  375. /* shift right a certain number of bits */
  376. void mp_rshb (mp_int *c, int x)
  377. {
  378. register mp_digit *tmpc, mask, shift;
  379. mp_digit r, rr;
  380. mp_digit D = x;
  381. /* mask */
  382. mask = (((mp_digit)1) << D) - 1;
  383. /* shift for lsb */
  384. shift = DIGIT_BIT - D;
  385. /* alias */
  386. tmpc = c->dp + (c->used - 1);
  387. /* carry */
  388. r = 0;
  389. for (x = c->used - 1; x >= 0; x--) {
  390. /* get the lower bits of this word in a temp */
  391. rr = *tmpc & mask;
  392. /* shift the current word and mix in the carry bits from previous word */
  393. *tmpc = (*tmpc >> D) | (r << shift);
  394. --tmpc;
  395. /* set the carry to the carry bits of the current word found above */
  396. r = rr;
  397. }
  398. }
  399. /* shift right a certain amount of digits */
  400. void mp_rshd (mp_int * a, int b)
  401. {
  402. int x;
  403. /* if b <= 0 then ignore it */
  404. if (b <= 0) {
  405. return;
  406. }
  407. /* if b > used then simply zero it and return */
  408. if (a->used <= b) {
  409. mp_zero (a);
  410. return;
  411. }
  412. {
  413. register mp_digit *bottom, *top;
  414. /* shift the digits down */
  415. /* bottom */
  416. bottom = a->dp;
  417. /* top [offset into digits] */
  418. top = a->dp + b;
  419. /* this is implemented as a sliding window where
  420. * the window is b-digits long and digits from
  421. * the top of the window are copied to the bottom
  422. *
  423. * e.g.
  424. b-2 | b-1 | b0 | b1 | b2 | ... | bb | ---->
  425. /\ | ---->
  426. \-------------------/ ---->
  427. */
  428. for (x = 0; x < (a->used - b); x++) {
  429. *bottom++ = *top++;
  430. }
  431. /* zero the top digits */
  432. for (; x < a->used; x++) {
  433. *bottom++ = 0;
  434. }
  435. }
  436. /* remove excess digits */
  437. a->used -= b;
  438. }
  439. /* calc a value mod 2**b */
  440. int
  441. mp_mod_2d (mp_int * a, int b, mp_int * c)
  442. {
  443. int x, res;
  444. /* if b is <= 0 then zero the int */
  445. if (b <= 0) {
  446. mp_zero (c);
  447. return MP_OKAY;
  448. }
  449. /* if the modulus is larger than the value than return */
  450. if (b >= (int) (a->used * DIGIT_BIT)) {
  451. res = mp_copy (a, c);
  452. return res;
  453. }
  454. /* copy */
  455. if ((res = mp_copy (a, c)) != MP_OKAY) {
  456. return res;
  457. }
  458. /* zero digits above the last digit of the modulus */
  459. for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x++) {
  460. c->dp[x] = 0;
  461. }
  462. /* clear the digit that is not completely outside/inside the modulus */
  463. c->dp[b / DIGIT_BIT] &= (mp_digit) ((((mp_digit) 1) <<
  464. (((mp_digit) b) % DIGIT_BIT)) - ((mp_digit) 1));
  465. mp_clamp (c);
  466. return MP_OKAY;
  467. }
  468. /* reads a unsigned char array, assumes the msb is stored first [big endian] */
  469. int mp_read_unsigned_bin (mp_int * a, const unsigned char *b, int c)
  470. {
  471. int res;
  472. /* make sure there are at least two digits */
  473. if (a->alloc < 2) {
  474. if ((res = mp_grow(a, 2)) != MP_OKAY) {
  475. return res;
  476. }
  477. }
  478. /* zero the int */
  479. mp_zero (a);
  480. /* read the bytes in */
  481. while (c-- > 0) {
  482. if ((res = mp_mul_2d (a, 8, a)) != MP_OKAY) {
  483. return res;
  484. }
  485. #ifndef MP_8BIT
  486. a->dp[0] |= *b++;
  487. a->used += 1;
  488. #else
  489. a->dp[0] = (*b & MP_MASK);
  490. a->dp[1] |= ((*b++ >> 7U) & 1);
  491. a->used += 2;
  492. #endif
  493. }
  494. mp_clamp (a);
  495. return MP_OKAY;
  496. }
  497. /* shift left by a certain bit count */
  498. int mp_mul_2d (mp_int * a, int b, mp_int * c)
  499. {
  500. mp_digit d;
  501. int res;
  502. /* copy */
  503. if (a != c) {
  504. if ((res = mp_copy (a, c)) != MP_OKAY) {
  505. return res;
  506. }
  507. }
  508. if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) {
  509. if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) {
  510. return res;
  511. }
  512. }
  513. /* shift by as many digits in the bit count */
  514. if (b >= (int)DIGIT_BIT) {
  515. if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) {
  516. return res;
  517. }
  518. }
  519. /* shift any bit count < DIGIT_BIT */
  520. d = (mp_digit) (b % DIGIT_BIT);
  521. if (d != 0) {
  522. register mp_digit *tmpc, shift, mask, r, rr;
  523. register int x;
  524. /* bitmask for carries */
  525. mask = (((mp_digit)1) << d) - 1;
  526. /* shift for msbs */
  527. shift = DIGIT_BIT - d;
  528. /* alias */
  529. tmpc = c->dp;
  530. /* carry */
  531. r = 0;
  532. for (x = 0; x < c->used; x++) {
  533. /* get the higher bits of the current word */
  534. rr = (*tmpc >> shift) & mask;
  535. /* shift the current word and OR in the carry */
  536. *tmpc = ((*tmpc << d) | r) & MP_MASK;
  537. ++tmpc;
  538. /* set the carry to the carry bits of the current word */
  539. r = rr;
  540. }
  541. /* set final carry */
  542. if (r != 0) {
  543. c->dp[(c->used)++] = r;
  544. }
  545. }
  546. mp_clamp (c);
  547. return MP_OKAY;
  548. }
  549. /* shift left a certain amount of digits */
  550. int mp_lshd (mp_int * a, int b)
  551. {
  552. int x, res;
  553. /* if its less than zero return */
  554. if (b <= 0) {
  555. return MP_OKAY;
  556. }
  557. /* grow to fit the new digits */
  558. if (a->alloc < a->used + b) {
  559. if ((res = mp_grow (a, a->used + b)) != MP_OKAY) {
  560. return res;
  561. }
  562. }
  563. {
  564. register mp_digit *top, *bottom;
  565. /* increment the used by the shift amount then copy upwards */
  566. a->used += b;
  567. /* top */
  568. top = a->dp + a->used - 1;
  569. /* base */
  570. bottom = a->dp + a->used - 1 - b;
  571. /* much like mp_rshd this is implemented using a sliding window
  572. * except the window goes the otherway around. Copying from
  573. * the bottom to the top. see bn_mp_rshd.c for more info.
  574. */
  575. for (x = a->used - 1; x >= b; x--) {
  576. *top-- = *bottom--;
  577. }
  578. /* zero the lower digits */
  579. top = a->dp;
  580. for (x = 0; x < b; x++) {
  581. *top++ = 0;
  582. }
  583. }
  584. return MP_OKAY;
  585. }
  586. /* this is a shell function that calls either the normal or Montgomery
  587. * exptmod functions. Originally the call to the montgomery code was
  588. * embedded in the normal function but that wasted alot of stack space
  589. * for nothing (since 99% of the time the Montgomery code would be called)
  590. */
  591. int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y)
  592. {
  593. int dr;
  594. /* modulus P must be positive */
  595. if (P->sign == MP_NEG) {
  596. return MP_VAL;
  597. }
  598. /* if exponent X is negative we have to recurse */
  599. if (X->sign == MP_NEG) {
  600. mp_int tmpG, tmpX;
  601. int err;
  602. /* first compute 1/G mod P */
  603. if ((err = mp_init(&tmpG)) != MP_OKAY) {
  604. return err;
  605. }
  606. if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) {
  607. mp_clear(&tmpG);
  608. return err;
  609. }
  610. /* now get |X| */
  611. if ((err = mp_init(&tmpX)) != MP_OKAY) {
  612. mp_clear(&tmpG);
  613. return err;
  614. }
  615. if ((err = mp_abs(X, &tmpX)) != MP_OKAY) {
  616. mp_clear(&tmpG);
  617. mp_clear(&tmpX);
  618. return err;
  619. }
  620. /* and now compute (1/G)**|X| instead of G**X [X < 0] */
  621. err = mp_exptmod(&tmpG, &tmpX, P, Y);
  622. mp_clear(&tmpG);
  623. mp_clear(&tmpX);
  624. return err;
  625. }
  626. /* modified diminished radix reduction */
  627. if (mp_reduce_is_2k_l(P) == MP_YES) {
  628. return s_mp_exptmod(G, X, P, Y, 1);
  629. }
  630. /* is it a DR modulus? */
  631. dr = mp_dr_is_modulus(P);
  632. /* if not, is it a unrestricted DR modulus? */
  633. if (dr == 0) {
  634. dr = mp_reduce_is_2k(P) << 1;
  635. }
  636. /* if the modulus is odd or dr != 0 use the montgomery method */
  637. if (mp_isodd (P) == 1 || dr != 0) {
  638. return mp_exptmod_fast (G, X, P, Y, dr);
  639. } else {
  640. /* otherwise use the generic Barrett reduction technique */
  641. return s_mp_exptmod (G, X, P, Y, 0);
  642. }
  643. }
  644. /* b = |a|
  645. *
  646. * Simple function copies the input and fixes the sign to positive
  647. */
  648. int
  649. mp_abs (mp_int * a, mp_int * b)
  650. {
  651. int res;
  652. /* copy a to b */
  653. if (a != b) {
  654. if ((res = mp_copy (a, b)) != MP_OKAY) {
  655. return res;
  656. }
  657. }
  658. /* force the sign of b to positive */
  659. b->sign = MP_ZPOS;
  660. return MP_OKAY;
  661. }
  662. /* hac 14.61, pp608 */
  663. int mp_invmod (mp_int * a, mp_int * b, mp_int * c)
  664. {
  665. /* b cannot be negative */
  666. if (b->sign == MP_NEG || mp_iszero(b) == 1) {
  667. return MP_VAL;
  668. }
  669. /* if the modulus is odd we can use a faster routine instead */
  670. if (mp_isodd (b) == 1) {
  671. return fast_mp_invmod (a, b, c);
  672. }
  673. return mp_invmod_slow(a, b, c);
  674. }
  675. /* computes the modular inverse via binary extended euclidean algorithm,
  676. * that is c = 1/a mod b
  677. *
  678. * Based on slow invmod except this is optimized for the case where b is
  679. * odd as per HAC Note 14.64 on pp. 610
  680. */
  681. int fast_mp_invmod (mp_int * a, mp_int * b, mp_int * c)
  682. {
  683. mp_int x, y, u, v, B, D;
  684. int res, neg;
  685. /* 2. [modified] b must be odd */
  686. if (mp_iseven (b) == 1) {
  687. return MP_VAL;
  688. }
  689. /* init all our temps */
  690. if ((res = mp_init_multi(&x, &y, &u, &v, &B, &D)) != MP_OKAY) {
  691. return res;
  692. }
  693. /* x == modulus, y == value to invert */
  694. if ((res = mp_copy (b, &x)) != MP_OKAY) {
  695. goto LBL_ERR;
  696. }
  697. /* we need y = |a| */
  698. if ((res = mp_mod (a, b, &y)) != MP_OKAY) {
  699. goto LBL_ERR;
  700. }
  701. /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
  702. if ((res = mp_copy (&x, &u)) != MP_OKAY) {
  703. goto LBL_ERR;
  704. }
  705. if ((res = mp_copy (&y, &v)) != MP_OKAY) {
  706. goto LBL_ERR;
  707. }
  708. mp_set (&D, 1);
  709. top:
  710. /* 4. while u is even do */
  711. while (mp_iseven (&u) == 1) {
  712. /* 4.1 u = u/2 */
  713. if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
  714. goto LBL_ERR;
  715. }
  716. /* 4.2 if B is odd then */
  717. if (mp_isodd (&B) == 1) {
  718. if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
  719. goto LBL_ERR;
  720. }
  721. }
  722. /* B = B/2 */
  723. if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
  724. goto LBL_ERR;
  725. }
  726. }
  727. /* 5. while v is even do */
  728. while (mp_iseven (&v) == 1) {
  729. /* 5.1 v = v/2 */
  730. if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
  731. goto LBL_ERR;
  732. }
  733. /* 5.2 if D is odd then */
  734. if (mp_isodd (&D) == 1) {
  735. /* D = (D-x)/2 */
  736. if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
  737. goto LBL_ERR;
  738. }
  739. }
  740. /* D = D/2 */
  741. if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
  742. goto LBL_ERR;
  743. }
  744. }
  745. /* 6. if u >= v then */
  746. if (mp_cmp (&u, &v) != MP_LT) {
  747. /* u = u - v, B = B - D */
  748. if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
  749. goto LBL_ERR;
  750. }
  751. if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
  752. goto LBL_ERR;
  753. }
  754. } else {
  755. /* v - v - u, D = D - B */
  756. if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
  757. goto LBL_ERR;
  758. }
  759. if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
  760. goto LBL_ERR;
  761. }
  762. }
  763. /* if not zero goto step 4 */
  764. if (mp_iszero (&u) == 0) {
  765. goto top;
  766. }
  767. /* now a = C, b = D, gcd == g*v */
  768. /* if v != 1 then there is no inverse */
  769. if (mp_cmp_d (&v, 1) != MP_EQ) {
  770. res = MP_VAL;
  771. goto LBL_ERR;
  772. }
  773. /* b is now the inverse */
  774. neg = a->sign;
  775. while (D.sign == MP_NEG) {
  776. if ((res = mp_add (&D, b, &D)) != MP_OKAY) {
  777. goto LBL_ERR;
  778. }
  779. }
  780. mp_exch (&D, c);
  781. c->sign = neg;
  782. res = MP_OKAY;
  783. LBL_ERR:mp_clear(&x);
  784. mp_clear(&y);
  785. mp_clear(&u);
  786. mp_clear(&v);
  787. mp_clear(&B);
  788. mp_clear(&D);
  789. return res;
  790. }
  791. /* hac 14.61, pp608 */
  792. int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c)
  793. {
  794. mp_int x, y, u, v, A, B, C, D;
  795. int res;
  796. /* b cannot be negative */
  797. if (b->sign == MP_NEG || mp_iszero(b) == 1) {
  798. return MP_VAL;
  799. }
  800. /* init temps */
  801. if ((res = mp_init_multi(&x, &y, &u, &v,
  802. &A, &B)) != MP_OKAY) {
  803. return res;
  804. }
  805. /* init rest of tmps temps */
  806. if ((res = mp_init_multi(&C, &D, 0, 0, 0, 0)) != MP_OKAY) {
  807. return res;
  808. }
  809. /* x = a, y = b */
  810. if ((res = mp_mod(a, b, &x)) != MP_OKAY) {
  811. goto LBL_ERR;
  812. }
  813. if ((res = mp_copy (b, &y)) != MP_OKAY) {
  814. goto LBL_ERR;
  815. }
  816. /* 2. [modified] if x,y are both even then return an error! */
  817. if (mp_iseven (&x) == 1 && mp_iseven (&y) == 1) {
  818. res = MP_VAL;
  819. goto LBL_ERR;
  820. }
  821. /* 3. u=x, v=y, A=1, B=0, C=0,D=1 */
  822. if ((res = mp_copy (&x, &u)) != MP_OKAY) {
  823. goto LBL_ERR;
  824. }
  825. if ((res = mp_copy (&y, &v)) != MP_OKAY) {
  826. goto LBL_ERR;
  827. }
  828. mp_set (&A, 1);
  829. mp_set (&D, 1);
  830. top:
  831. /* 4. while u is even do */
  832. while (mp_iseven (&u) == 1) {
  833. /* 4.1 u = u/2 */
  834. if ((res = mp_div_2 (&u, &u)) != MP_OKAY) {
  835. goto LBL_ERR;
  836. }
  837. /* 4.2 if A or B is odd then */
  838. if (mp_isodd (&A) == 1 || mp_isodd (&B) == 1) {
  839. /* A = (A+y)/2, B = (B-x)/2 */
  840. if ((res = mp_add (&A, &y, &A)) != MP_OKAY) {
  841. goto LBL_ERR;
  842. }
  843. if ((res = mp_sub (&B, &x, &B)) != MP_OKAY) {
  844. goto LBL_ERR;
  845. }
  846. }
  847. /* A = A/2, B = B/2 */
  848. if ((res = mp_div_2 (&A, &A)) != MP_OKAY) {
  849. goto LBL_ERR;
  850. }
  851. if ((res = mp_div_2 (&B, &B)) != MP_OKAY) {
  852. goto LBL_ERR;
  853. }
  854. }
  855. /* 5. while v is even do */
  856. while (mp_iseven (&v) == 1) {
  857. /* 5.1 v = v/2 */
  858. if ((res = mp_div_2 (&v, &v)) != MP_OKAY) {
  859. goto LBL_ERR;
  860. }
  861. /* 5.2 if C or D is odd then */
  862. if (mp_isodd (&C) == 1 || mp_isodd (&D) == 1) {
  863. /* C = (C+y)/2, D = (D-x)/2 */
  864. if ((res = mp_add (&C, &y, &C)) != MP_OKAY) {
  865. goto LBL_ERR;
  866. }
  867. if ((res = mp_sub (&D, &x, &D)) != MP_OKAY) {
  868. goto LBL_ERR;
  869. }
  870. }
  871. /* C = C/2, D = D/2 */
  872. if ((res = mp_div_2 (&C, &C)) != MP_OKAY) {
  873. goto LBL_ERR;
  874. }
  875. if ((res = mp_div_2 (&D, &D)) != MP_OKAY) {
  876. goto LBL_ERR;
  877. }
  878. }
  879. /* 6. if u >= v then */
  880. if (mp_cmp (&u, &v) != MP_LT) {
  881. /* u = u - v, A = A - C, B = B - D */
  882. if ((res = mp_sub (&u, &v, &u)) != MP_OKAY) {
  883. goto LBL_ERR;
  884. }
  885. if ((res = mp_sub (&A, &C, &A)) != MP_OKAY) {
  886. goto LBL_ERR;
  887. }
  888. if ((res = mp_sub (&B, &D, &B)) != MP_OKAY) {
  889. goto LBL_ERR;
  890. }
  891. } else {
  892. /* v - v - u, C = C - A, D = D - B */
  893. if ((res = mp_sub (&v, &u, &v)) != MP_OKAY) {
  894. goto LBL_ERR;
  895. }
  896. if ((res = mp_sub (&C, &A, &C)) != MP_OKAY) {
  897. goto LBL_ERR;
  898. }
  899. if ((res = mp_sub (&D, &B, &D)) != MP_OKAY) {
  900. goto LBL_ERR;
  901. }
  902. }
  903. /* if not zero goto step 4 */
  904. if (mp_iszero (&u) == 0)
  905. goto top;
  906. /* now a = C, b = D, gcd == g*v */
  907. /* if v != 1 then there is no inverse */
  908. if (mp_cmp_d (&v, 1) != MP_EQ) {
  909. res = MP_VAL;
  910. goto LBL_ERR;
  911. }
  912. /* if its too low */
  913. while (mp_cmp_d(&C, 0) == MP_LT) {
  914. if ((res = mp_add(&C, b, &C)) != MP_OKAY) {
  915. goto LBL_ERR;
  916. }
  917. }
  918. /* too big */
  919. while (mp_cmp_mag(&C, b) != MP_LT) {
  920. if ((res = mp_sub(&C, b, &C)) != MP_OKAY) {
  921. goto LBL_ERR;
  922. }
  923. }
  924. /* C is now the inverse */
  925. mp_exch (&C, c);
  926. res = MP_OKAY;
  927. LBL_ERR:mp_clear(&x);
  928. mp_clear(&y);
  929. mp_clear(&u);
  930. mp_clear(&v);
  931. mp_clear(&A);
  932. mp_clear(&B);
  933. mp_clear(&C);
  934. mp_clear(&D);
  935. return res;
  936. }
  937. /* compare maginitude of two ints (unsigned) */
  938. int mp_cmp_mag (mp_int * a, mp_int * b)
  939. {
  940. int n;
  941. mp_digit *tmpa, *tmpb;
  942. /* compare based on # of non-zero digits */
  943. if (a->used > b->used) {
  944. return MP_GT;
  945. }
  946. if (a->used < b->used) {
  947. return MP_LT;
  948. }
  949. /* alias for a */
  950. tmpa = a->dp + (a->used - 1);
  951. /* alias for b */
  952. tmpb = b->dp + (a->used - 1);
  953. /* compare based on digits */
  954. for (n = 0; n < a->used; ++n, --tmpa, --tmpb) {
  955. if (*tmpa > *tmpb) {
  956. return MP_GT;
  957. }
  958. if (*tmpa < *tmpb) {
  959. return MP_LT;
  960. }
  961. }
  962. return MP_EQ;
  963. }
  964. /* compare two ints (signed)*/
  965. int
  966. mp_cmp (mp_int * a, mp_int * b)
  967. {
  968. /* compare based on sign */
  969. if (a->sign != b->sign) {
  970. if (a->sign == MP_NEG) {
  971. return MP_LT;
  972. } else {
  973. return MP_GT;
  974. }
  975. }
  976. /* compare digits */
  977. if (a->sign == MP_NEG) {
  978. /* if negative compare opposite direction */
  979. return mp_cmp_mag(b, a);
  980. } else {
  981. return mp_cmp_mag(a, b);
  982. }
  983. }
  984. /* compare a digit */
  985. int mp_cmp_d(mp_int * a, mp_digit b)
  986. {
  987. /* compare based on sign */
  988. if (a->sign == MP_NEG) {
  989. return MP_LT;
  990. }
  991. /* compare based on magnitude */
  992. if (a->used > 1) {
  993. return MP_GT;
  994. }
  995. /* compare the only digit of a to b */
  996. if (a->dp[0] > b) {
  997. return MP_GT;
  998. } else if (a->dp[0] < b) {
  999. return MP_LT;
  1000. } else {
  1001. return MP_EQ;
  1002. }
  1003. }
  1004. /* set to a digit */
  1005. void mp_set (mp_int * a, mp_digit b)
  1006. {
  1007. mp_zero (a);
  1008. a->dp[0] = b & MP_MASK;
  1009. a->used = (a->dp[0] != 0) ? 1 : 0;
  1010. }
  1011. /* c = a mod b, 0 <= c < b */
  1012. int
  1013. mp_mod (mp_int * a, mp_int * b, mp_int * c)
  1014. {
  1015. mp_int t;
  1016. int res;
  1017. if ((res = mp_init (&t)) != MP_OKAY) {
  1018. return res;
  1019. }
  1020. if ((res = mp_div (a, b, NULL, &t)) != MP_OKAY) {
  1021. mp_clear (&t);
  1022. return res;
  1023. }
  1024. if (t.sign != b->sign) {
  1025. res = mp_add (b, &t, c);
  1026. } else {
  1027. res = MP_OKAY;
  1028. mp_exch (&t, c);
  1029. }
  1030. mp_clear (&t);
  1031. return res;
  1032. }
  1033. /* slower bit-bang division... also smaller */
  1034. int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d)
  1035. {
  1036. mp_int ta, tb, tq, q;
  1037. int res, n, n2;
  1038. /* is divisor zero ? */
  1039. if (mp_iszero (b) == 1) {
  1040. return MP_VAL;
  1041. }
  1042. /* if a < b then q=0, r = a */
  1043. if (mp_cmp_mag (a, b) == MP_LT) {
  1044. if (d != NULL) {
  1045. res = mp_copy (a, d);
  1046. } else {
  1047. res = MP_OKAY;
  1048. }
  1049. if (c != NULL) {
  1050. mp_zero (c);
  1051. }
  1052. return res;
  1053. }
  1054. /* init our temps */
  1055. if ((res = mp_init_multi(&ta, &tb, &tq, &q, 0, 0)) != MP_OKAY) {
  1056. return res;
  1057. }
  1058. mp_set(&tq, 1);
  1059. n = mp_count_bits(a) - mp_count_bits(b);
  1060. if (((res = mp_abs(a, &ta)) != MP_OKAY) ||
  1061. ((res = mp_abs(b, &tb)) != MP_OKAY) ||
  1062. ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) ||
  1063. ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) {
  1064. goto LBL_ERR;
  1065. }
  1066. while (n-- >= 0) {
  1067. if (mp_cmp(&tb, &ta) != MP_GT) {
  1068. if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) ||
  1069. ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) {
  1070. goto LBL_ERR;
  1071. }
  1072. }
  1073. if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) ||
  1074. ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) {
  1075. goto LBL_ERR;
  1076. }
  1077. }
  1078. /* now q == quotient and ta == remainder */
  1079. n = a->sign;
  1080. n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG);
  1081. if (c != NULL) {
  1082. mp_exch(c, &q);
  1083. c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2;
  1084. }
  1085. if (d != NULL) {
  1086. mp_exch(d, &ta);
  1087. d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n;
  1088. }
  1089. LBL_ERR:
  1090. mp_clear(&ta);
  1091. mp_clear(&tb);
  1092. mp_clear(&tq);
  1093. mp_clear(&q);
  1094. return res;
  1095. }
  1096. /* b = a/2 */
  1097. int mp_div_2(mp_int * a, mp_int * b)
  1098. {
  1099. int x, res, oldused;
  1100. /* copy */
  1101. if (b->alloc < a->used) {
  1102. if ((res = mp_grow (b, a->used)) != MP_OKAY) {
  1103. return res;
  1104. }
  1105. }
  1106. oldused = b->used;
  1107. b->used = a->used;
  1108. {
  1109. register mp_digit r, rr, *tmpa, *tmpb;
  1110. /* source alias */
  1111. tmpa = a->dp + b->used - 1;
  1112. /* dest alias */
  1113. tmpb = b->dp + b->used - 1;
  1114. /* carry */
  1115. r = 0;
  1116. for (x = b->used - 1; x >= 0; x--) {
  1117. /* get the carry for the next iteration */
  1118. rr = *tmpa & 1;
  1119. /* shift the current digit, add in carry and store */
  1120. *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1));
  1121. /* forward carry to next iteration */
  1122. r = rr;
  1123. }
  1124. /* zero excess digits */
  1125. tmpb = b->dp + b->used;
  1126. for (x = b->used; x < oldused; x++) {
  1127. *tmpb++ = 0;
  1128. }
  1129. }
  1130. b->sign = a->sign;
  1131. mp_clamp (b);
  1132. return MP_OKAY;
  1133. }
  1134. /* high level addition (handles signs) */
  1135. int mp_add (mp_int * a, mp_int * b, mp_int * c)
  1136. {
  1137. int sa, sb, res;
  1138. /* get sign of both inputs */
  1139. sa = a->sign;
  1140. sb = b->sign;
  1141. /* handle two cases, not four */
  1142. if (sa == sb) {
  1143. /* both positive or both negative */
  1144. /* add their magnitudes, copy the sign */
  1145. c->sign = sa;
  1146. res = s_mp_add (a, b, c);
  1147. } else {
  1148. /* one positive, the other negative */
  1149. /* subtract the one with the greater magnitude from */
  1150. /* the one of the lesser magnitude. The result gets */
  1151. /* the sign of the one with the greater magnitude. */
  1152. if (mp_cmp_mag (a, b) == MP_LT) {
  1153. c->sign = sb;
  1154. res = s_mp_sub (b, a, c);
  1155. } else {
  1156. c->sign = sa;
  1157. res = s_mp_sub (a, b, c);
  1158. }
  1159. }
  1160. return res;
  1161. }
  1162. /* low level addition, based on HAC pp.594, Algorithm 14.7 */
  1163. int
  1164. s_mp_add (mp_int * a, mp_int * b, mp_int * c)
  1165. {
  1166. mp_int *x;
  1167. int olduse, res, min, max;
  1168. /* find sizes, we let |a| <= |b| which means we have to sort
  1169. * them. "x" will point to the input with the most digits
  1170. */
  1171. if (a->used > b->used) {
  1172. min = b->used;
  1173. max = a->used;
  1174. x = a;
  1175. } else {
  1176. min = a->used;
  1177. max = b->used;
  1178. x = b;
  1179. }
  1180. /* init result */
  1181. if (c->alloc < max + 1) {
  1182. if ((res = mp_grow (c, max + 1)) != MP_OKAY) {
  1183. return res;
  1184. }
  1185. }
  1186. /* get old used digit count and set new one */
  1187. olduse = c->used;
  1188. c->used = max + 1;
  1189. {
  1190. register mp_digit u, *tmpa, *tmpb, *tmpc;
  1191. register int i;
  1192. /* alias for digit pointers */
  1193. /* first input */
  1194. tmpa = a->dp;
  1195. /* second input */
  1196. tmpb = b->dp;
  1197. /* destination */
  1198. tmpc = c->dp;
  1199. /* zero the carry */
  1200. u = 0;
  1201. for (i = 0; i < min; i++) {
  1202. /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */
  1203. *tmpc = *tmpa++ + *tmpb++ + u;
  1204. /* U = carry bit of T[i] */
  1205. u = *tmpc >> ((mp_digit)DIGIT_BIT);
  1206. /* take away carry bit from T[i] */
  1207. *tmpc++ &= MP_MASK;
  1208. }
  1209. /* now copy higher words if any, that is in A+B
  1210. * if A or B has more digits add those in
  1211. */
  1212. if (min != max) {
  1213. for (; i < max; i++) {
  1214. /* T[i] = X[i] + U */
  1215. *tmpc = x->dp[i] + u;
  1216. /* U = carry bit of T[i] */
  1217. u = *tmpc >> ((mp_digit)DIGIT_BIT);
  1218. /* take away carry bit from T[i] */
  1219. *tmpc++ &= MP_MASK;
  1220. }
  1221. }
  1222. /* add carry */
  1223. *tmpc++ = u;
  1224. /* clear digits above oldused */
  1225. for (i = c->used; i < olduse; i++) {
  1226. *tmpc++ = 0;
  1227. }
  1228. }
  1229. mp_clamp (c);
  1230. return MP_OKAY;
  1231. }
  1232. /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */
  1233. int
  1234. s_mp_sub (mp_int * a, mp_int * b, mp_int * c)
  1235. {
  1236. int olduse, res, min, max;
  1237. /* find sizes */
  1238. min = b->used;
  1239. max = a->used;
  1240. /* init result */
  1241. if (c->alloc < max) {
  1242. if ((res = mp_grow (c, max)) != MP_OKAY) {
  1243. return res;
  1244. }
  1245. }
  1246. olduse = c->used;
  1247. c->used = max;
  1248. {
  1249. register mp_digit u, *tmpa, *tmpb, *tmpc;
  1250. register int i;
  1251. /* alias for digit pointers */
  1252. tmpa = a->dp;
  1253. tmpb = b->dp;
  1254. tmpc = c->dp;
  1255. /* set carry to zero */
  1256. u = 0;
  1257. for (i = 0; i < min; i++) {
  1258. /* T[i] = A[i] - B[i] - U */
  1259. *tmpc = *tmpa++ - *tmpb++ - u;
  1260. /* U = carry bit of T[i]
  1261. * Note this saves performing an AND operation since
  1262. * if a carry does occur it will propagate all the way to the
  1263. * MSB. As a result a single shift is enough to get the carry
  1264. */
  1265. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  1266. /* Clear carry from T[i] */
  1267. *tmpc++ &= MP_MASK;
  1268. }
  1269. /* now copy higher words if any, e.g. if A has more digits than B */
  1270. for (; i < max; i++) {
  1271. /* T[i] = A[i] - U */
  1272. *tmpc = *tmpa++ - u;
  1273. /* U = carry bit of T[i] */
  1274. u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1));
  1275. /* Clear carry from T[i] */
  1276. *tmpc++ &= MP_MASK;
  1277. }
  1278. /* clear digits above used (since we may not have grown result above) */
  1279. for (i = c->used; i < olduse; i++) {
  1280. *tmpc++ = 0;
  1281. }
  1282. }
  1283. mp_clamp (c);
  1284. return MP_OKAY;
  1285. }
  1286. /* high level subtraction (handles signs) */
  1287. int
  1288. mp_sub (mp_int * a, mp_int * b, mp_int * c)
  1289. {
  1290. int sa, sb, res;
  1291. sa = a->sign;
  1292. sb = b->sign;
  1293. if (sa != sb) {
  1294. /* subtract a negative from a positive, OR */
  1295. /* subtract a positive from a negative. */
  1296. /* In either case, ADD their magnitudes, */
  1297. /* and use the sign of the first number. */
  1298. c->sign = sa;
  1299. res = s_mp_add (a, b, c);
  1300. } else {
  1301. /* subtract a positive from a positive, OR */
  1302. /* subtract a negative from a negative. */
  1303. /* First, take the difference between their */
  1304. /* magnitudes, then... */
  1305. if (mp_cmp_mag (a, b) != MP_LT) {
  1306. /* Copy the sign from the first */
  1307. c->sign = sa;
  1308. /* The first has a larger or equal magnitude */
  1309. res = s_mp_sub (a, b, c);
  1310. } else {
  1311. /* The result has the *opposite* sign from */
  1312. /* the first number. */
  1313. c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS;
  1314. /* The second has a larger magnitude */
  1315. res = s_mp_sub (b, a, c);
  1316. }
  1317. }
  1318. return res;
  1319. }
  1320. /* determines if reduce_2k_l can be used */
  1321. int mp_reduce_is_2k_l(mp_int *a)
  1322. {
  1323. int ix, iy;
  1324. if (a->used == 0) {
  1325. return MP_NO;
  1326. } else if (a->used == 1) {
  1327. return MP_YES;
  1328. } else if (a->used > 1) {
  1329. /* if more than half of the digits are -1 we're sold */
  1330. for (iy = ix = 0; ix < a->used; ix++) {
  1331. if (a->dp[ix] == MP_MASK) {
  1332. ++iy;
  1333. }
  1334. }
  1335. return (iy >= (a->used/2)) ? MP_YES : MP_NO;
  1336. }
  1337. return MP_NO;
  1338. }
  1339. /* determines if mp_reduce_2k can be used */
  1340. int mp_reduce_is_2k(mp_int *a)
  1341. {
  1342. int ix, iy, iw;
  1343. mp_digit iz;
  1344. if (a->used == 0) {
  1345. return MP_NO;
  1346. } else if (a->used == 1) {
  1347. return MP_YES;
  1348. } else if (a->used > 1) {
  1349. iy = mp_count_bits(a);
  1350. iz = 1;
  1351. iw = 1;
  1352. /* Test every bit from the second digit up, must be 1 */
  1353. for (ix = DIGIT_BIT; ix < iy; ix++) {
  1354. if ((a->dp[iw] & iz) == 0) {
  1355. return MP_NO;
  1356. }
  1357. iz <<= 1;
  1358. if (iz > (mp_digit)MP_MASK) {
  1359. ++iw;
  1360. iz = 1;
  1361. }
  1362. }
  1363. }
  1364. return MP_YES;
  1365. }
  1366. /* determines if a number is a valid DR modulus */
  1367. int mp_dr_is_modulus(mp_int *a)
  1368. {
  1369. int ix;
  1370. /* must be at least two digits */
  1371. if (a->used < 2) {
  1372. return 0;
  1373. }
  1374. /* must be of the form b**k - a [a <= b] so all
  1375. * but the first digit must be equal to -1 (mod b).
  1376. */
  1377. for (ix = 1; ix < a->used; ix++) {
  1378. if (a->dp[ix] != MP_MASK) {
  1379. return 0;
  1380. }
  1381. }
  1382. return 1;
  1383. }
  1384. /* computes Y == G**X mod P, HAC pp.616, Algorithm 14.85
  1385. *
  1386. * Uses a left-to-right k-ary sliding window to compute the modular
  1387. * exponentiation.
  1388. * The value of k changes based on the size of the exponent.
  1389. *
  1390. * Uses Montgomery or Diminished Radix reduction [whichever appropriate]
  1391. */
  1392. #define TAB_SIZE 256
  1393. int mp_exptmod_fast (mp_int * G, mp_int * X, mp_int * P, mp_int * Y,
  1394. int redmode)
  1395. {
  1396. mp_int M[TAB_SIZE], res;
  1397. mp_digit buf, mp;
  1398. int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
  1399. /* use a pointer to the reduction algorithm. This allows us to use
  1400. * one of many reduction algorithms without modding the guts of
  1401. * the code with if statements everywhere.
  1402. */
  1403. int (*redux)(mp_int*,mp_int*,mp_digit);
  1404. /* find window size */
  1405. x = mp_count_bits (X);
  1406. if (x <= 7) {
  1407. winsize = 2;
  1408. } else if (x <= 36) {
  1409. winsize = 3;
  1410. } else if (x <= 140) {
  1411. winsize = 4;
  1412. } else if (x <= 450) {
  1413. winsize = 5;
  1414. } else if (x <= 1303) {
  1415. winsize = 6;
  1416. } else if (x <= 3529) {
  1417. winsize = 7;
  1418. } else {
  1419. winsize = 8;
  1420. }
  1421. /* init M array */
  1422. /* init first cell */
  1423. if ((err = mp_init(&M[1])) != MP_OKAY) {
  1424. return err;
  1425. }
  1426. /* now init the second half of the array */
  1427. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  1428. if ((err = mp_init(&M[x])) != MP_OKAY) {
  1429. for (y = 1<<(winsize-1); y < x; y++) {
  1430. mp_clear (&M[y]);
  1431. }
  1432. mp_clear(&M[1]);
  1433. return err;
  1434. }
  1435. }
  1436. /* determine and setup reduction code */
  1437. if (redmode == 0) {
  1438. /* now setup montgomery */
  1439. if ((err = mp_montgomery_setup (P, &mp)) != MP_OKAY) {
  1440. goto LBL_M;
  1441. }
  1442. /* automatically pick the comba one if available (saves quite a few
  1443. calls/ifs) */
  1444. if (((P->used * 2 + 1) < MP_WARRAY) &&
  1445. P->used < (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  1446. redux = fast_mp_montgomery_reduce;
  1447. } else {
  1448. /* use slower baseline Montgomery method */
  1449. redux = mp_montgomery_reduce;
  1450. }
  1451. } else if (redmode == 1) {
  1452. #if defined(BN_MP_DR_SETUP_C) && defined(BN_MP_DR_REDUCE_C)
  1453. /* setup DR reduction for moduli of the form B**k - b */
  1454. mp_dr_setup(P, &mp);
  1455. redux = mp_dr_reduce;
  1456. #else
  1457. err = MP_VAL;
  1458. goto LBL_M;
  1459. #endif
  1460. } else {
  1461. #if defined(BN_MP_REDUCE_2K_SETUP_C) && defined(BN_MP_REDUCE_2K_C)
  1462. /* setup DR reduction for moduli of the form 2**k - b */
  1463. if ((err = mp_reduce_2k_setup(P, &mp)) != MP_OKAY) {
  1464. goto LBL_M;
  1465. }
  1466. redux = mp_reduce_2k;
  1467. #else
  1468. err = MP_VAL;
  1469. goto LBL_M;
  1470. #endif
  1471. }
  1472. /* setup result */
  1473. if ((err = mp_init (&res)) != MP_OKAY) {
  1474. goto LBL_M;
  1475. }
  1476. /* create M table
  1477. *
  1478. *
  1479. * The first half of the table is not computed though accept for M[0] and M[1]
  1480. */
  1481. if (redmode == 0) {
  1482. /* now we need R mod m */
  1483. if ((err = mp_montgomery_calc_normalization (&res, P)) != MP_OKAY) {
  1484. goto LBL_RES;
  1485. }
  1486. /* now set M[1] to G * R mod m */
  1487. if ((err = mp_mulmod (G, &res, P, &M[1])) != MP_OKAY) {
  1488. goto LBL_RES;
  1489. }
  1490. } else {
  1491. mp_set(&res, 1);
  1492. if ((err = mp_mod(G, P, &M[1])) != MP_OKAY) {
  1493. goto LBL_RES;
  1494. }
  1495. }
  1496. /* compute the value at M[1<<(winsize-1)] by squaring M[1] (winsize-1) times*/
  1497. if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  1498. goto LBL_RES;
  1499. }
  1500. for (x = 0; x < (winsize - 1); x++) {
  1501. if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  1502. goto LBL_RES;
  1503. }
  1504. if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, mp)) != MP_OKAY) {
  1505. goto LBL_RES;
  1506. }
  1507. }
  1508. /* create upper table */
  1509. for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
  1510. if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
  1511. goto LBL_RES;
  1512. }
  1513. if ((err = redux (&M[x], P, mp)) != MP_OKAY) {
  1514. goto LBL_RES;
  1515. }
  1516. }
  1517. /* set initial mode and bit cnt */
  1518. mode = 0;
  1519. bitcnt = 1;
  1520. buf = 0;
  1521. digidx = X->used - 1;
  1522. bitcpy = 0;
  1523. bitbuf = 0;
  1524. for (;;) {
  1525. /* grab next digit as required */
  1526. if (--bitcnt == 0) {
  1527. /* if digidx == -1 we are out of digits so break */
  1528. if (digidx == -1) {
  1529. break;
  1530. }
  1531. /* read next digit and reset bitcnt */
  1532. buf = X->dp[digidx--];
  1533. bitcnt = (int)DIGIT_BIT;
  1534. }
  1535. /* grab the next msb from the exponent */
  1536. y = (int)(buf >> (DIGIT_BIT - 1)) & 1;
  1537. buf <<= (mp_digit)1;
  1538. /* if the bit is zero and mode == 0 then we ignore it
  1539. * These represent the leading zero bits before the first 1 bit
  1540. * in the exponent. Technically this opt is not required but it
  1541. * does lower the # of trivial squaring/reductions used
  1542. */
  1543. if (mode == 0 && y == 0) {
  1544. continue;
  1545. }
  1546. /* if the bit is zero and mode == 1 then we square */
  1547. if (mode == 1 && y == 0) {
  1548. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1549. goto LBL_RES;
  1550. }
  1551. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1552. goto LBL_RES;
  1553. }
  1554. continue;
  1555. }
  1556. /* else we add it to the window */
  1557. bitbuf |= (y << (winsize - ++bitcpy));
  1558. mode = 2;
  1559. if (bitcpy == winsize) {
  1560. /* ok window is filled so square as required and multiply */
  1561. /* square first */
  1562. for (x = 0; x < winsize; x++) {
  1563. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1564. goto LBL_RES;
  1565. }
  1566. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1567. goto LBL_RES;
  1568. }
  1569. }
  1570. /* then multiply */
  1571. if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
  1572. goto LBL_RES;
  1573. }
  1574. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1575. goto LBL_RES;
  1576. }
  1577. /* empty window and reset */
  1578. bitcpy = 0;
  1579. bitbuf = 0;
  1580. mode = 1;
  1581. }
  1582. }
  1583. /* if bits remain then square/multiply */
  1584. if (mode == 2 && bitcpy > 0) {
  1585. /* square then multiply if the bit is set */
  1586. for (x = 0; x < bitcpy; x++) {
  1587. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  1588. goto LBL_RES;
  1589. }
  1590. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1591. goto LBL_RES;
  1592. }
  1593. /* get next bit of the window */
  1594. bitbuf <<= 1;
  1595. if ((bitbuf & (1 << winsize)) != 0) {
  1596. /* then multiply */
  1597. if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
  1598. goto LBL_RES;
  1599. }
  1600. if ((err = redux (&res, P, mp)) != MP_OKAY) {
  1601. goto LBL_RES;
  1602. }
  1603. }
  1604. }
  1605. }
  1606. if (redmode == 0) {
  1607. /* fixup result if Montgomery reduction is used
  1608. * recall that any value in a Montgomery system is
  1609. * actually multiplied by R mod n. So we have
  1610. * to reduce one more time to cancel out the factor
  1611. * of R.
  1612. */
  1613. if ((err = redux(&res, P, mp)) != MP_OKAY) {
  1614. goto LBL_RES;
  1615. }
  1616. }
  1617. /* swap res with Y */
  1618. mp_exch (&res, Y);
  1619. err = MP_OKAY;
  1620. LBL_RES:mp_clear (&res);
  1621. LBL_M:
  1622. mp_clear(&M[1]);
  1623. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  1624. mp_clear (&M[x]);
  1625. }
  1626. return err;
  1627. }
  1628. /* setups the montgomery reduction stuff */
  1629. int
  1630. mp_montgomery_setup (mp_int * n, mp_digit * rho)
  1631. {
  1632. mp_digit x, b;
  1633. /* fast inversion mod 2**k
  1634. *
  1635. * Based on the fact that
  1636. *
  1637. * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n)
  1638. * => 2*X*A - X*X*A*A = 1
  1639. * => 2*(1) - (1) = 1
  1640. */
  1641. b = n->dp[0];
  1642. if ((b & 1) == 0) {
  1643. return MP_VAL;
  1644. }
  1645. x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */
  1646. x *= 2 - b * x; /* here x*a==1 mod 2**8 */
  1647. #if !defined(MP_8BIT)
  1648. x *= 2 - b * x; /* here x*a==1 mod 2**16 */
  1649. #endif
  1650. #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT))
  1651. x *= 2 - b * x; /* here x*a==1 mod 2**32 */
  1652. #endif
  1653. #ifdef MP_64BIT
  1654. x *= 2 - b * x; /* here x*a==1 mod 2**64 */
  1655. #endif
  1656. /* rho = -1/m mod b */
  1657. /* TAO, switched mp_word casts to mp_digit to shut up compiler */
  1658. *rho = (((mp_digit)1 << ((mp_digit) DIGIT_BIT)) - x) & MP_MASK;
  1659. return MP_OKAY;
  1660. }
  1661. /* computes xR**-1 == x (mod N) via Montgomery Reduction
  1662. *
  1663. * This is an optimized implementation of montgomery_reduce
  1664. * which uses the comba method to quickly calculate the columns of the
  1665. * reduction.
  1666. *
  1667. * Based on Algorithm 14.32 on pp.601 of HAC.
  1668. */
  1669. int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
  1670. {
  1671. int ix, res, olduse;
  1672. mp_word W[MP_WARRAY];
  1673. /* get old used count */
  1674. olduse = x->used;
  1675. /* grow a as required */
  1676. if (x->alloc < n->used + 1) {
  1677. if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) {
  1678. return res;
  1679. }
  1680. }
  1681. /* first we have to get the digits of the input into
  1682. * an array of double precision words W[...]
  1683. */
  1684. {
  1685. register mp_word *_W;
  1686. register mp_digit *tmpx;
  1687. /* alias for the W[] array */
  1688. _W = W;
  1689. /* alias for the digits of x*/
  1690. tmpx = x->dp;
  1691. /* copy the digits of a into W[0..a->used-1] */
  1692. for (ix = 0; ix < x->used; ix++) {
  1693. *_W++ = *tmpx++;
  1694. }
  1695. /* zero the high words of W[a->used..m->used*2] */
  1696. for (; ix < n->used * 2 + 1; ix++) {
  1697. *_W++ = 0;
  1698. }
  1699. }
  1700. /* now we proceed to zero successive digits
  1701. * from the least significant upwards
  1702. */
  1703. for (ix = 0; ix < n->used; ix++) {
  1704. /* mu = ai * m' mod b
  1705. *
  1706. * We avoid a double precision multiplication (which isn't required)
  1707. * by casting the value down to a mp_digit. Note this requires
  1708. * that W[ix-1] have the carry cleared (see after the inner loop)
  1709. */
  1710. register mp_digit mu;
  1711. mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK);
  1712. /* a = a + mu * m * b**i
  1713. *
  1714. * This is computed in place and on the fly. The multiplication
  1715. * by b**i is handled by offseting which columns the results
  1716. * are added to.
  1717. *
  1718. * Note the comba method normally doesn't handle carries in the
  1719. * inner loop In this case we fix the carry from the previous
  1720. * column since the Montgomery reduction requires digits of the
  1721. * result (so far) [see above] to work. This is
  1722. * handled by fixing up one carry after the inner loop. The
  1723. * carry fixups are done in order so after these loops the
  1724. * first m->used words of W[] have the carries fixed
  1725. */
  1726. {
  1727. register int iy;
  1728. register mp_digit *tmpn;
  1729. register mp_word *_W;
  1730. /* alias for the digits of the modulus */
  1731. tmpn = n->dp;
  1732. /* Alias for the columns set by an offset of ix */
  1733. _W = W + ix;
  1734. /* inner loop */
  1735. for (iy = 0; iy < n->used; iy++) {
  1736. *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++);
  1737. }
  1738. }
  1739. /* now fix carry for next digit, W[ix+1] */
  1740. W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT);
  1741. }
  1742. /* now we have to propagate the carries and
  1743. * shift the words downward [all those least
  1744. * significant digits we zeroed].
  1745. */
  1746. {
  1747. register mp_digit *tmpx;
  1748. register mp_word *_W, *_W1;
  1749. /* nox fix rest of carries */
  1750. /* alias for current word */
  1751. _W1 = W + ix;
  1752. /* alias for next word, where the carry goes */
  1753. _W = W + ++ix;
  1754. for (; ix <= n->used * 2 + 1; ix++) {
  1755. *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT);
  1756. }
  1757. /* copy out, A = A/b**n
  1758. *
  1759. * The result is A/b**n but instead of converting from an
  1760. * array of mp_word to mp_digit than calling mp_rshd
  1761. * we just copy them in the right order
  1762. */
  1763. /* alias for destination word */
  1764. tmpx = x->dp;
  1765. /* alias for shifted double precision result */
  1766. _W = W + n->used;
  1767. for (ix = 0; ix < n->used + 1; ix++) {
  1768. *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK));
  1769. }
  1770. /* zero oldused digits, if the input a was larger than
  1771. * m->used+1 we'll have to clear the digits
  1772. */
  1773. for (; ix < olduse; ix++) {
  1774. *tmpx++ = 0;
  1775. }
  1776. }
  1777. /* set the max used and clamp */
  1778. x->used = n->used + 1;
  1779. mp_clamp (x);
  1780. /* if A >= m then A = A - m */
  1781. if (mp_cmp_mag (x, n) != MP_LT) {
  1782. return s_mp_sub (x, n, x);
  1783. }
  1784. return MP_OKAY;
  1785. }
  1786. /* computes xR**-1 == x (mod N) via Montgomery Reduction */
  1787. int
  1788. mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho)
  1789. {
  1790. int ix, res, digs;
  1791. mp_digit mu;
  1792. /* can the fast reduction [comba] method be used?
  1793. *
  1794. * Note that unlike in mul you're safely allowed *less*
  1795. * than the available columns [255 per default] since carries
  1796. * are fixed up in the inner loop.
  1797. */
  1798. digs = n->used * 2 + 1;
  1799. if ((digs < MP_WARRAY) &&
  1800. n->used <
  1801. (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  1802. return fast_mp_montgomery_reduce (x, n, rho);
  1803. }
  1804. /* grow the input as required */
  1805. if (x->alloc < digs) {
  1806. if ((res = mp_grow (x, digs)) != MP_OKAY) {
  1807. return res;
  1808. }
  1809. }
  1810. x->used = digs;
  1811. for (ix = 0; ix < n->used; ix++) {
  1812. /* mu = ai * rho mod b
  1813. *
  1814. * The value of rho must be precalculated via
  1815. * montgomery_setup() such that
  1816. * it equals -1/n0 mod b this allows the
  1817. * following inner loop to reduce the
  1818. * input one digit at a time
  1819. */
  1820. mu = (mp_digit) (((mp_word)x->dp[ix]) * ((mp_word)rho) & MP_MASK);
  1821. /* a = a + mu * m * b**i */
  1822. {
  1823. register int iy;
  1824. register mp_digit *tmpn, *tmpx, u;
  1825. register mp_word r;
  1826. /* alias for digits of the modulus */
  1827. tmpn = n->dp;
  1828. /* alias for the digits of x [the input] */
  1829. tmpx = x->dp + ix;
  1830. /* set the carry to zero */
  1831. u = 0;
  1832. /* Multiply and add in place */
  1833. for (iy = 0; iy < n->used; iy++) {
  1834. /* compute product and sum */
  1835. r = ((mp_word)mu) * ((mp_word)*tmpn++) +
  1836. ((mp_word) u) + ((mp_word) * tmpx);
  1837. /* get carry */
  1838. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  1839. /* fix digit */
  1840. *tmpx++ = (mp_digit)(r & ((mp_word) MP_MASK));
  1841. }
  1842. /* At this point the ix'th digit of x should be zero */
  1843. /* propagate carries upwards as required*/
  1844. while (u) {
  1845. *tmpx += u;
  1846. u = *tmpx >> DIGIT_BIT;
  1847. *tmpx++ &= MP_MASK;
  1848. }
  1849. }
  1850. }
  1851. /* at this point the n.used'th least
  1852. * significant digits of x are all zero
  1853. * which means we can shift x to the
  1854. * right by n.used digits and the
  1855. * residue is unchanged.
  1856. */
  1857. /* x = x/b**n.used */
  1858. mp_clamp(x);
  1859. mp_rshd (x, n->used);
  1860. /* if x >= n then x = x - n */
  1861. if (mp_cmp_mag (x, n) != MP_LT) {
  1862. return s_mp_sub (x, n, x);
  1863. }
  1864. return MP_OKAY;
  1865. }
  1866. /* determines the setup value */
  1867. void mp_dr_setup(mp_int *a, mp_digit *d)
  1868. {
  1869. /* the casts are required if DIGIT_BIT is one less than
  1870. * the number of bits in a mp_digit [e.g. DIGIT_BIT==31]
  1871. */
  1872. *d = (mp_digit)((((mp_word)1) << ((mp_word)DIGIT_BIT)) -
  1873. ((mp_word)a->dp[0]));
  1874. }
  1875. /* reduce "x" in place modulo "n" using the Diminished Radix algorithm.
  1876. *
  1877. * Based on algorithm from the paper
  1878. *
  1879. * "Generating Efficient Primes for Discrete Log Cryptosystems"
  1880. * Chae Hoon Lim, Pil Joong Lee,
  1881. * POSTECH Information Research Laboratories
  1882. *
  1883. * The modulus must be of a special format [see manual]
  1884. *
  1885. * Has been modified to use algorithm 7.10 from the LTM book instead
  1886. *
  1887. * Input x must be in the range 0 <= x <= (n-1)**2
  1888. */
  1889. int
  1890. mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k)
  1891. {
  1892. int err, i, m;
  1893. mp_word r;
  1894. mp_digit mu, *tmpx1, *tmpx2;
  1895. /* m = digits in modulus */
  1896. m = n->used;
  1897. /* ensure that "x" has at least 2m digits */
  1898. if (x->alloc < m + m) {
  1899. if ((err = mp_grow (x, m + m)) != MP_OKAY) {
  1900. return err;
  1901. }
  1902. }
  1903. /* top of loop, this is where the code resumes if
  1904. * another reduction pass is required.
  1905. */
  1906. top:
  1907. /* aliases for digits */
  1908. /* alias for lower half of x */
  1909. tmpx1 = x->dp;
  1910. /* alias for upper half of x, or x/B**m */
  1911. tmpx2 = x->dp + m;
  1912. /* set carry to zero */
  1913. mu = 0;
  1914. /* compute (x mod B**m) + k * [x/B**m] inline and inplace */
  1915. for (i = 0; i < m; i++) {
  1916. r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu;
  1917. *tmpx1++ = (mp_digit)(r & MP_MASK);
  1918. mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT));
  1919. }
  1920. /* set final carry */
  1921. *tmpx1++ = mu;
  1922. /* zero words above m */
  1923. for (i = m + 1; i < x->used; i++) {
  1924. *tmpx1++ = 0;
  1925. }
  1926. /* clamp, sub and return */
  1927. mp_clamp (x);
  1928. /* if x >= n then subtract and reduce again
  1929. * Each successive "recursion" makes the input smaller and smaller.
  1930. */
  1931. if (mp_cmp_mag (x, n) != MP_LT) {
  1932. s_mp_sub(x, n, x);
  1933. goto top;
  1934. }
  1935. return MP_OKAY;
  1936. }
  1937. /* reduces a modulo n where n is of the form 2**p - d */
  1938. int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d)
  1939. {
  1940. mp_int q;
  1941. int p, res;
  1942. if ((res = mp_init(&q)) != MP_OKAY) {
  1943. return res;
  1944. }
  1945. p = mp_count_bits(n);
  1946. top:
  1947. /* q = a/2**p, a = a mod 2**p */
  1948. if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  1949. goto ERR;
  1950. }
  1951. if (d != 1) {
  1952. /* q = q * d */
  1953. if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) {
  1954. goto ERR;
  1955. }
  1956. }
  1957. /* a = a + q */
  1958. if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
  1959. goto ERR;
  1960. }
  1961. if (mp_cmp_mag(a, n) != MP_LT) {
  1962. s_mp_sub(a, n, a);
  1963. goto top;
  1964. }
  1965. ERR:
  1966. mp_clear(&q);
  1967. return res;
  1968. }
  1969. /* determines the setup value */
  1970. int mp_reduce_2k_setup(mp_int *a, mp_digit *d)
  1971. {
  1972. int res, p;
  1973. mp_int tmp;
  1974. if ((res = mp_init(&tmp)) != MP_OKAY) {
  1975. return res;
  1976. }
  1977. p = mp_count_bits(a);
  1978. if ((res = mp_2expt(&tmp, p)) != MP_OKAY) {
  1979. mp_clear(&tmp);
  1980. return res;
  1981. }
  1982. if ((res = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) {
  1983. mp_clear(&tmp);
  1984. return res;
  1985. }
  1986. *d = tmp.dp[0];
  1987. mp_clear(&tmp);
  1988. return MP_OKAY;
  1989. }
  1990. /* computes a = 2**b
  1991. *
  1992. * Simple algorithm which zeroes the int, grows it then just sets one bit
  1993. * as required.
  1994. */
  1995. int
  1996. mp_2expt (mp_int * a, int b)
  1997. {
  1998. int res;
  1999. /* zero a as per default */
  2000. mp_zero (a);
  2001. /* grow a to accomodate the single bit */
  2002. if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) {
  2003. return res;
  2004. }
  2005. /* set the used count of where the bit will go */
  2006. a->used = b / DIGIT_BIT + 1;
  2007. /* put the single bit in its place */
  2008. a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT);
  2009. return MP_OKAY;
  2010. }
  2011. /* multiply by a digit */
  2012. int
  2013. mp_mul_d (mp_int * a, mp_digit b, mp_int * c)
  2014. {
  2015. mp_digit u, *tmpa, *tmpc;
  2016. mp_word r;
  2017. int ix, res, olduse;
  2018. /* make sure c is big enough to hold a*b */
  2019. if (c->alloc < a->used + 1) {
  2020. if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) {
  2021. return res;
  2022. }
  2023. }
  2024. /* get the original destinations used count */
  2025. olduse = c->used;
  2026. /* set the sign */
  2027. c->sign = a->sign;
  2028. /* alias for a->dp [source] */
  2029. tmpa = a->dp;
  2030. /* alias for c->dp [dest] */
  2031. tmpc = c->dp;
  2032. /* zero carry */
  2033. u = 0;
  2034. /* compute columns */
  2035. for (ix = 0; ix < a->used; ix++) {
  2036. /* compute product and carry sum for this term */
  2037. r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b);
  2038. /* mask off higher bits to get a single digit */
  2039. *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2040. /* send carry into next iteration */
  2041. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  2042. }
  2043. /* store final carry [if any] and increment ix offset */
  2044. *tmpc++ = u;
  2045. ++ix;
  2046. /* now zero digits above the top */
  2047. while (ix++ < olduse) {
  2048. *tmpc++ = 0;
  2049. }
  2050. /* set used count */
  2051. c->used = a->used + 1;
  2052. mp_clamp(c);
  2053. return MP_OKAY;
  2054. }
  2055. /* d = a * b (mod c) */
  2056. int mp_mulmod (mp_int * a, mp_int * b, mp_int * c, mp_int * d)
  2057. {
  2058. int res;
  2059. mp_int t;
  2060. if ((res = mp_init (&t)) != MP_OKAY) {
  2061. return res;
  2062. }
  2063. if ((res = mp_mul (a, b, &t)) != MP_OKAY) {
  2064. mp_clear (&t);
  2065. return res;
  2066. }
  2067. res = mp_mod (&t, c, d);
  2068. mp_clear (&t);
  2069. return res;
  2070. }
  2071. /* computes b = a*a */
  2072. int
  2073. mp_sqr (mp_int * a, mp_int * b)
  2074. {
  2075. int res;
  2076. {
  2077. /* can we use the fast comba multiplier? */
  2078. if ((a->used * 2 + 1) < MP_WARRAY &&
  2079. a->used <
  2080. (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) {
  2081. res = fast_s_mp_sqr (a, b);
  2082. } else
  2083. res = s_mp_sqr (a, b);
  2084. }
  2085. b->sign = MP_ZPOS;
  2086. return res;
  2087. }
  2088. /* high level multiplication (handles sign) */
  2089. int mp_mul (mp_int * a, mp_int * b, mp_int * c)
  2090. {
  2091. int res, neg;
  2092. neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG;
  2093. {
  2094. /* can we use the fast multiplier?
  2095. *
  2096. * The fast multiplier can be used if the output will
  2097. * have less than MP_WARRAY digits and the number of
  2098. * digits won't affect carry propagation
  2099. */
  2100. int digs = a->used + b->used + 1;
  2101. if ((digs < MP_WARRAY) &&
  2102. MIN(a->used, b->used) <=
  2103. (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  2104. res = fast_s_mp_mul_digs (a, b, c, digs);
  2105. } else
  2106. res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */
  2107. }
  2108. c->sign = (c->used > 0) ? neg : MP_ZPOS;
  2109. return res;
  2110. }
  2111. /* b = a*2 */
  2112. int mp_mul_2(mp_int * a, mp_int * b)
  2113. {
  2114. int x, res, oldused;
  2115. /* grow to accomodate result */
  2116. if (b->alloc < a->used + 1) {
  2117. if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) {
  2118. return res;
  2119. }
  2120. }
  2121. oldused = b->used;
  2122. b->used = a->used;
  2123. {
  2124. register mp_digit r, rr, *tmpa, *tmpb;
  2125. /* alias for source */
  2126. tmpa = a->dp;
  2127. /* alias for dest */
  2128. tmpb = b->dp;
  2129. /* carry */
  2130. r = 0;
  2131. for (x = 0; x < a->used; x++) {
  2132. /* get what will be the *next* carry bit from the
  2133. * MSB of the current digit
  2134. */
  2135. rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1));
  2136. /* now shift up this digit, add in the carry [from the previous] */
  2137. *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK;
  2138. /* copy the carry that would be from the source
  2139. * digit into the next iteration
  2140. */
  2141. r = rr;
  2142. }
  2143. /* new leading digit? */
  2144. if (r != 0) {
  2145. /* add a MSB which is always 1 at this point */
  2146. *tmpb = 1;
  2147. ++(b->used);
  2148. }
  2149. /* now zero any excess digits on the destination
  2150. * that we didn't write to
  2151. */
  2152. tmpb = b->dp + b->used;
  2153. for (x = b->used; x < oldused; x++) {
  2154. *tmpb++ = 0;
  2155. }
  2156. }
  2157. b->sign = a->sign;
  2158. return MP_OKAY;
  2159. }
  2160. /* divide by three (based on routine from MPI and the GMP manual) */
  2161. int
  2162. mp_div_3 (mp_int * a, mp_int *c, mp_digit * d)
  2163. {
  2164. mp_int q;
  2165. mp_word w, t;
  2166. mp_digit b;
  2167. int res, ix;
  2168. /* b = 2**DIGIT_BIT / 3 */
  2169. b = (((mp_word)1) << ((mp_word)DIGIT_BIT)) / ((mp_word)3);
  2170. if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
  2171. return res;
  2172. }
  2173. q.used = a->used;
  2174. q.sign = a->sign;
  2175. w = 0;
  2176. for (ix = a->used - 1; ix >= 0; ix--) {
  2177. w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
  2178. if (w >= 3) {
  2179. /* multiply w by [1/3] */
  2180. t = (w * ((mp_word)b)) >> ((mp_word)DIGIT_BIT);
  2181. /* now subtract 3 * [w/3] from w, to get the remainder */
  2182. w -= t+t+t;
  2183. /* fixup the remainder as required since
  2184. * the optimization is not exact.
  2185. */
  2186. while (w >= 3) {
  2187. t += 1;
  2188. w -= 3;
  2189. }
  2190. } else {
  2191. t = 0;
  2192. }
  2193. q.dp[ix] = (mp_digit)t;
  2194. }
  2195. /* [optional] store the remainder */
  2196. if (d != NULL) {
  2197. *d = (mp_digit)w;
  2198. }
  2199. /* [optional] store the quotient */
  2200. if (c != NULL) {
  2201. mp_clamp(&q);
  2202. mp_exch(&q, c);
  2203. }
  2204. mp_clear(&q);
  2205. return res;
  2206. }
  2207. /* init an mp_init for a given size */
  2208. int mp_init_size (mp_int * a, int size)
  2209. {
  2210. int x;
  2211. /* pad size so there are always extra digits */
  2212. size += (MP_PREC * 2) - (size % MP_PREC);
  2213. /* alloc mem */
  2214. a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size);
  2215. if (a->dp == NULL) {
  2216. return MP_MEM;
  2217. }
  2218. /* set the members */
  2219. a->used = 0;
  2220. a->alloc = size;
  2221. a->sign = MP_ZPOS;
  2222. /* zero the digits */
  2223. for (x = 0; x < size; x++) {
  2224. a->dp[x] = 0;
  2225. }
  2226. return MP_OKAY;
  2227. }
  2228. /* the jist of squaring...
  2229. * you do like mult except the offset of the tmpx [one that
  2230. * starts closer to zero] can't equal the offset of tmpy.
  2231. * So basically you set up iy like before then you min it with
  2232. * (ty-tx) so that it never happens. You double all those
  2233. * you add in the inner loop
  2234. After that loop you do the squares and add them in.
  2235. */
  2236. int fast_s_mp_sqr (mp_int * a, mp_int * b)
  2237. {
  2238. int olduse, res, pa, ix, iz;
  2239. mp_digit W[MP_WARRAY];
  2240. mp_digit *tmpx;
  2241. mp_word W1;
  2242. /* grow the destination as required */
  2243. pa = a->used + a->used;
  2244. if (b->alloc < pa) {
  2245. if ((res = mp_grow (b, pa)) != MP_OKAY) {
  2246. return res;
  2247. }
  2248. }
  2249. if (pa > MP_WARRAY)
  2250. return MP_RANGE; /* TAO range check */
  2251. /* number of output digits to produce */
  2252. W1 = 0;
  2253. for (ix = 0; ix < pa; ix++) {
  2254. int tx, ty, iy;
  2255. mp_word _W;
  2256. mp_digit *tmpy;
  2257. /* clear counter */
  2258. _W = 0;
  2259. /* get offsets into the two bignums */
  2260. ty = MIN(a->used-1, ix);
  2261. tx = ix - ty;
  2262. /* setup temp aliases */
  2263. tmpx = a->dp + tx;
  2264. tmpy = a->dp + ty;
  2265. /* this is the number of times the loop will iterrate, essentially
  2266. while (tx++ < a->used && ty-- >= 0) { ... }
  2267. */
  2268. iy = MIN(a->used-tx, ty+1);
  2269. /* now for squaring tx can never equal ty
  2270. * we halve the distance since they approach at a rate of 2x
  2271. * and we have to round because odd cases need to be executed
  2272. */
  2273. iy = MIN(iy, (ty-tx+1)>>1);
  2274. /* execute loop */
  2275. for (iz = 0; iz < iy; iz++) {
  2276. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  2277. }
  2278. /* double the inner product and add carry */
  2279. _W = _W + _W + W1;
  2280. /* even columns have the square term in them */
  2281. if ((ix&1) == 0) {
  2282. _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]);
  2283. }
  2284. /* store it */
  2285. W[ix] = (mp_digit)(_W & MP_MASK);
  2286. /* make next carry */
  2287. W1 = _W >> ((mp_word)DIGIT_BIT);
  2288. }
  2289. /* setup dest */
  2290. olduse = b->used;
  2291. b->used = a->used+a->used;
  2292. {
  2293. mp_digit *tmpb;
  2294. tmpb = b->dp;
  2295. for (ix = 0; ix < pa; ix++) {
  2296. *tmpb++ = W[ix] & MP_MASK;
  2297. }
  2298. /* clear unused digits [that existed in the old copy of c] */
  2299. for (; ix < olduse; ix++) {
  2300. *tmpb++ = 0;
  2301. }
  2302. }
  2303. mp_clamp (b);
  2304. return MP_OKAY;
  2305. }
  2306. /* Fast (comba) multiplier
  2307. *
  2308. * This is the fast column-array [comba] multiplier. It is
  2309. * designed to compute the columns of the product first
  2310. * then handle the carries afterwards. This has the effect
  2311. * of making the nested loops that compute the columns very
  2312. * simple and schedulable on super-scalar processors.
  2313. *
  2314. * This has been modified to produce a variable number of
  2315. * digits of output so if say only a half-product is required
  2316. * you don't have to compute the upper half (a feature
  2317. * required for fast Barrett reduction).
  2318. *
  2319. * Based on Algorithm 14.12 on pp.595 of HAC.
  2320. *
  2321. */
  2322. int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  2323. {
  2324. int olduse, res, pa, ix, iz;
  2325. mp_digit W[MP_WARRAY];
  2326. register mp_word _W;
  2327. /* grow the destination as required */
  2328. if (c->alloc < digs) {
  2329. if ((res = mp_grow (c, digs)) != MP_OKAY) {
  2330. return res;
  2331. }
  2332. }
  2333. /* number of output digits to produce */
  2334. pa = MIN(digs, a->used + b->used);
  2335. if (pa > MP_WARRAY)
  2336. return MP_RANGE; /* TAO range check */
  2337. /* clear the carry */
  2338. _W = 0;
  2339. for (ix = 0; ix < pa; ix++) {
  2340. int tx, ty;
  2341. int iy;
  2342. mp_digit *tmpx, *tmpy;
  2343. /* get offsets into the two bignums */
  2344. ty = MIN(b->used-1, ix);
  2345. tx = ix - ty;
  2346. /* setup temp aliases */
  2347. tmpx = a->dp + tx;
  2348. tmpy = b->dp + ty;
  2349. /* this is the number of times the loop will iterrate, essentially
  2350. while (tx++ < a->used && ty-- >= 0) { ... }
  2351. */
  2352. iy = MIN(a->used-tx, ty+1);
  2353. /* execute loop */
  2354. for (iz = 0; iz < iy; ++iz) {
  2355. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  2356. }
  2357. /* store term */
  2358. W[ix] = ((mp_digit)_W) & MP_MASK;
  2359. /* make next carry */
  2360. _W = _W >> ((mp_word)DIGIT_BIT);
  2361. }
  2362. /* setup dest */
  2363. olduse = c->used;
  2364. c->used = pa;
  2365. {
  2366. register mp_digit *tmpc;
  2367. tmpc = c->dp;
  2368. for (ix = 0; ix < pa+1; ix++) {
  2369. /* now extract the previous digit [below the carry] */
  2370. *tmpc++ = W[ix];
  2371. }
  2372. /* clear unused digits [that existed in the old copy of c] */
  2373. for (; ix < olduse; ix++) {
  2374. *tmpc++ = 0;
  2375. }
  2376. }
  2377. mp_clamp (c);
  2378. return MP_OKAY;
  2379. }
  2380. /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */
  2381. int s_mp_sqr (mp_int * a, mp_int * b)
  2382. {
  2383. mp_int t;
  2384. int res, ix, iy, pa;
  2385. mp_word r;
  2386. mp_digit u, tmpx, *tmpt;
  2387. pa = a->used;
  2388. if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) {
  2389. return res;
  2390. }
  2391. /* default used is maximum possible size */
  2392. t.used = 2*pa + 1;
  2393. for (ix = 0; ix < pa; ix++) {
  2394. /* first calculate the digit at 2*ix */
  2395. /* calculate double precision result */
  2396. r = ((mp_word) t.dp[2*ix]) +
  2397. ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]);
  2398. /* store lower part in result */
  2399. t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK));
  2400. /* get the carry */
  2401. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2402. /* left hand side of A[ix] * A[iy] */
  2403. tmpx = a->dp[ix];
  2404. /* alias for where to store the results */
  2405. tmpt = t.dp + (2*ix + 1);
  2406. for (iy = ix + 1; iy < pa; iy++) {
  2407. /* first calculate the product */
  2408. r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]);
  2409. /* now calculate the double precision result, note we use
  2410. * addition instead of *2 since it's easier to optimize
  2411. */
  2412. r = ((mp_word) *tmpt) + r + r + ((mp_word) u);
  2413. /* store lower part */
  2414. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2415. /* get carry */
  2416. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2417. }
  2418. /* propagate upwards */
  2419. while (u != ((mp_digit) 0)) {
  2420. r = ((mp_word) *tmpt) + ((mp_word) u);
  2421. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2422. u = (mp_digit)(r >> ((mp_word) DIGIT_BIT));
  2423. }
  2424. }
  2425. mp_clamp (&t);
  2426. mp_exch (&t, b);
  2427. mp_clear (&t);
  2428. return MP_OKAY;
  2429. }
  2430. /* multiplies |a| * |b| and only computes upto digs digits of result
  2431. * HAC pp. 595, Algorithm 14.12 Modified so you can control how
  2432. * many digits of output are created.
  2433. */
  2434. int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  2435. {
  2436. mp_int t;
  2437. int res, pa, pb, ix, iy;
  2438. mp_digit u;
  2439. mp_word r;
  2440. mp_digit tmpx, *tmpt, *tmpy;
  2441. /* can we use the fast multiplier? */
  2442. if (((digs) < MP_WARRAY) &&
  2443. MIN (a->used, b->used) <
  2444. (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) {
  2445. return fast_s_mp_mul_digs (a, b, c, digs);
  2446. }
  2447. if ((res = mp_init_size (&t, digs)) != MP_OKAY) {
  2448. return res;
  2449. }
  2450. t.used = digs;
  2451. /* compute the digits of the product directly */
  2452. pa = a->used;
  2453. for (ix = 0; ix < pa; ix++) {
  2454. /* set the carry to zero */
  2455. u = 0;
  2456. /* limit ourselves to making digs digits of output */
  2457. pb = MIN (b->used, digs - ix);
  2458. /* setup some aliases */
  2459. /* copy of the digit from a used within the nested loop */
  2460. tmpx = a->dp[ix];
  2461. /* an alias for the destination shifted ix places */
  2462. tmpt = t.dp + ix;
  2463. /* an alias for the digits of b */
  2464. tmpy = b->dp;
  2465. /* compute the columns of the output and propagate the carry */
  2466. for (iy = 0; iy < pb; iy++) {
  2467. /* compute the column as a mp_word */
  2468. r = ((mp_word)*tmpt) +
  2469. ((mp_word)tmpx) * ((mp_word)*tmpy++) +
  2470. ((mp_word) u);
  2471. /* the new column is the lower part of the result */
  2472. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2473. /* get the carry word from the result */
  2474. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  2475. }
  2476. /* set carry if it is placed below digs */
  2477. if (ix + iy < digs) {
  2478. *tmpt = u;
  2479. }
  2480. }
  2481. mp_clamp (&t);
  2482. mp_exch (&t, c);
  2483. mp_clear (&t);
  2484. return MP_OKAY;
  2485. }
  2486. /*
  2487. * shifts with subtractions when the result is greater than b.
  2488. *
  2489. * The method is slightly modified to shift B unconditionally upto just under
  2490. * the leading bit of b. This saves alot of multiple precision shifting.
  2491. */
  2492. int mp_montgomery_calc_normalization (mp_int * a, mp_int * b)
  2493. {
  2494. int x, bits, res;
  2495. /* how many bits of last digit does b use */
  2496. bits = mp_count_bits (b) % DIGIT_BIT;
  2497. if (b->used > 1) {
  2498. if ((res = mp_2expt (a, (b->used - 1) * DIGIT_BIT + bits - 1)) != MP_OKAY) {
  2499. return res;
  2500. }
  2501. } else {
  2502. mp_set(a, 1);
  2503. bits = 1;
  2504. }
  2505. /* now compute C = A * B mod b */
  2506. for (x = bits - 1; x < (int)DIGIT_BIT; x++) {
  2507. if ((res = mp_mul_2 (a, a)) != MP_OKAY) {
  2508. return res;
  2509. }
  2510. if (mp_cmp_mag (a, b) != MP_LT) {
  2511. if ((res = s_mp_sub (a, b, a)) != MP_OKAY) {
  2512. return res;
  2513. }
  2514. }
  2515. }
  2516. return MP_OKAY;
  2517. }
  2518. #define TAB_SIZE 256
  2519. int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmode)
  2520. {
  2521. mp_int M[TAB_SIZE], res, mu;
  2522. mp_digit buf;
  2523. int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize;
  2524. int (*redux)(mp_int*,mp_int*,mp_int*);
  2525. /* find window size */
  2526. x = mp_count_bits (X);
  2527. if (x <= 7) {
  2528. winsize = 2;
  2529. } else if (x <= 36) {
  2530. winsize = 3;
  2531. } else if (x <= 140) {
  2532. winsize = 4;
  2533. } else if (x <= 450) {
  2534. winsize = 5;
  2535. } else if (x <= 1303) {
  2536. winsize = 6;
  2537. } else if (x <= 3529) {
  2538. winsize = 7;
  2539. } else {
  2540. winsize = 8;
  2541. }
  2542. /* init M array */
  2543. /* init first cell */
  2544. if ((err = mp_init(&M[1])) != MP_OKAY) {
  2545. return err;
  2546. }
  2547. /* now init the second half of the array */
  2548. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  2549. if ((err = mp_init(&M[x])) != MP_OKAY) {
  2550. for (y = 1<<(winsize-1); y < x; y++) {
  2551. mp_clear (&M[y]);
  2552. }
  2553. mp_clear(&M[1]);
  2554. return err;
  2555. }
  2556. }
  2557. /* create mu, used for Barrett reduction */
  2558. if ((err = mp_init (&mu)) != MP_OKAY) {
  2559. goto LBL_M;
  2560. }
  2561. if (redmode == 0) {
  2562. if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) {
  2563. goto LBL_MU;
  2564. }
  2565. redux = mp_reduce;
  2566. } else {
  2567. if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) {
  2568. goto LBL_MU;
  2569. }
  2570. redux = mp_reduce_2k_l;
  2571. }
  2572. /* create M table
  2573. *
  2574. * The M table contains powers of the base,
  2575. * e.g. M[x] = G**x mod P
  2576. *
  2577. * The first half of the table is not
  2578. * computed though accept for M[0] and M[1]
  2579. */
  2580. if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) {
  2581. goto LBL_MU;
  2582. }
  2583. /* compute the value at M[1<<(winsize-1)] by squaring
  2584. * M[1] (winsize-1) times
  2585. */
  2586. if ((err = mp_copy (&M[1], &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  2587. goto LBL_MU;
  2588. }
  2589. for (x = 0; x < (winsize - 1); x++) {
  2590. /* square it */
  2591. if ((err = mp_sqr (&M[(mp_digit)(1 << (winsize - 1))],
  2592. &M[(mp_digit)(1 << (winsize - 1))])) != MP_OKAY) {
  2593. goto LBL_MU;
  2594. }
  2595. /* reduce modulo P */
  2596. if ((err = redux (&M[(mp_digit)(1 << (winsize - 1))], P, &mu)) != MP_OKAY) {
  2597. goto LBL_MU;
  2598. }
  2599. }
  2600. /* create upper table, that is M[x] = M[x-1] * M[1] (mod P)
  2601. * for x = (2**(winsize - 1) + 1) to (2**winsize - 1)
  2602. */
  2603. for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) {
  2604. if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) {
  2605. goto LBL_MU;
  2606. }
  2607. if ((err = redux (&M[x], P, &mu)) != MP_OKAY) {
  2608. goto LBL_MU;
  2609. }
  2610. }
  2611. /* setup result */
  2612. if ((err = mp_init (&res)) != MP_OKAY) {
  2613. goto LBL_MU;
  2614. }
  2615. mp_set (&res, 1);
  2616. /* set initial mode and bit cnt */
  2617. mode = 0;
  2618. bitcnt = 1;
  2619. buf = 0;
  2620. digidx = X->used - 1;
  2621. bitcpy = 0;
  2622. bitbuf = 0;
  2623. for (;;) {
  2624. /* grab next digit as required */
  2625. if (--bitcnt == 0) {
  2626. /* if digidx == -1 we are out of digits */
  2627. if (digidx == -1) {
  2628. break;
  2629. }
  2630. /* read next digit and reset the bitcnt */
  2631. buf = X->dp[digidx--];
  2632. bitcnt = (int) DIGIT_BIT;
  2633. }
  2634. /* grab the next msb from the exponent */
  2635. y = (int)(buf >> (mp_digit)(DIGIT_BIT - 1)) & 1;
  2636. buf <<= (mp_digit)1;
  2637. /* if the bit is zero and mode == 0 then we ignore it
  2638. * These represent the leading zero bits before the first 1 bit
  2639. * in the exponent. Technically this opt is not required but it
  2640. * does lower the # of trivial squaring/reductions used
  2641. */
  2642. if (mode == 0 && y == 0) {
  2643. continue;
  2644. }
  2645. /* if the bit is zero and mode == 1 then we square */
  2646. if (mode == 1 && y == 0) {
  2647. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  2648. goto LBL_RES;
  2649. }
  2650. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  2651. goto LBL_RES;
  2652. }
  2653. continue;
  2654. }
  2655. /* else we add it to the window */
  2656. bitbuf |= (y << (winsize - ++bitcpy));
  2657. mode = 2;
  2658. if (bitcpy == winsize) {
  2659. /* ok window is filled so square as required and multiply */
  2660. /* square first */
  2661. for (x = 0; x < winsize; x++) {
  2662. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  2663. goto LBL_RES;
  2664. }
  2665. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  2666. goto LBL_RES;
  2667. }
  2668. }
  2669. /* then multiply */
  2670. if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) {
  2671. goto LBL_RES;
  2672. }
  2673. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  2674. goto LBL_RES;
  2675. }
  2676. /* empty window and reset */
  2677. bitcpy = 0;
  2678. bitbuf = 0;
  2679. mode = 1;
  2680. }
  2681. }
  2682. /* if bits remain then square/multiply */
  2683. if (mode == 2 && bitcpy > 0) {
  2684. /* square then multiply if the bit is set */
  2685. for (x = 0; x < bitcpy; x++) {
  2686. if ((err = mp_sqr (&res, &res)) != MP_OKAY) {
  2687. goto LBL_RES;
  2688. }
  2689. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  2690. goto LBL_RES;
  2691. }
  2692. bitbuf <<= 1;
  2693. if ((bitbuf & (1 << winsize)) != 0) {
  2694. /* then multiply */
  2695. if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) {
  2696. goto LBL_RES;
  2697. }
  2698. if ((err = redux (&res, P, &mu)) != MP_OKAY) {
  2699. goto LBL_RES;
  2700. }
  2701. }
  2702. }
  2703. }
  2704. mp_exch (&res, Y);
  2705. err = MP_OKAY;
  2706. LBL_RES:mp_clear (&res);
  2707. LBL_MU:mp_clear (&mu);
  2708. LBL_M:
  2709. mp_clear(&M[1]);
  2710. for (x = 1<<(winsize-1); x < (1 << winsize); x++) {
  2711. mp_clear (&M[x]);
  2712. }
  2713. return err;
  2714. }
  2715. /* pre-calculate the value required for Barrett reduction
  2716. * For a given modulus "b" it calulates the value required in "a"
  2717. */
  2718. int mp_reduce_setup (mp_int * a, mp_int * b)
  2719. {
  2720. int res;
  2721. if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) {
  2722. return res;
  2723. }
  2724. return mp_div (a, b, a, NULL);
  2725. }
  2726. /* reduces x mod m, assumes 0 < x < m**2, mu is
  2727. * precomputed via mp_reduce_setup.
  2728. * From HAC pp.604 Algorithm 14.42
  2729. */
  2730. int mp_reduce (mp_int * x, mp_int * m, mp_int * mu)
  2731. {
  2732. mp_int q;
  2733. int res, um = m->used;
  2734. /* q = x */
  2735. if ((res = mp_init_copy (&q, x)) != MP_OKAY) {
  2736. return res;
  2737. }
  2738. /* q1 = x / b**(k-1) */
  2739. mp_rshd (&q, um - 1);
  2740. /* according to HAC this optimization is ok */
  2741. if (((mp_word) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) {
  2742. if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) {
  2743. goto CLEANUP;
  2744. }
  2745. } else {
  2746. if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) {
  2747. goto CLEANUP;
  2748. }
  2749. res = MP_VAL;
  2750. goto CLEANUP;
  2751. }
  2752. /* q3 = q2 / b**(k+1) */
  2753. mp_rshd (&q, um + 1);
  2754. /* x = x mod b**(k+1), quick (no division) */
  2755. if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) {
  2756. goto CLEANUP;
  2757. }
  2758. /* q = q * m mod b**(k+1), quick (no division) */
  2759. if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) {
  2760. goto CLEANUP;
  2761. }
  2762. /* x = x - q */
  2763. if ((res = mp_sub (x, &q, x)) != MP_OKAY) {
  2764. goto CLEANUP;
  2765. }
  2766. /* If x < 0, add b**(k+1) to it */
  2767. if (mp_cmp_d (x, 0) == MP_LT) {
  2768. mp_set (&q, 1);
  2769. if ((res = mp_lshd (&q, um + 1)) != MP_OKAY)
  2770. goto CLEANUP;
  2771. if ((res = mp_add (x, &q, x)) != MP_OKAY)
  2772. goto CLEANUP;
  2773. }
  2774. /* Back off if it's too big */
  2775. while (mp_cmp (x, m) != MP_LT) {
  2776. if ((res = s_mp_sub (x, m, x)) != MP_OKAY) {
  2777. goto CLEANUP;
  2778. }
  2779. }
  2780. CLEANUP:
  2781. mp_clear (&q);
  2782. return res;
  2783. }
  2784. /* reduces a modulo n where n is of the form 2**p - d
  2785. This differs from reduce_2k since "d" can be larger
  2786. than a single digit.
  2787. */
  2788. int mp_reduce_2k_l(mp_int *a, mp_int *n, mp_int *d)
  2789. {
  2790. mp_int q;
  2791. int p, res;
  2792. if ((res = mp_init(&q)) != MP_OKAY) {
  2793. return res;
  2794. }
  2795. p = mp_count_bits(n);
  2796. top:
  2797. /* q = a/2**p, a = a mod 2**p */
  2798. if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) {
  2799. goto ERR;
  2800. }
  2801. /* q = q * d */
  2802. if ((res = mp_mul(&q, d, &q)) != MP_OKAY) {
  2803. goto ERR;
  2804. }
  2805. /* a = a + q */
  2806. if ((res = s_mp_add(a, &q, a)) != MP_OKAY) {
  2807. goto ERR;
  2808. }
  2809. if (mp_cmp_mag(a, n) != MP_LT) {
  2810. s_mp_sub(a, n, a);
  2811. goto top;
  2812. }
  2813. ERR:
  2814. mp_clear(&q);
  2815. return res;
  2816. }
  2817. /* determines the setup value */
  2818. int mp_reduce_2k_setup_l(mp_int *a, mp_int *d)
  2819. {
  2820. int res;
  2821. mp_int tmp;
  2822. if ((res = mp_init(&tmp)) != MP_OKAY) {
  2823. return res;
  2824. }
  2825. if ((res = mp_2expt(&tmp, mp_count_bits(a))) != MP_OKAY) {
  2826. goto ERR;
  2827. }
  2828. if ((res = s_mp_sub(&tmp, a, d)) != MP_OKAY) {
  2829. goto ERR;
  2830. }
  2831. ERR:
  2832. mp_clear(&tmp);
  2833. return res;
  2834. }
  2835. /* multiplies |a| * |b| and does not compute the lower digs digits
  2836. * [meant to get the higher part of the product]
  2837. */
  2838. int
  2839. s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  2840. {
  2841. mp_int t;
  2842. int res, pa, pb, ix, iy;
  2843. mp_digit u;
  2844. mp_word r;
  2845. mp_digit tmpx, *tmpt, *tmpy;
  2846. if ((res = mp_init_size (&t, a->used + b->used + 1)) != MP_OKAY) {
  2847. return res;
  2848. }
  2849. t.used = a->used + b->used + 1;
  2850. pa = a->used;
  2851. pb = b->used;
  2852. for (ix = 0; ix < pa; ix++) {
  2853. /* clear the carry */
  2854. u = 0;
  2855. /* left hand side of A[ix] * B[iy] */
  2856. tmpx = a->dp[ix];
  2857. /* alias to the address of where the digits will be stored */
  2858. tmpt = &(t.dp[digs]);
  2859. /* alias for where to read the right hand side from */
  2860. tmpy = b->dp + (digs - ix);
  2861. for (iy = digs - ix; iy < pb; iy++) {
  2862. /* calculate the double precision result */
  2863. r = ((mp_word)*tmpt) +
  2864. ((mp_word)tmpx) * ((mp_word)*tmpy++) +
  2865. ((mp_word) u);
  2866. /* get the lower part */
  2867. *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK));
  2868. /* carry the carry */
  2869. u = (mp_digit) (r >> ((mp_word) DIGIT_BIT));
  2870. }
  2871. *tmpt = u;
  2872. }
  2873. mp_clamp (&t);
  2874. mp_exch (&t, c);
  2875. mp_clear (&t);
  2876. return MP_OKAY;
  2877. }
  2878. /* this is a modified version of fast_s_mul_digs that only produces
  2879. * output digits *above* digs. See the comments for fast_s_mul_digs
  2880. * to see how it works.
  2881. *
  2882. * This is used in the Barrett reduction since for one of the multiplications
  2883. * only the higher digits were needed. This essentially halves the work.
  2884. *
  2885. * Based on Algorithm 14.12 on pp.595 of HAC.
  2886. */
  2887. int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs)
  2888. {
  2889. int olduse, res, pa, ix, iz;
  2890. mp_digit W[MP_WARRAY];
  2891. mp_word _W;
  2892. /* grow the destination as required */
  2893. pa = a->used + b->used;
  2894. if (c->alloc < pa) {
  2895. if ((res = mp_grow (c, pa)) != MP_OKAY) {
  2896. return res;
  2897. }
  2898. }
  2899. if (pa > MP_WARRAY)
  2900. return MP_RANGE; /* TAO range check */
  2901. /* number of output digits to produce */
  2902. pa = a->used + b->used;
  2903. _W = 0;
  2904. for (ix = digs; ix < pa; ix++) {
  2905. int tx, ty, iy;
  2906. mp_digit *tmpx, *tmpy;
  2907. /* get offsets into the two bignums */
  2908. ty = MIN(b->used-1, ix);
  2909. tx = ix - ty;
  2910. /* setup temp aliases */
  2911. tmpx = a->dp + tx;
  2912. tmpy = b->dp + ty;
  2913. /* this is the number of times the loop will iterrate, essentially its
  2914. while (tx++ < a->used && ty-- >= 0) { ... }
  2915. */
  2916. iy = MIN(a->used-tx, ty+1);
  2917. /* execute loop */
  2918. for (iz = 0; iz < iy; iz++) {
  2919. _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--);
  2920. }
  2921. /* store term */
  2922. W[ix] = ((mp_digit)_W) & MP_MASK;
  2923. /* make next carry */
  2924. _W = _W >> ((mp_word)DIGIT_BIT);
  2925. }
  2926. /* setup dest */
  2927. olduse = c->used;
  2928. c->used = pa;
  2929. {
  2930. register mp_digit *tmpc;
  2931. tmpc = c->dp + digs;
  2932. for (ix = digs; ix <= pa; ix++) {
  2933. /* now extract the previous digit [below the carry] */
  2934. *tmpc++ = W[ix];
  2935. }
  2936. /* clear unused digits [that existed in the old copy of c] */
  2937. for (; ix < olduse; ix++) {
  2938. *tmpc++ = 0;
  2939. }
  2940. }
  2941. mp_clamp (c);
  2942. return MP_OKAY;
  2943. }
  2944. /* set a 32-bit const */
  2945. int mp_set_int (mp_int * a, unsigned long b)
  2946. {
  2947. int x, res;
  2948. mp_zero (a);
  2949. /* set four bits at a time */
  2950. for (x = 0; x < 8; x++) {
  2951. /* shift the number up four bits */
  2952. if ((res = mp_mul_2d (a, 4, a)) != MP_OKAY) {
  2953. return res;
  2954. }
  2955. /* OR in the top four bits of the source */
  2956. a->dp[0] |= (b >> 28) & 15;
  2957. /* shift the source up to the next four bits */
  2958. b <<= 4;
  2959. /* ensure that digits are not clamped off */
  2960. a->used += 1;
  2961. }
  2962. mp_clamp (a);
  2963. return MP_OKAY;
  2964. }
  2965. /* c = a * a (mod b) */
  2966. int mp_sqrmod (mp_int * a, mp_int * b, mp_int * c)
  2967. {
  2968. int res;
  2969. mp_int t;
  2970. if ((res = mp_init (&t)) != MP_OKAY) {
  2971. return res;
  2972. }
  2973. if ((res = mp_sqr (a, &t)) != MP_OKAY) {
  2974. mp_clear (&t);
  2975. return res;
  2976. }
  2977. res = mp_mod (&t, b, c);
  2978. mp_clear (&t);
  2979. return res;
  2980. }
  2981. /* single digit addition */
  2982. int mp_add_d (mp_int* a, mp_digit b, mp_int* c)
  2983. {
  2984. int res, ix, oldused;
  2985. mp_digit *tmpa, *tmpc, mu;
  2986. /* grow c as required */
  2987. if (c->alloc < a->used + 1) {
  2988. if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
  2989. return res;
  2990. }
  2991. }
  2992. /* if a is negative and |a| >= b, call c = |a| - b */
  2993. if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) {
  2994. /* temporarily fix sign of a */
  2995. a->sign = MP_ZPOS;
  2996. /* c = |a| - b */
  2997. res = mp_sub_d(a, b, c);
  2998. /* fix sign */
  2999. a->sign = c->sign = MP_NEG;
  3000. /* clamp */
  3001. mp_clamp(c);
  3002. return res;
  3003. }
  3004. /* old number of used digits in c */
  3005. oldused = c->used;
  3006. /* sign always positive */
  3007. c->sign = MP_ZPOS;
  3008. /* source alias */
  3009. tmpa = a->dp;
  3010. /* destination alias */
  3011. tmpc = c->dp;
  3012. /* if a is positive */
  3013. if (a->sign == MP_ZPOS) {
  3014. /* add digit, after this we're propagating
  3015. * the carry.
  3016. */
  3017. *tmpc = *tmpa++ + b;
  3018. mu = *tmpc >> DIGIT_BIT;
  3019. *tmpc++ &= MP_MASK;
  3020. /* now handle rest of the digits */
  3021. for (ix = 1; ix < a->used; ix++) {
  3022. *tmpc = *tmpa++ + mu;
  3023. mu = *tmpc >> DIGIT_BIT;
  3024. *tmpc++ &= MP_MASK;
  3025. }
  3026. /* set final carry */
  3027. if (mu != 0 && ix < c->alloc) {
  3028. ix++;
  3029. *tmpc++ = mu;
  3030. }
  3031. /* setup size */
  3032. c->used = a->used + 1;
  3033. } else {
  3034. /* a was negative and |a| < b */
  3035. c->used = 1;
  3036. /* the result is a single digit */
  3037. if (a->used == 1) {
  3038. *tmpc++ = b - a->dp[0];
  3039. } else {
  3040. *tmpc++ = b;
  3041. }
  3042. /* setup count so the clearing of oldused
  3043. * can fall through correctly
  3044. */
  3045. ix = 1;
  3046. }
  3047. /* now zero to oldused */
  3048. while (ix++ < oldused) {
  3049. *tmpc++ = 0;
  3050. }
  3051. mp_clamp(c);
  3052. return MP_OKAY;
  3053. }
  3054. /* single digit subtraction */
  3055. int mp_sub_d (mp_int * a, mp_digit b, mp_int * c)
  3056. {
  3057. mp_digit *tmpa, *tmpc, mu;
  3058. int res, ix, oldused;
  3059. /* grow c as required */
  3060. if (c->alloc < a->used + 1) {
  3061. if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) {
  3062. return res;
  3063. }
  3064. }
  3065. /* if a is negative just do an unsigned
  3066. * addition [with fudged signs]
  3067. */
  3068. if (a->sign == MP_NEG) {
  3069. a->sign = MP_ZPOS;
  3070. res = mp_add_d(a, b, c);
  3071. a->sign = c->sign = MP_NEG;
  3072. /* clamp */
  3073. mp_clamp(c);
  3074. return res;
  3075. }
  3076. /* setup regs */
  3077. oldused = c->used;
  3078. tmpa = a->dp;
  3079. tmpc = c->dp;
  3080. /* if a <= b simply fix the single digit */
  3081. if ((a->used == 1 && a->dp[0] <= b) || a->used == 0) {
  3082. if (a->used == 1) {
  3083. *tmpc++ = b - *tmpa;
  3084. } else {
  3085. *tmpc++ = b;
  3086. }
  3087. ix = 1;
  3088. /* negative/1digit */
  3089. c->sign = MP_NEG;
  3090. c->used = 1;
  3091. } else {
  3092. /* positive/size */
  3093. c->sign = MP_ZPOS;
  3094. c->used = a->used;
  3095. /* subtract first digit */
  3096. *tmpc = *tmpa++ - b;
  3097. mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
  3098. *tmpc++ &= MP_MASK;
  3099. /* handle rest of the digits */
  3100. for (ix = 1; ix < a->used; ix++) {
  3101. *tmpc = *tmpa++ - mu;
  3102. mu = *tmpc >> (sizeof(mp_digit) * CHAR_BIT - 1);
  3103. *tmpc++ &= MP_MASK;
  3104. }
  3105. }
  3106. /* zero excess digits */
  3107. while (ix++ < oldused) {
  3108. *tmpc++ = 0;
  3109. }
  3110. mp_clamp(c);
  3111. return MP_OKAY;
  3112. }
  3113. static const int lnz[16] = {
  3114. 4, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0
  3115. };
  3116. /* Counts the number of lsbs which are zero before the first zero bit */
  3117. int mp_cnt_lsb(mp_int *a)
  3118. {
  3119. int x;
  3120. mp_digit q, qq;
  3121. /* easy out */
  3122. if (mp_iszero(a) == 1) {
  3123. return 0;
  3124. }
  3125. /* scan lower digits until non-zero */
  3126. for (x = 0; x < a->used && a->dp[x] == 0; x++);
  3127. q = a->dp[x];
  3128. x *= DIGIT_BIT;
  3129. /* now scan this digit until a 1 is found */
  3130. if ((q & 1) == 0) {
  3131. do {
  3132. qq = q & 15;
  3133. x += lnz[qq];
  3134. q >>= 4;
  3135. } while (qq == 0);
  3136. }
  3137. return x;
  3138. }
  3139. static int s_is_power_of_two(mp_digit b, int *p)
  3140. {
  3141. int x;
  3142. /* fast return if no power of two */
  3143. if ((b==0) || (b & (b-1))) {
  3144. return 0;
  3145. }
  3146. for (x = 0; x < DIGIT_BIT; x++) {
  3147. if (b == (((mp_digit)1)<<x)) {
  3148. *p = x;
  3149. return 1;
  3150. }
  3151. }
  3152. return 0;
  3153. }
  3154. /* single digit division (based on routine from MPI) */
  3155. static int mp_div_d (mp_int * a, mp_digit b, mp_int * c, mp_digit * d)
  3156. {
  3157. mp_int q;
  3158. mp_word w;
  3159. mp_digit t;
  3160. int res, ix;
  3161. /* cannot divide by zero */
  3162. if (b == 0) {
  3163. return MP_VAL;
  3164. }
  3165. /* quick outs */
  3166. if (b == 1 || mp_iszero(a) == 1) {
  3167. if (d != NULL) {
  3168. *d = 0;
  3169. }
  3170. if (c != NULL) {
  3171. return mp_copy(a, c);
  3172. }
  3173. return MP_OKAY;
  3174. }
  3175. /* power of two ? */
  3176. if (s_is_power_of_two(b, &ix) == 1) {
  3177. if (d != NULL) {
  3178. *d = a->dp[0] & ((((mp_digit)1)<<ix) - 1);
  3179. }
  3180. if (c != NULL) {
  3181. return mp_div_2d(a, ix, c, NULL);
  3182. }
  3183. return MP_OKAY;
  3184. }
  3185. /* three? */
  3186. if (b == 3) {
  3187. return mp_div_3(a, c, d);
  3188. }
  3189. /* no easy answer [c'est la vie]. Just division */
  3190. if ((res = mp_init_size(&q, a->used)) != MP_OKAY) {
  3191. return res;
  3192. }
  3193. q.used = a->used;
  3194. q.sign = a->sign;
  3195. w = 0;
  3196. for (ix = a->used - 1; ix >= 0; ix--) {
  3197. w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]);
  3198. if (w >= b) {
  3199. t = (mp_digit)(w / b);
  3200. w -= ((mp_word)t) * ((mp_word)b);
  3201. } else {
  3202. t = 0;
  3203. }
  3204. q.dp[ix] = (mp_digit)t;
  3205. }
  3206. if (d != NULL) {
  3207. *d = (mp_digit)w;
  3208. }
  3209. if (c != NULL) {
  3210. mp_clamp(&q);
  3211. mp_exch(&q, c);
  3212. }
  3213. mp_clear(&q);
  3214. return res;
  3215. }
  3216. int mp_mod_d (mp_int * a, mp_digit b, mp_digit * c)
  3217. {
  3218. return mp_div_d(a, b, NULL, c);
  3219. }
  3220. const mp_digit ltm_prime_tab[] = {
  3221. 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013,
  3222. 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035,
  3223. 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059,
  3224. 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F,
  3225. #ifndef MP_8BIT
  3226. 0x0083,
  3227. 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD,
  3228. 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF,
  3229. 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107,
  3230. 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137,
  3231. 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167,
  3232. 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199,
  3233. 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9,
  3234. 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7,
  3235. 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239,
  3236. 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265,
  3237. 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293,
  3238. 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF,
  3239. 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301,
  3240. 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B,
  3241. 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371,
  3242. 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD,
  3243. 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5,
  3244. 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419,
  3245. 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449,
  3246. 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B,
  3247. 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7,
  3248. 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503,
  3249. 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529,
  3250. 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F,
  3251. 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3,
  3252. 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7,
  3253. 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623,
  3254. 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653
  3255. #endif
  3256. };
  3257. /* Miller-Rabin test of "a" to the base of "b" as described in
  3258. * HAC pp. 139 Algorithm 4.24
  3259. *
  3260. * Sets result to 0 if definitely composite or 1 if probably prime.
  3261. * Randomly the chance of error is no more than 1/4 and often
  3262. * very much lower.
  3263. */
  3264. static int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result)
  3265. {
  3266. mp_int n1, y, r;
  3267. int s, j, err;
  3268. /* default */
  3269. *result = MP_NO;
  3270. /* ensure b > 1 */
  3271. if (mp_cmp_d(b, 1) != MP_GT) {
  3272. return MP_VAL;
  3273. }
  3274. /* get n1 = a - 1 */
  3275. if ((err = mp_init_copy (&n1, a)) != MP_OKAY) {
  3276. return err;
  3277. }
  3278. if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) {
  3279. goto LBL_N1;
  3280. }
  3281. /* set 2**s * r = n1 */
  3282. if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) {
  3283. goto LBL_N1;
  3284. }
  3285. /* count the number of least significant bits
  3286. * which are zero
  3287. */
  3288. s = mp_cnt_lsb(&r);
  3289. /* now divide n - 1 by 2**s */
  3290. if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) {
  3291. goto LBL_R;
  3292. }
  3293. /* compute y = b**r mod a */
  3294. if ((err = mp_init (&y)) != MP_OKAY) {
  3295. goto LBL_R;
  3296. }
  3297. if ((err = mp_exptmod (b, &r, a, &y)) != MP_OKAY) {
  3298. goto LBL_Y;
  3299. }
  3300. /* if y != 1 and y != n1 do */
  3301. if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) {
  3302. j = 1;
  3303. /* while j <= s-1 and y != n1 */
  3304. while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) {
  3305. if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) {
  3306. goto LBL_Y;
  3307. }
  3308. /* if y == 1 then composite */
  3309. if (mp_cmp_d (&y, 1) == MP_EQ) {
  3310. goto LBL_Y;
  3311. }
  3312. ++j;
  3313. }
  3314. /* if y != n1 then composite */
  3315. if (mp_cmp (&y, &n1) != MP_EQ) {
  3316. goto LBL_Y;
  3317. }
  3318. }
  3319. /* probably prime now */
  3320. *result = MP_YES;
  3321. LBL_Y:mp_clear (&y);
  3322. LBL_R:mp_clear (&r);
  3323. LBL_N1:mp_clear (&n1);
  3324. return err;
  3325. }
  3326. /* determines if an integers is divisible by one
  3327. * of the first PRIME_SIZE primes or not
  3328. *
  3329. * sets result to 0 if not, 1 if yes
  3330. */
  3331. static int mp_prime_is_divisible (mp_int * a, int *result)
  3332. {
  3333. int err, ix;
  3334. mp_digit res;
  3335. /* default to not */
  3336. *result = MP_NO;
  3337. for (ix = 0; ix < PRIME_SIZE; ix++) {
  3338. /* what is a mod LBL_prime_tab[ix] */
  3339. if ((err = mp_mod_d (a, ltm_prime_tab[ix], &res)) != MP_OKAY) {
  3340. return err;
  3341. }
  3342. /* is the residue zero? */
  3343. if (res == 0) {
  3344. *result = MP_YES;
  3345. return MP_OKAY;
  3346. }
  3347. }
  3348. return MP_OKAY;
  3349. }
  3350. /*
  3351. * Sets result to 1 if probably prime, 0 otherwise
  3352. */
  3353. int mp_prime_is_prime (mp_int * a, int t, int *result)
  3354. {
  3355. mp_int b;
  3356. int ix, err, res;
  3357. /* default to no */
  3358. *result = MP_NO;
  3359. /* valid value of t? */
  3360. if (t <= 0 || t > PRIME_SIZE) {
  3361. return MP_VAL;
  3362. }
  3363. /* is the input equal to one of the primes in the table? */
  3364. for (ix = 0; ix < PRIME_SIZE; ix++) {
  3365. if (mp_cmp_d(a, ltm_prime_tab[ix]) == MP_EQ) {
  3366. *result = 1;
  3367. return MP_OKAY;
  3368. }
  3369. }
  3370. /* first perform trial division */
  3371. if ((err = mp_prime_is_divisible (a, &res)) != MP_OKAY) {
  3372. return err;
  3373. }
  3374. /* return if it was trivially divisible */
  3375. if (res == MP_YES) {
  3376. return MP_OKAY;
  3377. }
  3378. /* now perform the miller-rabin rounds */
  3379. if ((err = mp_init (&b)) != MP_OKAY) {
  3380. return err;
  3381. }
  3382. for (ix = 0; ix < t; ix++) {
  3383. /* set the prime */
  3384. mp_set (&b, ltm_prime_tab[ix]);
  3385. if ((err = mp_prime_miller_rabin (a, &b, &res)) != MP_OKAY) {
  3386. goto LBL_B;
  3387. }
  3388. if (res == MP_NO) {
  3389. goto LBL_B;
  3390. }
  3391. }
  3392. /* passed the test */
  3393. *result = MP_YES;
  3394. LBL_B:mp_clear (&b);
  3395. return err;
  3396. }
  3397. /* computes least common multiple as |a*b|/(a, b) */
  3398. int mp_lcm (mp_int * a, mp_int * b, mp_int * c)
  3399. {
  3400. int res;
  3401. mp_int t1, t2;
  3402. if ((res = mp_init_multi (&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) {
  3403. return res;
  3404. }
  3405. /* t1 = get the GCD of the two inputs */
  3406. if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) {
  3407. goto LBL_T;
  3408. }
  3409. /* divide the smallest by the GCD */
  3410. if (mp_cmp_mag(a, b) == MP_LT) {
  3411. /* store quotient in t2 such that t2 * b is the LCM */
  3412. if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) {
  3413. goto LBL_T;
  3414. }
  3415. res = mp_mul(b, &t2, c);
  3416. } else {
  3417. /* store quotient in t2 such that t2 * a is the LCM */
  3418. if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) {
  3419. goto LBL_T;
  3420. }
  3421. res = mp_mul(a, &t2, c);
  3422. }
  3423. /* fix the sign to positive */
  3424. c->sign = MP_ZPOS;
  3425. LBL_T:
  3426. mp_clear(&t1);
  3427. mp_clear(&t2);
  3428. return res;
  3429. }
  3430. /* Greatest Common Divisor using the binary method */
  3431. int mp_gcd (mp_int * a, mp_int * b, mp_int * c)
  3432. {
  3433. mp_int u, v;
  3434. int k, u_lsb, v_lsb, res;
  3435. /* either zero than gcd is the largest */
  3436. if (mp_iszero (a) == MP_YES) {
  3437. return mp_abs (b, c);
  3438. }
  3439. if (mp_iszero (b) == MP_YES) {
  3440. return mp_abs (a, c);
  3441. }
  3442. /* get copies of a and b we can modify */
  3443. if ((res = mp_init_copy (&u, a)) != MP_OKAY) {
  3444. return res;
  3445. }
  3446. if ((res = mp_init_copy (&v, b)) != MP_OKAY) {
  3447. goto LBL_U;
  3448. }
  3449. /* must be positive for the remainder of the algorithm */
  3450. u.sign = v.sign = MP_ZPOS;
  3451. /* B1. Find the common power of two for u and v */
  3452. u_lsb = mp_cnt_lsb(&u);
  3453. v_lsb = mp_cnt_lsb(&v);
  3454. k = MIN(u_lsb, v_lsb);
  3455. if (k > 0) {
  3456. /* divide the power of two out */
  3457. if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) {
  3458. goto LBL_V;
  3459. }
  3460. if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) {
  3461. goto LBL_V;
  3462. }
  3463. }
  3464. /* divide any remaining factors of two out */
  3465. if (u_lsb != k) {
  3466. if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) {
  3467. goto LBL_V;
  3468. }
  3469. }
  3470. if (v_lsb != k) {
  3471. if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) {
  3472. goto LBL_V;
  3473. }
  3474. }
  3475. while (mp_iszero(&v) == 0) {
  3476. /* make sure v is the largest */
  3477. if (mp_cmp_mag(&u, &v) == MP_GT) {
  3478. /* swap u and v to make sure v is >= u */
  3479. mp_exch(&u, &v);
  3480. }
  3481. /* subtract smallest from largest */
  3482. if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) {
  3483. goto LBL_V;
  3484. }
  3485. /* Divide out all factors of two */
  3486. if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) {
  3487. goto LBL_V;
  3488. }
  3489. }
  3490. /* multiply by 2**k which we divided out at the beginning */
  3491. if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) {
  3492. goto LBL_V;
  3493. }
  3494. c->sign = MP_ZPOS;
  3495. res = MP_OKAY;
  3496. LBL_V:mp_clear (&u);
  3497. LBL_U:mp_clear (&v);
  3498. return res;
  3499. }
  3500. /* chars used in radix conversions */
  3501. const char *mp_s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
  3502. /* read a string [ASCII] in a given radix */
  3503. int mp_read_radix (mp_int * a, const char *str, int radix)
  3504. {
  3505. int y, res, neg;
  3506. char ch;
  3507. /* zero the digit bignum */
  3508. mp_zero(a);
  3509. /* make sure the radix is ok */
  3510. if (radix < 2 || radix > 64) {
  3511. return MP_VAL;
  3512. }
  3513. /* if the leading digit is a
  3514. * minus set the sign to negative.
  3515. */
  3516. if (*str == '-') {
  3517. ++str;
  3518. neg = MP_NEG;
  3519. } else {
  3520. neg = MP_ZPOS;
  3521. }
  3522. /* set the integer to the default of zero */
  3523. mp_zero (a);
  3524. /* process each digit of the string */
  3525. while (*str) {
  3526. /* if the radix < 36 the conversion is case insensitive
  3527. * this allows numbers like 1AB and 1ab to represent the same value
  3528. * [e.g. in hex]
  3529. */
  3530. ch = (char) ((radix < 36) ? XTOUPPER(*str) : *str);
  3531. for (y = 0; y < 64; y++) {
  3532. if (ch == mp_s_rmap[y]) {
  3533. break;
  3534. }
  3535. }
  3536. /* if the char was found in the map
  3537. * and is less than the given radix add it
  3538. * to the number, otherwise exit the loop.
  3539. */
  3540. if (y < radix) {
  3541. if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
  3542. return res;
  3543. }
  3544. if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
  3545. return res;
  3546. }
  3547. } else {
  3548. break;
  3549. }
  3550. ++str;
  3551. }
  3552. /* set the sign only if a != 0 */
  3553. if (mp_iszero(a) != 1) {
  3554. a->sign = neg;
  3555. }
  3556. return MP_OKAY;
  3557. }