integer.c 93 KB

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