mpi.c 79 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985
  1. /*
  2. mpi.c
  3. by Michael J. Fromberger <sting@linguist.dartmouth.edu>
  4. Copyright (C) 1998 Michael J. Fromberger, All Rights Reserved
  5. Arbitrary precision integer arithmetic library
  6. $Id: mpi.c,v 1.2 2005/05/05 14:38:47 tom Exp $
  7. */
  8. #include "mpi.h"
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <ctype.h>
  12. #if MP_DEBUG
  13. #include <stdio.h>
  14. #define DIAG(T,V) {fprintf(stderr,T);mp_print(V,stderr);fputc('\n',stderr);}
  15. #else
  16. #define DIAG(T,V)
  17. #endif
  18. /*
  19. If MP_LOGTAB is not defined, use the math library to compute the
  20. logarithms on the fly. Otherwise, use the static table below.
  21. Pick which works best for your system.
  22. */
  23. #if MP_LOGTAB
  24. /* {{{ s_logv_2[] - log table for 2 in various bases */
  25. /*
  26. A table of the logs of 2 for various bases (the 0 and 1 entries of
  27. this table are meaningless and should not be referenced).
  28. This table is used to compute output lengths for the mp_toradix()
  29. function. Since a number n in radix r takes up about log_r(n)
  30. digits, we estimate the output size by taking the least integer
  31. greater than log_r(n), where:
  32. log_r(n) = log_2(n) * log_r(2)
  33. This table, therefore, is a table of log_r(2) for 2 <= r <= 36,
  34. which are the output bases supported.
  35. */
  36. #include "logtab.h"
  37. /* }}} */
  38. #define LOG_V_2(R) s_logv_2[(R)]
  39. #else
  40. #include <math.h>
  41. #define LOG_V_2(R) (log(2.0)/log(R))
  42. #endif
  43. /* Default precision for newly created mp_int's */
  44. static unsigned int s_mp_defprec = MP_DEFPREC;
  45. /* {{{ Digit arithmetic macros */
  46. /*
  47. When adding and multiplying digits, the results can be larger than
  48. can be contained in an mp_digit. Thus, an mp_word is used. These
  49. macros mask off the upper and lower digits of the mp_word (the
  50. mp_word may be more than 2 mp_digits wide, but we only concern
  51. ourselves with the low-order 2 mp_digits)
  52. If your mp_word DOES have more than 2 mp_digits, you need to
  53. uncomment the first line, and comment out the second.
  54. */
  55. /* #define CARRYOUT(W) (((W)>>DIGIT_BIT)&MP_DIGIT_MAX) */
  56. #define CARRYOUT(W) ((W)>>DIGIT_BIT)
  57. #define ACCUM(W) ((W)&MP_DIGIT_MAX)
  58. /* }}} */
  59. /* {{{ Comparison constants */
  60. #define MP_LT -1
  61. #define MP_EQ 0
  62. #define MP_GT 1
  63. /* }}} */
  64. /* {{{ Constant strings */
  65. /* Constant strings returned by mp_strerror() */
  66. static const char *mp_err_string[] = {
  67. "unknown result code", /* say what? */
  68. "boolean true", /* MP_OKAY, MP_YES */
  69. "boolean false", /* MP_NO */
  70. "out of memory", /* MP_MEM */
  71. "argument out of range", /* MP_RANGE */
  72. "invalid input parameter", /* MP_BADARG */
  73. "result is undefined" /* MP_UNDEF */
  74. };
  75. /* Value to digit maps for radix conversion */
  76. /* s_dmap_1 - standard digits and letters */
  77. static const char *s_dmap_1 =
  78. "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
  79. #if 0
  80. /* s_dmap_2 - base64 ordering for digits */
  81. static const char *s_dmap_2 =
  82. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  83. #endif
  84. /* }}} */
  85. /* {{{ Static function declarations */
  86. /*
  87. If MP_MACRO is false, these will be defined as actual functions;
  88. otherwise, suitable macro definitions will be used. This works
  89. around the fact that ANSI C89 doesn't support an 'inline' keyword
  90. (although I hear C9x will ... about bloody time). At present, the
  91. macro definitions are identical to the function bodies, but they'll
  92. expand in place, instead of generating a function call.
  93. I chose these particular functions to be made into macros because
  94. some profiling showed they are called a lot on a typical workload,
  95. and yet they are primarily housekeeping.
  96. */
  97. #if MP_MACRO == 0
  98. void s_mp_setz(mp_digit *dp, mp_size count); /* zero digits */
  99. void s_mp_copy(mp_digit *sp, mp_digit *dp, mp_size count); /* copy */
  100. void *s_mp_alloc(size_t nb, size_t ni); /* general allocator */
  101. void s_mp_free(void *ptr); /* general free function */
  102. #else
  103. /* Even if these are defined as macros, we need to respect the settings
  104. of the MP_MEMSET and MP_MEMCPY configuration options...
  105. */
  106. #if MP_MEMSET == 0
  107. #define s_mp_setz(dp, count) \
  108. {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=0;}
  109. #else
  110. #define s_mp_setz(dp, count) memset(dp, 0, (count) * sizeof(mp_digit))
  111. #endif /* MP_MEMSET */
  112. #if MP_MEMCPY == 0
  113. #define s_mp_copy(sp, dp, count) \
  114. {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=(sp)[ix];}
  115. #else
  116. #define s_mp_copy(sp, dp, count) memcpy(dp, sp, (count) * sizeof(mp_digit))
  117. #endif /* MP_MEMCPY */
  118. #define s_mp_alloc(nb, ni) calloc(nb, ni)
  119. #define s_mp_free(ptr) {if(ptr) free(ptr);}
  120. #endif /* MP_MACRO */
  121. mp_err s_mp_grow(mp_int *mp, mp_size min); /* increase allocated size */
  122. mp_err s_mp_pad(mp_int *mp, mp_size min); /* left pad with zeroes */
  123. void s_mp_clamp(mp_int *mp); /* clip leading zeroes */
  124. void s_mp_exch(mp_int *a, mp_int *b); /* swap a and b in place */
  125. mp_err s_mp_lshd(mp_int *mp, mp_size p); /* left-shift by p digits */
  126. void s_mp_rshd(mp_int *mp, mp_size p); /* right-shift by p digits */
  127. void s_mp_div_2d(mp_int *mp, mp_digit d); /* divide by 2^d in place */
  128. void s_mp_mod_2d(mp_int *mp, mp_digit d); /* modulo 2^d in place */
  129. mp_err s_mp_mul_2d(mp_int *mp, mp_digit d); /* multiply by 2^d in place*/
  130. void s_mp_div_2(mp_int *mp); /* divide by 2 in place */
  131. mp_err s_mp_mul_2(mp_int *mp); /* multiply by 2 in place */
  132. mp_digit s_mp_norm(mp_int *a, mp_int *b); /* normalize for division */
  133. mp_err s_mp_add_d(mp_int *mp, mp_digit d); /* unsigned digit addition */
  134. mp_err s_mp_sub_d(mp_int *mp, mp_digit d); /* unsigned digit subtract */
  135. mp_err s_mp_mul_d(mp_int *mp, mp_digit d); /* unsigned digit multiply */
  136. mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r);
  137. /* unsigned digit divide */
  138. mp_err s_mp_reduce(mp_int *x, mp_int *m, mp_int *mu);
  139. /* Barrett reduction */
  140. mp_err s_mp_add(mp_int *a, mp_int *b); /* magnitude addition */
  141. mp_err s_mp_sub(mp_int *a, mp_int *b); /* magnitude subtract */
  142. mp_err s_mp_mul(mp_int *a, mp_int *b); /* magnitude multiply */
  143. #if 0
  144. void s_mp_kmul(mp_digit *a, mp_digit *b, mp_digit *out, mp_size len);
  145. /* multiply buffers in place */
  146. #endif
  147. #if MP_SQUARE
  148. mp_err s_mp_sqr(mp_int *a); /* magnitude square */
  149. #else
  150. #define s_mp_sqr(a) s_mp_mul(a, a)
  151. #endif
  152. mp_err s_mp_div(mp_int *a, mp_int *b); /* magnitude divide */
  153. mp_err s_mp_2expt(mp_int *a, mp_digit k); /* a = 2^k */
  154. int s_mp_cmp(mp_int *a, mp_int *b); /* magnitude comparison */
  155. int s_mp_cmp_d(mp_int *a, mp_digit d); /* magnitude digit compare */
  156. int s_mp_ispow2(mp_int *v); /* is v a power of 2? */
  157. int s_mp_ispow2d(mp_digit d); /* is d a power of 2? */
  158. int s_mp_tovalue(char ch, int r); /* convert ch to value */
  159. char s_mp_todigit(int val, int r, int low); /* convert val to digit */
  160. int s_mp_outlen(int bits, int r); /* output length in bytes */
  161. /* }}} */
  162. /* {{{ Default precision manipulation */
  163. unsigned int mp_get_prec(void)
  164. {
  165. return s_mp_defprec;
  166. } /* end mp_get_prec() */
  167. void mp_set_prec(unsigned int prec)
  168. {
  169. if(prec == 0)
  170. s_mp_defprec = MP_DEFPREC;
  171. else
  172. s_mp_defprec = prec;
  173. } /* end mp_set_prec() */
  174. /* }}} */
  175. /*------------------------------------------------------------------------*/
  176. /* {{{ mp_init(mp) */
  177. /*
  178. mp_init(mp)
  179. Initialize a new zero-valued mp_int. Returns MP_OKAY if successful,
  180. MP_MEM if memory could not be allocated for the structure.
  181. */
  182. mp_err mp_init(mp_int *mp)
  183. {
  184. return mp_init_size(mp, s_mp_defprec);
  185. } /* end mp_init() */
  186. /* }}} */
  187. /* {{{ mp_init_array(mp[], count) */
  188. mp_err mp_init_array(mp_int mp[], int count)
  189. {
  190. mp_err res;
  191. int pos;
  192. ARGCHK(mp !=NULL && count > 0, MP_BADARG);
  193. for(pos = 0; pos < count; ++pos) {
  194. if((res = mp_init(&mp[pos])) != MP_OKAY)
  195. goto CLEANUP;
  196. }
  197. return MP_OKAY;
  198. CLEANUP:
  199. while(--pos >= 0)
  200. mp_clear(&mp[pos]);
  201. return res;
  202. } /* end mp_init_array() */
  203. /* }}} */
  204. /* {{{ mp_init_size(mp, prec) */
  205. /*
  206. mp_init_size(mp, prec)
  207. Initialize a new zero-valued mp_int with at least the given
  208. precision; returns MP_OKAY if successful, or MP_MEM if memory could
  209. not be allocated for the structure.
  210. */
  211. mp_err mp_init_size(mp_int *mp, mp_size prec)
  212. {
  213. ARGCHK(mp != NULL && prec > 0, MP_BADARG);
  214. if((DIGITS(mp) = s_mp_alloc(prec, sizeof(mp_digit))) == NULL)
  215. return MP_MEM;
  216. SIGN(mp) = MP_ZPOS;
  217. USED(mp) = 1;
  218. ALLOC(mp) = prec;
  219. return MP_OKAY;
  220. } /* end mp_init_size() */
  221. /* }}} */
  222. /* {{{ mp_init_copy(mp, from) */
  223. /*
  224. mp_init_copy(mp, from)
  225. Initialize mp as an exact copy of from. Returns MP_OKAY if
  226. successful, MP_MEM if memory could not be allocated for the new
  227. structure.
  228. */
  229. mp_err mp_init_copy(mp_int *mp, mp_int *from)
  230. {
  231. ARGCHK(mp != NULL && from != NULL, MP_BADARG);
  232. if(mp == from)
  233. return MP_OKAY;
  234. if((DIGITS(mp) = s_mp_alloc(USED(from), sizeof(mp_digit))) == NULL)
  235. return MP_MEM;
  236. s_mp_copy(DIGITS(from), DIGITS(mp), USED(from));
  237. USED(mp) = USED(from);
  238. ALLOC(mp) = USED(from);
  239. SIGN(mp) = SIGN(from);
  240. return MP_OKAY;
  241. } /* end mp_init_copy() */
  242. /* }}} */
  243. /* {{{ mp_copy(from, to) */
  244. /*
  245. mp_copy(from, to)
  246. Copies the mp_int 'from' to the mp_int 'to'. It is presumed that
  247. 'to' has already been initialized (if not, use mp_init_copy()
  248. instead). If 'from' and 'to' are identical, nothing happens.
  249. */
  250. mp_err mp_copy(mp_int *from, mp_int *to)
  251. {
  252. ARGCHK(from != NULL && to != NULL, MP_BADARG);
  253. if(from == to)
  254. return MP_OKAY;
  255. { /* copy */
  256. mp_digit *tmp;
  257. /*
  258. If the allocated buffer in 'to' already has enough space to hold
  259. all the used digits of 'from', we'll re-use it to avoid hitting
  260. the memory allocater more than necessary; otherwise, we'd have
  261. to grow anyway, so we just allocate a hunk and make the copy as
  262. usual
  263. */
  264. if(ALLOC(to) >= USED(from)) {
  265. s_mp_setz(DIGITS(to) + USED(from), ALLOC(to) - USED(from));
  266. s_mp_copy(DIGITS(from), DIGITS(to), USED(from));
  267. } else {
  268. if((tmp = s_mp_alloc(USED(from), sizeof(mp_digit))) == NULL)
  269. return MP_MEM;
  270. s_mp_copy(DIGITS(from), tmp, USED(from));
  271. if(DIGITS(to) != NULL) {
  272. #if MP_CRYPTO
  273. s_mp_setz(DIGITS(to), ALLOC(to));
  274. #endif
  275. s_mp_free(DIGITS(to));
  276. }
  277. DIGITS(to) = tmp;
  278. ALLOC(to) = USED(from);
  279. }
  280. /* Copy the precision and sign from the original */
  281. USED(to) = USED(from);
  282. SIGN(to) = SIGN(from);
  283. } /* end copy */
  284. return MP_OKAY;
  285. } /* end mp_copy() */
  286. /* }}} */
  287. /* {{{ mp_exch(mp1, mp2) */
  288. /*
  289. mp_exch(mp1, mp2)
  290. Exchange mp1 and mp2 without allocating any intermediate memory
  291. (well, unless you count the stack space needed for this call and the
  292. locals it creates...). This cannot fail.
  293. */
  294. void mp_exch(mp_int *mp1, mp_int *mp2)
  295. {
  296. #if MP_ARGCHK == 2
  297. assert(mp1 != NULL && mp2 != NULL);
  298. #else
  299. if(mp1 == NULL || mp2 == NULL)
  300. return;
  301. #endif
  302. s_mp_exch(mp1, mp2);
  303. } /* end mp_exch() */
  304. /* }}} */
  305. /* {{{ mp_clear(mp) */
  306. /*
  307. mp_clear(mp)
  308. Release the storage used by an mp_int, and void its fields so that
  309. if someone calls mp_clear() again for the same int later, we won't
  310. get tollchocked.
  311. */
  312. void mp_clear(mp_int *mp)
  313. {
  314. if(mp == NULL)
  315. return;
  316. if(DIGITS(mp) != NULL) {
  317. #if MP_CRYPTO
  318. s_mp_setz(DIGITS(mp), ALLOC(mp));
  319. #endif
  320. s_mp_free(DIGITS(mp));
  321. DIGITS(mp) = NULL;
  322. }
  323. USED(mp) = 0;
  324. ALLOC(mp) = 0;
  325. } /* end mp_clear() */
  326. /* }}} */
  327. /* {{{ mp_clear_array(mp[], count) */
  328. void mp_clear_array(mp_int mp[], int count)
  329. {
  330. ARGCHK(mp != NULL && count > 0, MP_BADARG);
  331. while(--count >= 0)
  332. mp_clear(&mp[count]);
  333. } /* end mp_clear_array() */
  334. /* }}} */
  335. /* {{{ mp_zero(mp) */
  336. /*
  337. mp_zero(mp)
  338. Set mp to zero. Does not change the allocated size of the structure,
  339. and therefore cannot fail (except on a bad argument, which we ignore)
  340. */
  341. void mp_zero(mp_int *mp)
  342. {
  343. if(mp == NULL)
  344. return;
  345. s_mp_setz(DIGITS(mp), ALLOC(mp));
  346. USED(mp) = 1;
  347. SIGN(mp) = MP_ZPOS;
  348. } /* end mp_zero() */
  349. /* }}} */
  350. /* {{{ mp_set(mp, d) */
  351. void mp_set(mp_int *mp, mp_digit d)
  352. {
  353. if(mp == NULL)
  354. return;
  355. mp_zero(mp);
  356. DIGIT(mp, 0) = d;
  357. } /* end mp_set() */
  358. /* }}} */
  359. /* {{{ mp_set_int(mp, z) */
  360. mp_err mp_set_int(mp_int *mp, long z)
  361. {
  362. int ix;
  363. unsigned long v = abs(z);
  364. mp_err res;
  365. ARGCHK(mp != NULL, MP_BADARG);
  366. mp_zero(mp);
  367. if(z == 0)
  368. return MP_OKAY; /* shortcut for zero */
  369. for(ix = sizeof(long) - 1; ix >= 0; ix--) {
  370. if((res = s_mp_mul_2d(mp, CHAR_BIT)) != MP_OKAY)
  371. return res;
  372. res = s_mp_add_d(mp,
  373. (mp_digit)((v >> (ix * CHAR_BIT)) & UCHAR_MAX));
  374. if(res != MP_OKAY)
  375. return res;
  376. }
  377. if(z < 0)
  378. SIGN(mp) = MP_NEG;
  379. return MP_OKAY;
  380. } /* end mp_set_int() */
  381. /* }}} */
  382. /*------------------------------------------------------------------------*/
  383. /* {{{ Digit arithmetic */
  384. /* {{{ mp_add_d(a, d, b) */
  385. /*
  386. mp_add_d(a, d, b)
  387. Compute the sum b = a + d, for a single digit d. Respects the sign of
  388. its primary addend (single digits are unsigned anyway).
  389. */
  390. mp_err mp_add_d(mp_int *a, mp_digit d, mp_int *b)
  391. {
  392. mp_err res = MP_OKAY;
  393. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  394. if((res = mp_copy(a, b)) != MP_OKAY)
  395. return res;
  396. if(SIGN(b) == MP_ZPOS) {
  397. res = s_mp_add_d(b, d);
  398. } else if(s_mp_cmp_d(b, d) >= 0) {
  399. res = s_mp_sub_d(b, d);
  400. } else {
  401. SIGN(b) = MP_ZPOS;
  402. DIGIT(b, 0) = d - DIGIT(b, 0);
  403. }
  404. return res;
  405. } /* end mp_add_d() */
  406. /* }}} */
  407. /* {{{ mp_sub_d(a, d, b) */
  408. /*
  409. mp_sub_d(a, d, b)
  410. Compute the difference b = a - d, for a single digit d. Respects the
  411. sign of its subtrahend (single digits are unsigned anyway).
  412. */
  413. mp_err mp_sub_d(mp_int *a, mp_digit d, mp_int *b)
  414. {
  415. mp_err res;
  416. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  417. if((res = mp_copy(a, b)) != MP_OKAY)
  418. return res;
  419. if(SIGN(b) == MP_NEG) {
  420. if((res = s_mp_add_d(b, d)) != MP_OKAY)
  421. return res;
  422. } else if(s_mp_cmp_d(b, d) >= 0) {
  423. if((res = s_mp_sub_d(b, d)) != MP_OKAY)
  424. return res;
  425. } else {
  426. mp_neg(b, b);
  427. DIGIT(b, 0) = d - DIGIT(b, 0);
  428. SIGN(b) = MP_NEG;
  429. }
  430. if(s_mp_cmp_d(b, 0) == 0)
  431. SIGN(b) = MP_ZPOS;
  432. return MP_OKAY;
  433. } /* end mp_sub_d() */
  434. /* }}} */
  435. /* {{{ mp_mul_d(a, d, b) */
  436. /*
  437. mp_mul_d(a, d, b)
  438. Compute the product b = a * d, for a single digit d. Respects the sign
  439. of its multiplicand (single digits are unsigned anyway)
  440. */
  441. mp_err mp_mul_d(mp_int *a, mp_digit d, mp_int *b)
  442. {
  443. mp_err res;
  444. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  445. if(d == 0) {
  446. mp_zero(b);
  447. return MP_OKAY;
  448. }
  449. if((res = mp_copy(a, b)) != MP_OKAY)
  450. return res;
  451. res = s_mp_mul_d(b, d);
  452. return res;
  453. } /* end mp_mul_d() */
  454. /* }}} */
  455. /* {{{ mp_mul_2(a, c) */
  456. mp_err mp_mul_2(mp_int *a, mp_int *c)
  457. {
  458. mp_err res;
  459. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  460. if((res = mp_copy(a, c)) != MP_OKAY)
  461. return res;
  462. return s_mp_mul_2(c);
  463. } /* end mp_mul_2() */
  464. /* }}} */
  465. /* {{{ mp_div_d(a, d, q, r) */
  466. /*
  467. mp_div_d(a, d, q, r)
  468. Compute the quotient q = a / d and remainder r = a mod d, for a
  469. single digit d. Respects the sign of its divisor (single digits are
  470. unsigned anyway).
  471. */
  472. mp_err mp_div_d(mp_int *a, mp_digit d, mp_int *q, mp_digit *r)
  473. {
  474. mp_err res;
  475. mp_digit rem;
  476. int pow;
  477. ARGCHK(a != NULL, MP_BADARG);
  478. if(d == 0)
  479. return MP_RANGE;
  480. /* Shortcut for powers of two ... */
  481. if((pow = s_mp_ispow2d(d)) >= 0) {
  482. mp_digit mask;
  483. mask = (1 << pow) - 1;
  484. rem = DIGIT(a, 0) & mask;
  485. if(q) {
  486. mp_copy(a, q);
  487. s_mp_div_2d(q, pow);
  488. }
  489. if(r)
  490. *r = rem;
  491. return MP_OKAY;
  492. }
  493. /*
  494. If the quotient is actually going to be returned, we'll try to
  495. avoid hitting the memory allocator by copying the dividend into it
  496. and doing the division there. This can't be any _worse_ than
  497. always copying, and will sometimes be better (since it won't make
  498. another copy)
  499. If it's not going to be returned, we need to allocate a temporary
  500. to hold the quotient, which will just be discarded.
  501. */
  502. if(q) {
  503. if((res = mp_copy(a, q)) != MP_OKAY)
  504. return res;
  505. res = s_mp_div_d(q, d, &rem);
  506. if(s_mp_cmp_d(q, 0) == MP_EQ)
  507. SIGN(q) = MP_ZPOS;
  508. } else {
  509. mp_int qp;
  510. if((res = mp_init_copy(&qp, a)) != MP_OKAY)
  511. return res;
  512. res = s_mp_div_d(&qp, d, &rem);
  513. if(s_mp_cmp_d(&qp, 0) == 0)
  514. SIGN(&qp) = MP_ZPOS;
  515. mp_clear(&qp);
  516. }
  517. if(r)
  518. *r = rem;
  519. return res;
  520. } /* end mp_div_d() */
  521. /* }}} */
  522. /* {{{ mp_div_2(a, c) */
  523. /*
  524. mp_div_2(a, c)
  525. Compute c = a / 2, disregarding the remainder.
  526. */
  527. mp_err mp_div_2(mp_int *a, mp_int *c)
  528. {
  529. mp_err res;
  530. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  531. if((res = mp_copy(a, c)) != MP_OKAY)
  532. return res;
  533. s_mp_div_2(c);
  534. return MP_OKAY;
  535. } /* end mp_div_2() */
  536. /* }}} */
  537. /* {{{ mp_expt_d(a, d, b) */
  538. mp_err mp_expt_d(mp_int *a, mp_digit d, mp_int *c)
  539. {
  540. mp_int s, x;
  541. mp_err res;
  542. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  543. if((res = mp_init(&s)) != MP_OKAY)
  544. return res;
  545. if((res = mp_init_copy(&x, a)) != MP_OKAY)
  546. goto X;
  547. DIGIT(&s, 0) = 1;
  548. while(d != 0) {
  549. if(d & 1) {
  550. if((res = s_mp_mul(&s, &x)) != MP_OKAY)
  551. goto CLEANUP;
  552. }
  553. d >>= 1;
  554. if((res = s_mp_sqr(&x)) != MP_OKAY)
  555. goto CLEANUP;
  556. }
  557. s_mp_exch(&s, c);
  558. CLEANUP:
  559. mp_clear(&x);
  560. X:
  561. mp_clear(&s);
  562. return res;
  563. } /* end mp_expt_d() */
  564. /* }}} */
  565. /* }}} */
  566. /*------------------------------------------------------------------------*/
  567. /* {{{ Full arithmetic */
  568. /* {{{ mp_abs(a, b) */
  569. /*
  570. mp_abs(a, b)
  571. Compute b = |a|. 'a' and 'b' may be identical.
  572. */
  573. mp_err mp_abs(mp_int *a, mp_int *b)
  574. {
  575. mp_err res;
  576. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  577. if((res = mp_copy(a, b)) != MP_OKAY)
  578. return res;
  579. SIGN(b) = MP_ZPOS;
  580. return MP_OKAY;
  581. } /* end mp_abs() */
  582. /* }}} */
  583. /* {{{ mp_neg(a, b) */
  584. /*
  585. mp_neg(a, b)
  586. Compute b = -a. 'a' and 'b' may be identical.
  587. */
  588. mp_err mp_neg(mp_int *a, mp_int *b)
  589. {
  590. mp_err res;
  591. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  592. if((res = mp_copy(a, b)) != MP_OKAY)
  593. return res;
  594. if(s_mp_cmp_d(b, 0) == MP_EQ)
  595. SIGN(b) = MP_ZPOS;
  596. else
  597. SIGN(b) = (SIGN(b) == MP_NEG) ? MP_ZPOS : MP_NEG;
  598. return MP_OKAY;
  599. } /* end mp_neg() */
  600. /* }}} */
  601. /* {{{ mp_add(a, b, c) */
  602. /*
  603. mp_add(a, b, c)
  604. Compute c = a + b. All parameters may be identical.
  605. */
  606. mp_err mp_add(mp_int *a, mp_int *b, mp_int *c)
  607. {
  608. mp_err res;
  609. int cmp;
  610. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  611. if(SIGN(a) == SIGN(b)) { /* same sign: add values, keep sign */
  612. /* Commutativity of addition lets us do this in either order,
  613. so we avoid having to use a temporary even if the result
  614. is supposed to replace the output
  615. */
  616. if(c == b) {
  617. if((res = s_mp_add(c, a)) != MP_OKAY)
  618. return res;
  619. } else {
  620. if(c != a && (res = mp_copy(a, c)) != MP_OKAY)
  621. return res;
  622. if((res = s_mp_add(c, b)) != MP_OKAY)
  623. return res;
  624. }
  625. } else if((cmp = s_mp_cmp(a, b)) > 0) { /* different sign: a > b */
  626. /* If the output is going to be clobbered, we will use a temporary
  627. variable; otherwise, we'll do it without touching the memory
  628. allocator at all, if possible
  629. */
  630. if(c == b) {
  631. mp_int tmp;
  632. if((res = mp_init_copy(&tmp, a)) != MP_OKAY)
  633. return res;
  634. if((res = s_mp_sub(&tmp, b)) != MP_OKAY) {
  635. mp_clear(&tmp);
  636. return res;
  637. }
  638. s_mp_exch(&tmp, c);
  639. mp_clear(&tmp);
  640. } else {
  641. if(c != a && (res = mp_copy(a, c)) != MP_OKAY)
  642. return res;
  643. if((res = s_mp_sub(c, b)) != MP_OKAY)
  644. return res;
  645. }
  646. } else if(cmp == 0) { /* different sign, a == b */
  647. mp_zero(c);
  648. return MP_OKAY;
  649. } else { /* different sign: a < b */
  650. /* See above... */
  651. if(c == a) {
  652. mp_int tmp;
  653. if((res = mp_init_copy(&tmp, b)) != MP_OKAY)
  654. return res;
  655. if((res = s_mp_sub(&tmp, a)) != MP_OKAY) {
  656. mp_clear(&tmp);
  657. return res;
  658. }
  659. s_mp_exch(&tmp, c);
  660. mp_clear(&tmp);
  661. } else {
  662. if(c != b && (res = mp_copy(b, c)) != MP_OKAY)
  663. return res;
  664. if((res = s_mp_sub(c, a)) != MP_OKAY)
  665. return res;
  666. }
  667. }
  668. if(USED(c) == 1 && DIGIT(c, 0) == 0)
  669. SIGN(c) = MP_ZPOS;
  670. return MP_OKAY;
  671. } /* end mp_add() */
  672. /* }}} */
  673. /* {{{ mp_sub(a, b, c) */
  674. /*
  675. mp_sub(a, b, c)
  676. Compute c = a - b. All parameters may be identical.
  677. */
  678. mp_err mp_sub(mp_int *a, mp_int *b, mp_int *c)
  679. {
  680. mp_err res;
  681. int cmp;
  682. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  683. if(SIGN(a) != SIGN(b)) {
  684. if(c == a) {
  685. if((res = s_mp_add(c, b)) != MP_OKAY)
  686. return res;
  687. } else {
  688. if(c != b && ((res = mp_copy(b, c)) != MP_OKAY))
  689. return res;
  690. if((res = s_mp_add(c, a)) != MP_OKAY)
  691. return res;
  692. SIGN(c) = SIGN(a);
  693. }
  694. } else if((cmp = s_mp_cmp(a, b)) > 0) { /* Same sign, a > b */
  695. if(c == b) {
  696. mp_int tmp;
  697. if((res = mp_init_copy(&tmp, a)) != MP_OKAY)
  698. return res;
  699. if((res = s_mp_sub(&tmp, b)) != MP_OKAY) {
  700. mp_clear(&tmp);
  701. return res;
  702. }
  703. s_mp_exch(&tmp, c);
  704. mp_clear(&tmp);
  705. } else {
  706. if(c != a && ((res = mp_copy(a, c)) != MP_OKAY))
  707. return res;
  708. if((res = s_mp_sub(c, b)) != MP_OKAY)
  709. return res;
  710. }
  711. } else if(cmp == 0) { /* Same sign, equal magnitude */
  712. mp_zero(c);
  713. return MP_OKAY;
  714. } else { /* Same sign, b > a */
  715. if(c == a) {
  716. mp_int tmp;
  717. if((res = mp_init_copy(&tmp, b)) != MP_OKAY)
  718. return res;
  719. if((res = s_mp_sub(&tmp, a)) != MP_OKAY) {
  720. mp_clear(&tmp);
  721. return res;
  722. }
  723. s_mp_exch(&tmp, c);
  724. mp_clear(&tmp);
  725. } else {
  726. if(c != b && ((res = mp_copy(b, c)) != MP_OKAY))
  727. return res;
  728. if((res = s_mp_sub(c, a)) != MP_OKAY)
  729. return res;
  730. }
  731. SIGN(c) = !SIGN(b);
  732. }
  733. if(USED(c) == 1 && DIGIT(c, 0) == 0)
  734. SIGN(c) = MP_ZPOS;
  735. return MP_OKAY;
  736. } /* end mp_sub() */
  737. /* }}} */
  738. /* {{{ mp_mul(a, b, c) */
  739. /*
  740. mp_mul(a, b, c)
  741. Compute c = a * b. All parameters may be identical.
  742. */
  743. mp_err mp_mul(mp_int *a, mp_int *b, mp_int *c)
  744. {
  745. mp_err res;
  746. mp_sign sgn;
  747. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  748. sgn = (SIGN(a) == SIGN(b)) ? MP_ZPOS : MP_NEG;
  749. if(c == b) {
  750. if((res = s_mp_mul(c, a)) != MP_OKAY)
  751. return res;
  752. } else {
  753. if((res = mp_copy(a, c)) != MP_OKAY)
  754. return res;
  755. if((res = s_mp_mul(c, b)) != MP_OKAY)
  756. return res;
  757. }
  758. if(sgn == MP_ZPOS || s_mp_cmp_d(c, 0) == MP_EQ)
  759. SIGN(c) = MP_ZPOS;
  760. else
  761. SIGN(c) = sgn;
  762. return MP_OKAY;
  763. } /* end mp_mul() */
  764. /* }}} */
  765. /* {{{ mp_mul_2d(a, d, c) */
  766. /*
  767. mp_mul_2d(a, d, c)
  768. Compute c = a * 2^d. a may be the same as c.
  769. */
  770. mp_err mp_mul_2d(mp_int *a, mp_digit d, mp_int *c)
  771. {
  772. mp_err res;
  773. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  774. if((res = mp_copy(a, c)) != MP_OKAY)
  775. return res;
  776. if(d == 0)
  777. return MP_OKAY;
  778. return s_mp_mul_2d(c, d);
  779. } /* end mp_mul() */
  780. /* }}} */
  781. /* {{{ mp_sqr(a, b) */
  782. #if MP_SQUARE
  783. mp_err mp_sqr(mp_int *a, mp_int *b)
  784. {
  785. mp_err res;
  786. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  787. if((res = mp_copy(a, b)) != MP_OKAY)
  788. return res;
  789. if((res = s_mp_sqr(b)) != MP_OKAY)
  790. return res;
  791. SIGN(b) = MP_ZPOS;
  792. return MP_OKAY;
  793. } /* end mp_sqr() */
  794. #endif
  795. /* }}} */
  796. /* {{{ mp_div(a, b, q, r) */
  797. /*
  798. mp_div(a, b, q, r)
  799. Compute q = a / b and r = a mod b. Input parameters may be re-used
  800. as output parameters. If q or r is NULL, that portion of the
  801. computation will be discarded (although it will still be computed)
  802. Pay no attention to the hacker behind the curtain.
  803. */
  804. mp_err mp_div(mp_int *a, mp_int *b, mp_int *q, mp_int *r)
  805. {
  806. mp_err res;
  807. mp_int qtmp, rtmp;
  808. int cmp;
  809. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  810. if(mp_cmp_z(b) == MP_EQ)
  811. return MP_RANGE;
  812. /* If a <= b, we can compute the solution without division, and
  813. avoid any memory allocation
  814. */
  815. if((cmp = s_mp_cmp(a, b)) < 0) {
  816. if(r) {
  817. if((res = mp_copy(a, r)) != MP_OKAY)
  818. return res;
  819. }
  820. if(q)
  821. mp_zero(q);
  822. return MP_OKAY;
  823. } else if(cmp == 0) {
  824. /* Set quotient to 1, with appropriate sign */
  825. if(q) {
  826. int qneg = (SIGN(a) != SIGN(b));
  827. mp_set(q, 1);
  828. if(qneg)
  829. SIGN(q) = MP_NEG;
  830. }
  831. if(r)
  832. mp_zero(r);
  833. return MP_OKAY;
  834. }
  835. /* If we get here, it means we actually have to do some division */
  836. /* Set up some temporaries... */
  837. if((res = mp_init_copy(&qtmp, a)) != MP_OKAY)
  838. return res;
  839. if((res = mp_init_copy(&rtmp, b)) != MP_OKAY)
  840. goto CLEANUP;
  841. if((res = s_mp_div(&qtmp, &rtmp)) != MP_OKAY)
  842. goto CLEANUP;
  843. /* Compute the signs for the output */
  844. SIGN(&rtmp) = SIGN(a); /* Sr = Sa */
  845. if(SIGN(a) == SIGN(b))
  846. SIGN(&qtmp) = MP_ZPOS; /* Sq = MP_ZPOS if Sa = Sb */
  847. else
  848. SIGN(&qtmp) = MP_NEG; /* Sq = MP_NEG if Sa != Sb */
  849. if(s_mp_cmp_d(&qtmp, 0) == MP_EQ)
  850. SIGN(&qtmp) = MP_ZPOS;
  851. if(s_mp_cmp_d(&rtmp, 0) == MP_EQ)
  852. SIGN(&rtmp) = MP_ZPOS;
  853. /* Copy output, if it is needed */
  854. if(q)
  855. s_mp_exch(&qtmp, q);
  856. if(r)
  857. s_mp_exch(&rtmp, r);
  858. CLEANUP:
  859. mp_clear(&rtmp);
  860. mp_clear(&qtmp);
  861. return res;
  862. } /* end mp_div() */
  863. /* }}} */
  864. /* {{{ mp_div_2d(a, d, q, r) */
  865. mp_err mp_div_2d(mp_int *a, mp_digit d, mp_int *q, mp_int *r)
  866. {
  867. mp_err res;
  868. ARGCHK(a != NULL, MP_BADARG);
  869. if(q) {
  870. if((res = mp_copy(a, q)) != MP_OKAY)
  871. return res;
  872. s_mp_div_2d(q, d);
  873. }
  874. if(r) {
  875. if((res = mp_copy(a, r)) != MP_OKAY)
  876. return res;
  877. s_mp_mod_2d(r, d);
  878. }
  879. return MP_OKAY;
  880. } /* end mp_div_2d() */
  881. /* }}} */
  882. /* {{{ mp_expt(a, b, c) */
  883. /*
  884. mp_expt(a, b, c)
  885. Compute c = a ** b, that is, raise a to the b power. Uses a
  886. standard iterative square-and-multiply technique.
  887. */
  888. mp_err mp_expt(mp_int *a, mp_int *b, mp_int *c)
  889. {
  890. mp_int s, x;
  891. mp_err res;
  892. mp_digit d;
  893. int dig, bit;
  894. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  895. if(mp_cmp_z(b) < 0)
  896. return MP_RANGE;
  897. if((res = mp_init(&s)) != MP_OKAY)
  898. return res;
  899. mp_set(&s, 1);
  900. if((res = mp_init_copy(&x, a)) != MP_OKAY)
  901. goto X;
  902. /* Loop over low-order digits in ascending order */
  903. for(dig = 0; dig < (USED(b) - 1); dig++) {
  904. d = DIGIT(b, dig);
  905. /* Loop over bits of each non-maximal digit */
  906. for(bit = 0; bit < DIGIT_BIT; bit++) {
  907. if(d & 1) {
  908. if((res = s_mp_mul(&s, &x)) != MP_OKAY)
  909. goto CLEANUP;
  910. }
  911. d >>= 1;
  912. if((res = s_mp_sqr(&x)) != MP_OKAY)
  913. goto CLEANUP;
  914. }
  915. }
  916. /* Consider now the last digit... */
  917. d = DIGIT(b, dig);
  918. while(d) {
  919. if(d & 1) {
  920. if((res = s_mp_mul(&s, &x)) != MP_OKAY)
  921. goto CLEANUP;
  922. }
  923. d >>= 1;
  924. if((res = s_mp_sqr(&x)) != MP_OKAY)
  925. goto CLEANUP;
  926. }
  927. if(mp_iseven(b))
  928. SIGN(&s) = SIGN(a);
  929. res = mp_copy(&s, c);
  930. CLEANUP:
  931. mp_clear(&x);
  932. X:
  933. mp_clear(&s);
  934. return res;
  935. } /* end mp_expt() */
  936. /* }}} */
  937. /* {{{ mp_2expt(a, k) */
  938. /* Compute a = 2^k */
  939. mp_err mp_2expt(mp_int *a, mp_digit k)
  940. {
  941. ARGCHK(a != NULL, MP_BADARG);
  942. return s_mp_2expt(a, k);
  943. } /* end mp_2expt() */
  944. /* }}} */
  945. /* {{{ mp_mod(a, m, c) */
  946. /*
  947. mp_mod(a, m, c)
  948. Compute c = a (mod m). Result will always be 0 <= c < m.
  949. */
  950. mp_err mp_mod(mp_int *a, mp_int *m, mp_int *c)
  951. {
  952. mp_err res;
  953. int mag;
  954. ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG);
  955. if(SIGN(m) == MP_NEG)
  956. return MP_RANGE;
  957. /*
  958. If |a| > m, we need to divide to get the remainder and take the
  959. absolute value.
  960. If |a| < m, we don't need to do any division, just copy and adjust
  961. the sign (if a is negative).
  962. If |a| == m, we can simply set the result to zero.
  963. This order is intended to minimize the average path length of the
  964. comparison chain on common workloads -- the most frequent cases are
  965. that |a| != m, so we do those first.
  966. */
  967. if((mag = s_mp_cmp(a, m)) > 0) {
  968. if((res = mp_div(a, m, NULL, c)) != MP_OKAY)
  969. return res;
  970. if(SIGN(c) == MP_NEG) {
  971. if((res = mp_add(c, m, c)) != MP_OKAY)
  972. return res;
  973. }
  974. } else if(mag < 0) {
  975. if((res = mp_copy(a, c)) != MP_OKAY)
  976. return res;
  977. if(mp_cmp_z(a) < 0) {
  978. if((res = mp_add(c, m, c)) != MP_OKAY)
  979. return res;
  980. }
  981. } else {
  982. mp_zero(c);
  983. }
  984. return MP_OKAY;
  985. } /* end mp_mod() */
  986. /* }}} */
  987. /* {{{ mp_mod_d(a, d, c) */
  988. /*
  989. mp_mod_d(a, d, c)
  990. Compute c = a (mod d). Result will always be 0 <= c < d
  991. */
  992. mp_err mp_mod_d(mp_int *a, mp_digit d, mp_digit *c)
  993. {
  994. mp_err res;
  995. mp_digit rem;
  996. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  997. if(s_mp_cmp_d(a, d) > 0) {
  998. if((res = mp_div_d(a, d, NULL, &rem)) != MP_OKAY)
  999. return res;
  1000. } else {
  1001. if(SIGN(a) == MP_NEG)
  1002. rem = d - DIGIT(a, 0);
  1003. else
  1004. rem = DIGIT(a, 0);
  1005. }
  1006. if(c)
  1007. *c = rem;
  1008. return MP_OKAY;
  1009. } /* end mp_mod_d() */
  1010. /* }}} */
  1011. /* {{{ mp_sqrt(a, b) */
  1012. /*
  1013. mp_sqrt(a, b)
  1014. Compute the integer square root of a, and store the result in b.
  1015. Uses an integer-arithmetic version of Newton's iterative linear
  1016. approximation technique to determine this value; the result has the
  1017. following two properties:
  1018. b^2 <= a
  1019. (b+1)^2 >= a
  1020. It is a range error to pass a negative value.
  1021. */
  1022. mp_err mp_sqrt(mp_int *a, mp_int *b)
  1023. {
  1024. mp_int x, t;
  1025. mp_err res;
  1026. ARGCHK(a != NULL && b != NULL, MP_BADARG);
  1027. /* Cannot take square root of a negative value */
  1028. if(SIGN(a) == MP_NEG)
  1029. return MP_RANGE;
  1030. /* Special cases for zero and one, trivial */
  1031. if(mp_cmp_d(a, 0) == MP_EQ || mp_cmp_d(a, 1) == MP_EQ)
  1032. return mp_copy(a, b);
  1033. /* Initialize the temporaries we'll use below */
  1034. if((res = mp_init_size(&t, USED(a))) != MP_OKAY)
  1035. return res;
  1036. /* Compute an initial guess for the iteration as a itself */
  1037. if((res = mp_init_copy(&x, a)) != MP_OKAY)
  1038. goto X;
  1039. s_mp_rshd(&x, (USED(&x)/2)+1);
  1040. mp_add_d(&x, 1, &x);
  1041. for(;;) {
  1042. /* t = (x * x) - a */
  1043. mp_copy(&x, &t); /* can't fail, t is big enough for original x */
  1044. if((res = mp_sqr(&t, &t)) != MP_OKAY ||
  1045. (res = mp_sub(&t, a, &t)) != MP_OKAY)
  1046. goto CLEANUP;
  1047. /* t = t / 2x */
  1048. s_mp_mul_2(&x);
  1049. if((res = mp_div(&t, &x, &t, NULL)) != MP_OKAY)
  1050. goto CLEANUP;
  1051. s_mp_div_2(&x);
  1052. /* Terminate the loop, if the quotient is zero */
  1053. if(mp_cmp_z(&t) == MP_EQ)
  1054. break;
  1055. /* x = x - t */
  1056. if((res = mp_sub(&x, &t, &x)) != MP_OKAY)
  1057. goto CLEANUP;
  1058. }
  1059. /* Copy result to output parameter */
  1060. mp_sub_d(&x, 1, &x);
  1061. s_mp_exch(&x, b);
  1062. CLEANUP:
  1063. mp_clear(&x);
  1064. X:
  1065. mp_clear(&t);
  1066. return res;
  1067. } /* end mp_sqrt() */
  1068. /* }}} */
  1069. /* }}} */
  1070. /*------------------------------------------------------------------------*/
  1071. /* {{{ Modular arithmetic */
  1072. #if MP_MODARITH
  1073. /* {{{ mp_addmod(a, b, m, c) */
  1074. /*
  1075. mp_addmod(a, b, m, c)
  1076. Compute c = (a + b) mod m
  1077. */
  1078. mp_err mp_addmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
  1079. {
  1080. mp_err res;
  1081. ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
  1082. if((res = mp_add(a, b, c)) != MP_OKAY)
  1083. return res;
  1084. if((res = mp_mod(c, m, c)) != MP_OKAY)
  1085. return res;
  1086. return MP_OKAY;
  1087. }
  1088. /* }}} */
  1089. /* {{{ mp_submod(a, b, m, c) */
  1090. /*
  1091. mp_submod(a, b, m, c)
  1092. Compute c = (a - b) mod m
  1093. */
  1094. mp_err mp_submod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
  1095. {
  1096. mp_err res;
  1097. ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
  1098. if((res = mp_sub(a, b, c)) != MP_OKAY)
  1099. return res;
  1100. if((res = mp_mod(c, m, c)) != MP_OKAY)
  1101. return res;
  1102. return MP_OKAY;
  1103. }
  1104. /* }}} */
  1105. /* {{{ mp_mulmod(a, b, m, c) */
  1106. /*
  1107. mp_mulmod(a, b, m, c)
  1108. Compute c = (a * b) mod m
  1109. */
  1110. mp_err mp_mulmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
  1111. {
  1112. mp_err res;
  1113. ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG);
  1114. if((res = mp_mul(a, b, c)) != MP_OKAY)
  1115. return res;
  1116. if((res = mp_mod(c, m, c)) != MP_OKAY)
  1117. return res;
  1118. return MP_OKAY;
  1119. }
  1120. /* }}} */
  1121. /* {{{ mp_sqrmod(a, m, c) */
  1122. #if MP_SQUARE
  1123. mp_err mp_sqrmod(mp_int *a, mp_int *m, mp_int *c)
  1124. {
  1125. mp_err res;
  1126. ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG);
  1127. if((res = mp_sqr(a, c)) != MP_OKAY)
  1128. return res;
  1129. if((res = mp_mod(c, m, c)) != MP_OKAY)
  1130. return res;
  1131. return MP_OKAY;
  1132. } /* end mp_sqrmod() */
  1133. #endif
  1134. /* }}} */
  1135. /* {{{ mp_exptmod(a, b, m, c) */
  1136. /*
  1137. mp_exptmod(a, b, m, c)
  1138. Compute c = (a ** b) mod m. Uses a standard square-and-multiply
  1139. method with modular reductions at each step. (This is basically the
  1140. same code as mp_expt(), except for the addition of the reductions)
  1141. The modular reductions are done using Barrett's algorithm (see
  1142. s_mp_reduce() below for details)
  1143. */
  1144. mp_err mp_exptmod(mp_int *a, mp_int *b, mp_int *m, mp_int *c)
  1145. {
  1146. mp_int s, x, mu;
  1147. mp_err res;
  1148. mp_digit d, *db = DIGITS(b);
  1149. mp_size ub = USED(b);
  1150. int dig, bit;
  1151. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  1152. if(mp_cmp_z(b) < 0 || mp_cmp_z(m) <= 0)
  1153. return MP_RANGE;
  1154. if((res = mp_init(&s)) != MP_OKAY)
  1155. return res;
  1156. if((res = mp_init_copy(&x, a)) != MP_OKAY)
  1157. goto X;
  1158. if((res = mp_mod(&x, m, &x)) != MP_OKAY ||
  1159. (res = mp_init(&mu)) != MP_OKAY)
  1160. goto MU;
  1161. mp_set(&s, 1);
  1162. /* mu = b^2k / m */
  1163. s_mp_add_d(&mu, 1);
  1164. s_mp_lshd(&mu, 2 * USED(m));
  1165. if((res = mp_div(&mu, m, &mu, NULL)) != MP_OKAY)
  1166. goto CLEANUP;
  1167. /* Loop over digits of b in ascending order, except highest order */
  1168. for(dig = 0; dig < (ub - 1); dig++) {
  1169. d = *db++;
  1170. /* Loop over the bits of the lower-order digits */
  1171. for(bit = 0; bit < DIGIT_BIT; bit++) {
  1172. if(d & 1) {
  1173. if((res = s_mp_mul(&s, &x)) != MP_OKAY)
  1174. goto CLEANUP;
  1175. if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY)
  1176. goto CLEANUP;
  1177. }
  1178. d >>= 1;
  1179. if((res = s_mp_sqr(&x)) != MP_OKAY)
  1180. goto CLEANUP;
  1181. if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY)
  1182. goto CLEANUP;
  1183. }
  1184. }
  1185. /* Now do the last digit... */
  1186. d = *db;
  1187. while(d) {
  1188. if(d & 1) {
  1189. if((res = s_mp_mul(&s, &x)) != MP_OKAY)
  1190. goto CLEANUP;
  1191. if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY)
  1192. goto CLEANUP;
  1193. }
  1194. d >>= 1;
  1195. if((res = s_mp_sqr(&x)) != MP_OKAY)
  1196. goto CLEANUP;
  1197. if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY)
  1198. goto CLEANUP;
  1199. }
  1200. s_mp_exch(&s, c);
  1201. CLEANUP:
  1202. mp_clear(&mu);
  1203. MU:
  1204. mp_clear(&x);
  1205. X:
  1206. mp_clear(&s);
  1207. return res;
  1208. } /* end mp_exptmod() */
  1209. /* }}} */
  1210. /* {{{ mp_exptmod_d(a, d, m, c) */
  1211. mp_err mp_exptmod_d(mp_int *a, mp_digit d, mp_int *m, mp_int *c)
  1212. {
  1213. mp_int s, x;
  1214. mp_err res;
  1215. ARGCHK(a != NULL && c != NULL, MP_BADARG);
  1216. if((res = mp_init(&s)) != MP_OKAY)
  1217. return res;
  1218. if((res = mp_init_copy(&x, a)) != MP_OKAY)
  1219. goto X;
  1220. mp_set(&s, 1);
  1221. while(d != 0) {
  1222. if(d & 1) {
  1223. if((res = s_mp_mul(&s, &x)) != MP_OKAY ||
  1224. (res = mp_mod(&s, m, &s)) != MP_OKAY)
  1225. goto CLEANUP;
  1226. }
  1227. d /= 2;
  1228. if((res = s_mp_sqr(&x)) != MP_OKAY ||
  1229. (res = mp_mod(&x, m, &x)) != MP_OKAY)
  1230. goto CLEANUP;
  1231. }
  1232. s_mp_exch(&s, c);
  1233. CLEANUP:
  1234. mp_clear(&x);
  1235. X:
  1236. mp_clear(&s);
  1237. return res;
  1238. } /* end mp_exptmod_d() */
  1239. /* }}} */
  1240. #endif /* if MP_MODARITH */
  1241. /* }}} */
  1242. /*------------------------------------------------------------------------*/
  1243. /* {{{ Comparison functions */
  1244. /* {{{ mp_cmp_z(a) */
  1245. /*
  1246. mp_cmp_z(a)
  1247. Compare a <=> 0. Returns <0 if a<0, 0 if a=0, >0 if a>0.
  1248. */
  1249. int mp_cmp_z(mp_int *a)
  1250. {
  1251. if(SIGN(a) == MP_NEG)
  1252. return MP_LT;
  1253. else if(USED(a) == 1 && DIGIT(a, 0) == 0)
  1254. return MP_EQ;
  1255. else
  1256. return MP_GT;
  1257. } /* end mp_cmp_z() */
  1258. /* }}} */
  1259. /* {{{ mp_cmp_d(a, d) */
  1260. /*
  1261. mp_cmp_d(a, d)
  1262. Compare a <=> d. Returns <0 if a<d, 0 if a=d, >0 if a>d
  1263. */
  1264. int mp_cmp_d(mp_int *a, mp_digit d)
  1265. {
  1266. ARGCHK(a != NULL, MP_EQ);
  1267. if(SIGN(a) == MP_NEG)
  1268. return MP_LT;
  1269. return s_mp_cmp_d(a, d);
  1270. } /* end mp_cmp_d() */
  1271. /* }}} */
  1272. /* {{{ mp_cmp(a, b) */
  1273. int mp_cmp(mp_int *a, mp_int *b)
  1274. {
  1275. ARGCHK(a != NULL && b != NULL, MP_EQ);
  1276. if(SIGN(a) == SIGN(b)) {
  1277. int mag;
  1278. if((mag = s_mp_cmp(a, b)) == MP_EQ)
  1279. return MP_EQ;
  1280. if(SIGN(a) == MP_ZPOS)
  1281. return mag;
  1282. else
  1283. return -mag;
  1284. } else if(SIGN(a) == MP_ZPOS) {
  1285. return MP_GT;
  1286. } else {
  1287. return MP_LT;
  1288. }
  1289. } /* end mp_cmp() */
  1290. /* }}} */
  1291. /* {{{ mp_cmp_mag(a, b) */
  1292. /*
  1293. mp_cmp_mag(a, b)
  1294. Compares |a| <=> |b|, and returns an appropriate comparison result
  1295. */
  1296. int mp_cmp_mag(mp_int *a, mp_int *b)
  1297. {
  1298. ARGCHK(a != NULL && b != NULL, MP_EQ);
  1299. return s_mp_cmp(a, b);
  1300. } /* end mp_cmp_mag() */
  1301. /* }}} */
  1302. /* {{{ mp_cmp_int(a, z) */
  1303. /*
  1304. This just converts z to an mp_int, and uses the existing comparison
  1305. routines. This is sort of inefficient, but it's not clear to me how
  1306. frequently this wil get used anyway. For small positive constants,
  1307. you can always use mp_cmp_d(), and for zero, there is mp_cmp_z().
  1308. */
  1309. int mp_cmp_int(mp_int *a, long z)
  1310. {
  1311. mp_int tmp;
  1312. int out;
  1313. ARGCHK(a != NULL, MP_EQ);
  1314. mp_init(&tmp); mp_set_int(&tmp, z);
  1315. out = mp_cmp(a, &tmp);
  1316. mp_clear(&tmp);
  1317. return out;
  1318. } /* end mp_cmp_int() */
  1319. /* }}} */
  1320. /* {{{ mp_isodd(a) */
  1321. /*
  1322. mp_isodd(a)
  1323. Returns a true (non-zero) value if a is odd, false (zero) otherwise.
  1324. */
  1325. int mp_isodd(mp_int *a)
  1326. {
  1327. ARGCHK(a != NULL, 0);
  1328. return (DIGIT(a, 0) & 1);
  1329. } /* end mp_isodd() */
  1330. /* }}} */
  1331. /* {{{ mp_iseven(a) */
  1332. int mp_iseven(mp_int *a)
  1333. {
  1334. return !mp_isodd(a);
  1335. } /* end mp_iseven() */
  1336. /* }}} */
  1337. /* }}} */
  1338. /*------------------------------------------------------------------------*/
  1339. /* {{{ Number theoretic functions */
  1340. #if MP_NUMTH
  1341. /* {{{ mp_gcd(a, b, c) */
  1342. /*
  1343. Like the old mp_gcd() function, except computes the GCD using the
  1344. binary algorithm due to Josef Stein in 1961 (via Knuth).
  1345. */
  1346. mp_err mp_gcd(mp_int *a, mp_int *b, mp_int *c)
  1347. {
  1348. mp_err res;
  1349. mp_int u, v, t;
  1350. mp_size k = 0;
  1351. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  1352. if(mp_cmp_z(a) == MP_EQ && mp_cmp_z(b) == MP_EQ)
  1353. return MP_RANGE;
  1354. if(mp_cmp_z(a) == MP_EQ) {
  1355. return mp_copy(b, c);
  1356. } else if(mp_cmp_z(b) == MP_EQ) {
  1357. return mp_copy(a, c);
  1358. }
  1359. if((res = mp_init(&t)) != MP_OKAY)
  1360. return res;
  1361. if((res = mp_init_copy(&u, a)) != MP_OKAY)
  1362. goto U;
  1363. if((res = mp_init_copy(&v, b)) != MP_OKAY)
  1364. goto V;
  1365. SIGN(&u) = MP_ZPOS;
  1366. SIGN(&v) = MP_ZPOS;
  1367. /* Divide out common factors of 2 until at least 1 of a, b is even */
  1368. while(mp_iseven(&u) && mp_iseven(&v)) {
  1369. s_mp_div_2(&u);
  1370. s_mp_div_2(&v);
  1371. ++k;
  1372. }
  1373. /* Initialize t */
  1374. if(mp_isodd(&u)) {
  1375. if((res = mp_copy(&v, &t)) != MP_OKAY)
  1376. goto CLEANUP;
  1377. /* t = -v */
  1378. if(SIGN(&v) == MP_ZPOS)
  1379. SIGN(&t) = MP_NEG;
  1380. else
  1381. SIGN(&t) = MP_ZPOS;
  1382. } else {
  1383. if((res = mp_copy(&u, &t)) != MP_OKAY)
  1384. goto CLEANUP;
  1385. }
  1386. for(;;) {
  1387. while(mp_iseven(&t)) {
  1388. s_mp_div_2(&t);
  1389. }
  1390. if(mp_cmp_z(&t) == MP_GT) {
  1391. if((res = mp_copy(&t, &u)) != MP_OKAY)
  1392. goto CLEANUP;
  1393. } else {
  1394. if((res = mp_copy(&t, &v)) != MP_OKAY)
  1395. goto CLEANUP;
  1396. /* v = -t */
  1397. if(SIGN(&t) == MP_ZPOS)
  1398. SIGN(&v) = MP_NEG;
  1399. else
  1400. SIGN(&v) = MP_ZPOS;
  1401. }
  1402. if((res = mp_sub(&u, &v, &t)) != MP_OKAY)
  1403. goto CLEANUP;
  1404. if(s_mp_cmp_d(&t, 0) == MP_EQ)
  1405. break;
  1406. }
  1407. s_mp_2expt(&v, k); /* v = 2^k */
  1408. res = mp_mul(&u, &v, c); /* c = u * v */
  1409. CLEANUP:
  1410. mp_clear(&v);
  1411. V:
  1412. mp_clear(&u);
  1413. U:
  1414. mp_clear(&t);
  1415. return res;
  1416. } /* end mp_bgcd() */
  1417. /* }}} */
  1418. /* {{{ mp_lcm(a, b, c) */
  1419. /* We compute the least common multiple using the rule:
  1420. ab = [a, b](a, b)
  1421. ... by computing the product, and dividing out the gcd.
  1422. */
  1423. mp_err mp_lcm(mp_int *a, mp_int *b, mp_int *c)
  1424. {
  1425. mp_int gcd, prod;
  1426. mp_err res;
  1427. ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG);
  1428. /* Set up temporaries */
  1429. if((res = mp_init(&gcd)) != MP_OKAY)
  1430. return res;
  1431. if((res = mp_init(&prod)) != MP_OKAY)
  1432. goto GCD;
  1433. if((res = mp_mul(a, b, &prod)) != MP_OKAY)
  1434. goto CLEANUP;
  1435. if((res = mp_gcd(a, b, &gcd)) != MP_OKAY)
  1436. goto CLEANUP;
  1437. res = mp_div(&prod, &gcd, c, NULL);
  1438. CLEANUP:
  1439. mp_clear(&prod);
  1440. GCD:
  1441. mp_clear(&gcd);
  1442. return res;
  1443. } /* end mp_lcm() */
  1444. /* }}} */
  1445. /* {{{ mp_xgcd(a, b, g, x, y) */
  1446. /*
  1447. mp_xgcd(a, b, g, x, y)
  1448. Compute g = (a, b) and values x and y satisfying Bezout's identity
  1449. (that is, ax + by = g). This uses the extended binary GCD algorithm
  1450. based on the Stein algorithm used for mp_gcd()
  1451. */
  1452. mp_err mp_xgcd(mp_int *a, mp_int *b, mp_int *g, mp_int *x, mp_int *y)
  1453. {
  1454. mp_int gx, xc, yc, u, v, A, B, C, D;
  1455. mp_int *clean[9];
  1456. mp_err res;
  1457. int last = -1;
  1458. if(mp_cmp_z(b) == 0)
  1459. return MP_RANGE;
  1460. /* Initialize all these variables we need */
  1461. if((res = mp_init(&u)) != MP_OKAY) goto CLEANUP;
  1462. clean[++last] = &u;
  1463. if((res = mp_init(&v)) != MP_OKAY) goto CLEANUP;
  1464. clean[++last] = &v;
  1465. if((res = mp_init(&gx)) != MP_OKAY) goto CLEANUP;
  1466. clean[++last] = &gx;
  1467. if((res = mp_init(&A)) != MP_OKAY) goto CLEANUP;
  1468. clean[++last] = &A;
  1469. if((res = mp_init(&B)) != MP_OKAY) goto CLEANUP;
  1470. clean[++last] = &B;
  1471. if((res = mp_init(&C)) != MP_OKAY) goto CLEANUP;
  1472. clean[++last] = &C;
  1473. if((res = mp_init(&D)) != MP_OKAY) goto CLEANUP;
  1474. clean[++last] = &D;
  1475. if((res = mp_init_copy(&xc, a)) != MP_OKAY) goto CLEANUP;
  1476. clean[++last] = &xc;
  1477. mp_abs(&xc, &xc);
  1478. if((res = mp_init_copy(&yc, b)) != MP_OKAY) goto CLEANUP;
  1479. clean[++last] = &yc;
  1480. mp_abs(&yc, &yc);
  1481. mp_set(&gx, 1);
  1482. /* Divide by two until at least one of them is even */
  1483. while(mp_iseven(&xc) && mp_iseven(&yc)) {
  1484. s_mp_div_2(&xc);
  1485. s_mp_div_2(&yc);
  1486. if((res = s_mp_mul_2(&gx)) != MP_OKAY)
  1487. goto CLEANUP;
  1488. }
  1489. mp_copy(&xc, &u);
  1490. mp_copy(&yc, &v);
  1491. mp_set(&A, 1); mp_set(&D, 1);
  1492. /* Loop through binary GCD algorithm */
  1493. for(;;) {
  1494. while(mp_iseven(&u)) {
  1495. s_mp_div_2(&u);
  1496. if(mp_iseven(&A) && mp_iseven(&B)) {
  1497. s_mp_div_2(&A); s_mp_div_2(&B);
  1498. } else {
  1499. if((res = mp_add(&A, &yc, &A)) != MP_OKAY) goto CLEANUP;
  1500. s_mp_div_2(&A);
  1501. if((res = mp_sub(&B, &xc, &B)) != MP_OKAY) goto CLEANUP;
  1502. s_mp_div_2(&B);
  1503. }
  1504. }
  1505. while(mp_iseven(&v)) {
  1506. s_mp_div_2(&v);
  1507. if(mp_iseven(&C) && mp_iseven(&D)) {
  1508. s_mp_div_2(&C); s_mp_div_2(&D);
  1509. } else {
  1510. if((res = mp_add(&C, &yc, &C)) != MP_OKAY) goto CLEANUP;
  1511. s_mp_div_2(&C);
  1512. if((res = mp_sub(&D, &xc, &D)) != MP_OKAY) goto CLEANUP;
  1513. s_mp_div_2(&D);
  1514. }
  1515. }
  1516. if(mp_cmp(&u, &v) >= 0) {
  1517. if((res = mp_sub(&u, &v, &u)) != MP_OKAY) goto CLEANUP;
  1518. if((res = mp_sub(&A, &C, &A)) != MP_OKAY) goto CLEANUP;
  1519. if((res = mp_sub(&B, &D, &B)) != MP_OKAY) goto CLEANUP;
  1520. } else {
  1521. if((res = mp_sub(&v, &u, &v)) != MP_OKAY) goto CLEANUP;
  1522. if((res = mp_sub(&C, &A, &C)) != MP_OKAY) goto CLEANUP;
  1523. if((res = mp_sub(&D, &B, &D)) != MP_OKAY) goto CLEANUP;
  1524. }
  1525. /* If we're done, copy results to output */
  1526. if(mp_cmp_z(&u) == 0) {
  1527. if(x)
  1528. if((res = mp_copy(&C, x)) != MP_OKAY) goto CLEANUP;
  1529. if(y)
  1530. if((res = mp_copy(&D, y)) != MP_OKAY) goto CLEANUP;
  1531. if(g)
  1532. if((res = mp_mul(&gx, &v, g)) != MP_OKAY) goto CLEANUP;
  1533. break;
  1534. }
  1535. }
  1536. CLEANUP:
  1537. while(last >= 0)
  1538. mp_clear(clean[last--]);
  1539. return res;
  1540. } /* end mp_xgcd() */
  1541. /* }}} */
  1542. /* {{{ mp_invmod(a, m, c) */
  1543. /*
  1544. mp_invmod(a, m, c)
  1545. Compute c = a^-1 (mod m), if there is an inverse for a (mod m).
  1546. This is equivalent to the question of whether (a, m) = 1. If not,
  1547. MP_UNDEF is returned, and there is no inverse.
  1548. */
  1549. mp_err mp_invmod(mp_int *a, mp_int *m, mp_int *c)
  1550. {
  1551. mp_int g, x;
  1552. mp_err res;
  1553. ARGCHK(a && m && c, MP_BADARG);
  1554. if(mp_cmp_z(a) == 0 || mp_cmp_z(m) == 0)
  1555. return MP_RANGE;
  1556. if((res = mp_init(&g)) != MP_OKAY)
  1557. return res;
  1558. if((res = mp_init(&x)) != MP_OKAY)
  1559. goto X;
  1560. if((res = mp_xgcd(a, m, &g, &x, NULL)) != MP_OKAY)
  1561. goto CLEANUP;
  1562. if(mp_cmp_d(&g, 1) != MP_EQ) {
  1563. res = MP_UNDEF;
  1564. goto CLEANUP;
  1565. }
  1566. res = mp_mod(&x, m, c);
  1567. SIGN(c) = SIGN(a);
  1568. CLEANUP:
  1569. mp_clear(&x);
  1570. X:
  1571. mp_clear(&g);
  1572. return res;
  1573. } /* end mp_invmod() */
  1574. /* }}} */
  1575. #endif /* if MP_NUMTH */
  1576. /* }}} */
  1577. /*------------------------------------------------------------------------*/
  1578. /* {{{ mp_print(mp, ofp) */
  1579. #if MP_IOFUNC
  1580. /*
  1581. mp_print(mp, ofp)
  1582. Print a textual representation of the given mp_int on the output
  1583. stream 'ofp'. Output is generated using the internal radix.
  1584. */
  1585. void mp_print(mp_int *mp, FILE *ofp)
  1586. {
  1587. int ix;
  1588. if(mp == NULL || ofp == NULL)
  1589. return;
  1590. fputc((SIGN(mp) == MP_NEG) ? '-' : '+', ofp);
  1591. for(ix = USED(mp) - 1; ix >= 0; ix--) {
  1592. fprintf(ofp, DIGIT_FMT, DIGIT(mp, ix));
  1593. }
  1594. } /* end mp_print() */
  1595. #endif /* if MP_IOFUNC */
  1596. /* }}} */
  1597. /*------------------------------------------------------------------------*/
  1598. /* {{{ More I/O Functions */
  1599. /* {{{ mp_read_signed_bin(mp, str, len) */
  1600. /*
  1601. mp_read_signed_bin(mp, str, len)
  1602. Read in a raw value (base 256) into the given mp_int
  1603. */
  1604. mp_err mp_read_signed_bin(mp_int *mp, unsigned char *str, int len)
  1605. {
  1606. mp_err res;
  1607. ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG);
  1608. if((res = mp_read_unsigned_bin(mp, str + 1, len - 1)) == MP_OKAY) {
  1609. /* Get sign from first byte */
  1610. if(str[0])
  1611. SIGN(mp) = MP_NEG;
  1612. else
  1613. SIGN(mp) = MP_ZPOS;
  1614. }
  1615. return res;
  1616. } /* end mp_read_signed_bin() */
  1617. /* }}} */
  1618. /* {{{ mp_signed_bin_size(mp) */
  1619. int mp_signed_bin_size(mp_int *mp)
  1620. {
  1621. ARGCHK(mp != NULL, 0);
  1622. return mp_unsigned_bin_size(mp) + 1;
  1623. } /* end mp_signed_bin_size() */
  1624. /* }}} */
  1625. /* {{{ mp_to_signed_bin(mp, str) */
  1626. mp_err mp_to_signed_bin(mp_int *mp, unsigned char *str)
  1627. {
  1628. ARGCHK(mp != NULL && str != NULL, MP_BADARG);
  1629. /* Caller responsible for allocating enough memory (use mp_raw_size(mp)) */
  1630. str[0] = (char)SIGN(mp);
  1631. return mp_to_unsigned_bin(mp, str + 1);
  1632. } /* end mp_to_signed_bin() */
  1633. /* }}} */
  1634. /* {{{ mp_read_unsigned_bin(mp, str, len) */
  1635. /*
  1636. mp_read_unsigned_bin(mp, str, len)
  1637. Read in an unsigned value (base 256) into the given mp_int
  1638. */
  1639. mp_err mp_read_unsigned_bin(mp_int *mp, unsigned char *str, int len)
  1640. {
  1641. int ix;
  1642. mp_err res;
  1643. ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG);
  1644. mp_zero(mp);
  1645. for(ix = 0; ix < len; ix++) {
  1646. if((res = s_mp_mul_2d(mp, CHAR_BIT)) != MP_OKAY)
  1647. return res;
  1648. if((res = mp_add_d(mp, str[ix], mp)) != MP_OKAY)
  1649. return res;
  1650. }
  1651. return MP_OKAY;
  1652. } /* end mp_read_unsigned_bin() */
  1653. /* }}} */
  1654. /* {{{ mp_unsigned_bin_size(mp) */
  1655. int mp_unsigned_bin_size(mp_int *mp)
  1656. {
  1657. mp_digit topdig;
  1658. int count;
  1659. ARGCHK(mp != NULL, 0);
  1660. /* Special case for the value zero */
  1661. if(USED(mp) == 1 && DIGIT(mp, 0) == 0)
  1662. return 1;
  1663. count = (USED(mp) - 1) * sizeof(mp_digit);
  1664. topdig = DIGIT(mp, USED(mp) - 1);
  1665. while(topdig != 0) {
  1666. ++count;
  1667. topdig >>= CHAR_BIT;
  1668. }
  1669. return count;
  1670. } /* end mp_unsigned_bin_size() */
  1671. /* }}} */
  1672. /* {{{ mp_to_unsigned_bin(mp, str) */
  1673. mp_err mp_to_unsigned_bin(mp_int *mp, unsigned char *str)
  1674. {
  1675. mp_digit *dp, *end, d;
  1676. unsigned char *spos;
  1677. ARGCHK(mp != NULL && str != NULL, MP_BADARG);
  1678. dp = DIGITS(mp);
  1679. end = dp + USED(mp) - 1;
  1680. spos = str;
  1681. /* Special case for zero, quick test */
  1682. if(dp == end && *dp == 0) {
  1683. *str = '\0';
  1684. return MP_OKAY;
  1685. }
  1686. /* Generate digits in reverse order */
  1687. while(dp < end) {
  1688. int ix;
  1689. d = *dp;
  1690. for(ix = 0; ix < sizeof(mp_digit); ++ix) {
  1691. *spos = d & UCHAR_MAX;
  1692. d >>= CHAR_BIT;
  1693. ++spos;
  1694. }
  1695. ++dp;
  1696. }
  1697. /* Now handle last digit specially, high order zeroes are not written */
  1698. d = *end;
  1699. while(d != 0) {
  1700. *spos = d & UCHAR_MAX;
  1701. d >>= CHAR_BIT;
  1702. ++spos;
  1703. }
  1704. /* Reverse everything to get digits in the correct order */
  1705. while(--spos > str) {
  1706. unsigned char t = *str;
  1707. *str = *spos;
  1708. *spos = t;
  1709. ++str;
  1710. }
  1711. return MP_OKAY;
  1712. } /* end mp_to_unsigned_bin() */
  1713. /* }}} */
  1714. /* {{{ mp_count_bits(mp) */
  1715. int mp_count_bits(mp_int *mp)
  1716. {
  1717. int len;
  1718. mp_digit d;
  1719. ARGCHK(mp != NULL, MP_BADARG);
  1720. len = DIGIT_BIT * (USED(mp) - 1);
  1721. d = DIGIT(mp, USED(mp) - 1);
  1722. while(d != 0) {
  1723. ++len;
  1724. d >>= 1;
  1725. }
  1726. return len;
  1727. } /* end mp_count_bits() */
  1728. /* }}} */
  1729. /* {{{ mp_read_radix(mp, str, radix) */
  1730. /*
  1731. mp_read_radix(mp, str, radix)
  1732. Read an integer from the given string, and set mp to the resulting
  1733. value. The input is presumed to be in base 10. Leading non-digit
  1734. characters are ignored, and the function reads until a non-digit
  1735. character or the end of the string.
  1736. */
  1737. mp_err mp_read_radix(mp_int *mp, unsigned char *str, int radix)
  1738. {
  1739. int ix = 0, val = 0;
  1740. mp_err res;
  1741. mp_sign sig = MP_ZPOS;
  1742. ARGCHK(mp != NULL && str != NULL && radix >= 2 && radix <= MAX_RADIX,
  1743. MP_BADARG);
  1744. mp_zero(mp);
  1745. /* Skip leading non-digit characters until a digit or '-' or '+' */
  1746. while(str[ix] &&
  1747. (s_mp_tovalue(str[ix], radix) < 0) &&
  1748. str[ix] != '-' &&
  1749. str[ix] != '+') {
  1750. ++ix;
  1751. }
  1752. if(str[ix] == '-') {
  1753. sig = MP_NEG;
  1754. ++ix;
  1755. } else if(str[ix] == '+') {
  1756. sig = MP_ZPOS; /* this is the default anyway... */
  1757. ++ix;
  1758. }
  1759. while((val = s_mp_tovalue(str[ix], radix)) >= 0) {
  1760. if((res = s_mp_mul_d(mp, radix)) != MP_OKAY)
  1761. return res;
  1762. if((res = s_mp_add_d(mp, val)) != MP_OKAY)
  1763. return res;
  1764. ++ix;
  1765. }
  1766. if(s_mp_cmp_d(mp, 0) == MP_EQ)
  1767. SIGN(mp) = MP_ZPOS;
  1768. else
  1769. SIGN(mp) = sig;
  1770. return MP_OKAY;
  1771. } /* end mp_read_radix() */
  1772. /* }}} */
  1773. /* {{{ mp_radix_size(mp, radix) */
  1774. int mp_radix_size(mp_int *mp, int radix)
  1775. {
  1776. int len;
  1777. ARGCHK(mp != NULL, 0);
  1778. len = s_mp_outlen(mp_count_bits(mp), radix) + 1; /* for NUL terminator */
  1779. if(mp_cmp_z(mp) < 0)
  1780. ++len; /* for sign */
  1781. return len;
  1782. } /* end mp_radix_size() */
  1783. /* }}} */
  1784. /* {{{ mp_value_radix_size(num, qty, radix) */
  1785. /* num = number of digits
  1786. qty = number of bits per digit
  1787. radix = target base
  1788. Return the number of digits in the specified radix that would be
  1789. needed to express 'num' digits of 'qty' bits each.
  1790. */
  1791. int mp_value_radix_size(int num, int qty, int radix)
  1792. {
  1793. ARGCHK(num >= 0 && qty > 0 && radix >= 2 && radix <= MAX_RADIX, 0);
  1794. return s_mp_outlen(num * qty, radix);
  1795. } /* end mp_value_radix_size() */
  1796. /* }}} */
  1797. /* {{{ mp_toradix(mp, str, radix) */
  1798. mp_err mp_toradix(mp_int *mp, unsigned char *str, int radix)
  1799. {
  1800. int ix, pos = 0;
  1801. ARGCHK(mp != NULL && str != NULL, MP_BADARG);
  1802. ARGCHK(radix > 1 && radix <= MAX_RADIX, MP_RANGE);
  1803. if(mp_cmp_z(mp) == MP_EQ) {
  1804. str[0] = '0';
  1805. str[1] = '\0';
  1806. } else {
  1807. mp_err res;
  1808. mp_int tmp;
  1809. mp_sign sgn;
  1810. mp_digit rem, rdx = (mp_digit)radix;
  1811. char ch;
  1812. if((res = mp_init_copy(&tmp, mp)) != MP_OKAY)
  1813. return res;
  1814. /* Save sign for later, and take absolute value */
  1815. sgn = SIGN(&tmp); SIGN(&tmp) = MP_ZPOS;
  1816. /* Generate output digits in reverse order */
  1817. while(mp_cmp_z(&tmp) != 0) {
  1818. if((res = s_mp_div_d(&tmp, rdx, &rem)) != MP_OKAY) {
  1819. mp_clear(&tmp);
  1820. return res;
  1821. }
  1822. /* Generate digits, use capital letters */
  1823. ch = s_mp_todigit(rem, radix, 0);
  1824. str[pos++] = ch;
  1825. }
  1826. /* Add - sign if original value was negative */
  1827. if(sgn == MP_NEG)
  1828. str[pos++] = '-';
  1829. /* Add trailing NUL to end the string */
  1830. str[pos--] = '\0';
  1831. /* Reverse the digits and sign indicator */
  1832. ix = 0;
  1833. while(ix < pos) {
  1834. char tmp = str[ix];
  1835. str[ix] = str[pos];
  1836. str[pos] = tmp;
  1837. ++ix;
  1838. --pos;
  1839. }
  1840. mp_clear(&tmp);
  1841. }
  1842. return MP_OKAY;
  1843. } /* end mp_toradix() */
  1844. /* }}} */
  1845. /* {{{ mp_char2value(ch, r) */
  1846. int mp_char2value(char ch, int r)
  1847. {
  1848. return s_mp_tovalue(ch, r);
  1849. } /* end mp_tovalue() */
  1850. /* }}} */
  1851. /* }}} */
  1852. /* {{{ mp_strerror(ec) */
  1853. /*
  1854. mp_strerror(ec)
  1855. Return a string describing the meaning of error code 'ec'. The
  1856. string returned is allocated in static memory, so the caller should
  1857. not attempt to modify or free the memory associated with this
  1858. string.
  1859. */
  1860. const char *mp_strerror(mp_err ec)
  1861. {
  1862. int aec = (ec < 0) ? -ec : ec;
  1863. /* Code values are negative, so the senses of these comparisons
  1864. are accurate */
  1865. if(ec < MP_LAST_CODE || ec > MP_OKAY) {
  1866. return mp_err_string[0]; /* unknown error code */
  1867. } else {
  1868. return mp_err_string[aec + 1];
  1869. }
  1870. } /* end mp_strerror() */
  1871. /* }}} */
  1872. /*========================================================================*/
  1873. /*------------------------------------------------------------------------*/
  1874. /* Static function definitions (internal use only) */
  1875. /* {{{ Memory management */
  1876. /* {{{ s_mp_grow(mp, min) */
  1877. /* Make sure there are at least 'min' digits allocated to mp */
  1878. mp_err s_mp_grow(mp_int *mp, mp_size min)
  1879. {
  1880. if(min > ALLOC(mp)) {
  1881. mp_digit *tmp;
  1882. /* Set min to next nearest default precision block size */
  1883. min = ((min + (s_mp_defprec - 1)) / s_mp_defprec) * s_mp_defprec;
  1884. if((tmp = s_mp_alloc(min, sizeof(mp_digit))) == NULL)
  1885. return MP_MEM;
  1886. s_mp_copy(DIGITS(mp), tmp, USED(mp));
  1887. #if MP_CRYPTO
  1888. s_mp_setz(DIGITS(mp), ALLOC(mp));
  1889. #endif
  1890. s_mp_free(DIGITS(mp));
  1891. DIGITS(mp) = tmp;
  1892. ALLOC(mp) = min;
  1893. }
  1894. return MP_OKAY;
  1895. } /* end s_mp_grow() */
  1896. /* }}} */
  1897. /* {{{ s_mp_pad(mp, min) */
  1898. /* Make sure the used size of mp is at least 'min', growing if needed */
  1899. mp_err s_mp_pad(mp_int *mp, mp_size min)
  1900. {
  1901. if(min > USED(mp)) {
  1902. mp_err res;
  1903. /* Make sure there is room to increase precision */
  1904. if(min > ALLOC(mp) && (res = s_mp_grow(mp, min)) != MP_OKAY)
  1905. return res;
  1906. /* Increase precision; should already be 0-filled */
  1907. USED(mp) = min;
  1908. }
  1909. return MP_OKAY;
  1910. } /* end s_mp_pad() */
  1911. /* }}} */
  1912. /* {{{ s_mp_setz(dp, count) */
  1913. #if MP_MACRO == 0
  1914. /* Set 'count' digits pointed to by dp to be zeroes */
  1915. void s_mp_setz(mp_digit *dp, mp_size count)
  1916. {
  1917. #if MP_MEMSET == 0
  1918. int ix;
  1919. for(ix = 0; ix < count; ix++)
  1920. dp[ix] = 0;
  1921. #else
  1922. memset(dp, 0, count * sizeof(mp_digit));
  1923. #endif
  1924. } /* end s_mp_setz() */
  1925. #endif
  1926. /* }}} */
  1927. /* {{{ s_mp_copy(sp, dp, count) */
  1928. #if MP_MACRO == 0
  1929. /* Copy 'count' digits from sp to dp */
  1930. void s_mp_copy(mp_digit *sp, mp_digit *dp, mp_size count)
  1931. {
  1932. #if MP_MEMCPY == 0
  1933. int ix;
  1934. for(ix = 0; ix < count; ix++)
  1935. dp[ix] = sp[ix];
  1936. #else
  1937. memcpy(dp, sp, count * sizeof(mp_digit));
  1938. #endif
  1939. } /* end s_mp_copy() */
  1940. #endif
  1941. /* }}} */
  1942. /* {{{ s_mp_alloc(nb, ni) */
  1943. #if MP_MACRO == 0
  1944. /* Allocate ni records of nb bytes each, and return a pointer to that */
  1945. void *s_mp_alloc(size_t nb, size_t ni)
  1946. {
  1947. return calloc(nb, ni);
  1948. } /* end s_mp_alloc() */
  1949. #endif
  1950. /* }}} */
  1951. /* {{{ s_mp_free(ptr) */
  1952. #if MP_MACRO == 0
  1953. /* Free the memory pointed to by ptr */
  1954. void s_mp_free(void *ptr)
  1955. {
  1956. if(ptr)
  1957. free(ptr);
  1958. } /* end s_mp_free() */
  1959. #endif
  1960. /* }}} */
  1961. /* {{{ s_mp_clamp(mp) */
  1962. /* Remove leading zeroes from the given value */
  1963. void s_mp_clamp(mp_int *mp)
  1964. {
  1965. mp_size du = USED(mp);
  1966. mp_digit *zp = DIGITS(mp) + du - 1;
  1967. while(du > 1 && !*zp--)
  1968. --du;
  1969. USED(mp) = du;
  1970. } /* end s_mp_clamp() */
  1971. /* }}} */
  1972. /* {{{ s_mp_exch(a, b) */
  1973. /* Exchange the data for a and b; (b, a) = (a, b) */
  1974. void s_mp_exch(mp_int *a, mp_int *b)
  1975. {
  1976. mp_int tmp;
  1977. tmp = *a;
  1978. *a = *b;
  1979. *b = tmp;
  1980. } /* end s_mp_exch() */
  1981. /* }}} */
  1982. /* }}} */
  1983. /* {{{ Arithmetic helpers */
  1984. /* {{{ s_mp_lshd(mp, p) */
  1985. /*
  1986. Shift mp leftward by p digits, growing if needed, and zero-filling
  1987. the in-shifted digits at the right end. This is a convenient
  1988. alternative to multiplication by powers of the radix
  1989. */
  1990. mp_err s_mp_lshd(mp_int *mp, mp_size p)
  1991. {
  1992. mp_err res;
  1993. mp_size pos;
  1994. mp_digit *dp;
  1995. int ix;
  1996. if(p == 0)
  1997. return MP_OKAY;
  1998. if((res = s_mp_pad(mp, USED(mp) + p)) != MP_OKAY)
  1999. return res;
  2000. pos = USED(mp) - 1;
  2001. dp = DIGITS(mp);
  2002. /* Shift all the significant figures over as needed */
  2003. for(ix = pos - p; ix >= 0; ix--)
  2004. dp[ix + p] = dp[ix];
  2005. /* Fill the bottom digits with zeroes */
  2006. for(ix = 0; ix < p; ix++)
  2007. dp[ix] = 0;
  2008. return MP_OKAY;
  2009. } /* end s_mp_lshd() */
  2010. /* }}} */
  2011. /* {{{ s_mp_rshd(mp, p) */
  2012. /*
  2013. Shift mp rightward by p digits. Maintains the invariant that
  2014. digits above the precision are all zero. Digits shifted off the
  2015. end are lost. Cannot fail.
  2016. */
  2017. void s_mp_rshd(mp_int *mp, mp_size p)
  2018. {
  2019. mp_size ix;
  2020. mp_digit *dp;
  2021. if(p == 0)
  2022. return;
  2023. /* Shortcut when all digits are to be shifted off */
  2024. if(p >= USED(mp)) {
  2025. s_mp_setz(DIGITS(mp), ALLOC(mp));
  2026. USED(mp) = 1;
  2027. SIGN(mp) = MP_ZPOS;
  2028. return;
  2029. }
  2030. /* Shift all the significant figures over as needed */
  2031. dp = DIGITS(mp);
  2032. for(ix = p; ix < USED(mp); ix++)
  2033. dp[ix - p] = dp[ix];
  2034. /* Fill the top digits with zeroes */
  2035. ix -= p;
  2036. while(ix < USED(mp))
  2037. dp[ix++] = 0;
  2038. /* Strip off any leading zeroes */
  2039. s_mp_clamp(mp);
  2040. } /* end s_mp_rshd() */
  2041. /* }}} */
  2042. /* {{{ s_mp_div_2(mp) */
  2043. /* Divide by two -- take advantage of radix properties to do it fast */
  2044. void s_mp_div_2(mp_int *mp)
  2045. {
  2046. s_mp_div_2d(mp, 1);
  2047. } /* end s_mp_div_2() */
  2048. /* }}} */
  2049. /* {{{ s_mp_mul_2(mp) */
  2050. mp_err s_mp_mul_2(mp_int *mp)
  2051. {
  2052. int ix;
  2053. mp_digit kin = 0, kout, *dp = DIGITS(mp);
  2054. mp_err res;
  2055. /* Shift digits leftward by 1 bit */
  2056. for(ix = 0; ix < USED(mp); ix++) {
  2057. kout = (dp[ix] >> (DIGIT_BIT - 1)) & 1;
  2058. dp[ix] = (dp[ix] << 1) | kin;
  2059. kin = kout;
  2060. }
  2061. /* Deal with rollover from last digit */
  2062. if(kin) {
  2063. if(ix >= ALLOC(mp)) {
  2064. if((res = s_mp_grow(mp, ALLOC(mp) + 1)) != MP_OKAY)
  2065. return res;
  2066. dp = DIGITS(mp);
  2067. }
  2068. dp[ix] = kin;
  2069. USED(mp) += 1;
  2070. }
  2071. return MP_OKAY;
  2072. } /* end s_mp_mul_2() */
  2073. /* }}} */
  2074. /* {{{ s_mp_mod_2d(mp, d) */
  2075. /*
  2076. Remainder the integer by 2^d, where d is a number of bits. This
  2077. amounts to a bitwise AND of the value, and does not require the full
  2078. division code
  2079. */
  2080. void s_mp_mod_2d(mp_int *mp, mp_digit d)
  2081. {
  2082. unsigned int ndig = (d / DIGIT_BIT), nbit = (d % DIGIT_BIT);
  2083. unsigned int ix;
  2084. mp_digit dmask, *dp = DIGITS(mp);
  2085. if(ndig >= USED(mp))
  2086. return;
  2087. /* Flush all the bits above 2^d in its digit */
  2088. dmask = (1 << nbit) - 1;
  2089. dp[ndig] &= dmask;
  2090. /* Flush all digits above the one with 2^d in it */
  2091. for(ix = ndig + 1; ix < USED(mp); ix++)
  2092. dp[ix] = 0;
  2093. s_mp_clamp(mp);
  2094. } /* end s_mp_mod_2d() */
  2095. /* }}} */
  2096. /* {{{ s_mp_mul_2d(mp, d) */
  2097. /*
  2098. Multiply by the integer 2^d, where d is a number of bits. This
  2099. amounts to a bitwise shift of the value, and does not require the
  2100. full multiplication code.
  2101. */
  2102. mp_err s_mp_mul_2d(mp_int *mp, mp_digit d)
  2103. {
  2104. mp_err res;
  2105. mp_digit save, next, mask, *dp;
  2106. mp_size used;
  2107. int ix;
  2108. if((res = s_mp_lshd(mp, d / DIGIT_BIT)) != MP_OKAY)
  2109. return res;
  2110. dp = DIGITS(mp); used = USED(mp);
  2111. d %= DIGIT_BIT;
  2112. mask = (1 << d) - 1;
  2113. /* If the shift requires another digit, make sure we've got one to
  2114. work with */
  2115. if((dp[used - 1] >> (DIGIT_BIT - d)) & mask) {
  2116. if((res = s_mp_grow(mp, used + 1)) != MP_OKAY)
  2117. return res;
  2118. dp = DIGITS(mp);
  2119. }
  2120. /* Do the shifting... */
  2121. save = 0;
  2122. for(ix = 0; ix < used; ix++) {
  2123. next = (dp[ix] >> (DIGIT_BIT - d)) & mask;
  2124. dp[ix] = (dp[ix] << d) | save;
  2125. save = next;
  2126. }
  2127. /* If, at this point, we have a nonzero carryout into the next
  2128. digit, we'll increase the size by one digit, and store it...
  2129. */
  2130. if(save) {
  2131. dp[used] = save;
  2132. USED(mp) += 1;
  2133. }
  2134. s_mp_clamp(mp);
  2135. return MP_OKAY;
  2136. } /* end s_mp_mul_2d() */
  2137. /* }}} */
  2138. /* {{{ s_mp_div_2d(mp, d) */
  2139. /*
  2140. Divide the integer by 2^d, where d is a number of bits. This
  2141. amounts to a bitwise shift of the value, and does not require the
  2142. full division code (used in Barrett reduction, see below)
  2143. */
  2144. void s_mp_div_2d(mp_int *mp, mp_digit d)
  2145. {
  2146. int ix;
  2147. mp_digit save, next, mask, *dp = DIGITS(mp);
  2148. s_mp_rshd(mp, d / DIGIT_BIT);
  2149. d %= DIGIT_BIT;
  2150. mask = (1 << d) - 1;
  2151. save = 0;
  2152. for(ix = USED(mp) - 1; ix >= 0; ix--) {
  2153. next = dp[ix] & mask;
  2154. dp[ix] = (dp[ix] >> d) | (save << (DIGIT_BIT - d));
  2155. save = next;
  2156. }
  2157. s_mp_clamp(mp);
  2158. } /* end s_mp_div_2d() */
  2159. /* }}} */
  2160. /* {{{ s_mp_norm(a, b) */
  2161. /*
  2162. s_mp_norm(a, b)
  2163. Normalize a and b for division, where b is the divisor. In order
  2164. that we might make good guesses for quotient digits, we want the
  2165. leading digit of b to be at least half the radix, which we
  2166. accomplish by multiplying a and b by a constant. This constant is
  2167. returned (so that it can be divided back out of the remainder at the
  2168. end of the division process).
  2169. We multiply by the smallest power of 2 that gives us a leading digit
  2170. at least half the radix. By choosing a power of 2, we simplify the
  2171. multiplication and division steps to simple shifts.
  2172. */
  2173. mp_digit s_mp_norm(mp_int *a, mp_int *b)
  2174. {
  2175. mp_digit t, d = 0;
  2176. t = DIGIT(b, USED(b) - 1);
  2177. while(t < (RADIX / 2)) {
  2178. t <<= 1;
  2179. ++d;
  2180. }
  2181. if(d != 0) {
  2182. s_mp_mul_2d(a, d);
  2183. s_mp_mul_2d(b, d);
  2184. }
  2185. return d;
  2186. } /* end s_mp_norm() */
  2187. /* }}} */
  2188. /* }}} */
  2189. /* {{{ Primitive digit arithmetic */
  2190. /* {{{ s_mp_add_d(mp, d) */
  2191. /* Add d to |mp| in place */
  2192. mp_err s_mp_add_d(mp_int *mp, mp_digit d) /* unsigned digit addition */
  2193. {
  2194. mp_word w, k = 0;
  2195. mp_size ix = 1, used = USED(mp);
  2196. mp_digit *dp = DIGITS(mp);
  2197. w = dp[0] + d;
  2198. dp[0] = ACCUM(w);
  2199. k = CARRYOUT(w);
  2200. while(ix < used && k) {
  2201. w = dp[ix] + k;
  2202. dp[ix] = ACCUM(w);
  2203. k = CARRYOUT(w);
  2204. ++ix;
  2205. }
  2206. if(k != 0) {
  2207. mp_err res;
  2208. if((res = s_mp_pad(mp, USED(mp) + 1)) != MP_OKAY)
  2209. return res;
  2210. DIGIT(mp, ix) = k;
  2211. }
  2212. return MP_OKAY;
  2213. } /* end s_mp_add_d() */
  2214. /* }}} */
  2215. /* {{{ s_mp_sub_d(mp, d) */
  2216. /* Subtract d from |mp| in place, assumes |mp| > d */
  2217. mp_err s_mp_sub_d(mp_int *mp, mp_digit d) /* unsigned digit subtract */
  2218. {
  2219. mp_word w, b = 0;
  2220. mp_size ix = 1, used = USED(mp);
  2221. mp_digit *dp = DIGITS(mp);
  2222. /* Compute initial subtraction */
  2223. w = (RADIX + dp[0]) - d;
  2224. b = CARRYOUT(w) ? 0 : 1;
  2225. dp[0] = ACCUM(w);
  2226. /* Propagate borrows leftward */
  2227. while(b && ix < used) {
  2228. w = (RADIX + dp[ix]) - b;
  2229. b = CARRYOUT(w) ? 0 : 1;
  2230. dp[ix] = ACCUM(w);
  2231. ++ix;
  2232. }
  2233. /* Remove leading zeroes */
  2234. s_mp_clamp(mp);
  2235. /* If we have a borrow out, it's a violation of the input invariant */
  2236. if(b)
  2237. return MP_RANGE;
  2238. else
  2239. return MP_OKAY;
  2240. } /* end s_mp_sub_d() */
  2241. /* }}} */
  2242. /* {{{ s_mp_mul_d(a, d) */
  2243. /* Compute a = a * d, single digit multiplication */
  2244. mp_err s_mp_mul_d(mp_int *a, mp_digit d)
  2245. {
  2246. mp_word w, k = 0;
  2247. mp_size ix, max;
  2248. mp_err res;
  2249. mp_digit *dp = DIGITS(a);
  2250. /*
  2251. Single-digit multiplication will increase the precision of the
  2252. output by at most one digit. However, we can detect when this
  2253. will happen -- if the high-order digit of a, times d, gives a
  2254. two-digit result, then the precision of the result will increase;
  2255. otherwise it won't. We use this fact to avoid calling s_mp_pad()
  2256. unless absolutely necessary.
  2257. */
  2258. max = USED(a);
  2259. w = dp[max - 1] * d;
  2260. if(CARRYOUT(w) != 0) {
  2261. if((res = s_mp_pad(a, max + 1)) != MP_OKAY)
  2262. return res;
  2263. dp = DIGITS(a);
  2264. }
  2265. for(ix = 0; ix < max; ix++) {
  2266. w = (dp[ix] * d) + k;
  2267. dp[ix] = ACCUM(w);
  2268. k = CARRYOUT(w);
  2269. }
  2270. /* If there is a precision increase, take care of it here; the above
  2271. test guarantees we have enough storage to do this safely.
  2272. */
  2273. if(k) {
  2274. dp[max] = k;
  2275. USED(a) = max + 1;
  2276. }
  2277. s_mp_clamp(a);
  2278. return MP_OKAY;
  2279. } /* end s_mp_mul_d() */
  2280. /* }}} */
  2281. /* {{{ s_mp_div_d(mp, d, r) */
  2282. /*
  2283. s_mp_div_d(mp, d, r)
  2284. Compute the quotient mp = mp / d and remainder r = mp mod d, for a
  2285. single digit d. If r is null, the remainder will be discarded.
  2286. */
  2287. mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r)
  2288. {
  2289. mp_word w = 0, t;
  2290. mp_int quot;
  2291. mp_err res;
  2292. mp_digit *dp = DIGITS(mp), *qp;
  2293. int ix;
  2294. if(d == 0)
  2295. return MP_RANGE;
  2296. /* Make room for the quotient */
  2297. if((res = mp_init_size(&quot, USED(mp))) != MP_OKAY)
  2298. return res;
  2299. USED(&quot) = USED(mp); /* so clamping will work below */
  2300. qp = DIGITS(&quot);
  2301. /* Divide without subtraction */
  2302. for(ix = USED(mp) - 1; ix >= 0; ix--) {
  2303. w = (w << DIGIT_BIT) | dp[ix];
  2304. if(w >= d) {
  2305. t = w / d;
  2306. w = w % d;
  2307. } else {
  2308. t = 0;
  2309. }
  2310. qp[ix] = t;
  2311. }
  2312. /* Deliver the remainder, if desired */
  2313. if(r)
  2314. *r = w;
  2315. s_mp_clamp(&quot);
  2316. mp_exch(&quot, mp);
  2317. mp_clear(&quot);
  2318. return MP_OKAY;
  2319. } /* end s_mp_div_d() */
  2320. /* }}} */
  2321. /* }}} */
  2322. /* {{{ Primitive full arithmetic */
  2323. /* {{{ s_mp_add(a, b) */
  2324. /* Compute a = |a| + |b| */
  2325. mp_err s_mp_add(mp_int *a, mp_int *b) /* magnitude addition */
  2326. {
  2327. mp_word w = 0;
  2328. mp_digit *pa, *pb;
  2329. mp_size ix, used = USED(b);
  2330. mp_err res;
  2331. /* Make sure a has enough precision for the output value */
  2332. if((used > USED(a)) && (res = s_mp_pad(a, used)) != MP_OKAY)
  2333. return res;
  2334. /*
  2335. Add up all digits up to the precision of b. If b had initially
  2336. the same precision as a, or greater, we took care of it by the
  2337. padding step above, so there is no problem. If b had initially
  2338. less precision, we'll have to make sure the carry out is duly
  2339. propagated upward among the higher-order digits of the sum.
  2340. */
  2341. pa = DIGITS(a);
  2342. pb = DIGITS(b);
  2343. for(ix = 0; ix < used; ++ix) {
  2344. w += *pa + *pb++;
  2345. *pa++ = ACCUM(w);
  2346. w = CARRYOUT(w);
  2347. }
  2348. /* If we run out of 'b' digits before we're actually done, make
  2349. sure the carries get propagated upward...
  2350. */
  2351. used = USED(a);
  2352. while(w && ix < used) {
  2353. w += *pa;
  2354. *pa++ = ACCUM(w);
  2355. w = CARRYOUT(w);
  2356. ++ix;
  2357. }
  2358. /* If there's an overall carry out, increase precision and include
  2359. it. We could have done this initially, but why touch the memory
  2360. allocator unless we're sure we have to?
  2361. */
  2362. if(w) {
  2363. if((res = s_mp_pad(a, used + 1)) != MP_OKAY)
  2364. return res;
  2365. DIGIT(a, ix) = w; /* pa may not be valid after s_mp_pad() call */
  2366. }
  2367. return MP_OKAY;
  2368. } /* end s_mp_add() */
  2369. /* }}} */
  2370. /* {{{ s_mp_sub(a, b) */
  2371. /* Compute a = |a| - |b|, assumes |a| >= |b| */
  2372. mp_err s_mp_sub(mp_int *a, mp_int *b) /* magnitude subtract */
  2373. {
  2374. mp_word w = 0;
  2375. mp_digit *pa, *pb;
  2376. mp_size ix, used = USED(b);
  2377. /*
  2378. Subtract and propagate borrow. Up to the precision of b, this
  2379. accounts for the digits of b; after that, we just make sure the
  2380. carries get to the right place. This saves having to pad b out to
  2381. the precision of a just to make the loops work right...
  2382. */
  2383. pa = DIGITS(a);
  2384. pb = DIGITS(b);
  2385. for(ix = 0; ix < used; ++ix) {
  2386. w = (RADIX + *pa) - w - *pb++;
  2387. *pa++ = ACCUM(w);
  2388. w = CARRYOUT(w) ? 0 : 1;
  2389. }
  2390. used = USED(a);
  2391. while(ix < used) {
  2392. w = RADIX + *pa - w;
  2393. *pa++ = ACCUM(w);
  2394. w = CARRYOUT(w) ? 0 : 1;
  2395. ++ix;
  2396. }
  2397. /* Clobber any leading zeroes we created */
  2398. s_mp_clamp(a);
  2399. /*
  2400. If there was a borrow out, then |b| > |a| in violation
  2401. of our input invariant. We've already done the work,
  2402. but we'll at least complain about it...
  2403. */
  2404. if(w)
  2405. return MP_RANGE;
  2406. else
  2407. return MP_OKAY;
  2408. } /* end s_mp_sub() */
  2409. /* }}} */
  2410. mp_err s_mp_reduce(mp_int *x, mp_int *m, mp_int *mu)
  2411. {
  2412. mp_int q;
  2413. mp_err res;
  2414. mp_size um = USED(m);
  2415. if((res = mp_init_copy(&q, x)) != MP_OKAY)
  2416. return res;
  2417. s_mp_rshd(&q, um - 1); /* q1 = x / b^(k-1) */
  2418. s_mp_mul(&q, mu); /* q2 = q1 * mu */
  2419. s_mp_rshd(&q, um + 1); /* q3 = q2 / b^(k+1) */
  2420. /* x = x mod b^(k+1), quick (no division) */
  2421. s_mp_mod_2d(x, (mp_digit)(DIGIT_BIT * (um + 1)));
  2422. /* q = q * m mod b^(k+1), quick (no division), uses the short multiplier */
  2423. #ifndef SHRT_MUL
  2424. s_mp_mul(&q, m);
  2425. s_mp_mod_2d(&q, (mp_digit)(DIGIT_BIT * (um + 1)));
  2426. #else
  2427. s_mp_mul_dig(&q, m, um + 1);
  2428. #endif
  2429. /* x = x - q */
  2430. if((res = mp_sub(x, &q, x)) != MP_OKAY)
  2431. goto CLEANUP;
  2432. /* If x < 0, add b^(k+1) to it */
  2433. if(mp_cmp_z(x) < 0) {
  2434. mp_set(&q, 1);
  2435. if((res = s_mp_lshd(&q, um + 1)) != MP_OKAY)
  2436. goto CLEANUP;
  2437. if((res = mp_add(x, &q, x)) != MP_OKAY)
  2438. goto CLEANUP;
  2439. }
  2440. /* Back off if it's too big */
  2441. while(mp_cmp(x, m) >= 0) {
  2442. if((res = s_mp_sub(x, m)) != MP_OKAY)
  2443. break;
  2444. }
  2445. CLEANUP:
  2446. mp_clear(&q);
  2447. return res;
  2448. } /* end s_mp_reduce() */
  2449. /* {{{ s_mp_mul(a, b) */
  2450. /* Compute a = |a| * |b| */
  2451. mp_err s_mp_mul(mp_int *a, mp_int *b)
  2452. {
  2453. mp_word w, k = 0;
  2454. mp_int tmp;
  2455. mp_err res;
  2456. mp_size ix, jx, ua = USED(a), ub = USED(b);
  2457. mp_digit *pa, *pb, *pt, *pbt;
  2458. if((res = mp_init_size(&tmp, ua + ub)) != MP_OKAY)
  2459. return res;
  2460. /* This has the effect of left-padding with zeroes... */
  2461. USED(&tmp) = ua + ub;
  2462. /* We're going to need the base value each iteration */
  2463. pbt = DIGITS(&tmp);
  2464. /* Outer loop: Digits of b */
  2465. pb = DIGITS(b);
  2466. for(ix = 0; ix < ub; ++ix, ++pb) {
  2467. if(*pb == 0)
  2468. continue;
  2469. /* Inner product: Digits of a */
  2470. pa = DIGITS(a);
  2471. for(jx = 0; jx < ua; ++jx, ++pa) {
  2472. pt = pbt + ix + jx;
  2473. w = *pb * *pa + k + *pt;
  2474. *pt = ACCUM(w);
  2475. k = CARRYOUT(w);
  2476. }
  2477. pbt[ix + jx] = k;
  2478. k = 0;
  2479. }
  2480. s_mp_clamp(&tmp);
  2481. s_mp_exch(&tmp, a);
  2482. mp_clear(&tmp);
  2483. return MP_OKAY;
  2484. } /* end s_mp_mul() */
  2485. /* }}} */
  2486. /* {{{ s_mp_kmul(a, b, out, len) */
  2487. #if 0
  2488. void s_mp_kmul(mp_digit *a, mp_digit *b, mp_digit *out, mp_size len)
  2489. {
  2490. mp_word w, k = 0;
  2491. mp_size ix, jx;
  2492. mp_digit *pa, *pt;
  2493. for(ix = 0; ix < len; ++ix, ++b) {
  2494. if(*b == 0)
  2495. continue;
  2496. pa = a;
  2497. for(jx = 0; jx < len; ++jx, ++pa) {
  2498. pt = out + ix + jx;
  2499. w = *b * *pa + k + *pt;
  2500. *pt = ACCUM(w);
  2501. k = CARRYOUT(w);
  2502. }
  2503. out[ix + jx] = k;
  2504. k = 0;
  2505. }
  2506. } /* end s_mp_kmul() */
  2507. #endif
  2508. /* }}} */
  2509. /* {{{ s_mp_sqr(a) */
  2510. /*
  2511. Computes the square of a, in place. This can be done more
  2512. efficiently than a general multiplication, because many of the
  2513. computation steps are redundant when squaring. The inner product
  2514. step is a bit more complicated, but we save a fair number of
  2515. iterations of the multiplication loop.
  2516. */
  2517. #if MP_SQUARE
  2518. mp_err s_mp_sqr(mp_int *a)
  2519. {
  2520. mp_word w, k = 0;
  2521. mp_int tmp;
  2522. mp_err res;
  2523. mp_size ix, jx, kx, used = USED(a);
  2524. mp_digit *pa1, *pa2, *pt, *pbt;
  2525. if((res = mp_init_size(&tmp, 2 * used)) != MP_OKAY)
  2526. return res;
  2527. /* Left-pad with zeroes */
  2528. USED(&tmp) = 2 * used;
  2529. /* We need the base value each time through the loop */
  2530. pbt = DIGITS(&tmp);
  2531. pa1 = DIGITS(a);
  2532. for(ix = 0; ix < used; ++ix, ++pa1) {
  2533. if(*pa1 == 0)
  2534. continue;
  2535. w = DIGIT(&tmp, ix + ix) + (*pa1 * *pa1);
  2536. pbt[ix + ix] = ACCUM(w);
  2537. k = CARRYOUT(w);
  2538. /*
  2539. The inner product is computed as:
  2540. (C, S) = t[i,j] + 2 a[i] a[j] + C
  2541. This can overflow what can be represented in an mp_word, and
  2542. since C arithmetic does not provide any way to check for
  2543. overflow, we have to check explicitly for overflow conditions
  2544. before they happen.
  2545. */
  2546. for(jx = ix + 1, pa2 = DIGITS(a) + jx; jx < used; ++jx, ++pa2) {
  2547. mp_word u = 0, v;
  2548. /* Store this in a temporary to avoid indirections later */
  2549. pt = pbt + ix + jx;
  2550. /* Compute the multiplicative step */
  2551. w = *pa1 * *pa2;
  2552. /* If w is more than half MP_WORD_MAX, the doubling will
  2553. overflow, and we need to record a carry out into the next
  2554. word */
  2555. u = (w >> (MP_WORD_BIT - 1)) & 1;
  2556. /* Double what we've got, overflow will be ignored as defined
  2557. for C arithmetic (we've already noted if it is to occur)
  2558. */
  2559. w *= 2;
  2560. /* Compute the additive step */
  2561. v = *pt + k;
  2562. /* If we do not already have an overflow carry, check to see
  2563. if the addition will cause one, and set the carry out if so
  2564. */
  2565. u |= ((MP_WORD_MAX - v) < w);
  2566. /* Add in the rest, again ignoring overflow */
  2567. w += v;
  2568. /* Set the i,j digit of the output */
  2569. *pt = ACCUM(w);
  2570. /* Save carry information for the next iteration of the loop.
  2571. This is why k must be an mp_word, instead of an mp_digit */
  2572. k = CARRYOUT(w) | (u << DIGIT_BIT);
  2573. } /* for(jx ...) */
  2574. /* Set the last digit in the cycle and reset the carry */
  2575. k = DIGIT(&tmp, ix + jx) + k;
  2576. pbt[ix + jx] = ACCUM(k);
  2577. k = CARRYOUT(k);
  2578. /* If we are carrying out, propagate the carry to the next digit
  2579. in the output. This may cascade, so we have to be somewhat
  2580. circumspect -- but we will have enough precision in the output
  2581. that we won't overflow
  2582. */
  2583. kx = 1;
  2584. while(k) {
  2585. k = pbt[ix + jx + kx] + 1;
  2586. pbt[ix + jx + kx] = ACCUM(k);
  2587. k = CARRYOUT(k);
  2588. ++kx;
  2589. }
  2590. } /* for(ix ...) */
  2591. s_mp_clamp(&tmp);
  2592. s_mp_exch(&tmp, a);
  2593. mp_clear(&tmp);
  2594. return MP_OKAY;
  2595. } /* end s_mp_sqr() */
  2596. #endif
  2597. /* }}} */
  2598. /* {{{ s_mp_div(a, b) */
  2599. /*
  2600. s_mp_div(a, b)
  2601. Compute a = a / b and b = a mod b. Assumes b > a.
  2602. */
  2603. mp_err s_mp_div(mp_int *a, mp_int *b)
  2604. {
  2605. mp_int quot, rem, t;
  2606. mp_word q;
  2607. mp_err res;
  2608. mp_digit d;
  2609. int ix;
  2610. if(mp_cmp_z(b) == 0)
  2611. return MP_RANGE;
  2612. /* Shortcut if b is power of two */
  2613. if((ix = s_mp_ispow2(b)) >= 0) {
  2614. mp_copy(a, b); /* need this for remainder */
  2615. s_mp_div_2d(a, (mp_digit)ix);
  2616. s_mp_mod_2d(b, (mp_digit)ix);
  2617. return MP_OKAY;
  2618. }
  2619. /* Allocate space to store the quotient */
  2620. if((res = mp_init_size(&quot, USED(a))) != MP_OKAY)
  2621. return res;
  2622. /* A working temporary for division */
  2623. if((res = mp_init_size(&t, USED(a))) != MP_OKAY)
  2624. goto T;
  2625. /* Allocate space for the remainder */
  2626. if((res = mp_init_size(&rem, USED(a))) != MP_OKAY)
  2627. goto REM;
  2628. /* Normalize to optimize guessing */
  2629. d = s_mp_norm(a, b);
  2630. /* Perform the division itself...woo! */
  2631. ix = USED(a) - 1;
  2632. while(ix >= 0) {
  2633. /* Find a partial substring of a which is at least b */
  2634. while(s_mp_cmp(&rem, b) < 0 && ix >= 0) {
  2635. if((res = s_mp_lshd(&rem, 1)) != MP_OKAY)
  2636. goto CLEANUP;
  2637. if((res = s_mp_lshd(&quot, 1)) != MP_OKAY)
  2638. goto CLEANUP;
  2639. DIGIT(&rem, 0) = DIGIT(a, ix);
  2640. s_mp_clamp(&rem);
  2641. --ix;
  2642. }
  2643. /* If we didn't find one, we're finished dividing */
  2644. if(s_mp_cmp(&rem, b) < 0)
  2645. break;
  2646. /* Compute a guess for the next quotient digit */
  2647. q = DIGIT(&rem, USED(&rem) - 1);
  2648. if(q <= DIGIT(b, USED(b) - 1) && USED(&rem) > 1)
  2649. q = (q << DIGIT_BIT) | DIGIT(&rem, USED(&rem) - 2);
  2650. q /= DIGIT(b, USED(b) - 1);
  2651. /* The guess can be as much as RADIX + 1 */
  2652. if(q >= RADIX)
  2653. q = RADIX - 1;
  2654. /* See what that multiplies out to */
  2655. mp_copy(b, &t);
  2656. if((res = s_mp_mul_d(&t, q)) != MP_OKAY)
  2657. goto CLEANUP;
  2658. /*
  2659. If it's too big, back it off. We should not have to do this
  2660. more than once, or, in rare cases, twice. Knuth describes a
  2661. method by which this could be reduced to a maximum of once, but
  2662. I didn't implement that here.
  2663. */
  2664. while(s_mp_cmp(&t, &rem) > 0) {
  2665. --q;
  2666. s_mp_sub(&t, b);
  2667. }
  2668. /* At this point, q should be the right next digit */
  2669. if((res = s_mp_sub(&rem, &t)) != MP_OKAY)
  2670. goto CLEANUP;
  2671. /*
  2672. Include the digit in the quotient. We allocated enough memory
  2673. for any quotient we could ever possibly get, so we should not
  2674. have to check for failures here
  2675. */
  2676. DIGIT(&quot, 0) = q;
  2677. }
  2678. /* Denormalize remainder */
  2679. if(d != 0)
  2680. s_mp_div_2d(&rem, d);
  2681. s_mp_clamp(&quot);
  2682. s_mp_clamp(&rem);
  2683. /* Copy quotient back to output */
  2684. s_mp_exch(&quot, a);
  2685. /* Copy remainder back to output */
  2686. s_mp_exch(&rem, b);
  2687. CLEANUP:
  2688. mp_clear(&rem);
  2689. REM:
  2690. mp_clear(&t);
  2691. T:
  2692. mp_clear(&quot);
  2693. return res;
  2694. } /* end s_mp_div() */
  2695. /* }}} */
  2696. /* {{{ s_mp_2expt(a, k) */
  2697. mp_err s_mp_2expt(mp_int *a, mp_digit k)
  2698. {
  2699. mp_err res;
  2700. mp_size dig, bit;
  2701. dig = k / DIGIT_BIT;
  2702. bit = k % DIGIT_BIT;
  2703. mp_zero(a);
  2704. if((res = s_mp_pad(a, dig + 1)) != MP_OKAY)
  2705. return res;
  2706. DIGIT(a, dig) |= (1 << bit);
  2707. return MP_OKAY;
  2708. } /* end s_mp_2expt() */
  2709. /* }}} */
  2710. /* }}} */
  2711. /* }}} */
  2712. /* {{{ Primitive comparisons */
  2713. /* {{{ s_mp_cmp(a, b) */
  2714. /* Compare |a| <=> |b|, return 0 if equal, <0 if a<b, >0 if a>b */
  2715. int s_mp_cmp(mp_int *a, mp_int *b)
  2716. {
  2717. mp_size ua = USED(a), ub = USED(b);
  2718. if(ua > ub)
  2719. return MP_GT;
  2720. else if(ua < ub)
  2721. return MP_LT;
  2722. else {
  2723. int ix = ua - 1;
  2724. mp_digit *ap = DIGITS(a) + ix, *bp = DIGITS(b) + ix;
  2725. while(ix >= 0) {
  2726. if(*ap > *bp)
  2727. return MP_GT;
  2728. else if(*ap < *bp)
  2729. return MP_LT;
  2730. --ap; --bp; --ix;
  2731. }
  2732. return MP_EQ;
  2733. }
  2734. } /* end s_mp_cmp() */
  2735. /* }}} */
  2736. /* {{{ s_mp_cmp_d(a, d) */
  2737. /* Compare |a| <=> d, return 0 if equal, <0 if a<d, >0 if a>d */
  2738. int s_mp_cmp_d(mp_int *a, mp_digit d)
  2739. {
  2740. mp_size ua = USED(a);
  2741. mp_digit *ap = DIGITS(a);
  2742. if(ua > 1)
  2743. return MP_GT;
  2744. if(*ap < d)
  2745. return MP_LT;
  2746. else if(*ap > d)
  2747. return MP_GT;
  2748. else
  2749. return MP_EQ;
  2750. } /* end s_mp_cmp_d() */
  2751. /* }}} */
  2752. /* {{{ s_mp_ispow2(v) */
  2753. /*
  2754. Returns -1 if the value is not a power of two; otherwise, it returns
  2755. k such that v = 2^k, i.e. lg(v).
  2756. */
  2757. int s_mp_ispow2(mp_int *v)
  2758. {
  2759. mp_digit d, *dp;
  2760. mp_size uv = USED(v);
  2761. int extra = 0, ix;
  2762. d = DIGIT(v, uv - 1); /* most significant digit of v */
  2763. while(d && ((d & 1) == 0)) {
  2764. d >>= 1;
  2765. ++extra;
  2766. }
  2767. if(d == 1) {
  2768. ix = uv - 2;
  2769. dp = DIGITS(v) + ix;
  2770. while(ix >= 0) {
  2771. if(*dp)
  2772. return -1; /* not a power of two */
  2773. --dp; --ix;
  2774. }
  2775. return ((uv - 1) * DIGIT_BIT) + extra;
  2776. }
  2777. return -1;
  2778. } /* end s_mp_ispow2() */
  2779. /* }}} */
  2780. /* {{{ s_mp_ispow2d(d) */
  2781. int s_mp_ispow2d(mp_digit d)
  2782. {
  2783. int pow = 0;
  2784. while((d & 1) == 0) {
  2785. ++pow; d >>= 1;
  2786. }
  2787. if(d == 1)
  2788. return pow;
  2789. return -1;
  2790. } /* end s_mp_ispow2d() */
  2791. /* }}} */
  2792. /* }}} */
  2793. /* {{{ Primitive I/O helpers */
  2794. /* {{{ s_mp_tovalue(ch, r) */
  2795. /*
  2796. Convert the given character to its digit value, in the given radix.
  2797. If the given character is not understood in the given radix, -1 is
  2798. returned. Otherwise the digit's numeric value is returned.
  2799. The results will be odd if you use a radix < 2 or > 62, you are
  2800. expected to know what you're up to.
  2801. */
  2802. int s_mp_tovalue(char ch, int r)
  2803. {
  2804. int val, xch;
  2805. if(r > 36)
  2806. xch = ch;
  2807. else
  2808. xch = toupper(ch);
  2809. if(isdigit(xch))
  2810. val = xch - '0';
  2811. else if(isupper(xch))
  2812. val = xch - 'A' + 10;
  2813. else if(islower(xch))
  2814. val = xch - 'a' + 36;
  2815. else if(xch == '+')
  2816. val = 62;
  2817. else if(xch == '/')
  2818. val = 63;
  2819. else
  2820. return -1;
  2821. if(val < 0 || val >= r)
  2822. return -1;
  2823. return val;
  2824. } /* end s_mp_tovalue() */
  2825. /* }}} */
  2826. /* {{{ s_mp_todigit(val, r, low) */
  2827. /*
  2828. Convert val to a radix-r digit, if possible. If val is out of range
  2829. for r, returns zero. Otherwise, returns an ASCII character denoting
  2830. the value in the given radix.
  2831. The results may be odd if you use a radix < 2 or > 64, you are
  2832. expected to know what you're doing.
  2833. */
  2834. char s_mp_todigit(int val, int r, int low)
  2835. {
  2836. char ch;
  2837. if(val < 0 || val >= r)
  2838. return 0;
  2839. ch = s_dmap_1[val];
  2840. if(r <= 36 && low)
  2841. ch = tolower(ch);
  2842. return ch;
  2843. } /* end s_mp_todigit() */
  2844. /* }}} */
  2845. /* {{{ s_mp_outlen(bits, radix) */
  2846. /*
  2847. Return an estimate for how long a string is needed to hold a radix
  2848. r representation of a number with 'bits' significant bits.
  2849. Does not include space for a sign or a NUL terminator.
  2850. */
  2851. int s_mp_outlen(int bits, int r)
  2852. {
  2853. return (int)((double)bits * LOG_V_2(r));
  2854. } /* end s_mp_outlen() */
  2855. /* }}} */
  2856. /* }}} */
  2857. /*------------------------------------------------------------------------*/
  2858. /* HERE THERE BE DRAGONS */
  2859. /* crc==4242132123, version==2, Sat Feb 02 06:43:52 2002 */
  2860. /* $Source: /cvs/libtom/libtommath/mtest/mpi.c,v $ */
  2861. /* $Revision: 1.2 $ */
  2862. /* $Date: 2005/05/05 14:38:47 $ */