diff --git a/bn.ind b/bn.ind index e5f7d4a..c099b52 100644 --- a/bn.ind +++ b/bn.ind @@ -1,82 +1,82 @@ \begin{theindex} - \item mp\_add, \hyperpage{29} - \item mp\_add\_d, \hyperpage{52} - \item mp\_and, \hyperpage{29} - \item mp\_clear, \hyperpage{11} - \item mp\_clear\_multi, \hyperpage{12} - \item mp\_cmp, \hyperpage{24} - \item mp\_cmp\_d, \hyperpage{25} + \item mp\_add, \hyperpage{31} + \item mp\_add\_d, \hyperpage{56} + \item mp\_and, \hyperpage{31} + \item mp\_clear, \hyperpage{12} + \item mp\_clear\_multi, \hyperpage{13} + \item mp\_cmp, \hyperpage{25} + \item mp\_cmp\_d, \hyperpage{26} \item mp\_cmp\_mag, \hyperpage{23} - \item mp\_div, \hyperpage{30} - \item mp\_div\_2, \hyperpage{26} - \item mp\_div\_2d, \hyperpage{28} - \item mp\_div\_d, \hyperpage{52} - \item mp\_dr\_reduce, \hyperpage{40} - \item mp\_dr\_setup, \hyperpage{40} - \item MP\_EQ, \hyperpage{22} - \item mp\_error\_to\_string, \hyperpage{10} - \item mp\_expt\_d, \hyperpage{43} - \item mp\_exptmod, \hyperpage{43} - \item mp\_exteuclid, \hyperpage{51} - \item mp\_gcd, \hyperpage{51} + \item mp\_div, \hyperpage{32} + \item mp\_div\_2, \hyperpage{28} + \item mp\_div\_2d, \hyperpage{30} + \item mp\_div\_d, \hyperpage{56} + \item mp\_dr\_reduce, \hyperpage{45} + \item mp\_dr\_setup, \hyperpage{45} + \item MP\_EQ, \hyperpage{23} + \item mp\_error\_to\_string, \hyperpage{9} + \item mp\_expt\_d, \hyperpage{47} + \item mp\_exptmod, \hyperpage{47} + \item mp\_exteuclid, \hyperpage{55} + \item mp\_gcd, \hyperpage{55} \item mp\_get\_int, \hyperpage{20} - \item mp\_grow, \hyperpage{16} - \item MP\_GT, \hyperpage{22} + \item mp\_grow, \hyperpage{17} + \item MP\_GT, \hyperpage{23} \item mp\_init, \hyperpage{11} - \item mp\_init\_copy, \hyperpage{13} - \item mp\_init\_multi, \hyperpage{12} + \item mp\_init\_copy, \hyperpage{14} + \item mp\_init\_multi, \hyperpage{13} \item mp\_init\_set, \hyperpage{21} \item mp\_init\_set\_int, \hyperpage{21} - \item mp\_init\_size, \hyperpage{14} + \item mp\_init\_size, \hyperpage{15} \item mp\_int, \hyperpage{10} - \item mp\_invmod, \hyperpage{52} - \item mp\_jacobi, \hyperpage{52} - \item mp\_lcm, \hyperpage{51} - \item mp\_lshd, \hyperpage{28} - \item MP\_LT, \hyperpage{22} + \item mp\_invmod, \hyperpage{56} + \item mp\_jacobi, \hyperpage{56} + \item mp\_lcm, \hyperpage{56} + \item mp\_lshd, \hyperpage{30} + \item MP\_LT, \hyperpage{23} \item MP\_MEM, \hyperpage{9} - \item mp\_mod, \hyperpage{35} - \item mp\_mod\_d, \hyperpage{52} - \item mp\_montgomery\_calc\_normalization, \hyperpage{38} - \item mp\_montgomery\_reduce, \hyperpage{37} - \item mp\_montgomery\_setup, \hyperpage{37} - \item mp\_mul, \hyperpage{31} - \item mp\_mul\_2, \hyperpage{26} - \item mp\_mul\_2d, \hyperpage{28} - \item mp\_mul\_d, \hyperpage{52} - \item mp\_n\_root, \hyperpage{44} - \item mp\_neg, \hyperpage{29} + \item mp\_mod, \hyperpage{39} + \item mp\_mod\_d, \hyperpage{56} + \item mp\_montgomery\_calc\_normalization, \hyperpage{42} + \item mp\_montgomery\_reduce, \hyperpage{42} + \item mp\_montgomery\_setup, \hyperpage{42} + \item mp\_mul, \hyperpage{33} + \item mp\_mul\_2, \hyperpage{28} + \item mp\_mul\_2d, \hyperpage{29} + \item mp\_mul\_d, \hyperpage{56} + \item mp\_n\_root, \hyperpage{48} + \item mp\_neg, \hyperpage{31, 32} \item MP\_NO, \hyperpage{9} \item MP\_OKAY, \hyperpage{9} - \item mp\_or, \hyperpage{29} - \item mp\_prime\_fermat, \hyperpage{45} - \item mp\_prime\_is\_divisible, \hyperpage{45} - \item mp\_prime\_is\_prime, \hyperpage{46} - \item mp\_prime\_miller\_rabin, \hyperpage{45} - \item mp\_prime\_next\_prime, \hyperpage{46} - \item mp\_prime\_rabin\_miller\_trials, \hyperpage{46} - \item mp\_prime\_random, \hyperpage{47} - \item mp\_prime\_random\_ex, \hyperpage{47} - \item mp\_radix\_size, \hyperpage{49} - \item mp\_read\_radix, \hyperpage{49} - \item mp\_read\_unsigned\_bin, \hyperpage{50} - \item mp\_reduce, \hyperpage{36} - \item mp\_reduce\_2k, \hyperpage{41} - \item mp\_reduce\_2k\_setup, \hyperpage{41} - \item mp\_reduce\_setup, \hyperpage{36} - \item mp\_rshd, \hyperpage{28} + \item mp\_or, \hyperpage{31} + \item mp\_prime\_fermat, \hyperpage{49} + \item mp\_prime\_is\_divisible, \hyperpage{49} + \item mp\_prime\_is\_prime, \hyperpage{51} + \item mp\_prime\_miller\_rabin, \hyperpage{50} + \item mp\_prime\_next\_prime, \hyperpage{51} + \item mp\_prime\_rabin\_miller\_trials, \hyperpage{50} + \item mp\_prime\_random, \hyperpage{51} + \item mp\_prime\_random\_ex, \hyperpage{52} + \item mp\_radix\_size, \hyperpage{53} + \item mp\_read\_radix, \hyperpage{53} + \item mp\_read\_unsigned\_bin, \hyperpage{54} + \item mp\_reduce, \hyperpage{40} + \item mp\_reduce\_2k, \hyperpage{46} + \item mp\_reduce\_2k\_setup, \hyperpage{46} + \item mp\_reduce\_setup, \hyperpage{40} + \item mp\_rshd, \hyperpage{30} \item mp\_set, \hyperpage{19} \item mp\_set\_int, \hyperpage{20} - \item mp\_shrink, \hyperpage{15} - \item mp\_sqr, \hyperpage{33} - \item mp\_sub, \hyperpage{29} - \item mp\_sub\_d, \hyperpage{52} - \item mp\_to\_unsigned\_bin, \hyperpage{50} - \item mp\_toradix, \hyperpage{49} - \item mp\_unsigned\_bin\_size, \hyperpage{50} + \item mp\_shrink, \hyperpage{16} + \item mp\_sqr, \hyperpage{35} + \item mp\_sub, \hyperpage{31} + \item mp\_sub\_d, \hyperpage{56} + \item mp\_to\_unsigned\_bin, \hyperpage{54} + \item mp\_toradix, \hyperpage{53} + \item mp\_unsigned\_bin\_size, \hyperpage{54} \item MP\_VAL, \hyperpage{9} - \item mp\_xor, \hyperpage{29} + \item mp\_xor, \hyperpage{31} \item MP\_YES, \hyperpage{9} \end{theindex} diff --git a/bn.pdf b/bn.pdf index 392b649..7e0a85f 100644 Binary files a/bn.pdf and b/bn.pdf differ diff --git a/bn.tex b/bn.tex index e8eb994..38ece04 100644 --- a/bn.tex +++ b/bn.tex @@ -1,4 +1,4 @@ -\documentclass[b5paper]{book} +\documentclass[synpaper]{book} \usepackage{hyperref} \usepackage{makeidx} \usepackage{amssymb} @@ -49,8 +49,8 @@ \begin{document} \frontmatter \pagestyle{empty} -\title{LibTomMath User Manual \\ v0.39} -\author{Tom St Denis \\ tomstdenis@iahu.ca} +\title{LibTomMath User Manual \\ v0.40} +\author{Tom St Denis \\ tomstdenis@gmail.com} \maketitle This text, the library and the accompanying textbook are all hereby placed in the public domain. This book has been formatted for B5 [176x250] paper using the \LaTeX{} {\em book} macro package. diff --git a/bn_fast_s_mp_mul_high_digs.c b/bn_fast_s_mp_mul_high_digs.c index 31a7bac..28f6e3c 100644 --- a/bn_fast_s_mp_mul_high_digs.c +++ b/bn_fast_s_mp_mul_high_digs.c @@ -78,7 +78,7 @@ int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) register mp_digit *tmpc; tmpc = c->dp + digs; - for (ix = digs; ix <= pa; ix++) { + for (ix = digs; ix < pa; ix++) { /* now extract the previous digit [below the carry] */ *tmpc++ = W[ix]; } diff --git a/bn_mp_montgomery_setup.c b/bn_mp_montgomery_setup.c index afa8b6e..0f6dc71 100644 --- a/bn_mp_montgomery_setup.c +++ b/bn_mp_montgomery_setup.c @@ -48,7 +48,7 @@ mp_montgomery_setup (mp_int * n, mp_digit * rho) #endif /* rho = -1/m mod b */ - *rho = (((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; + *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; return MP_OKAY; } diff --git a/booker.pl b/booker.pl index df8b30d..49f1889 100644 --- a/booker.pl +++ b/booker.pl @@ -82,7 +82,7 @@ while () { # scan till next end of comment, e.g. skip license while () { $text[$line++] = $_; - last if ($_ =~ /math\.libtomcrypt\.org/); + last if ($_ =~ /math\.libtomcrypt\.com/); } ; } diff --git a/changes.txt b/changes.txt index 9498d36..aaaf69f 100644 --- a/changes.txt +++ b/changes.txt @@ -1,3 +1,7 @@ +December 24th, 2006 +v0.40 -- Updated makefile to properly support LIBNAME + -- Fixed bug in fast_s_mp_mul_high_digs() which overflowed (line 83), thanks Valgrind! + April 4th, 2006 v0.39 -- Jim Wigginton pointed out my Montgomery examples in figures 6.4 and 6.6 were off by one, k should be 9 not 8 -- Bruce Guenter suggested I use --tag=CC for libtool builds where the compiler may think it's C++. diff --git a/etc/drprimes.txt b/etc/drprimes.txt index 2c887ea..7c97f67 100644 --- a/etc/drprimes.txt +++ b/etc/drprimes.txt @@ -1,6 +1,9 @@ -280-bit prime: -p == 1942668892225729070919461906823518906642406839052139521251812409738904285204940164839 +300-bit prime: +p == 2037035976334486086268445688409378161051468393665936250636140449354381298610415201576637819 -532-bit prime: -p == 14059105607947488696282932836518693308967803494693489478439861164411992439598399594747002144074658928593502845729752797260025831423419686528151609940203368691747 +540-bit prime: +p == 3599131035634557106248430806148785487095757694641533306480604458089470064537190296255232548883112685719936728506816716098566612844395439751206810991770626477344739 + +780-bit prime: +p == 6359114106063703798370219984742410466332205126109989319225557147754704702203399726411277962562135973685197744935448875852478791860694279747355800678568677946181447581781401213133886609947027230004277244697462656003655947791725966271167 diff --git a/makefile b/makefile index e08a888..9f69678 100644 --- a/makefile +++ b/makefile @@ -3,7 +3,7 @@ #Tom St Denis #version of library -VERSION=0.39 +VERSION=0.40 CFLAGS += -I./ -Wall -W -Wshadow -Wsign-compare @@ -40,12 +40,13 @@ else USER=$(INSTALL_USER) endif -default: libtommath.a - #default files to install ifndef LIBNAME LIBNAME=libtommath.a endif + +default: ${LIBNAME} + HEADERS=tommath.h tommath_class.h tommath_superclass.h #LIBPATH-The directory for libtommath to be installed to. diff --git a/makefile.shared b/makefile.shared index 8522d44..e230fb8 100644 --- a/makefile.shared +++ b/makefile.shared @@ -1,7 +1,7 @@ #Makefile for GCC # #Tom St Denis -VERSION=0:39 +VERSION=0:40 CC = libtool --mode=compile --tag=CC gcc diff --git a/poster.pdf b/poster.pdf index 1f705cf..c1f04c7 100644 Binary files a/poster.pdf and b/poster.pdf differ diff --git a/pre_gen/mpi.c b/pre_gen/mpi.c index 2274e9a..3763a05 100644 --- a/pre_gen/mpi.c +++ b/pre_gen/mpi.c @@ -569,7 +569,7 @@ int fast_s_mp_mul_high_digs (mp_int * a, mp_int * b, mp_int * c, int digs) register mp_digit *tmpc; tmpc = c->dp + digs; - for (ix = digs; ix <= pa; ix++) { + for (ix = digs; ix < pa; ix++) { /* now extract the previous digit [below the carry] */ *tmpc++ = W[ix]; } @@ -4900,7 +4900,7 @@ mp_montgomery_setup (mp_int * n, mp_digit * rho) #endif /* rho = -1/m mod b */ - *rho = (((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; + *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MASK; return MP_OKAY; } diff --git a/tommath.pdf b/tommath.pdf index c9571d8..a9edeb6 100644 Binary files a/tommath.pdf and b/tommath.pdf differ diff --git a/tommath.tex b/tommath.tex index c79a537..c9c5976 100644 --- a/tommath.tex +++ b/tommath.tex @@ -788,6 +788,33 @@ decrementally. \hspace{-5.1mm}{\bf File}: bn\_mp\_init.c \vspace{-3mm} \begin{alltt} +016 +017 /* init a new mp_int */ +018 int mp_init (mp_int * a) +019 \{ +020 int i; +021 +022 /* allocate memory required and clear it */ +023 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * MP_PREC); +024 if (a->dp == NULL) \{ +025 return MP_MEM; +026 \} +027 +028 /* set the digits to zero */ +029 for (i = 0; i < MP_PREC; i++) \{ +030 a->dp[i] = 0; +031 \} +032 +033 /* set the used to zero, allocated digits to the default precision +034 * and sign to positive */ +035 a->used = 0; +036 a->alloc = MP_PREC; +037 a->sign = MP_ZPOS; +038 +039 return MP_OKAY; +040 \} +041 #endif +042 \end{alltt} \end{small} @@ -795,7 +822,7 @@ One immediate observation of this initializtion function is that it does not ret is assumed that the caller has already allocated memory for the mp\_int structure, typically on the application stack. The call to mp\_init() is used only to initialize the members of the structure to a known default state. -Here we see (line 24) the memory allocation is performed first. This allows us to exit cleanly and quickly +Here we see (line 23) the memory allocation is performed first. This allows us to exit cleanly and quickly if there is an error. If the allocation fails the routine will return \textbf{MP\_MEM} to the caller to indicate there was a memory error. The function XMALLOC is what actually allocates the memory. Technically XMALLOC is not a function but a macro defined in ``tommath.h``. By default, XMALLOC will evaluate to malloc() which is the C library's built--in @@ -803,11 +830,11 @@ memory allocation routine. In order to assure the mp\_int is in a known state the digits must be set to zero. On most platforms this could have been accomplished by using calloc() instead of malloc(). However, to correctly initialize a integer type to a given value in a -portable fashion you have to actually assign the value. The for loop (line 30) performs this required +portable fashion you have to actually assign the value. The for loop (line 29) performs this required operation. After the memory has been successfully initialized the remainder of the members are initialized -(lines 34 through 35) to their respective default states. At this point the algorithm has succeeded and +(lines 33 through 34) to their respective default states. At this point the algorithm has succeeded and a success code is returned to the calling function. If this function returns \textbf{MP\_OKAY} it is safe to assume the mp\_int structure has been properly initialized and is safe to use with other functions within the library. @@ -852,21 +879,46 @@ with the exception of algorithms mp\_init, mp\_init\_copy, mp\_init\_size and mp \hspace{-5.1mm}{\bf File}: bn\_mp\_clear.c \vspace{-3mm} \begin{alltt} +016 +017 /* clear one (frees) */ +018 void +019 mp_clear (mp_int * a) +020 \{ +021 int i; +022 +023 /* only do anything if a hasn't been freed previously */ +024 if (a->dp != NULL) \{ +025 /* first zero the digits */ +026 for (i = 0; i < a->used; i++) \{ +027 a->dp[i] = 0; +028 \} +029 +030 /* free ram */ +031 XFREE(a->dp); +032 +033 /* reset members to make debugging easier */ +034 a->dp = NULL; +035 a->alloc = a->used = 0; +036 a->sign = MP_ZPOS; +037 \} +038 \} +039 #endif +040 \end{alltt} \end{small} -The algorithm only operates on the mp\_int if it hasn't been previously cleared. The if statement (line 25) +The algorithm only operates on the mp\_int if it hasn't been previously cleared. The if statement (line 24) checks to see if the \textbf{dp} member is not \textbf{NULL}. If the mp\_int is a valid mp\_int then \textbf{dp} cannot be \textbf{NULL} in which case the if statement will evaluate to true. -The digits of the mp\_int are cleared by the for loop (line 27) which assigns a zero to every digit. Similar to mp\_init() +The digits of the mp\_int are cleared by the for loop (line 26) which assigns a zero to every digit. Similar to mp\_init() the digits are assigned zero instead of using block memory operations (such as memset()) since this is more portable. The digits are deallocated off the heap via the XFREE macro. Similar to XMALLOC the XFREE macro actually evaluates to a standard C library function. In this case the free() function. Since free() only deallocates the memory the pointer -still has to be reset to \textbf{NULL} manually (line 35). +still has to be reset to \textbf{NULL} manually (line 34). -Now that the digits have been cleared and deallocated the other members are set to their final values (lines 36 and 37). +Now that the digits have been cleared and deallocated the other members are set to their final values (lines 35 and 36). \section{Maintenance Algorithms} @@ -921,6 +973,44 @@ assumed to contain undefined values they are initially set to zero. \hspace{-5.1mm}{\bf File}: bn\_mp\_grow.c \vspace{-3mm} \begin{alltt} +016 +017 /* grow as required */ +018 int mp_grow (mp_int * a, int size) +019 \{ +020 int i; +021 mp_digit *tmp; +022 +023 /* if the alloc size is smaller alloc more ram */ +024 if (a->alloc < size) \{ +025 /* ensure there are always at least MP_PREC digits extra on top */ +026 size += (MP_PREC * 2) - (size % MP_PREC); +027 +028 /* reallocate the array a->dp +029 * +030 * We store the return in a temporary variable +031 * in case the operation failed we don't want +032 * to overwrite the dp member of a. +033 */ +034 tmp = OPT_CAST(mp_digit) XREALLOC (a->dp, sizeof (mp_digit) * size); +035 if (tmp == NULL) \{ +036 /* reallocation failed but "a" is still valid [can be freed] */ +037 return MP_MEM; +038 \} +039 +040 /* reallocation succeeded so set a->dp */ +041 a->dp = tmp; +042 +043 /* zero excess digits */ +044 i = a->alloc; +045 a->alloc = size; +046 for (; i < a->alloc; i++) \{ +047 a->dp[i] = 0; +048 \} +049 \} +050 return MP_OKAY; +051 \} +052 #endif +053 \end{alltt} \end{small} @@ -929,7 +1019,7 @@ if the \textbf{alloc} member of the mp\_int is smaller than the requested digit the function skips the re-allocation part thus saving time. When a re-allocation is performed it is turned into an optimal request to save time in the future. The requested digit count is -padded upwards to 2nd multiple of \textbf{MP\_PREC} larger than \textbf{alloc} (line 25). The XREALLOC function is used +padded upwards to 2nd multiple of \textbf{MP\_PREC} larger than \textbf{alloc} (line 26). The XREALLOC function is used to re-allocate the memory. As per the other functions XREALLOC is actually a macro which evaluates to realloc by default. The realloc function leaves the base of the allocation intact which means the first \textbf{alloc} digits of the mp\_int are the same as before the re-allocation. All that is left is to clear the newly allocated digits and return. @@ -981,17 +1071,46 @@ correct no further memory re-allocations are required to work with the mp\_int. \hspace{-5.1mm}{\bf File}: bn\_mp\_init\_size.c \vspace{-3mm} \begin{alltt} +016 +017 /* init an mp_init for a given size */ +018 int mp_init_size (mp_int * a, int size) +019 \{ +020 int x; +021 +022 /* pad size so there are always extra digits */ +023 size += (MP_PREC * 2) - (size % MP_PREC); +024 +025 /* alloc mem */ +026 a->dp = OPT_CAST(mp_digit) XMALLOC (sizeof (mp_digit) * size); +027 if (a->dp == NULL) \{ +028 return MP_MEM; +029 \} +030 +031 /* set the members */ +032 a->used = 0; +033 a->alloc = size; +034 a->sign = MP_ZPOS; +035 +036 /* zero the digits */ +037 for (x = 0; x < size; x++) \{ +038 a->dp[x] = 0; +039 \} +040 +041 return MP_OKAY; +042 \} +043 #endif +044 \end{alltt} \end{small} -The number of digits $b$ requested is padded (line 24) by first augmenting it to the next multiple of +The number of digits $b$ requested is padded (line 23) by first augmenting it to the next multiple of \textbf{MP\_PREC} and then adding \textbf{MP\_PREC} to the result. If the memory can be successfully allocated the mp\_int is placed in a default state representing the integer zero. Otherwise, the error code \textbf{MP\_MEM} will be -returned (line 29). +returned (line 28). The digits are allocated and set to zero at the same time with the calloc() function (line @25,XCALLOC@). The \textbf{used} count is set to zero, the \textbf{alloc} count set to the padded digit count and the \textbf{sign} flag set -to \textbf{MP\_ZPOS} to achieve a default valid mp\_int state (lines 33, 34 and 35). If the function +to \textbf{MP\_ZPOS} to achieve a default valid mp\_int state (lines 32, 33 and 34). If the function returns succesfully then it is correct to assume that the mp\_int structure is in a valid state for the remainder of the functions to work with. @@ -1029,6 +1148,46 @@ initialization which allows for quick recovery from runtime errors. \hspace{-5.1mm}{\bf File}: bn\_mp\_init\_multi.c \vspace{-3mm} \begin{alltt} +016 #include +017 +018 int mp_init_multi(mp_int *mp, ...) +019 \{ +020 mp_err res = MP_OKAY; /* Assume ok until proven otherwise */ +021 int n = 0; /* Number of ok inits */ +022 mp_int* cur_arg = mp; +023 va_list args; +024 +025 va_start(args, mp); /* init args to next argument from caller */ +026 while (cur_arg != NULL) \{ +027 if (mp_init(cur_arg) != MP_OKAY) \{ +028 /* Oops - error! Back-track and mp_clear what we already +029 succeeded in init-ing, then return error. +030 */ +031 va_list clean_args; +032 +033 /* end the current list */ +034 va_end(args); +035 +036 /* now start cleaning up */ +037 cur_arg = mp; +038 va_start(clean_args, mp); +039 while (n--) \{ +040 mp_clear(cur_arg); +041 cur_arg = va_arg(clean_args, mp_int*); +042 \} +043 va_end(clean_args); +044 res = MP_MEM; +045 break; +046 \} +047 n++; +048 cur_arg = va_arg(args, mp_int*); +049 \} +050 va_end(args); +051 return res; /* Assumed ok, if error flagged above. */ +052 \} +053 +054 #endif +055 \end{alltt} \end{small} @@ -1038,8 +1197,8 @@ structures in an actual C array they are simply passed as arguments to the funct appended on the right. The function uses the ``stdarg.h'' \textit{va} functions to step portably through the arguments to the function. A count -$n$ of succesfully initialized mp\_int structures is maintained (line 48) such that if a failure does occur, -the algorithm can backtrack and free the previously initialized structures (lines 28 to 47). +$n$ of succesfully initialized mp\_int structures is maintained (line 47) such that if a failure does occur, +the algorithm can backtrack and free the previously initialized structures (lines 27 to 46). \subsection{Clamping Excess Digits} @@ -1090,13 +1249,38 @@ when all of the digits are zero to ensure that the mp\_int is valid at all times \hspace{-5.1mm}{\bf File}: bn\_mp\_clamp.c \vspace{-3mm} \begin{alltt} +016 +017 /* trim unused digits +018 * +019 * This is used to ensure that leading zero digits are +020 * trimed and the leading "used" digit will be non-zero +021 * Typically very fast. Also fixes the sign if there +022 * are no more leading digits +023 */ +024 void +025 mp_clamp (mp_int * a) +026 \{ +027 /* decrease used while the most significant digit is +028 * zero. +029 */ +030 while (a->used > 0 && a->dp[a->used - 1] == 0) \{ +031 --(a->used); +032 \} +033 +034 /* reset the sign flag if used == 0 */ +035 if (a->used == 0) \{ +036 a->sign = MP_ZPOS; +037 \} +038 \} +039 #endif +040 \end{alltt} \end{small} -Note on line 28 how to test for the \textbf{used} count is made on the left of the \&\& operator. In the C programming +Note on line 27 how to test for the \textbf{used} count is made on the left of the \&\& operator. In the C programming language the terms to \&\& are evaluated left to right with a boolean short-circuit if any condition fails. This is important since if the \textbf{used} is zero the test on the right would fetch below the array. That is obviously -undesirable. The parenthesis on line 31 is used to make sure the \textbf{used} count is decremented and not +undesirable. The parenthesis on line 30 is used to make sure the \textbf{used} count is decremented and not the pointer ``a''. \section*{Exercises} @@ -1179,21 +1363,70 @@ implement the pseudo-code. \hspace{-5.1mm}{\bf File}: bn\_mp\_copy.c \vspace{-3mm} \begin{alltt} +016 +017 /* copy, b = a */ +018 int +019 mp_copy (mp_int * a, mp_int * b) +020 \{ +021 int res, n; +022 +023 /* if dst == src do nothing */ +024 if (a == b) \{ +025 return MP_OKAY; +026 \} +027 +028 /* grow dest */ +029 if (b->alloc < a->used) \{ +030 if ((res = mp_grow (b, a->used)) != MP_OKAY) \{ +031 return res; +032 \} +033 \} +034 +035 /* zero b and copy the parameters over */ +036 \{ +037 register mp_digit *tmpa, *tmpb; +038 +039 /* pointer aliases */ +040 +041 /* source */ +042 tmpa = a->dp; +043 +044 /* destination */ +045 tmpb = b->dp; +046 +047 /* copy all the digits */ +048 for (n = 0; n < a->used; n++) \{ +049 *tmpb++ = *tmpa++; +050 \} +051 +052 /* clear high digits */ +053 for (; n < b->used; n++) \{ +054 *tmpb++ = 0; +055 \} +056 \} +057 +058 /* copy used count and sign */ +059 b->used = a->used; +060 b->sign = a->sign; +061 return MP_OKAY; +062 \} +063 #endif +064 \end{alltt} \end{small} Occasionally a dependent algorithm may copy an mp\_int effectively into itself such as when the input and output mp\_int structures passed to a function are one and the same. For this case it is optimal to return immediately without -copying digits (line 25). +copying digits (line 24). The mp\_int $b$ must have enough digits to accomodate the used digits of the mp\_int $a$. If $b.alloc$ is less than -$a.used$ the algorithm mp\_grow is used to augment the precision of $b$ (lines 30 to 33). In order to +$a.used$ the algorithm mp\_grow is used to augment the precision of $b$ (lines 29 to 33). In order to simplify the inner loop that copies the digits from $a$ to $b$, two aliases $tmpa$ and $tmpb$ point directly at the digits -of the mp\_ints $a$ and $b$ respectively. These aliases (lines 43 and 46) allow the compiler to access the digits without first dereferencing the +of the mp\_ints $a$ and $b$ respectively. These aliases (lines 42 and 45) allow the compiler to access the digits without first dereferencing the mp\_int pointers and then subsequently the pointer to the digits. -After the aliases are established the digits from $a$ are copied into $b$ (lines 49 to 51) and then the excess -digits of $b$ are set to zero (lines 54 to 56). Both ``for'' loops make use of the pointer aliases and in +After the aliases are established the digits from $a$ are copied into $b$ (lines 48 to 50) and then the excess +digits of $b$ are set to zero (lines 53 to 55). Both ``for'' loops make use of the pointer aliases and in fact the alias for $b$ is carried through into the second ``for'' loop to clear the excess digits. This optimization allows the alias to stay in a machine register fairly easy between the two loops. @@ -1281,6 +1514,19 @@ such this algorithm will perform two operations in one step. \hspace{-5.1mm}{\bf File}: bn\_mp\_init\_copy.c \vspace{-3mm} \begin{alltt} +016 +017 /* creates "a" then copies b into it */ +018 int mp_init_copy (mp_int * a, mp_int * b) +019 \{ +020 int res; +021 +022 if ((res = mp_init (a)) != MP_OKAY) \{ +023 return res; +024 \} +025 return mp_copy (b, a); +026 \} +027 #endif +028 \end{alltt} \end{small} @@ -1316,6 +1562,23 @@ This algorithm simply resets a mp\_int to the default state. \hspace{-5.1mm}{\bf File}: bn\_mp\_zero.c \vspace{-3mm} \begin{alltt} +016 +017 /* set to zero */ +018 void mp_zero (mp_int * a) +019 \{ +020 int n; +021 mp_digit *tmp; +022 +023 a->sign = MP_ZPOS; +024 a->used = 0; +025 +026 tmp = a->dp; +027 for (n = 0; n < a->alloc; n++) \{ +028 *tmp++ = 0; +029 \} +030 \} +031 #endif +032 \end{alltt} \end{small} @@ -1354,10 +1617,34 @@ logic to handle it. \hspace{-5.1mm}{\bf File}: bn\_mp\_abs.c \vspace{-3mm} \begin{alltt} +016 +017 /* b = |a| +018 * +019 * Simple function copies the input and fixes the sign to positive +020 */ +021 int +022 mp_abs (mp_int * a, mp_int * b) +023 \{ +024 int res; +025 +026 /* copy a to b */ +027 if (a != b) \{ +028 if ((res = mp_copy (a, b)) != MP_OKAY) \{ +029 return res; +030 \} +031 \} +032 +033 /* force the sign of b to positive */ +034 b->sign = MP_ZPOS; +035 +036 return MP_OKAY; +037 \} +038 #endif +039 \end{alltt} \end{small} -This fairly trivial algorithm first eliminates non--required duplications (line 28) and then sets the +This fairly trivial algorithm first eliminates non--required duplications (line 27) and then sets the \textbf{sign} flag to \textbf{MP\_ZPOS}. \subsection{Integer Negation} @@ -1395,10 +1682,31 @@ zero as negative. \hspace{-5.1mm}{\bf File}: bn\_mp\_neg.c \vspace{-3mm} \begin{alltt} +016 +017 /* b = -a */ +018 int mp_neg (mp_int * a, mp_int * b) +019 \{ +020 int res; +021 if (a != b) \{ +022 if ((res = mp_copy (a, b)) != MP_OKAY) \{ +023 return res; +024 \} +025 \} +026 +027 if (mp_iszero(b) != MP_YES) \{ +028 b->sign = (a->sign == MP_ZPOS) ? MP_NEG : MP_ZPOS; +029 \} else \{ +030 b->sign = MP_ZPOS; +031 \} +032 +033 return MP_OKAY; +034 \} +035 #endif +036 \end{alltt} \end{small} -Like mp\_abs() this function avoids non--required duplications (line 22) and then sets the sign. We +Like mp\_abs() this function avoids non--required duplications (line 21) and then sets the sign. We have to make sure that only non--zero values get a \textbf{sign} of \textbf{MP\_NEG}. If the mp\_int is zero than the \textbf{sign} is hard--coded to \textbf{MP\_ZPOS}. @@ -1433,12 +1741,22 @@ single digit is set (\textit{modulo $\beta$}) and the \textbf{used} count is adj \hspace{-5.1mm}{\bf File}: bn\_mp\_set.c \vspace{-3mm} \begin{alltt} +016 +017 /* set to a digit */ +018 void mp_set (mp_int * a, mp_digit b) +019 \{ +020 mp_zero (a); +021 a->dp[0] = b & MP_MASK; +022 a->used = (a->dp[0] != 0) ? 1 : 0; +023 \} +024 #endif +025 \end{alltt} \end{small} -First we zero (line 21) the mp\_int to make sure that the other members are initialized for a +First we zero (line 20) the mp\_int to make sure that the other members are initialized for a small positive constant. mp\_zero() ensures that the \textbf{sign} is positive and the \textbf{used} count -is zero. Next we set the digit and reduce it modulo $\beta$ (line 22). After this step we have to +is zero. Next we set the digit and reduce it modulo $\beta$ (line 21). After this step we have to check if the resulting digit is zero or not. If it is not then we set the \textbf{used} count to one, otherwise to zero. @@ -1485,13 +1803,42 @@ Excess zero digits are trimmed in steps 2.1 and 3 by using higher level algorith \hspace{-5.1mm}{\bf File}: bn\_mp\_set\_int.c \vspace{-3mm} \begin{alltt} +016 +017 /* set a 32-bit const */ +018 int mp_set_int (mp_int * a, unsigned long b) +019 \{ +020 int x, res; +021 +022 mp_zero (a); +023 +024 /* set four bits at a time */ +025 for (x = 0; x < 8; x++) \{ +026 /* shift the number up four bits */ +027 if ((res = mp_mul_2d (a, 4, a)) != MP_OKAY) \{ +028 return res; +029 \} +030 +031 /* OR in the top four bits of the source */ +032 a->dp[0] |= (b >> 28) & 15; +033 +034 /* shift the source up to the next four bits */ +035 b <<= 4; +036 +037 /* ensure that digits are not clamped off */ +038 a->used += 1; +039 \} +040 mp_clamp (a); +041 return MP_OKAY; +042 \} +043 #endif +044 \end{alltt} \end{small} This function sets four bits of the number at a time to handle all practical \textbf{DIGIT\_BIT} sizes. The weird -addition on line 39 ensures that the newly added in bits are added to the number of digits. While it may not -seem obvious as to why the digit counter does not grow exceedingly large it is because of the shift on line 28 -as well as the call to mp\_clamp() on line 41. Both functions will clamp excess leading digits which keeps +addition on line 38 ensures that the newly added in bits are added to the number of digits. While it may not +seem obvious as to why the digit counter does not grow exceedingly large it is because of the shift on line 27 +as well as the call to mp\_clamp() on line 40. Both functions will clamp excess leading digits which keeps the number of used digits low. \section{Comparisons} @@ -1552,10 +1899,46 @@ the zero'th digit. If after all of the digits have been compared, no difference \hspace{-5.1mm}{\bf File}: bn\_mp\_cmp\_mag.c \vspace{-3mm} \begin{alltt} +016 +017 /* compare maginitude of two ints (unsigned) */ +018 int mp_cmp_mag (mp_int * a, mp_int * b) +019 \{ +020 int n; +021 mp_digit *tmpa, *tmpb; +022 +023 /* compare based on # of non-zero digits */ +024 if (a->used > b->used) \{ +025 return MP_GT; +026 \} +027 +028 if (a->used < b->used) \{ +029 return MP_LT; +030 \} +031 +032 /* alias for a */ +033 tmpa = a->dp + (a->used - 1); +034 +035 /* alias for b */ +036 tmpb = b->dp + (a->used - 1); +037 +038 /* compare based on digits */ +039 for (n = 0; n < a->used; ++n, --tmpa, --tmpb) \{ +040 if (*tmpa > *tmpb) \{ +041 return MP_GT; +042 \} +043 +044 if (*tmpa < *tmpb) \{ +045 return MP_LT; +046 \} +047 \} +048 return MP_EQ; +049 \} +050 #endif +051 \end{alltt} \end{small} -The two if statements (lines 25 and 29) compare the number of digits in the two inputs. These two are +The two if statements (lines 24 and 28) compare the number of digits in the two inputs. These two are performed before all of the digits are compared since it is a very cheap test to perform and can potentially save considerable time. The implementation given is also not valid without those two statements. $b.alloc$ may be smaller than $a.used$, meaning that undefined values will be read from $b$ past the end of the array of digits. @@ -1595,12 +1978,36 @@ $\vert a \vert < \vert b \vert$. Step number four will compare the two when the \hspace{-5.1mm}{\bf File}: bn\_mp\_cmp.c \vspace{-3mm} \begin{alltt} +016 +017 /* compare two ints (signed)*/ +018 int +019 mp_cmp (mp_int * a, mp_int * b) +020 \{ +021 /* compare based on sign */ +022 if (a->sign != b->sign) \{ +023 if (a->sign == MP_NEG) \{ +024 return MP_LT; +025 \} else \{ +026 return MP_GT; +027 \} +028 \} +029 +030 /* compare digits */ +031 if (a->sign == MP_NEG) \{ +032 /* if negative compare opposite direction */ +033 return mp_cmp_mag(b, a); +034 \} else \{ +035 return mp_cmp_mag(a, b); +036 \} +037 \} +038 #endif +039 \end{alltt} \end{small} -The two if statements (lines 23 and 24) perform the initial sign comparison. If the signs are not the equal then which ever -has the positive sign is larger. The inputs are compared (line 32) based on magnitudes. If the signs were both -negative then the unsigned comparison is performed in the opposite direction (line 34). Otherwise, the signs are assumed to +The two if statements (lines 22 and 23) perform the initial sign comparison. If the signs are not the equal then which ever +has the positive sign is larger. The inputs are compared (line 31) based on magnitudes. If the signs were both +negative then the unsigned comparison is performed in the opposite direction (line 33). Otherwise, the signs are assumed to be both positive and a forward direction unsigned comparison is performed. \section*{Exercises} @@ -1724,24 +2131,114 @@ The final carry is stored in $c_{max}$ and digits above $max$ upto $oldused$ are \hspace{-5.1mm}{\bf File}: bn\_s\_mp\_add.c \vspace{-3mm} \begin{alltt} +016 +017 /* low level addition, based on HAC pp.594, Algorithm 14.7 */ +018 int +019 s_mp_add (mp_int * a, mp_int * b, mp_int * c) +020 \{ +021 mp_int *x; +022 int olduse, res, min, max; +023 +024 /* find sizes, we let |a| <= |b| which means we have to sort +025 * them. "x" will point to the input with the most digits +026 */ +027 if (a->used > b->used) \{ +028 min = b->used; +029 max = a->used; +030 x = a; +031 \} else \{ +032 min = a->used; +033 max = b->used; +034 x = b; +035 \} +036 +037 /* init result */ +038 if (c->alloc < max + 1) \{ +039 if ((res = mp_grow (c, max + 1)) != MP_OKAY) \{ +040 return res; +041 \} +042 \} +043 +044 /* get old used digit count and set new one */ +045 olduse = c->used; +046 c->used = max + 1; +047 +048 \{ +049 register mp_digit u, *tmpa, *tmpb, *tmpc; +050 register int i; +051 +052 /* alias for digit pointers */ +053 +054 /* first input */ +055 tmpa = a->dp; +056 +057 /* second input */ +058 tmpb = b->dp; +059 +060 /* destination */ +061 tmpc = c->dp; +062 +063 /* zero the carry */ +064 u = 0; +065 for (i = 0; i < min; i++) \{ +066 /* Compute the sum at one digit, T[i] = A[i] + B[i] + U */ +067 *tmpc = *tmpa++ + *tmpb++ + u; +068 +069 /* U = carry bit of T[i] */ +070 u = *tmpc >> ((mp_digit)DIGIT_BIT); +071 +072 /* take away carry bit from T[i] */ +073 *tmpc++ &= MP_MASK; +074 \} +075 +076 /* now copy higher words if any, that is in A+B +077 * if A or B has more digits add those in +078 */ +079 if (min != max) \{ +080 for (; i < max; i++) \{ +081 /* T[i] = X[i] + U */ +082 *tmpc = x->dp[i] + u; +083 +084 /* U = carry bit of T[i] */ +085 u = *tmpc >> ((mp_digit)DIGIT_BIT); +086 +087 /* take away carry bit from T[i] */ +088 *tmpc++ &= MP_MASK; +089 \} +090 \} +091 +092 /* add carry */ +093 *tmpc++ = u; +094 +095 /* clear digits above oldused */ +096 for (i = c->used; i < olduse; i++) \{ +097 *tmpc++ = 0; +098 \} +099 \} +100 +101 mp_clamp (c); +102 return MP_OKAY; +103 \} +104 #endif +105 \end{alltt} \end{small} -We first sort (lines 28 to 36) the inputs based on magnitude and determine the $min$ and $max$ variables. +We first sort (lines 27 to 35) the inputs based on magnitude and determine the $min$ and $max$ variables. Note that $x$ is a pointer to an mp\_int assigned to the largest input, in effect it is a local alias. Next we -grow the destination (38 to 42) ensure that it can accomodate the result of the addition. +grow the destination (37 to 42) ensure that it can accomodate the result of the addition. Similar to the implementation of mp\_copy this function uses the braced code and local aliases coding style. The three aliases that are on -lines 56, 59 and 62 represent the two inputs and destination variables respectively. These aliases are used to ensure the +lines 55, 58 and 61 represent the two inputs and destination variables respectively. These aliases are used to ensure the compiler does not have to dereference $a$, $b$ or $c$ (respectively) to access the digits of the respective mp\_int. -The initial carry $u$ will be cleared (line 65), note that $u$ is of type mp\_digit which ensures type -compatibility within the implementation. The initial addition (line 66 to 75) adds digits from +The initial carry $u$ will be cleared (line 64), note that $u$ is of type mp\_digit which ensures type +compatibility within the implementation. The initial addition (line 65 to 74) adds digits from both inputs until the smallest input runs out of digits. Similarly the conditional addition loop -(line 81 to 90) adds the remaining digits from the larger of the two inputs. The addition is finished -with the final carry being stored in $tmpc$ (line 94). Note the ``++'' operator within the same expression. -After line 94, $tmpc$ will point to the $c.used$'th digit of the mp\_int $c$. This is useful -for the next loop (line 97 to 99) which set any old upper digits to zero. +(line 80 to 90) adds the remaining digits from the larger of the two inputs. The addition is finished +with the final carry being stored in $tmpc$ (line 93). Note the ``++'' operator within the same expression. +After line 93, $tmpc$ will point to the $c.used$'th digit of the mp\_int $c$. This is useful +for the next loop (line 96 to 99) which set any old upper digits to zero. \subsection{Low Level Subtraction} The low level unsigned subtraction algorithm is very similar to the low level unsigned addition algorithm. The principle difference is that the @@ -1825,25 +2322,96 @@ If $b$ has a smaller magnitude than $a$ then step 9 will force the carry and cop \hspace{-5.1mm}{\bf File}: bn\_s\_mp\_sub.c \vspace{-3mm} \begin{alltt} +016 +017 /* low level subtraction (assumes |a| > |b|), HAC pp.595 Algorithm 14.9 */ +018 int +019 s_mp_sub (mp_int * a, mp_int * b, mp_int * c) +020 \{ +021 int olduse, res, min, max; +022 +023 /* find sizes */ +024 min = b->used; +025 max = a->used; +026 +027 /* init result */ +028 if (c->alloc < max) \{ +029 if ((res = mp_grow (c, max)) != MP_OKAY) \{ +030 return res; +031 \} +032 \} +033 olduse = c->used; +034 c->used = max; +035 +036 \{ +037 register mp_digit u, *tmpa, *tmpb, *tmpc; +038 register int i; +039 +040 /* alias for digit pointers */ +041 tmpa = a->dp; +042 tmpb = b->dp; +043 tmpc = c->dp; +044 +045 /* set carry to zero */ +046 u = 0; +047 for (i = 0; i < min; i++) \{ +048 /* T[i] = A[i] - B[i] - U */ +049 *tmpc = *tmpa++ - *tmpb++ - u; +050 +051 /* U = carry bit of T[i] +052 * Note this saves performing an AND operation since +053 * if a carry does occur it will propagate all the way to the +054 * MSB. As a result a single shift is enough to get the carry +055 */ +056 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1)); +057 +058 /* Clear carry from T[i] */ +059 *tmpc++ &= MP_MASK; +060 \} +061 +062 /* now copy higher words if any, e.g. if A has more digits than B */ +063 for (; i < max; i++) \{ +064 /* T[i] = A[i] - U */ +065 *tmpc = *tmpa++ - u; +066 +067 /* U = carry bit of T[i] */ +068 u = *tmpc >> ((mp_digit)(CHAR_BIT * sizeof (mp_digit) - 1)); +069 +070 /* Clear carry from T[i] */ +071 *tmpc++ &= MP_MASK; +072 \} +073 +074 /* clear digits above used (since we may not have grown result above) */ + +075 for (i = c->used; i < olduse; i++) \{ +076 *tmpc++ = 0; +077 \} +078 \} +079 +080 mp_clamp (c); +081 return MP_OKAY; +082 \} +083 +084 #endif +085 \end{alltt} \end{small} Like low level addition we ``sort'' the inputs. Except in this case the sorting is hardcoded -(lines 25 and 26). In reality the $min$ and $max$ variables are only aliases and are only +(lines 24 and 25). In reality the $min$ and $max$ variables are only aliases and are only used to make the source code easier to read. Again the pointer alias optimization is used within this algorithm. The aliases $tmpa$, $tmpb$ and $tmpc$ are initialized -(lines 42, 43 and 44) for $a$, $b$ and $c$ respectively. +(lines 41, 42 and 43) for $a$, $b$ and $c$ respectively. -The first subtraction loop (lines 47 through 61) subtract digits from both inputs until the smaller of +The first subtraction loop (lines 46 through 60) subtract digits from both inputs until the smaller of the two inputs has been exhausted. As remarked earlier there is an implementation reason for using the ``awkward'' -method of extracting the carry (line 57). The traditional method for extracting the carry would be to shift +method of extracting the carry (line 56). The traditional method for extracting the carry would be to shift by $lg(\beta)$ positions and logically AND the least significant bit. The AND operation is required because all of the bits above the $\lg(\beta)$'th bit will be set to one after a carry occurs from subtraction. This carry extraction requires two relatively cheap operations to extract the carry. The other method is to simply shift the most significant bit to the least significant bit thus extracting the carry with a single cheap operation. This optimization only works on twos compliment machines which is a safe assumption to make. -If $a$ has a larger magnitude than $b$ an additional loop (lines 64 through 73) is required to propagate +If $a$ has a larger magnitude than $b$ an additional loop (lines 63 through 72) is required to propagate the carry through $a$ and copy the result to $c$. \subsection{High Level Addition} @@ -1927,6 +2495,40 @@ within algorithm s\_mp\_add will force $-0$ to become $0$. \hspace{-5.1mm}{\bf File}: bn\_mp\_add.c \vspace{-3mm} \begin{alltt} +016 +017 /* high level addition (handles signs) */ +018 int mp_add (mp_int * a, mp_int * b, mp_int * c) +019 \{ +020 int sa, sb, res; +021 +022 /* get sign of both inputs */ +023 sa = a->sign; +024 sb = b->sign; +025 +026 /* handle two cases, not four */ +027 if (sa == sb) \{ +028 /* both positive or both negative */ +029 /* add their magnitudes, copy the sign */ +030 c->sign = sa; +031 res = s_mp_add (a, b, c); +032 \} else \{ +033 /* one positive, the other negative */ +034 /* subtract the one with the greater magnitude from */ +035 /* the one of the lesser magnitude. The result gets */ +036 /* the sign of the one with the greater magnitude. */ +037 if (mp_cmp_mag (a, b) == MP_LT) \{ +038 c->sign = sb; +039 res = s_mp_sub (b, a, c); +040 \} else \{ +041 c->sign = sa; +042 res = s_mp_sub (a, b, c); +043 \} +044 \} +045 return res; +046 \} +047 +048 #endif +049 \end{alltt} \end{small} @@ -2000,11 +2602,51 @@ algorithm from producing $-a - -a = -0$ as a result. \hspace{-5.1mm}{\bf File}: bn\_mp\_sub.c \vspace{-3mm} \begin{alltt} +016 +017 /* high level subtraction (handles signs) */ +018 int +019 mp_sub (mp_int * a, mp_int * b, mp_int * c) +020 \{ +021 int sa, sb, res; +022 +023 sa = a->sign; +024 sb = b->sign; +025 +026 if (sa != sb) \{ +027 /* subtract a negative from a positive, OR */ +028 /* subtract a positive from a negative. */ +029 /* In either case, ADD their magnitudes, */ +030 /* and use the sign of the first number. */ +031 c->sign = sa; +032 res = s_mp_add (a, b, c); +033 \} else \{ +034 /* subtract a positive from a positive, OR */ +035 /* subtract a negative from a negative. */ +036 /* First, take the difference between their */ +037 /* magnitudes, then... */ +038 if (mp_cmp_mag (a, b) != MP_LT) \{ +039 /* Copy the sign from the first */ +040 c->sign = sa; +041 /* The first has a larger or equal magnitude */ +042 res = s_mp_sub (a, b, c); +043 \} else \{ +044 /* The result has the *opposite* sign from */ +045 /* the first number. */ +046 c->sign = (sa == MP_ZPOS) ? MP_NEG : MP_ZPOS; +047 /* The second has a larger magnitude */ +048 res = s_mp_sub (b, a, c); +049 \} +050 \} +051 return res; +052 \} +053 +054 #endif +055 \end{alltt} \end{small} Much like the implementation of algorithm mp\_add the variable $res$ is used to catch the return code of the unsigned addition or subtraction operations -and forward it to the end of the function. On line 39 the ``not equal to'' \textbf{MP\_LT} expression is used to emulate a +and forward it to the end of the function. On line 38 the ``not equal to'' \textbf{MP\_LT} expression is used to emulate a ``greater than or equal to'' comparison. \section{Bit and Digit Shifting} @@ -2072,11 +2714,74 @@ Step 8 clears any leading digits of $b$ in case it originally had a larger magni \hspace{-5.1mm}{\bf File}: bn\_mp\_mul\_2.c \vspace{-3mm} \begin{alltt} +016 +017 /* b = a*2 */ +018 int mp_mul_2(mp_int * a, mp_int * b) +019 \{ +020 int x, res, oldused; +021 +022 /* grow to accomodate result */ +023 if (b->alloc < a->used + 1) \{ +024 if ((res = mp_grow (b, a->used + 1)) != MP_OKAY) \{ +025 return res; +026 \} +027 \} +028 +029 oldused = b->used; +030 b->used = a->used; +031 +032 \{ +033 register mp_digit r, rr, *tmpa, *tmpb; +034 +035 /* alias for source */ +036 tmpa = a->dp; +037 +038 /* alias for dest */ +039 tmpb = b->dp; +040 +041 /* carry */ +042 r = 0; +043 for (x = 0; x < a->used; x++) \{ +044 +045 /* get what will be the *next* carry bit from the +046 * MSB of the current digit +047 */ +048 rr = *tmpa >> ((mp_digit)(DIGIT_BIT - 1)); +049 +050 /* now shift up this digit, add in the carry [from the previous] */ +051 *tmpb++ = ((*tmpa++ << ((mp_digit)1)) | r) & MP_MASK; +052 +053 /* copy the carry that would be from the source +054 * digit into the next iteration +055 */ +056 r = rr; +057 \} +058 +059 /* new leading digit? */ +060 if (r != 0) \{ +061 /* add a MSB which is always 1 at this point */ +062 *tmpb = 1; +063 ++(b->used); +064 \} +065 +066 /* now zero any excess digits on the destination +067 * that we didn't write to +068 */ +069 tmpb = b->dp + b->used; +070 for (x = b->used; x < oldused; x++) \{ +071 *tmpb++ = 0; +072 \} +073 \} +074 b->sign = a->sign; +075 return MP_OKAY; +076 \} +077 #endif +078 \end{alltt} \end{small} This implementation is essentially an optimized implementation of s\_mp\_add for the case of doubling an input. The only noteworthy difference -is the use of the logical shift operator on line 52 to perform a single precision doubling. +is the use of the logical shift operator on line 51 to perform a single precision doubling. \subsection{Division by Two} A division by two can just as easily be accomplished with a logical shift right as multiplication by two can be with a logical shift left. @@ -2124,6 +2829,55 @@ least significant bit not the most significant bit. \hspace{-5.1mm}{\bf File}: bn\_mp\_div\_2.c \vspace{-3mm} \begin{alltt} +016 +017 /* b = a/2 */ +018 int mp_div_2(mp_int * a, mp_int * b) +019 \{ +020 int x, res, oldused; +021 +022 /* copy */ +023 if (b->alloc < a->used) \{ +024 if ((res = mp_grow (b, a->used)) != MP_OKAY) \{ +025 return res; +026 \} +027 \} +028 +029 oldused = b->used; +030 b->used = a->used; +031 \{ +032 register mp_digit r, rr, *tmpa, *tmpb; +033 +034 /* source alias */ +035 tmpa = a->dp + b->used - 1; +036 +037 /* dest alias */ +038 tmpb = b->dp + b->used - 1; +039 +040 /* carry */ +041 r = 0; +042 for (x = b->used - 1; x >= 0; x--) \{ +043 /* get the carry for the next iteration */ +044 rr = *tmpa & 1; +045 +046 /* shift the current digit, add in carry and store */ +047 *tmpb-- = (*tmpa-- >> 1) | (r << (DIGIT_BIT - 1)); +048 +049 /* forward carry to next iteration */ +050 r = rr; +051 \} +052 +053 /* zero excess digits */ +054 tmpb = b->dp + b->used; +055 for (x = b->used; x < oldused; x++) \{ +056 *tmpb++ = 0; +057 \} +058 \} +059 b->sign = a->sign; +060 mp_clamp (b); +061 return MP_OKAY; +062 \} +063 #endif +064 \end{alltt} \end{small} @@ -2197,13 +2951,61 @@ step 8 sets the lower $b$ digits to zero. \hspace{-5.1mm}{\bf File}: bn\_mp\_lshd.c \vspace{-3mm} \begin{alltt} +016 +017 /* shift left a certain amount of digits */ +018 int mp_lshd (mp_int * a, int b) +019 \{ +020 int x, res; +021 +022 /* if its less than zero return */ +023 if (b <= 0) \{ +024 return MP_OKAY; +025 \} +026 +027 /* grow to fit the new digits */ +028 if (a->alloc < a->used + b) \{ +029 if ((res = mp_grow (a, a->used + b)) != MP_OKAY) \{ +030 return res; +031 \} +032 \} +033 +034 \{ +035 register mp_digit *top, *bottom; +036 +037 /* increment the used by the shift amount then copy upwards */ +038 a->used += b; +039 +040 /* top */ +041 top = a->dp + a->used - 1; +042 +043 /* base */ +044 bottom = a->dp + a->used - 1 - b; +045 +046 /* much like mp_rshd this is implemented using a sliding window +047 * except the window goes the otherway around. Copying from +048 * the bottom to the top. see bn_mp_rshd.c for more info. +049 */ +050 for (x = a->used - 1; x >= b; x--) \{ +051 *top-- = *bottom--; +052 \} +053 +054 /* zero the lower digits */ +055 top = a->dp; +056 for (x = 0; x < b; x++) \{ +057 *top++ = 0; +058 \} +059 \} +060 return MP_OKAY; +061 \} +062 #endif +063 \end{alltt} \end{small} -The if statement (line 24) ensures that the $b$ variable is greater than zero since we do not interpret negative +The if statement (line 23) ensures that the $b$ variable is greater than zero since we do not interpret negative shift counts properly. The \textbf{used} count is incremented by $b$ before the copy loop begins. This elminates -the need for an additional variable in the for loop. The variable $top$ (line 42) is an alias -for the leading digit while $bottom$ (line 45) is an alias for the trailing edge. The aliases form a +the need for an additional variable in the for loop. The variable $top$ (line 41) is an alias +for the leading digit while $bottom$ (line 44) is an alias for the trailing edge. The aliases form a window of exactly $b$ digits over the input. \subsection{Division by $x$} @@ -2256,11 +3058,64 @@ Once the window copy is complete the upper digits must be zeroed and the \textbf \hspace{-5.1mm}{\bf File}: bn\_mp\_rshd.c \vspace{-3mm} \begin{alltt} +016 +017 /* shift right a certain amount of digits */ +018 void mp_rshd (mp_int * a, int b) +019 \{ +020 int x; +021 +022 /* if b <= 0 then ignore it */ +023 if (b <= 0) \{ +024 return; +025 \} +026 +027 /* if b > used then simply zero it and return */ +028 if (a->used <= b) \{ +029 mp_zero (a); +030 return; +031 \} +032 +033 \{ +034 register mp_digit *bottom, *top; +035 +036 /* shift the digits down */ +037 +038 /* bottom */ +039 bottom = a->dp; +040 +041 /* top [offset into digits] */ +042 top = a->dp + b; +043 +044 /* this is implemented as a sliding window where +045 * the window is b-digits long and digits from +046 * the top of the window are copied to the bottom +047 * +048 * e.g. +049 +050 b-2 | b-1 | b0 | b1 | b2 | ... | bb | ----> +051 /\symbol{92} | ----> +052 \symbol{92}-------------------/ ----> +053 */ +054 for (x = 0; x < (a->used - b); x++) \{ +055 *bottom++ = *top++; +056 \} +057 +058 /* zero the top digits */ +059 for (; x < a->used; x++) \{ +060 *bottom++ = 0; +061 \} +062 \} +063 +064 /* remove excess digits */ +065 a->used -= b; +066 \} +067 #endif +068 \end{alltt} \end{small} The only noteworthy element of this routine is the lack of a return type since it cannot fail. Like mp\_lshd() we -form a sliding window except we copy in the other direction. After the window (line 60) we then zero +form a sliding window except we copy in the other direction. After the window (line 59) we then zero the upper digits of the input to make sure the result is correct. \section{Powers of Two} @@ -2324,16 +3179,82 @@ complete. It is possible to optimize this algorithm down to a $O(n)$ algorithm \hspace{-5.1mm}{\bf File}: bn\_mp\_mul\_2d.c \vspace{-3mm} \begin{alltt} +016 +017 /* shift left by a certain bit count */ +018 int mp_mul_2d (mp_int * a, int b, mp_int * c) +019 \{ +020 mp_digit d; +021 int res; +022 +023 /* copy */ +024 if (a != c) \{ +025 if ((res = mp_copy (a, c)) != MP_OKAY) \{ +026 return res; +027 \} +028 \} +029 +030 if (c->alloc < (int)(c->used + b/DIGIT_BIT + 1)) \{ +031 if ((res = mp_grow (c, c->used + b / DIGIT_BIT + 1)) != MP_OKAY) \{ +032 return res; +033 \} +034 \} +035 +036 /* shift by as many digits in the bit count */ +037 if (b >= (int)DIGIT_BIT) \{ +038 if ((res = mp_lshd (c, b / DIGIT_BIT)) != MP_OKAY) \{ +039 return res; +040 \} +041 \} +042 +043 /* shift any bit count < DIGIT_BIT */ +044 d = (mp_digit) (b % DIGIT_BIT); +045 if (d != 0) \{ +046 register mp_digit *tmpc, shift, mask, r, rr; +047 register int x; +048 +049 /* bitmask for carries */ +050 mask = (((mp_digit)1) << d) - 1; +051 +052 /* shift for msbs */ +053 shift = DIGIT_BIT - d; +054 +055 /* alias */ +056 tmpc = c->dp; +057 +058 /* carry */ +059 r = 0; +060 for (x = 0; x < c->used; x++) \{ +061 /* get the higher bits of the current word */ +062 rr = (*tmpc >> shift) & mask; +063 +064 /* shift the current word and OR in the carry */ +065 *tmpc = ((*tmpc << d) | r) & MP_MASK; +066 ++tmpc; +067 +068 /* set the carry to the carry bits of the current word */ +069 r = rr; +070 \} +071 +072 /* set final carry */ +073 if (r != 0) \{ +074 c->dp[(c->used)++] = r; +075 \} +076 \} +077 mp_clamp (c); +078 return MP_OKAY; +079 \} +080 #endif +081 \end{alltt} \end{small} -The shifting is performed in--place which means the first step (line 25) is to copy the input to the +The shifting is performed in--place which means the first step (line 24) is to copy the input to the destination. We avoid calling mp\_copy() by making sure the mp\_ints are different. The destination then -has to be grown (line 32) to accomodate the result. +has to be grown (line 31) to accomodate the result. If the shift count $b$ is larger than $lg(\beta)$ then a call to mp\_lshd() is used to handle all of the multiples of $lg(\beta)$. Leaving only a remaining shift of $lg(\beta) - 1$ or fewer bits left. Inside the actual shift -loop (lines 46 to 76) we make use of pre--computed values $shift$ and $mask$. These are used to +loop (lines 45 to 76) we make use of pre--computed values $shift$ and $mask$. These are used to extract the carry bit(s) to pass into the next iteration of the loop. The $r$ and $rr$ variables form a chain between consecutive iterations to propagate the carry. @@ -2381,6 +3302,86 @@ by using algorithm mp\_mod\_2d. \hspace{-5.1mm}{\bf File}: bn\_mp\_div\_2d.c \vspace{-3mm} \begin{alltt} +016 +017 /* shift right by a certain bit count (store quotient in c, optional remaind + er in d) */ +018 int mp_div_2d (mp_int * a, int b, mp_int * c, mp_int * d) +019 \{ +020 mp_digit D, r, rr; +021 int x, res; +022 mp_int t; +023 +024 +025 /* if the shift count is <= 0 then we do no work */ +026 if (b <= 0) \{ +027 res = mp_copy (a, c); +028 if (d != NULL) \{ +029 mp_zero (d); +030 \} +031 return res; +032 \} +033 +034 if ((res = mp_init (&t)) != MP_OKAY) \{ +035 return res; +036 \} +037 +038 /* get the remainder */ +039 if (d != NULL) \{ +040 if ((res = mp_mod_2d (a, b, &t)) != MP_OKAY) \{ +041 mp_clear (&t); +042 return res; +043 \} +044 \} +045 +046 /* copy */ +047 if ((res = mp_copy (a, c)) != MP_OKAY) \{ +048 mp_clear (&t); +049 return res; +050 \} +051 +052 /* shift by as many digits in the bit count */ +053 if (b >= (int)DIGIT_BIT) \{ +054 mp_rshd (c, b / DIGIT_BIT); +055 \} +056 +057 /* shift any bit count < DIGIT_BIT */ +058 D = (mp_digit) (b % DIGIT_BIT); +059 if (D != 0) \{ +060 register mp_digit *tmpc, mask, shift; +061 +062 /* mask */ +063 mask = (((mp_digit)1) << D) - 1; +064 +065 /* shift for lsb */ +066 shift = DIGIT_BIT - D; +067 +068 /* alias */ +069 tmpc = c->dp + (c->used - 1); +070 +071 /* carry */ +072 r = 0; +073 for (x = c->used - 1; x >= 0; x--) \{ +074 /* get the lower bits of this word in a temp */ +075 rr = *tmpc & mask; +076 +077 /* shift the current word and mix in the carry bits from the previous + word */ +078 *tmpc = (*tmpc >> D) | (r << shift); +079 --tmpc; +080 +081 /* set the carry to the carry bits of the current word found above */ +082 r = rr; +083 \} +084 \} +085 mp_clamp (c); +086 if (d != NULL) \{ +087 mp_exch (&t, d); +088 \} +089 mp_clear (&t); +090 return MP_OKAY; +091 \} +092 #endif +093 \end{alltt} \end{small} @@ -2435,6 +3436,44 @@ is copied to $b$, leading digits are removed and the remaining leading digit is \hspace{-5.1mm}{\bf File}: bn\_mp\_mod\_2d.c \vspace{-3mm} \begin{alltt} +016 +017 /* calc a value mod 2**b */ +018 int +019 mp_mod_2d (mp_int * a, int b, mp_int * c) +020 \{ +021 int x, res; +022 +023 /* if b is <= 0 then zero the int */ +024 if (b <= 0) \{ +025 mp_zero (c); +026 return MP_OKAY; +027 \} +028 +029 /* if the modulus is larger than the value than return */ +030 if (b >= (int) (a->used * DIGIT_BIT)) \{ +031 res = mp_copy (a, c); +032 return res; +033 \} +034 +035 /* copy */ +036 if ((res = mp_copy (a, c)) != MP_OKAY) \{ +037 return res; +038 \} +039 +040 /* zero digits above the last digit of the modulus */ +041 for (x = (b / DIGIT_BIT) + ((b % DIGIT_BIT) == 0 ? 0 : 1); x < c->used; x+ + +) \{ +042 c->dp[x] = 0; +043 \} +044 /* clear the digit that is not completely outside/inside the modulus */ +045 c->dp[b / DIGIT_BIT] &= +046 (mp_digit) ((((mp_digit) 1) << (((mp_digit) b) % DIGIT_BIT)) - ((mp_digi + t) 1)); +047 mp_clamp (c); +048 return MP_OKAY; +049 \} +050 #endif +051 \end{alltt} \end{small} @@ -2443,8 +3482,8 @@ than the input we just mp\_copy() the input and return right away. After this p perform some work to produce the remainder. Recalling that reducing modulo $2^k$ and a binary ``and'' with $2^k - 1$ are numerically equivalent we can quickly reduce -the number. First we zero any digits above the last digit in $2^b$ (line 42). Next we reduce the -leading digit of both (line 46) and then mp\_clamp(). +the number. First we zero any digits above the last digit in $2^b$ (line 41). Next we reduce the +leading digit of both (line 45) and then mp\_clamp(). \section*{Exercises} \begin{tabular}{cl} @@ -2604,20 +3643,91 @@ exceed the precision requested. \hspace{-5.1mm}{\bf File}: bn\_s\_mp\_mul\_digs.c \vspace{-3mm} \begin{alltt} +016 +017 /* multiplies |a| * |b| and only computes upto digs digits of result +018 * HAC pp. 595, Algorithm 14.12 Modified so you can control how +019 * many digits of output are created. +020 */ +021 int s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) +022 \{ +023 mp_int t; +024 int res, pa, pb, ix, iy; +025 mp_digit u; +026 mp_word r; +027 mp_digit tmpx, *tmpt, *tmpy; +028 +029 /* can we use the fast multiplier? */ +030 if (((digs) < MP_WARRAY) && +031 MIN (a->used, b->used) < +032 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) \{ +033 return fast_s_mp_mul_digs (a, b, c, digs); +034 \} +035 +036 if ((res = mp_init_size (&t, digs)) != MP_OKAY) \{ +037 return res; +038 \} +039 t.used = digs; +040 +041 /* compute the digits of the product directly */ +042 pa = a->used; +043 for (ix = 0; ix < pa; ix++) \{ +044 /* set the carry to zero */ +045 u = 0; +046 +047 /* limit ourselves to making digs digits of output */ +048 pb = MIN (b->used, digs - ix); +049 +050 /* setup some aliases */ +051 /* copy of the digit from a used within the nested loop */ +052 tmpx = a->dp[ix]; +053 +054 /* an alias for the destination shifted ix places */ +055 tmpt = t.dp + ix; +056 +057 /* an alias for the digits of b */ +058 tmpy = b->dp; +059 +060 /* compute the columns of the output and propagate the carry */ +061 for (iy = 0; iy < pb; iy++) \{ +062 /* compute the column as a mp_word */ +063 r = ((mp_word)*tmpt) + +064 ((mp_word)tmpx) * ((mp_word)*tmpy++) + +065 ((mp_word) u); +066 +067 /* the new column is the lower part of the result */ +068 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); +069 +070 /* get the carry word from the result */ +071 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); +072 \} +073 /* set carry if it is placed below digs */ +074 if (ix + iy < digs) \{ +075 *tmpt = u; +076 \} +077 \} +078 +079 mp_clamp (&t); +080 mp_exch (&t, c); +081 +082 mp_clear (&t); +083 return MP_OKAY; +084 \} +085 #endif +086 \end{alltt} \end{small} -First we determine (line 31) if the Comba method can be used first since it's faster. The conditions for +First we determine (line 30) if the Comba method can be used first since it's faster. The conditions for sing the Comba routine are that min$(a.used, b.used) < \delta$ and the number of digits of output is less than \textbf{MP\_WARRAY}. This new constant is used to control the stack usage in the Comba routines. By default it is set to $\delta$ but can be reduced when memory is at a premium. If we cannot use the Comba method we proceed to setup the baseline routine. We allocate the the destination mp\_int -$t$ (line 37) to the exact size of the output to avoid further re--allocations. At this point we now +$t$ (line 36) to the exact size of the output to avoid further re--allocations. At this point we now begin the $O(n^2)$ loop. This implementation of multiplication has the caveat that it can be trimmed to only produce a variable number of -digits as output. In each iteration of the outer loop the $pb$ variable is set (line 49) to the maximum +digits as output. In each iteration of the outer loop the $pb$ variable is set (line 48) to the maximum number of inner loop iterations. Inside the inner loop we calculate $\hat r$ as the mp\_word product of the two mp\_digits and the addition of the @@ -2625,7 +3735,7 @@ carry from the previous iteration. A particularly important observation is that C compilers (GCC for instance) can recognize that a $N \times N \rightarrow 2N$ multiplication is all that is required for the product. In x86 terms for example, this means using the MUL instruction. -Each digit of the product is stored in turn (line 69) and the carry propagated (line 72) to the +Each digit of the product is stored in turn (line 68) and the carry propagated (line 71) to the next iteration. \subsection{Faster Multiplication by the ``Comba'' Method} @@ -2802,14 +3912,102 @@ and addition operations in the nested loop in parallel. \hspace{-5.1mm}{\bf File}: bn\_fast\_s\_mp\_mul\_digs.c \vspace{-3mm} \begin{alltt} +016 +017 /* Fast (comba) multiplier +018 * +019 * This is the fast column-array [comba] multiplier. It is +020 * designed to compute the columns of the product first +021 * then handle the carries afterwards. This has the effect +022 * of making the nested loops that compute the columns very +023 * simple and schedulable on super-scalar processors. +024 * +025 * This has been modified to produce a variable number of +026 * digits of output so if say only a half-product is required +027 * you don't have to compute the upper half (a feature +028 * required for fast Barrett reduction). +029 * +030 * Based on Algorithm 14.12 on pp.595 of HAC. +031 * +032 */ +033 int fast_s_mp_mul_digs (mp_int * a, mp_int * b, mp_int * c, int digs) +034 \{ +035 int olduse, res, pa, ix, iz; +036 mp_digit W[MP_WARRAY]; +037 register mp_word _W; +038 +039 /* grow the destination as required */ +040 if (c->alloc < digs) \{ +041 if ((res = mp_grow (c, digs)) != MP_OKAY) \{ +042 return res; +043 \} +044 \} +045 +046 /* number of output digits to produce */ +047 pa = MIN(digs, a->used + b->used); +048 +049 /* clear the carry */ +050 _W = 0; +051 for (ix = 0; ix < pa; ix++) \{ +052 int tx, ty; +053 int iy; +054 mp_digit *tmpx, *tmpy; +055 +056 /* get offsets into the two bignums */ +057 ty = MIN(b->used-1, ix); +058 tx = ix - ty; +059 +060 /* setup temp aliases */ +061 tmpx = a->dp + tx; +062 tmpy = b->dp + ty; +063 +064 /* this is the number of times the loop will iterrate, essentially +065 while (tx++ < a->used && ty-- >= 0) \{ ... \} +066 */ +067 iy = MIN(a->used-tx, ty+1); +068 +069 /* execute loop */ +070 for (iz = 0; iz < iy; ++iz) \{ +071 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--); +072 +073 \} +074 +075 /* store term */ +076 W[ix] = ((mp_digit)_W) & MP_MASK; +077 +078 /* make next carry */ +079 _W = _W >> ((mp_word)DIGIT_BIT); +080 \} +081 +082 /* setup dest */ +083 olduse = c->used; +084 c->used = pa; +085 +086 \{ +087 register mp_digit *tmpc; +088 tmpc = c->dp; +089 for (ix = 0; ix < pa+1; ix++) \{ +090 /* now extract the previous digit [below the carry] */ +091 *tmpc++ = W[ix]; +092 \} +093 +094 /* clear unused digits [that existed in the old copy of c] */ +095 for (; ix < olduse; ix++) \{ +096 *tmpc++ = 0; +097 \} +098 \} +099 mp_clamp (c); +100 return MP_OKAY; +101 \} +102 #endif +103 \end{alltt} \end{small} -As per the pseudo--code we first calculate $pa$ (line 48) as the number of digits to output. Next we begin the outer loop -to produce the individual columns of the product. We use the two aliases $tmpx$ and $tmpy$ (lines 62, 63) to point +As per the pseudo--code we first calculate $pa$ (line 47) as the number of digits to output. Next we begin the outer loop +to produce the individual columns of the product. We use the two aliases $tmpx$ and $tmpy$ (lines 61, 62) to point inside the two multiplicands quickly. -The inner loop (lines 71 to 74) of this implementation is where the tradeoff come into play. Originally this comba +The inner loop (lines 70 to 73) of this implementation is where the tradeoff come into play. Originally this comba implementation was ``row--major'' which means it adds to each of the columns in each pass. After the outer loop it would then fix the carries. This was very fast except it had an annoying drawback. You had to read a mp\_word and two mp\_digits and write one mp\_word per iteration. On processors such as the Athlon XP and P4 this did not matter much since the cache bandwidth @@ -2817,8 +4015,8 @@ is very high and it can keep the ALU fed with data. It did, however, matter on slower and also often doesn't exist. This new algorithm only performs two reads per iteration under the assumption that the compiler has aliased $\_ \hat W$ to a CPU register. -After the inner loop we store the current accumulator in $W$ and shift $\_ \hat W$ (lines 77, 80) to forward it as -a carry for the next pass. After the outer loop we use the final carry (line 77) as the last digit of the product. +After the inner loop we store the current accumulator in $W$ and shift $\_ \hat W$ (lines 76, 79) to forward it as +a carry for the next pass. After the outer loop we use the final carry (line 76) as the last digit of the product. \subsection{Polynomial Basis Multiplication} To break the $O(n^2)$ barrier in multiplication requires a completely different look at integer multiplication. In the following algorithms @@ -3005,12 +4203,160 @@ The remaining steps 13 through 18 compute the Karatsuba polynomial through a var \hspace{-5.1mm}{\bf File}: bn\_mp\_karatsuba\_mul.c \vspace{-3mm} \begin{alltt} +016 +017 /* c = |a| * |b| using Karatsuba Multiplication using +018 * three half size multiplications +019 * +020 * Let B represent the radix [e.g. 2**DIGIT_BIT] and +021 * let n represent half of the number of digits in +022 * the min(a,b) +023 * +024 * a = a1 * B**n + a0 +025 * b = b1 * B**n + b0 +026 * +027 * Then, a * b => +028 a1b1 * B**2n + ((a1 + a0)(b1 + b0) - (a0b0 + a1b1)) * B + a0b0 +029 * +030 * Note that a1b1 and a0b0 are used twice and only need to be +031 * computed once. So in total three half size (half # of +032 * digit) multiplications are performed, a0b0, a1b1 and +033 * (a1+b1)(a0+b0) +034 * +035 * Note that a multiplication of half the digits requires +036 * 1/4th the number of single precision multiplications so in +037 * total after one call 25% of the single precision multiplications +038 * are saved. Note also that the call to mp_mul can end up back +039 * in this function if the a0, a1, b0, or b1 are above the threshold. +040 * This is known as divide-and-conquer and leads to the famous +041 * O(N**lg(3)) or O(N**1.584) work which is asymptopically lower than +042 * the standard O(N**2) that the baseline/comba methods use. +043 * Generally though the overhead of this method doesn't pay off +044 * until a certain size (N ~ 80) is reached. +045 */ +046 int mp_karatsuba_mul (mp_int * a, mp_int * b, mp_int * c) +047 \{ +048 mp_int x0, x1, y0, y1, t1, x0y0, x1y1; +049 int B, err; +050 +051 /* default the return code to an error */ +052 err = MP_MEM; +053 +054 /* min # of digits */ +055 B = MIN (a->used, b->used); +056 +057 /* now divide in two */ +058 B = B >> 1; +059 +060 /* init copy all the temps */ +061 if (mp_init_size (&x0, B) != MP_OKAY) +062 goto ERR; +063 if (mp_init_size (&x1, a->used - B) != MP_OKAY) +064 goto X0; +065 if (mp_init_size (&y0, B) != MP_OKAY) +066 goto X1; +067 if (mp_init_size (&y1, b->used - B) != MP_OKAY) +068 goto Y0; +069 +070 /* init temps */ +071 if (mp_init_size (&t1, B * 2) != MP_OKAY) +072 goto Y1; +073 if (mp_init_size (&x0y0, B * 2) != MP_OKAY) +074 goto T1; +075 if (mp_init_size (&x1y1, B * 2) != MP_OKAY) +076 goto X0Y0; +077 +078 /* now shift the digits */ +079 x0.used = y0.used = B; +080 x1.used = a->used - B; +081 y1.used = b->used - B; +082 +083 \{ +084 register int x; +085 register mp_digit *tmpa, *tmpb, *tmpx, *tmpy; +086 +087 /* we copy the digits directly instead of using higher level functions +088 * since we also need to shift the digits +089 */ +090 tmpa = a->dp; +091 tmpb = b->dp; +092 +093 tmpx = x0.dp; +094 tmpy = y0.dp; +095 for (x = 0; x < B; x++) \{ +096 *tmpx++ = *tmpa++; +097 *tmpy++ = *tmpb++; +098 \} +099 +100 tmpx = x1.dp; +101 for (x = B; x < a->used; x++) \{ +102 *tmpx++ = *tmpa++; +103 \} +104 +105 tmpy = y1.dp; +106 for (x = B; x < b->used; x++) \{ +107 *tmpy++ = *tmpb++; +108 \} +109 \} +110 +111 /* only need to clamp the lower words since by definition the +112 * upper words x1/y1 must have a known number of digits +113 */ +114 mp_clamp (&x0); +115 mp_clamp (&y0); +116 +117 /* now calc the products x0y0 and x1y1 */ +118 /* after this x0 is no longer required, free temp [x0==t2]! */ +119 if (mp_mul (&x0, &y0, &x0y0) != MP_OKAY) +120 goto X1Y1; /* x0y0 = x0*y0 */ +121 if (mp_mul (&x1, &y1, &x1y1) != MP_OKAY) +122 goto X1Y1; /* x1y1 = x1*y1 */ +123 +124 /* now calc x1+x0 and y1+y0 */ +125 if (s_mp_add (&x1, &x0, &t1) != MP_OKAY) +126 goto X1Y1; /* t1 = x1 - x0 */ +127 if (s_mp_add (&y1, &y0, &x0) != MP_OKAY) +128 goto X1Y1; /* t2 = y1 - y0 */ +129 if (mp_mul (&t1, &x0, &t1) != MP_OKAY) +130 goto X1Y1; /* t1 = (x1 + x0) * (y1 + y0) */ +131 +132 /* add x0y0 */ +133 if (mp_add (&x0y0, &x1y1, &x0) != MP_OKAY) +134 goto X1Y1; /* t2 = x0y0 + x1y1 */ +135 if (s_mp_sub (&t1, &x0, &t1) != MP_OKAY) +136 goto X1Y1; /* t1 = (x1+x0)*(y1+y0) - (x1y1 + x0y0) */ +137 +138 /* shift by B */ +139 if (mp_lshd (&t1, B) != MP_OKAY) +140 goto X1Y1; /* t1 = (x0y0 + x1y1 - (x1-x0)*(y1-y0))<used, b->used) / 3; +038 +039 /* a = a2 * B**2 + a1 * B + a0 */ +040 if ((res = mp_mod_2d(a, DIGIT_BIT * B, &a0)) != MP_OKAY) \{ +041 goto ERR; +042 \} +043 +044 if ((res = mp_copy(a, &a1)) != MP_OKAY) \{ +045 goto ERR; +046 \} +047 mp_rshd(&a1, B); +048 mp_mod_2d(&a1, DIGIT_BIT * B, &a1); +049 +050 if ((res = mp_copy(a, &a2)) != MP_OKAY) \{ +051 goto ERR; +052 \} +053 mp_rshd(&a2, B*2); +054 +055 /* b = b2 * B**2 + b1 * B + b0 */ +056 if ((res = mp_mod_2d(b, DIGIT_BIT * B, &b0)) != MP_OKAY) \{ +057 goto ERR; +058 \} +059 +060 if ((res = mp_copy(b, &b1)) != MP_OKAY) \{ +061 goto ERR; +062 \} +063 mp_rshd(&b1, B); +064 mp_mod_2d(&b1, DIGIT_BIT * B, &b1); +065 +066 if ((res = mp_copy(b, &b2)) != MP_OKAY) \{ +067 goto ERR; +068 \} +069 mp_rshd(&b2, B*2); +070 +071 /* w0 = a0*b0 */ +072 if ((res = mp_mul(&a0, &b0, &w0)) != MP_OKAY) \{ +073 goto ERR; +074 \} +075 +076 /* w4 = a2 * b2 */ +077 if ((res = mp_mul(&a2, &b2, &w4)) != MP_OKAY) \{ +078 goto ERR; +079 \} +080 +081 /* w1 = (a2 + 2(a1 + 2a0))(b2 + 2(b1 + 2b0)) */ +082 if ((res = mp_mul_2(&a0, &tmp1)) != MP_OKAY) \{ +083 goto ERR; +084 \} +085 if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) \{ +086 goto ERR; +087 \} +088 if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) \{ +089 goto ERR; +090 \} +091 if ((res = mp_add(&tmp1, &a2, &tmp1)) != MP_OKAY) \{ +092 goto ERR; +093 \} +094 +095 if ((res = mp_mul_2(&b0, &tmp2)) != MP_OKAY) \{ +096 goto ERR; +097 \} +098 if ((res = mp_add(&tmp2, &b1, &tmp2)) != MP_OKAY) \{ +099 goto ERR; +100 \} +101 if ((res = mp_mul_2(&tmp2, &tmp2)) != MP_OKAY) \{ +102 goto ERR; +103 \} +104 if ((res = mp_add(&tmp2, &b2, &tmp2)) != MP_OKAY) \{ +105 goto ERR; +106 \} +107 +108 if ((res = mp_mul(&tmp1, &tmp2, &w1)) != MP_OKAY) \{ +109 goto ERR; +110 \} +111 +112 /* w3 = (a0 + 2(a1 + 2a2))(b0 + 2(b1 + 2b2)) */ +113 if ((res = mp_mul_2(&a2, &tmp1)) != MP_OKAY) \{ +114 goto ERR; +115 \} +116 if ((res = mp_add(&tmp1, &a1, &tmp1)) != MP_OKAY) \{ +117 goto ERR; +118 \} +119 if ((res = mp_mul_2(&tmp1, &tmp1)) != MP_OKAY) \{ +120 goto ERR; +121 \} +122 if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) \{ +123 goto ERR; +124 \} +125 +126 if ((res = mp_mul_2(&b2, &tmp2)) != MP_OKAY) \{ +127 goto ERR; +128 \} +129 if ((res = mp_add(&tmp2, &b1, &tmp2)) != MP_OKAY) \{ +130 goto ERR; +131 \} +132 if ((res = mp_mul_2(&tmp2, &tmp2)) != MP_OKAY) \{ +133 goto ERR; +134 \} +135 if ((res = mp_add(&tmp2, &b0, &tmp2)) != MP_OKAY) \{ +136 goto ERR; +137 \} +138 +139 if ((res = mp_mul(&tmp1, &tmp2, &w3)) != MP_OKAY) \{ +140 goto ERR; +141 \} +142 +143 +144 /* w2 = (a2 + a1 + a0)(b2 + b1 + b0) */ +145 if ((res = mp_add(&a2, &a1, &tmp1)) != MP_OKAY) \{ +146 goto ERR; +147 \} +148 if ((res = mp_add(&tmp1, &a0, &tmp1)) != MP_OKAY) \{ +149 goto ERR; +150 \} +151 if ((res = mp_add(&b2, &b1, &tmp2)) != MP_OKAY) \{ +152 goto ERR; +153 \} +154 if ((res = mp_add(&tmp2, &b0, &tmp2)) != MP_OKAY) \{ +155 goto ERR; +156 \} +157 if ((res = mp_mul(&tmp1, &tmp2, &w2)) != MP_OKAY) \{ +158 goto ERR; +159 \} +160 +161 /* now solve the matrix +162 +163 0 0 0 0 1 +164 1 2 4 8 16 +165 1 1 1 1 1 +166 16 8 4 2 1 +167 1 0 0 0 0 +168 +169 using 12 subtractions, 4 shifts, +170 2 small divisions and 1 small multiplication +171 */ +172 +173 /* r1 - r4 */ +174 if ((res = mp_sub(&w1, &w4, &w1)) != MP_OKAY) \{ +175 goto ERR; +176 \} +177 /* r3 - r0 */ +178 if ((res = mp_sub(&w3, &w0, &w3)) != MP_OKAY) \{ +179 goto ERR; +180 \} +181 /* r1/2 */ +182 if ((res = mp_div_2(&w1, &w1)) != MP_OKAY) \{ +183 goto ERR; +184 \} +185 /* r3/2 */ +186 if ((res = mp_div_2(&w3, &w3)) != MP_OKAY) \{ +187 goto ERR; +188 \} +189 /* r2 - r0 - r4 */ +190 if ((res = mp_sub(&w2, &w0, &w2)) != MP_OKAY) \{ +191 goto ERR; +192 \} +193 if ((res = mp_sub(&w2, &w4, &w2)) != MP_OKAY) \{ +194 goto ERR; +195 \} +196 /* r1 - r2 */ +197 if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) \{ +198 goto ERR; +199 \} +200 /* r3 - r2 */ +201 if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) \{ +202 goto ERR; +203 \} +204 /* r1 - 8r0 */ +205 if ((res = mp_mul_2d(&w0, 3, &tmp1)) != MP_OKAY) \{ +206 goto ERR; +207 \} +208 if ((res = mp_sub(&w1, &tmp1, &w1)) != MP_OKAY) \{ +209 goto ERR; +210 \} +211 /* r3 - 8r4 */ +212 if ((res = mp_mul_2d(&w4, 3, &tmp1)) != MP_OKAY) \{ +213 goto ERR; +214 \} +215 if ((res = mp_sub(&w3, &tmp1, &w3)) != MP_OKAY) \{ +216 goto ERR; +217 \} +218 /* 3r2 - r1 - r3 */ +219 if ((res = mp_mul_d(&w2, 3, &w2)) != MP_OKAY) \{ +220 goto ERR; +221 \} +222 if ((res = mp_sub(&w2, &w1, &w2)) != MP_OKAY) \{ +223 goto ERR; +224 \} +225 if ((res = mp_sub(&w2, &w3, &w2)) != MP_OKAY) \{ +226 goto ERR; +227 \} +228 /* r1 - r2 */ +229 if ((res = mp_sub(&w1, &w2, &w1)) != MP_OKAY) \{ +230 goto ERR; +231 \} +232 /* r3 - r2 */ +233 if ((res = mp_sub(&w3, &w2, &w3)) != MP_OKAY) \{ +234 goto ERR; +235 \} +236 /* r1/3 */ +237 if ((res = mp_div_3(&w1, &w1, NULL)) != MP_OKAY) \{ +238 goto ERR; +239 \} +240 /* r3/3 */ +241 if ((res = mp_div_3(&w3, &w3, NULL)) != MP_OKAY) \{ +242 goto ERR; +243 \} +244 +245 /* at this point shift W[n] by B*n */ +246 if ((res = mp_lshd(&w1, 1*B)) != MP_OKAY) \{ +247 goto ERR; +248 \} +249 if ((res = mp_lshd(&w2, 2*B)) != MP_OKAY) \{ +250 goto ERR; +251 \} +252 if ((res = mp_lshd(&w3, 3*B)) != MP_OKAY) \{ +253 goto ERR; +254 \} +255 if ((res = mp_lshd(&w4, 4*B)) != MP_OKAY) \{ +256 goto ERR; +257 \} +258 +259 if ((res = mp_add(&w0, &w1, c)) != MP_OKAY) \{ +260 goto ERR; +261 \} +262 if ((res = mp_add(&w2, &w3, &tmp1)) != MP_OKAY) \{ +263 goto ERR; +264 \} +265 if ((res = mp_add(&w4, &tmp1, &tmp1)) != MP_OKAY) \{ +266 goto ERR; +267 \} +268 if ((res = mp_add(&tmp1, c, c)) != MP_OKAY) \{ +269 goto ERR; +270 \} +271 +272 ERR: +273 mp_clear_multi(&w0, &w1, &w2, &w3, &w4, +274 &a0, &a1, &a2, &b0, &b1, +275 &b2, &tmp1, &tmp2, NULL); +276 return res; +277 \} +278 +279 #endif +280 \end{alltt} \end{small} @@ -3152,12 +4763,12 @@ large numbers. For example, a 10,000 digit multiplication takes approximaly 99, Toom--Cook than a Comba or baseline approach (this is a savings of more than 99$\%$). For most ``crypto'' sized numbers this algorithm is not practical as Karatsuba has a much lower cutoff point. -First we split $a$ and $b$ into three roughly equal portions. This has been accomplished (lines 41 to 70) with +First we split $a$ and $b$ into three roughly equal portions. This has been accomplished (lines 40 to 69) with combinations of mp\_rshd() and mp\_mod\_2d() function calls. At this point $a = a2 \cdot \beta^2 + a1 \cdot \beta + a0$ and similiarly for $b$. Next we compute the five points $w0, w1, w2, w3$ and $w4$. Recall that $w0$ and $w4$ can be computed directly from the portions so -we get those out of the way first (lines 73 and 78). Next we compute $w1, w2$ and $w3$ using Horners method. +we get those out of the way first (lines 72 and 77). Next we compute $w1, w2$ and $w3$ using Horners method. After this point we solve for the actual values of $w1, w2$ and $w3$ by reducing the $5 \times 5$ system which is relatively straight forward. @@ -3206,11 +4817,58 @@ s\_mp\_mul\_digs will clear it. \hspace{-5.1mm}{\bf File}: bn\_mp\_mul.c \vspace{-3mm} \begin{alltt} +016 +017 /* high level multiplication (handles sign) */ +018 int mp_mul (mp_int * a, mp_int * b, mp_int * c) +019 \{ +020 int res, neg; +021 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG; +022 +023 /* use Toom-Cook? */ +024 #ifdef BN_MP_TOOM_MUL_C +025 if (MIN (a->used, b->used) >= TOOM_MUL_CUTOFF) \{ +026 res = mp_toom_mul(a, b, c); +027 \} else +028 #endif +029 #ifdef BN_MP_KARATSUBA_MUL_C +030 /* use Karatsuba? */ +031 if (MIN (a->used, b->used) >= KARATSUBA_MUL_CUTOFF) \{ +032 res = mp_karatsuba_mul (a, b, c); +033 \} else +034 #endif +035 \{ +036 /* can we use the fast multiplier? +037 * +038 * The fast multiplier can be used if the output will +039 * have less than MP_WARRAY digits and the number of +040 * digits won't affect carry propagation +041 */ +042 int digs = a->used + b->used + 1; +043 +044 #ifdef BN_FAST_S_MP_MUL_DIGS_C +045 if ((digs < MP_WARRAY) && +046 MIN(a->used, b->used) <= +047 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) \{ +048 res = fast_s_mp_mul_digs (a, b, c, digs); +049 \} else +050 #endif +051 #ifdef BN_S_MP_MUL_DIGS_C +052 res = s_mp_mul (a, b, c); /* uses s_mp_mul_digs */ +053 #else +054 res = MP_VAL; +055 #endif +056 +057 \} +058 c->sign = (c->used > 0) ? neg : MP_ZPOS; +059 return res; +060 \} +061 #endif +062 \end{alltt} \end{small} -The implementation is rather simplistic and is not particularly noteworthy. Line 22 computes the sign of the result using the ``?'' -operator from the C programming language. Line 48 computes $\delta$ using the fact that $1 << k$ is equal to $2^k$. +The implementation is rather simplistic and is not particularly noteworthy. Line 23 computes the sign of the result using the ``?'' +operator from the C programming language. Line 47 computes $\delta$ using the fact that $1 << k$ is equal to $2^k$. \section{Squaring} \label{sec:basesquare} @@ -3311,13 +4969,78 @@ results calculated so far. This involves expensive carry propagation which will \hspace{-5.1mm}{\bf File}: bn\_s\_mp\_sqr.c \vspace{-3mm} \begin{alltt} +016 +017 /* low level squaring, b = a*a, HAC pp.596-597, Algorithm 14.16 */ +018 int s_mp_sqr (mp_int * a, mp_int * b) +019 \{ +020 mp_int t; +021 int res, ix, iy, pa; +022 mp_word r; +023 mp_digit u, tmpx, *tmpt; +024 +025 pa = a->used; +026 if ((res = mp_init_size (&t, 2*pa + 1)) != MP_OKAY) \{ +027 return res; +028 \} +029 +030 /* default used is maximum possible size */ +031 t.used = 2*pa + 1; +032 +033 for (ix = 0; ix < pa; ix++) \{ +034 /* first calculate the digit at 2*ix */ +035 /* calculate double precision result */ +036 r = ((mp_word) t.dp[2*ix]) + +037 ((mp_word)a->dp[ix])*((mp_word)a->dp[ix]); +038 +039 /* store lower part in result */ +040 t.dp[ix+ix] = (mp_digit) (r & ((mp_word) MP_MASK)); +041 +042 /* get the carry */ +043 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); +044 +045 /* left hand side of A[ix] * A[iy] */ +046 tmpx = a->dp[ix]; +047 +048 /* alias for where to store the results */ +049 tmpt = t.dp + (2*ix + 1); +050 +051 for (iy = ix + 1; iy < pa; iy++) \{ +052 /* first calculate the product */ +053 r = ((mp_word)tmpx) * ((mp_word)a->dp[iy]); +054 +055 /* now calculate the double precision result, note we use +056 * addition instead of *2 since it's easier to optimize +057 */ +058 r = ((mp_word) *tmpt) + r + r + ((mp_word) u); +059 +060 /* store lower part */ +061 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); +062 +063 /* get carry */ +064 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); +065 \} +066 /* propagate upwards */ +067 while (u != ((mp_digit) 0)) \{ +068 r = ((mp_word) *tmpt) + ((mp_word) u); +069 *tmpt++ = (mp_digit) (r & ((mp_word) MP_MASK)); +070 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); +071 \} +072 \} +073 +074 mp_clamp (&t); +075 mp_exch (&t, b); +076 mp_clear (&t); +077 return MP_OKAY; +078 \} +079 #endif +080 \end{alltt} \end{small} -Inside the outer loop (line 34) the square term is calculated on line 37. The carry (line 44) has been +Inside the outer loop (line 33) the square term is calculated on line 36. The carry (line 43) has been extracted from the mp\_word accumulator using a right shift. Aliases for $a_{ix}$ and $t_{ix+iy}$ are initialized -(lines 47 and 50) to simplify the inner loop. The doubling is performed using two -additions (line 59) since it is usually faster than shifting, if not at least as fast. +(lines 46 and 49) to simplify the inner loop. The doubling is performed using two +additions (line 58) since it is usually faster than shifting, if not at least as fast. The important observation is that the inner loop does not begin at $iy = 0$ like for multiplication. As such the inner loops get progressively shorter as the algorithm proceeds. This is what leads to the savings compared to using a multiplication to @@ -3399,6 +5122,101 @@ only to even outputs and it is the square of the term at the $\lfloor ix / 2 \rf \hspace{-5.1mm}{\bf File}: bn\_fast\_s\_mp\_sqr.c \vspace{-3mm} \begin{alltt} +016 +017 /* the jist of squaring... +018 * you do like mult except the offset of the tmpx [one that +019 * starts closer to zero] can't equal the offset of tmpy. +020 * So basically you set up iy like before then you min it with +021 * (ty-tx) so that it never happens. You double all those +022 * you add in the inner loop +023 +024 After that loop you do the squares and add them in. +025 */ +026 +027 int fast_s_mp_sqr (mp_int * a, mp_int * b) +028 \{ +029 int olduse, res, pa, ix, iz; +030 mp_digit W[MP_WARRAY], *tmpx; +031 mp_word W1; +032 +033 /* grow the destination as required */ +034 pa = a->used + a->used; +035 if (b->alloc < pa) \{ +036 if ((res = mp_grow (b, pa)) != MP_OKAY) \{ +037 return res; +038 \} +039 \} +040 +041 /* number of output digits to produce */ +042 W1 = 0; +043 for (ix = 0; ix < pa; ix++) \{ +044 int tx, ty, iy; +045 mp_word _W; +046 mp_digit *tmpy; +047 +048 /* clear counter */ +049 _W = 0; +050 +051 /* get offsets into the two bignums */ +052 ty = MIN(a->used-1, ix); +053 tx = ix - ty; +054 +055 /* setup temp aliases */ +056 tmpx = a->dp + tx; +057 tmpy = a->dp + ty; +058 +059 /* this is the number of times the loop will iterrate, essentially +060 while (tx++ < a->used && ty-- >= 0) \{ ... \} +061 */ +062 iy = MIN(a->used-tx, ty+1); +063 +064 /* now for squaring tx can never equal ty +065 * we halve the distance since they approach at a rate of 2x +066 * and we have to round because odd cases need to be executed +067 */ +068 iy = MIN(iy, (ty-tx+1)>>1); +069 +070 /* execute loop */ +071 for (iz = 0; iz < iy; iz++) \{ +072 _W += ((mp_word)*tmpx++)*((mp_word)*tmpy--); +073 \} +074 +075 /* double the inner product and add carry */ +076 _W = _W + _W + W1; +077 +078 /* even columns have the square term in them */ +079 if ((ix&1) == 0) \{ +080 _W += ((mp_word)a->dp[ix>>1])*((mp_word)a->dp[ix>>1]); +081 \} +082 +083 /* store it */ +084 W[ix] = (mp_digit)(_W & MP_MASK); +085 +086 /* make next carry */ +087 W1 = _W >> ((mp_word)DIGIT_BIT); +088 \} +089 +090 /* setup dest */ +091 olduse = b->used; +092 b->used = a->used+a->used; +093 +094 \{ +095 mp_digit *tmpb; +096 tmpb = b->dp; +097 for (ix = 0; ix < pa; ix++) \{ +098 *tmpb++ = W[ix] & MP_MASK; +099 \} +100 +101 /* clear unused digits [that existed in the old copy of c] */ +102 for (; ix < olduse; ix++) \{ +103 *tmpb++ = 0; +104 \} +105 \} +106 mp_clamp (b); +107 return MP_OKAY; +108 \} +109 #endif +110 \end{alltt} \end{small} @@ -3508,11 +5326,113 @@ ratio of 1:7. } than simpler operations such as addition. \hspace{-5.1mm}{\bf File}: bn\_mp\_karatsuba\_sqr.c \vspace{-3mm} \begin{alltt} +016 +017 /* Karatsuba squaring, computes b = a*a using three +018 * half size squarings +019 * +020 * See comments of karatsuba_mul for details. It +021 * is essentially the same algorithm but merely +022 * tuned to perform recursive squarings. +023 */ +024 int mp_karatsuba_sqr (mp_int * a, mp_int * b) +025 \{ +026 mp_int x0, x1, t1, t2, x0x0, x1x1; +027 int B, err; +028 +029 err = MP_MEM; +030 +031 /* min # of digits */ +032 B = a->used; +033 +034 /* now divide in two */ +035 B = B >> 1; +036 +037 /* init copy all the temps */ +038 if (mp_init_size (&x0, B) != MP_OKAY) +039 goto ERR; +040 if (mp_init_size (&x1, a->used - B) != MP_OKAY) +041 goto X0; +042 +043 /* init temps */ +044 if (mp_init_size (&t1, a->used * 2) != MP_OKAY) +045 goto X1; +046 if (mp_init_size (&t2, a->used * 2) != MP_OKAY) +047 goto T1; +048 if (mp_init_size (&x0x0, B * 2) != MP_OKAY) +049 goto T2; +050 if (mp_init_size (&x1x1, (a->used - B) * 2) != MP_OKAY) +051 goto X0X0; +052 +053 \{ +054 register int x; +055 register mp_digit *dst, *src; +056 +057 src = a->dp; +058 +059 /* now shift the digits */ +060 dst = x0.dp; +061 for (x = 0; x < B; x++) \{ +062 *dst++ = *src++; +063 \} +064 +065 dst = x1.dp; +066 for (x = B; x < a->used; x++) \{ +067 *dst++ = *src++; +068 \} +069 \} +070 +071 x0.used = B; +072 x1.used = a->used - B; +073 +074 mp_clamp (&x0); +075 +076 /* now calc the products x0*x0 and x1*x1 */ +077 if (mp_sqr (&x0, &x0x0) != MP_OKAY) +078 goto X1X1; /* x0x0 = x0*x0 */ +079 if (mp_sqr (&x1, &x1x1) != MP_OKAY) +080 goto X1X1; /* x1x1 = x1*x1 */ +081 +082 /* now calc (x1+x0)**2 */ +083 if (s_mp_add (&x1, &x0, &t1) != MP_OKAY) +084 goto X1X1; /* t1 = x1 - x0 */ +085 if (mp_sqr (&t1, &t1) != MP_OKAY) +086 goto X1X1; /* t1 = (x1 - x0) * (x1 - x0) */ +087 +088 /* add x0y0 */ +089 if (s_mp_add (&x0x0, &x1x1, &t2) != MP_OKAY) +090 goto X1X1; /* t2 = x0x0 + x1x1 */ +091 if (s_mp_sub (&t1, &t2, &t1) != MP_OKAY) +092 goto X1X1; /* t1 = (x1+x0)**2 - (x0x0 + x1x1) */ +093 +094 /* shift by B */ +095 if (mp_lshd (&t1, B) != MP_OKAY) +096 goto X1X1; /* t1 = (x0x0 + x1x1 - (x1-x0)*(x1-x0))<used >= TOOM_SQR_CUTOFF) \{ +026 res = mp_toom_sqr(a, b); +027 /* Karatsuba? */ +028 \} else +029 #endif +030 #ifdef BN_MP_KARATSUBA_SQR_C +031 if (a->used >= KARATSUBA_SQR_CUTOFF) \{ +032 res = mp_karatsuba_sqr (a, b); +033 \} else +034 #endif +035 \{ +036 #ifdef BN_FAST_S_MP_SQR_C +037 /* can we use the fast comba multiplier? */ +038 if ((a->used * 2 + 1) < MP_WARRAY && +039 a->used < +040 (1 << (sizeof(mp_word) * CHAR_BIT - 2*DIGIT_BIT - 1))) \{ +041 res = fast_s_mp_sqr (a, b); +042 \} else +043 #endif +044 #ifdef BN_S_MP_SQR_C +045 res = s_mp_sqr (a, b); +046 #else +047 res = MP_VAL; +048 #endif +049 \} +050 b->sign = MP_ZPOS; +051 return res; +052 \} +053 #endif +054 \end{alltt} \end{small} @@ -3819,12 +5778,93 @@ performed at most twice, and on average once. However, if $a \ge b^2$ than it wi \hspace{-5.1mm}{\bf File}: bn\_mp\_reduce.c \vspace{-3mm} \begin{alltt} +016 +017 /* reduces x mod m, assumes 0 < x < m**2, mu is +018 * precomputed via mp_reduce_setup. +019 * From HAC pp.604 Algorithm 14.42 +020 */ +021 int mp_reduce (mp_int * x, mp_int * m, mp_int * mu) +022 \{ +023 mp_int q; +024 int res, um = m->used; +025 +026 /* q = x */ +027 if ((res = mp_init_copy (&q, x)) != MP_OKAY) \{ +028 return res; +029 \} +030 +031 /* q1 = x / b**(k-1) */ +032 mp_rshd (&q, um - 1); +033 +034 /* according to HAC this optimization is ok */ +035 if (((unsigned long) um) > (((mp_digit)1) << (DIGIT_BIT - 1))) \{ +036 if ((res = mp_mul (&q, mu, &q)) != MP_OKAY) \{ +037 goto CLEANUP; +038 \} +039 \} else \{ +040 #ifdef BN_S_MP_MUL_HIGH_DIGS_C +041 if ((res = s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) \{ +042 goto CLEANUP; +043 \} +044 #elif defined(BN_FAST_S_MP_MUL_HIGH_DIGS_C) +045 if ((res = fast_s_mp_mul_high_digs (&q, mu, &q, um)) != MP_OKAY) \{ +046 goto CLEANUP; +047 \} +048 #else +049 \{ +050 res = MP_VAL; +051 goto CLEANUP; +052 \} +053 #endif +054 \} +055 +056 /* q3 = q2 / b**(k+1) */ +057 mp_rshd (&q, um + 1); +058 +059 /* x = x mod b**(k+1), quick (no division) */ +060 if ((res = mp_mod_2d (x, DIGIT_BIT * (um + 1), x)) != MP_OKAY) \{ +061 goto CLEANUP; +062 \} +063 +064 /* q = q * m mod b**(k+1), quick (no division) */ +065 if ((res = s_mp_mul_digs (&q, m, &q, um + 1)) != MP_OKAY) \{ +066 goto CLEANUP; +067 \} +068 +069 /* x = x - q */ +070 if ((res = mp_sub (x, &q, x)) != MP_OKAY) \{ +071 goto CLEANUP; +072 \} +073 +074 /* If x < 0, add b**(k+1) to it */ +075 if (mp_cmp_d (x, 0) == MP_LT) \{ +076 mp_set (&q, 1); +077 if ((res = mp_lshd (&q, um + 1)) != MP_OKAY) +078 goto CLEANUP; +079 if ((res = mp_add (x, &q, x)) != MP_OKAY) +080 goto CLEANUP; +081 \} +082 +083 /* Back off if it's too big */ +084 while (mp_cmp (x, m) != MP_LT) \{ +085 if ((res = s_mp_sub (x, m, x)) != MP_OKAY) \{ +086 goto CLEANUP; +087 \} +088 \} +089 +090 CLEANUP: +091 mp_clear (&q); +092 +093 return res; +094 \} +095 #endif +096 \end{alltt} \end{small} The first multiplication that determines the quotient can be performed by only producing the digits from $m - 1$ and up. This essentially halves the number of single precision multiplications required. However, the optimization is only safe if $\beta$ is much larger than the number of digits -in the modulus. In the source code this is evaluated on lines 36 to 44 where algorithm s\_mp\_mul\_high\_digs is used when it is +in the modulus. In the source code this is evaluated on lines 36 to 43 where algorithm s\_mp\_mul\_high\_digs is used when it is safe to do so. \subsection{The Barrett Setup Algorithm} @@ -3857,6 +5897,21 @@ is equivalent and much faster. The final value is computed by taking the intege \hspace{-5.1mm}{\bf File}: bn\_mp\_reduce\_setup.c \vspace{-3mm} \begin{alltt} +016 +017 /* pre-calculate the value required for Barrett reduction +018 * For a given modulus "b" it calulates the value required in "a" +019 */ +020 int mp_reduce_setup (mp_int * a, mp_int * b) +021 \{ +022 int res; +023 +024 if ((res = mp_2expt (a, b->used * 2 * DIGIT_BIT)) != MP_OKAY) \{ +025 return res; +026 \} +027 return mp_div (a, b, a, NULL); +028 \} +029 #endif +030 \end{alltt} \end{small} @@ -4116,11 +6171,110 @@ multiplications. \hspace{-5.1mm}{\bf File}: bn\_mp\_montgomery\_reduce.c \vspace{-3mm} \begin{alltt} +016 +017 /* computes xR**-1 == x (mod N) via Montgomery Reduction */ +018 int +019 mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) +020 \{ +021 int ix, res, digs; +022 mp_digit mu; +023 +024 /* can the fast reduction [comba] method be used? +025 * +026 * Note that unlike in mul you're safely allowed *less* +027 * than the available columns [255 per default] since carries +028 * are fixed up in the inner loop. +029 */ +030 digs = n->used * 2 + 1; +031 if ((digs < MP_WARRAY) && +032 n->used < +033 (1 << ((CHAR_BIT * sizeof (mp_word)) - (2 * DIGIT_BIT)))) \{ +034 return fast_mp_montgomery_reduce (x, n, rho); +035 \} +036 +037 /* grow the input as required */ +038 if (x->alloc < digs) \{ +039 if ((res = mp_grow (x, digs)) != MP_OKAY) \{ +040 return res; +041 \} +042 \} +043 x->used = digs; +044 +045 for (ix = 0; ix < n->used; ix++) \{ +046 /* mu = ai * rho mod b +047 * +048 * The value of rho must be precalculated via +049 * montgomery_setup() such that +050 * it equals -1/n0 mod b this allows the +051 * following inner loop to reduce the +052 * input one digit at a time +053 */ +054 mu = (mp_digit) (((mp_word)x->dp[ix]) * ((mp_word)rho) & MP_MASK); +055 +056 /* a = a + mu * m * b**i */ +057 \{ +058 register int iy; +059 register mp_digit *tmpn, *tmpx, u; +060 register mp_word r; +061 +062 /* alias for digits of the modulus */ +063 tmpn = n->dp; +064 +065 /* alias for the digits of x [the input] */ +066 tmpx = x->dp + ix; +067 +068 /* set the carry to zero */ +069 u = 0; +070 +071 /* Multiply and add in place */ +072 for (iy = 0; iy < n->used; iy++) \{ +073 /* compute product and sum */ +074 r = ((mp_word)mu) * ((mp_word)*tmpn++) + +075 ((mp_word) u) + ((mp_word) * tmpx); +076 +077 /* get carry */ +078 u = (mp_digit)(r >> ((mp_word) DIGIT_BIT)); +079 +080 /* fix digit */ +081 *tmpx++ = (mp_digit)(r & ((mp_word) MP_MASK)); +082 \} +083 /* At this point the ix'th digit of x should be zero */ +084 +085 +086 /* propagate carries upwards as required*/ +087 while (u) \{ +088 *tmpx += u; +089 u = *tmpx >> DIGIT_BIT; +090 *tmpx++ &= MP_MASK; +091 \} +092 \} +093 \} +094 +095 /* at this point the n.used'th least +096 * significant digits of x are all zero +097 * which means we can shift x to the +098 * right by n.used digits and the +099 * residue is unchanged. +100 */ +101 +102 /* x = x/b**n.used */ +103 mp_clamp(x); +104 mp_rshd (x, n->used); +105 +106 /* if x >= n then x = x - n */ +107 if (mp_cmp_mag (x, n) != MP_LT) \{ +108 return s_mp_sub (x, n, x); +109 \} +110 +111 return MP_OKAY; +112 \} +113 #endif +114 \end{alltt} \end{small} -This is the baseline implementation of the Montgomery reduction algorithm. Lines 31 to 36 determine if the Comba based -routine can be used instead. Line 47 computes the value of $\mu$ for that particular iteration of the outer loop. +This is the baseline implementation of the Montgomery reduction algorithm. Lines 30 to 35 determine if the Comba based +routine can be used instead. Line 48 computes the value of $\mu$ for that particular iteration of the outer loop. The multiplication $\mu n \beta^{ix}$ is performed in one step in the inner loop. The alias $tmpx$ refers to the $ix$'th digit of $x$ and the alias $tmpn$ refers to the modulus $n$. @@ -4208,17 +6362,170 @@ stored in the destination $x$. \hspace{-5.1mm}{\bf File}: bn\_fast\_mp\_montgomery\_reduce.c \vspace{-3mm} \begin{alltt} +016 +017 /* computes xR**-1 == x (mod N) via Montgomery Reduction +018 * +019 * This is an optimized implementation of montgomery_reduce +020 * which uses the comba method to quickly calculate the columns of the +021 * reduction. +022 * +023 * Based on Algorithm 14.32 on pp.601 of HAC. +024 */ +025 int fast_mp_montgomery_reduce (mp_int * x, mp_int * n, mp_digit rho) +026 \{ +027 int ix, res, olduse; +028 mp_word W[MP_WARRAY]; +029 +030 /* get old used count */ +031 olduse = x->used; +032 +033 /* grow a as required */ +034 if (x->alloc < n->used + 1) \{ +035 if ((res = mp_grow (x, n->used + 1)) != MP_OKAY) \{ +036 return res; +037 \} +038 \} +039 +040 /* first we have to get the digits of the input into +041 * an array of double precision words W[...] +042 */ +043 \{ +044 register mp_word *_W; +045 register mp_digit *tmpx; +046 +047 /* alias for the W[] array */ +048 _W = W; +049 +050 /* alias for the digits of x*/ +051 tmpx = x->dp; +052 +053 /* copy the digits of a into W[0..a->used-1] */ +054 for (ix = 0; ix < x->used; ix++) \{ +055 *_W++ = *tmpx++; +056 \} +057 +058 /* zero the high words of W[a->used..m->used*2] */ +059 for (; ix < n->used * 2 + 1; ix++) \{ +060 *_W++ = 0; +061 \} +062 \} +063 +064 /* now we proceed to zero successive digits +065 * from the least significant upwards +066 */ +067 for (ix = 0; ix < n->used; ix++) \{ +068 /* mu = ai * m' mod b +069 * +070 * We avoid a double precision multiplication (which isn't required) +071 * by casting the value down to a mp_digit. Note this requires +072 * that W[ix-1] have the carry cleared (see after the inner loop) +073 */ +074 register mp_digit mu; +075 mu = (mp_digit) (((W[ix] & MP_MASK) * rho) & MP_MASK); +076 +077 /* a = a + mu * m * b**i +078 * +079 * This is computed in place and on the fly. The multiplication +080 * by b**i is handled by offseting which columns the results +081 * are added to. +082 * +083 * Note the comba method normally doesn't handle carries in the +084 * inner loop In this case we fix the carry from the previous +085 * column since the Montgomery reduction requires digits of the +086 * result (so far) [see above] to work. This is +087 * handled by fixing up one carry after the inner loop. The +088 * carry fixups are done in order so after these loops the +089 * first m->used words of W[] have the carries fixed +090 */ +091 \{ +092 register int iy; +093 register mp_digit *tmpn; +094 register mp_word *_W; +095 +096 /* alias for the digits of the modulus */ +097 tmpn = n->dp; +098 +099 /* Alias for the columns set by an offset of ix */ +100 _W = W + ix; +101 +102 /* inner loop */ +103 for (iy = 0; iy < n->used; iy++) \{ +104 *_W++ += ((mp_word)mu) * ((mp_word)*tmpn++); +105 \} +106 \} +107 +108 /* now fix carry for next digit, W[ix+1] */ +109 W[ix + 1] += W[ix] >> ((mp_word) DIGIT_BIT); +110 \} +111 +112 /* now we have to propagate the carries and +113 * shift the words downward [all those least +114 * significant digits we zeroed]. +115 */ +116 \{ +117 register mp_digit *tmpx; +118 register mp_word *_W, *_W1; +119 +120 /* nox fix rest of carries */ +121 +122 /* alias for current word */ +123 _W1 = W + ix; +124 +125 /* alias for next word, where the carry goes */ +126 _W = W + ++ix; +127 +128 for (; ix <= n->used * 2 + 1; ix++) \{ +129 *_W++ += *_W1++ >> ((mp_word) DIGIT_BIT); +130 \} +131 +132 /* copy out, A = A/b**n +133 * +134 * The result is A/b**n but instead of converting from an +135 * array of mp_word to mp_digit than calling mp_rshd +136 * we just copy them in the right order +137 */ +138 +139 /* alias for destination word */ +140 tmpx = x->dp; +141 +142 /* alias for shifted double precision result */ +143 _W = W + n->used; +144 +145 for (ix = 0; ix < n->used + 1; ix++) \{ +146 *tmpx++ = (mp_digit)(*_W++ & ((mp_word) MP_MASK)); +147 \} +148 +149 /* zero oldused digits, if the input a was larger than +150 * m->used+1 we'll have to clear the digits +151 */ +152 for (; ix < olduse; ix++) \{ +153 *tmpx++ = 0; +154 \} +155 \} +156 +157 /* set the max used and clamp */ +158 x->used = n->used + 1; +159 mp_clamp (x); +160 +161 /* if A >= m then A = A - m */ +162 if (mp_cmp_mag (x, n) != MP_LT) \{ +163 return s_mp_sub (x, n, x); +164 \} +165 return MP_OKAY; +166 \} +167 #endif +168 \end{alltt} \end{small} -The $\hat W$ array is first filled with digits of $x$ on line 48 then the rest of the digits are zeroed on line 55. Both loops share +The $\hat W$ array is first filled with digits of $x$ on line 50 then the rest of the digits are zeroed on line 54. Both loops share the same alias variables to make the code easier to read. The value of $\mu$ is calculated in an interesting fashion. First the value $\hat W_{ix}$ is reduced modulo $\beta$ and cast to a mp\_digit. This -forces the compiler to use a single precision multiplication and prevents any concerns about loss of precision. Line 110 fixes the carry +forces the compiler to use a single precision multiplication and prevents any concerns about loss of precision. Line 109 fixes the carry for the next iteration of the loop by propagating the carry from $\hat W_{ix}$ to $\hat W_{ix+1}$. -The for loop on line 109 propagates the rest of the carries upwards through the columns. The for loop on line 126 reduces the columns +The for loop on line 108 propagates the rest of the carries upwards through the columns. The for loop on line 125 reduces the columns modulo $\beta$ and shifts them $k$ places at the same time. The alias $\_ \hat W$ actually refers to the array $\hat W$ starting at the $n.used$'th digit, that is $\_ \hat W_{t} = \hat W_{n.used + t}$. @@ -4255,6 +6562,47 @@ to calculate $1/n_0$ when $\beta$ is a power of two. \hspace{-5.1mm}{\bf File}: bn\_mp\_montgomery\_setup.c \vspace{-3mm} \begin{alltt} +016 +017 /* setups the montgomery reduction stuff */ +018 int +019 mp_montgomery_setup (mp_int * n, mp_digit * rho) +020 \{ +021 mp_digit x, b; +022 +023 /* fast inversion mod 2**k +024 * +025 * Based on the fact that +026 * +027 * XA = 1 (mod 2**n) => (X(2-XA)) A = 1 (mod 2**2n) +028 * => 2*X*A - X*X*A*A = 1 +029 * => 2*(1) - (1) = 1 +030 */ +031 b = n->dp[0]; +032 +033 if ((b & 1) == 0) \{ +034 return MP_VAL; +035 \} +036 +037 x = (((b + 2) & 4) << 1) + b; /* here x*a==1 mod 2**4 */ +038 x *= 2 - b * x; /* here x*a==1 mod 2**8 */ +039 #if !defined(MP_8BIT) +040 x *= 2 - b * x; /* here x*a==1 mod 2**16 */ +041 #endif +042 #if defined(MP_64BIT) || !(defined(MP_8BIT) || defined(MP_16BIT)) +043 x *= 2 - b * x; /* here x*a==1 mod 2**32 */ +044 #endif +045 #ifdef MP_64BIT +046 x *= 2 - b * x; /* here x*a==1 mod 2**64 */ +047 #endif +048 +049 /* rho = -1/m mod b */ +050 *rho = (unsigned long)(((mp_word)1 << ((mp_word) DIGIT_BIT)) - x) & MP_MAS + K; +051 +052 return MP_OKAY; +053 \} +054 #endif +055 \end{alltt} \end{small} @@ -4447,22 +6795,97 @@ at step 3. \hspace{-5.1mm}{\bf File}: bn\_mp\_dr\_reduce.c \vspace{-3mm} \begin{alltt} +016 +017 /* reduce "x" in place modulo "n" using the Diminished Radix algorithm. +018 * +019 * Based on algorithm from the paper +020 * +021 * "Generating Efficient Primes for Discrete Log Cryptosystems" +022 * Chae Hoon Lim, Pil Joong Lee, +023 * POSTECH Information Research Laboratories +024 * +025 * The modulus must be of a special format [see manual] +026 * +027 * Has been modified to use algorithm 7.10 from the LTM book instead +028 * +029 * Input x must be in the range 0 <= x <= (n-1)**2 +030 */ +031 int +032 mp_dr_reduce (mp_int * x, mp_int * n, mp_digit k) +033 \{ +034 int err, i, m; +035 mp_word r; +036 mp_digit mu, *tmpx1, *tmpx2; +037 +038 /* m = digits in modulus */ +039 m = n->used; +040 +041 /* ensure that "x" has at least 2m digits */ +042 if (x->alloc < m + m) \{ +043 if ((err = mp_grow (x, m + m)) != MP_OKAY) \{ +044 return err; +045 \} +046 \} +047 +048 /* top of loop, this is where the code resumes if +049 * another reduction pass is required. +050 */ +051 top: +052 /* aliases for digits */ +053 /* alias for lower half of x */ +054 tmpx1 = x->dp; +055 +056 /* alias for upper half of x, or x/B**m */ +057 tmpx2 = x->dp + m; +058 +059 /* set carry to zero */ +060 mu = 0; +061 +062 /* compute (x mod B**m) + k * [x/B**m] inline and inplace */ +063 for (i = 0; i < m; i++) \{ +064 r = ((mp_word)*tmpx2++) * ((mp_word)k) + *tmpx1 + mu; +065 *tmpx1++ = (mp_digit)(r & MP_MASK); +066 mu = (mp_digit)(r >> ((mp_word)DIGIT_BIT)); +067 \} +068 +069 /* set final carry */ +070 *tmpx1++ = mu; +071 +072 /* zero words above m */ +073 for (i = m + 1; i < x->used; i++) \{ +074 *tmpx1++ = 0; +075 \} +076 +077 /* clamp, sub and return */ +078 mp_clamp (x); +079 +080 /* if x >= n then subtract and reduce again +081 * Each successive "recursion" makes the input smaller and smaller. +082 */ +083 if (mp_cmp_mag (x, n) != MP_LT) \{ +084 s_mp_sub(x, n, x); +085 goto top; +086 \} +087 return MP_OKAY; +088 \} +089 #endif +090 \end{alltt} \end{small} -The first step is to grow $x$ as required to $2m$ digits since the reduction is performed in place on $x$. The label on line 52 is where +The first step is to grow $x$ as required to $2m$ digits since the reduction is performed in place on $x$. The label on line 51 is where the algorithm will resume if further reduction passes are required. In theory it could be placed at the top of the function however, the size of the modulus and question of whether $x$ is large enough are invariant after the first pass meaning that it would be a waste of time. The aliases $tmpx1$ and $tmpx2$ refer to the digits of $x$ where the latter is offset by $m$ digits. By reading digits from $x$ offset by $m$ digits -a division by $\beta^m$ can be simulated virtually for free. The loop on line 64 performs the bulk of the work (\textit{corresponds to step 4 of algorithm 7.11}) +a division by $\beta^m$ can be simulated virtually for free. The loop on line 63 performs the bulk of the work (\textit{corresponds to step 4 of algorithm 7.11}) in this algorithm. -By line 67 the pointer $tmpx1$ points to the $m$'th digit of $x$ which is where the final carry will be placed. Similarly by line 74 the +By line 70 the pointer $tmpx1$ points to the $m$'th digit of $x$ which is where the final carry will be placed. Similarly by line 73 the same pointer will point to the $m+1$'th digit where the zeroes will be placed. Since the algorithm is only valid if both $x$ and $n$ are greater than zero an unsigned comparison suffices to determine if another pass is required. -With the same logic at line 81 the value of $x$ is known to be greater than or equal to $n$ meaning that an unsigned subtraction can be used +With the same logic at line 84 the value of $x$ is known to be greater than or equal to $n$ meaning that an unsigned subtraction can be used as well. Since the destination of the subtraction is the larger of the inputs the call to algorithm s\_mp\_sub cannot fail and the return code does not need to be checked. @@ -4490,6 +6913,19 @@ completeness. \hspace{-5.1mm}{\bf File}: bn\_mp\_dr\_setup.c \vspace{-3mm} \begin{alltt} +016 +017 /* determines the setup value */ +018 void mp_dr_setup(mp_int *a, mp_digit *d) +019 \{ +020 /* the casts are required if DIGIT_BIT is one less than +021 * the number of bits in a mp_digit [e.g. DIGIT_BIT==31] +022 */ +023 *d = (mp_digit)((((mp_word)1) << ((mp_word)DIGIT_BIT)) - +024 ((mp_word)a->dp[0])); +025 \} +026 +027 #endif +028 \end{alltt} \end{small} @@ -4525,6 +6961,30 @@ step 3 then $n$ must be of Diminished Radix form. \hspace{-5.1mm}{\bf File}: bn\_mp\_dr\_is\_modulus.c \vspace{-3mm} \begin{alltt} +016 +017 /* determines if a number is a valid DR modulus */ +018 int mp_dr_is_modulus(mp_int *a) +019 \{ +020 int ix; +021 +022 /* must be at least two digits */ +023 if (a->used < 2) \{ +024 return 0; +025 \} +026 +027 /* must be of the form b**k - a [a <= b] so all +028 * but the first digit must be equal to -1 (mod b). +029 */ +030 for (ix = 1; ix < a->used; ix++) \{ +031 if (a->dp[ix] != MP_MASK) \{ +032 return 0; +033 \} +034 \} +035 return 1; +036 \} +037 +038 #endif +039 \end{alltt} \end{small} @@ -4568,11 +7028,53 @@ shift which makes the algorithm fairly inexpensive to use. \hspace{-5.1mm}{\bf File}: bn\_mp\_reduce\_2k.c \vspace{-3mm} \begin{alltt} +016 +017 /* reduces a modulo n where n is of the form 2**p - d */ +018 int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d) +019 \{ +020 mp_int q; +021 int p, res; +022 +023 if ((res = mp_init(&q)) != MP_OKAY) \{ +024 return res; +025 \} +026 +027 p = mp_count_bits(n); +028 top: +029 /* q = a/2**p, a = a mod 2**p */ +030 if ((res = mp_div_2d(a, p, &q, a)) != MP_OKAY) \{ +031 goto ERR; +032 \} +033 +034 if (d != 1) \{ +035 /* q = q * d */ +036 if ((res = mp_mul_d(&q, d, &q)) != MP_OKAY) \{ +037 goto ERR; +038 \} +039 \} +040 +041 /* a = a + q */ +042 if ((res = s_mp_add(a, &q, a)) != MP_OKAY) \{ +043 goto ERR; +044 \} +045 +046 if (mp_cmp_mag(a, n) != MP_LT) \{ +047 s_mp_sub(a, n, a); +048 goto top; +049 \} +050 +051 ERR: +052 mp_clear(&q); +053 return res; +054 \} +055 +056 #endif +057 \end{alltt} \end{small} The algorithm mp\_count\_bits calculates the number of bits in an mp\_int which is used to find the initial value of $p$. The call to mp\_div\_2d -on line 31 calculates both the quotient $q$ and the remainder $a$ required. By doing both in a single function call the code size +on line 30 calculates both the quotient $q$ and the remainder $a$ required. By doing both in a single function call the code size is kept fairly small. The multiplication by $k$ is only performed if $k > 1$. This allows reductions modulo $2^p - 1$ to be performed without any multiplications. @@ -4610,6 +7112,34 @@ is sufficient to solve for $k$. Alternatively if $n$ has more than one digit th \hspace{-5.1mm}{\bf File}: bn\_mp\_reduce\_2k\_setup.c \vspace{-3mm} \begin{alltt} +016 +017 /* determines the setup value */ +018 int mp_reduce_2k_setup(mp_int *a, mp_digit *d) +019 \{ +020 int res, p; +021 mp_int tmp; +022 +023 if ((res = mp_init(&tmp)) != MP_OKAY) \{ +024 return res; +025 \} +026 +027 p = mp_count_bits(a); +028 if ((res = mp_2expt(&tmp, p)) != MP_OKAY) \{ +029 mp_clear(&tmp); +030 return res; +031 \} +032 +033 if ((res = s_mp_sub(&tmp, a, &tmp)) != MP_OKAY) \{ +034 mp_clear(&tmp); +035 return res; +036 \} +037 +038 *d = tmp.dp[0]; +039 mp_clear(&tmp); +040 return MP_OKAY; +041 \} +042 #endif +043 \end{alltt} \end{small} @@ -4654,6 +7184,39 @@ This algorithm quickly determines if a modulus is of the form required for algor \hspace{-5.1mm}{\bf File}: bn\_mp\_reduce\_is\_2k.c \vspace{-3mm} \begin{alltt} +016 +017 /* determines if mp_reduce_2k can be used */ +018 int mp_reduce_is_2k(mp_int *a) +019 \{ +020 int ix, iy, iw; +021 mp_digit iz; +022 +023 if (a->used == 0) \{ +024 return MP_NO; +025 \} else if (a->used == 1) \{ +026 return MP_YES; +027 \} else if (a->used > 1) \{ +028 iy = mp_count_bits(a); +029 iz = 1; +030 iw = 1; +031 +032 /* Test every bit from the second digit up, must be 1 */ +033 for (ix = DIGIT_BIT; ix < iy; ix++) \{ +034 if ((a->dp[iw] & iz) == 0) \{ +035 return MP_NO; +036 \} +037 iz <<= 1; +038 if (iz > (mp_digit)MP_MASK) \{ +039 ++iw; +040 iz = 1; +041 \} +042 \} +043 \} +044 return MP_YES; +045 \} +046 +047 #endif +048 \end{alltt} \end{small} @@ -4826,13 +7389,51 @@ iteration of the loop moves the bits of the exponent $b$ upwards to the most sig \hspace{-5.1mm}{\bf File}: bn\_mp\_expt\_d.c \vspace{-3mm} \begin{alltt} +016 +017 /* calculate c = a**b using a square-multiply algorithm */ +018 int mp_expt_d (mp_int * a, mp_digit b, mp_int * c) +019 \{ +020 int res, x; +021 mp_int g; +022 +023 if ((res = mp_init_copy (&g, a)) != MP_OKAY) \{ +024 return res; +025 \} +026 +027 /* set initial result */ +028 mp_set (c, 1); +029 +030 for (x = 0; x < (int) DIGIT_BIT; x++) \{ +031 /* square */ +032 if ((res = mp_sqr (c, c)) != MP_OKAY) \{ +033 mp_clear (&g); +034 return res; +035 \} +036 +037 /* if the bit is set multiply */ +038 if ((b & (mp_digit) (((mp_digit)1) << (DIGIT_BIT - 1))) != 0) \{ +039 if ((res = mp_mul (c, &g, c)) != MP_OKAY) \{ +040 mp_clear (&g); +041 return res; +042 \} +043 \} +044 +045 /* shift to next bit */ +046 b <<= 1; +047 \} +048 +049 mp_clear (&g); +050 return MP_OKAY; +051 \} +052 #endif +053 \end{alltt} \end{small} -Line 29 sets the initial value of the result to $1$. Next the loop on line 31 steps through each bit of the exponent starting from -the most significant down towards the least significant. The invariant squaring operation placed on line 33 is performed first. After +Line 28 sets the initial value of the result to $1$. Next the loop on line 30 steps through each bit of the exponent starting from +the most significant down towards the least significant. The invariant squaring operation placed on line 32 is performed first. After the squaring the result $c$ is multiplied by the base $g$ if and only if the most significant bit of the exponent is set. The shift on line -47 moves all of the bits of the exponent upwards towards the most significant location. +46 moves all of the bits of the exponent upwards towards the most significant location. \section{$k$-ary Exponentiation} When calculating an exponentiation the most time consuming bottleneck is the multiplications which are in general a small factor @@ -5013,16 +7614,110 @@ algorithm since their arguments are essentially the same (\textit{two mp\_ints a \hspace{-5.1mm}{\bf File}: bn\_mp\_exptmod.c \vspace{-3mm} \begin{alltt} +016 +017 +018 /* this is a shell function that calls either the normal or Montgomery +019 * exptmod functions. Originally the call to the montgomery code was +020 * embedded in the normal function but that wasted alot of stack space +021 * for nothing (since 99% of the time the Montgomery code would be called) +022 */ +023 int mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y) +024 \{ +025 int dr; +026 +027 /* modulus P must be positive */ +028 if (P->sign == MP_NEG) \{ +029 return MP_VAL; +030 \} +031 +032 /* if exponent X is negative we have to recurse */ +033 if (X->sign == MP_NEG) \{ +034 #ifdef BN_MP_INVMOD_C +035 mp_int tmpG, tmpX; +036 int err; +037 +038 /* first compute 1/G mod P */ +039 if ((err = mp_init(&tmpG)) != MP_OKAY) \{ +040 return err; +041 \} +042 if ((err = mp_invmod(G, P, &tmpG)) != MP_OKAY) \{ +043 mp_clear(&tmpG); +044 return err; +045 \} +046 +047 /* now get |X| */ +048 if ((err = mp_init(&tmpX)) != MP_OKAY) \{ +049 mp_clear(&tmpG); +050 return err; +051 \} +052 if ((err = mp_abs(X, &tmpX)) != MP_OKAY) \{ +053 mp_clear_multi(&tmpG, &tmpX, NULL); +054 return err; +055 \} +056 +057 /* and now compute (1/G)**|X| instead of G**X [X < 0] */ +058 err = mp_exptmod(&tmpG, &tmpX, P, Y); +059 mp_clear_multi(&tmpG, &tmpX, NULL); +060 return err; +061 #else +062 /* no invmod */ +063 return MP_VAL; +064 #endif +065 \} +066 +067 /* modified diminished radix reduction */ +068 #if defined(BN_MP_REDUCE_IS_2K_L_C) && defined(BN_MP_REDUCE_2K_L_C) && defin + ed(BN_S_MP_EXPTMOD_C) +069 if (mp_reduce_is_2k_l(P) == MP_YES) \{ +070 return s_mp_exptmod(G, X, P, Y, 1); +071 \} +072 #endif +073 +074 #ifdef BN_MP_DR_IS_MODULUS_C +075 /* is it a DR modulus? */ +076 dr = mp_dr_is_modulus(P); +077 #else +078 /* default to no */ +079 dr = 0; +080 #endif +081 +082 #ifdef BN_MP_REDUCE_IS_2K_C +083 /* if not, is it a unrestricted DR modulus? */ +084 if (dr == 0) \{ +085 dr = mp_reduce_is_2k(P) << 1; +086 \} +087 #endif +088 +089 /* if the modulus is odd or dr != 0 use the montgomery method */ +090 #ifdef BN_MP_EXPTMOD_FAST_C +091 if (mp_isodd (P) == 1 || dr != 0) \{ +092 return mp_exptmod_fast (G, X, P, Y, dr); +093 \} else \{ +094 #endif +095 #ifdef BN_S_MP_EXPTMOD_C +096 /* otherwise use the generic Barrett reduction technique */ +097 return s_mp_exptmod (G, X, P, Y, 0); +098 #else +099 /* no exptmod for evens */ +100 return MP_VAL; +101 #endif +102 #ifdef BN_MP_EXPTMOD_FAST_C +103 \} +104 #endif +105 \} +106 +107 #endif +108 \end{alltt} \end{small} -In order to keep the algorithms in a known state the first step on line 29 is to reject any negative modulus as input. If the exponent is +In order to keep the algorithms in a known state the first step on line 28 is to reject any negative modulus as input. If the exponent is negative the algorithm tries to perform a modular exponentiation with the modular inverse of the base $G$. The temporary variable $tmpG$ is assigned the modular inverse of $G$ and $tmpX$ is assigned the absolute value of $X$. The algorithm will recuse with these new values with a positive exponent. -If the exponent is positive the algorithm resumes the exponentiation. Line 77 determines if the modulus is of the restricted Diminished Radix -form. If it is not line 70 attempts to determine if it is of a unrestricted Diminished Radix form. The integer $dr$ will take on one +If the exponent is positive the algorithm resumes the exponentiation. Line 76 determines if the modulus is of the restricted Diminished Radix +form. If it is not line 69 attempts to determine if it is of a unrestricted Diminished Radix form. The integer $dr$ will take on one of three values. \begin{enumerate} @@ -5192,17 +7887,251 @@ a Left-to-Right algorithm is used to process the remaining few bits. \hspace{-5.1mm}{\bf File}: bn\_s\_mp\_exptmod.c \vspace{-3mm} \begin{alltt} +016 #ifdef MP_LOW_MEM +017 #define TAB_SIZE 32 +018 #else +019 #define TAB_SIZE 256 +020 #endif +021 +022 int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y, int redmod + e) +023 \{ +024 mp_int M[TAB_SIZE], res, mu; +025 mp_digit buf; +026 int err, bitbuf, bitcpy, bitcnt, mode, digidx, x, y, winsize; +027 int (*redux)(mp_int*,mp_int*,mp_int*); +028 +029 /* find window size */ +030 x = mp_count_bits (X); +031 if (x <= 7) \{ +032 winsize = 2; +033 \} else if (x <= 36) \{ +034 winsize = 3; +035 \} else if (x <= 140) \{ +036 winsize = 4; +037 \} else if (x <= 450) \{ +038 winsize = 5; +039 \} else if (x <= 1303) \{ +040 winsize = 6; +041 \} else if (x <= 3529) \{ +042 winsize = 7; +043 \} else \{ +044 winsize = 8; +045 \} +046 +047 #ifdef MP_LOW_MEM +048 if (winsize > 5) \{ +049 winsize = 5; +050 \} +051 #endif +052 +053 /* init M array */ +054 /* init first cell */ +055 if ((err = mp_init(&M[1])) != MP_OKAY) \{ +056 return err; +057 \} +058 +059 /* now init the second half of the array */ +060 for (x = 1<<(winsize-1); x < (1 << winsize); x++) \{ +061 if ((err = mp_init(&M[x])) != MP_OKAY) \{ +062 for (y = 1<<(winsize-1); y < x; y++) \{ +063 mp_clear (&M[y]); +064 \} +065 mp_clear(&M[1]); +066 return err; +067 \} +068 \} +069 +070 /* create mu, used for Barrett reduction */ +071 if ((err = mp_init (&mu)) != MP_OKAY) \{ +072 goto LBL_M; +073 \} +074 +075 if (redmode == 0) \{ +076 if ((err = mp_reduce_setup (&mu, P)) != MP_OKAY) \{ +077 goto LBL_MU; +078 \} +079 redux = mp_reduce; +080 \} else \{ +081 if ((err = mp_reduce_2k_setup_l (P, &mu)) != MP_OKAY) \{ +082 goto LBL_MU; +083 \} +084 redux = mp_reduce_2k_l; +085 \} +086 +087 /* create M table +088 * +089 * The M table contains powers of the base, +090 * e.g. M[x] = G**x mod P +091 * +092 * The first half of the table is not +093 * computed though accept for M[0] and M[1] +094 */ +095 if ((err = mp_mod (G, P, &M[1])) != MP_OKAY) \{ +096 goto LBL_MU; +097 \} +098 +099 /* compute the value at M[1<<(winsize-1)] by squaring +100 * M[1] (winsize-1) times +101 */ +102 if ((err = mp_copy (&M[1], &M[1 << (winsize - 1)])) != MP_OKAY) \{ +103 goto LBL_MU; +104 \} +105 +106 for (x = 0; x < (winsize - 1); x++) \{ +107 /* square it */ +108 if ((err = mp_sqr (&M[1 << (winsize - 1)], +109 &M[1 << (winsize - 1)])) != MP_OKAY) \{ +110 goto LBL_MU; +111 \} +112 +113 /* reduce modulo P */ +114 if ((err = redux (&M[1 << (winsize - 1)], P, &mu)) != MP_OKAY) \{ +115 goto LBL_MU; +116 \} +117 \} +118 +119 /* create upper table, that is M[x] = M[x-1] * M[1] (mod P) +120 * for x = (2**(winsize - 1) + 1) to (2**winsize - 1) +121 */ +122 for (x = (1 << (winsize - 1)) + 1; x < (1 << winsize); x++) \{ +123 if ((err = mp_mul (&M[x - 1], &M[1], &M[x])) != MP_OKAY) \{ +124 goto LBL_MU; +125 \} +126 if ((err = redux (&M[x], P, &mu)) != MP_OKAY) \{ +127 goto LBL_MU; +128 \} +129 \} +130 +131 /* setup result */ +132 if ((err = mp_init (&res)) != MP_OKAY) \{ +133 goto LBL_MU; +134 \} +135 mp_set (&res, 1); +136 +137 /* set initial mode and bit cnt */ +138 mode = 0; +139 bitcnt = 1; +140 buf = 0; +141 digidx = X->used - 1; +142 bitcpy = 0; +143 bitbuf = 0; +144 +145 for (;;) \{ +146 /* grab next digit as required */ +147 if (--bitcnt == 0) \{ +148 /* if digidx == -1 we are out of digits */ +149 if (digidx == -1) \{ +150 break; +151 \} +152 /* read next digit and reset the bitcnt */ +153 buf = X->dp[digidx--]; +154 bitcnt = (int) DIGIT_BIT; +155 \} +156 +157 /* grab the next msb from the exponent */ +158 y = (buf >> (mp_digit)(DIGIT_BIT - 1)) & 1; +159 buf <<= (mp_digit)1; +160 +161 /* if the bit is zero and mode == 0 then we ignore it +162 * These represent the leading zero bits before the first 1 bit +163 * in the exponent. Technically this opt is not required but it +164 * does lower the # of trivial squaring/reductions used +165 */ +166 if (mode == 0 && y == 0) \{ +167 continue; +168 \} +169 +170 /* if the bit is zero and mode == 1 then we square */ +171 if (mode == 1 && y == 0) \{ +172 if ((err = mp_sqr (&res, &res)) != MP_OKAY) \{ +173 goto LBL_RES; +174 \} +175 if ((err = redux (&res, P, &mu)) != MP_OKAY) \{ +176 goto LBL_RES; +177 \} +178 continue; +179 \} +180 +181 /* else we add it to the window */ +182 bitbuf |= (y << (winsize - ++bitcpy)); +183 mode = 2; +184 +185 if (bitcpy == winsize) \{ +186 /* ok window is filled so square as required and multiply */ +187 /* square first */ +188 for (x = 0; x < winsize; x++) \{ +189 if ((err = mp_sqr (&res, &res)) != MP_OKAY) \{ +190 goto LBL_RES; +191 \} +192 if ((err = redux (&res, P, &mu)) != MP_OKAY) \{ +193 goto LBL_RES; +194 \} +195 \} +196 +197 /* then multiply */ +198 if ((err = mp_mul (&res, &M[bitbuf], &res)) != MP_OKAY) \{ +199 goto LBL_RES; +200 \} +201 if ((err = redux (&res, P, &mu)) != MP_OKAY) \{ +202 goto LBL_RES; +203 \} +204 +205 /* empty window and reset */ +206 bitcpy = 0; +207 bitbuf = 0; +208 mode = 1; +209 \} +210 \} +211 +212 /* if bits remain then square/multiply */ +213 if (mode == 2 && bitcpy > 0) \{ +214 /* square then multiply if the bit is set */ +215 for (x = 0; x < bitcpy; x++) \{ +216 if ((err = mp_sqr (&res, &res)) != MP_OKAY) \{ +217 goto LBL_RES; +218 \} +219 if ((err = redux (&res, P, &mu)) != MP_OKAY) \{ +220 goto LBL_RES; +221 \} +222 +223 bitbuf <<= 1; +224 if ((bitbuf & (1 << winsize)) != 0) \{ +225 /* then multiply */ +226 if ((err = mp_mul (&res, &M[1], &res)) != MP_OKAY) \{ +227 goto LBL_RES; +228 \} +229 if ((err = redux (&res, P, &mu)) != MP_OKAY) \{ +230 goto LBL_RES; +231 \} +232 \} +233 \} +234 \} +235 +236 mp_exch (&res, Y); +237 err = MP_OKAY; +238 LBL_RES:mp_clear (&res); +239 LBL_MU:mp_clear (&mu); +240 LBL_M: +241 mp_clear(&M[1]); +242 for (x = 1<<(winsize-1); x < (1 << winsize); x++) \{ +243 mp_clear (&M[x]); +244 \} +245 return err; +246 \} +247 #endif +248 \end{alltt} \end{small} -Lines 32 through 46 determine the optimal window size based on the length of the exponent in bits. The window divisions are sorted +Lines 31 through 45 determine the optimal window size based on the length of the exponent in bits. The window divisions are sorted from smallest to greatest so that in each \textbf{if} statement only one condition must be tested. For example, by the \textbf{if} statement -on line 38 the value of $x$ is already known to be greater than $140$. +on line 37 the value of $x$ is already known to be greater than $140$. -The conditional piece of code beginning on line 48 allows the window size to be restricted to five bits. This logic is used to ensure +The conditional piece of code beginning on line 47 allows the window size to be restricted to five bits. This logic is used to ensure the table of precomputed powers of $G$ remains relatively small. -The for loop on line 61 initializes the $M$ array while lines 72 and 77 through 86 initialize the reduction +The for loop on line 60 initializes the $M$ array while lines 71 and 76 through 85 initialize the reduction function that will be used for this modulus. -- More later. @@ -5237,6 +8166,35 @@ equivalent to $m \cdot 2^k$. By this logic when $m = 1$ a quick power of two ca \hspace{-5.1mm}{\bf File}: bn\_mp\_2expt.c \vspace{-3mm} \begin{alltt} +016 +017 /* computes a = 2**b +018 * +019 * Simple algorithm which zeroes the int, grows it then just sets one bit +020 * as required. +021 */ +022 int +023 mp_2expt (mp_int * a, int b) +024 \{ +025 int res; +026 +027 /* zero a as per default */ +028 mp_zero (a); +029 +030 /* grow a to accomodate the single bit */ +031 if ((res = mp_grow (a, b / DIGIT_BIT + 1)) != MP_OKAY) \{ +032 return res; +033 \} +034 +035 /* set the used count of where the bit will go */ +036 a->used = b / DIGIT_BIT + 1; +037 +038 /* put the single bit in its place */ +039 a->dp[b / DIGIT_BIT] = ((mp_digit)1) << (b % DIGIT_BIT); +040 +041 return MP_OKAY; +042 \} +043 #endif +044 \end{alltt} \end{small} @@ -5485,6 +8443,279 @@ respectively be replaced with a zero. \hspace{-5.1mm}{\bf File}: bn\_mp\_div.c \vspace{-3mm} \begin{alltt} +016 +017 #ifdef BN_MP_DIV_SMALL +018 +019 /* slower bit-bang division... also smaller */ +020 int mp_div(mp_int * a, mp_int * b, mp_int * c, mp_int * d) +021 \{ +022 mp_int ta, tb, tq, q; +023 int res, n, n2; +024 +025 /* is divisor zero ? */ +026 if (mp_iszero (b) == 1) \{ +027 return MP_VAL; +028 \} +029 +030 /* if a < b then q=0, r = a */ +031 if (mp_cmp_mag (a, b) == MP_LT) \{ +032 if (d != NULL) \{ +033 res = mp_copy (a, d); +034 \} else \{ +035 res = MP_OKAY; +036 \} +037 if (c != NULL) \{ +038 mp_zero (c); +039 \} +040 return res; +041 \} +042 +043 /* init our temps */ +044 if ((res = mp_init_multi(&ta, &tb, &tq, &q, NULL) != MP_OKAY)) \{ +045 return res; +046 \} +047 +048 +049 mp_set(&tq, 1); +050 n = mp_count_bits(a) - mp_count_bits(b); +051 if (((res = mp_abs(a, &ta)) != MP_OKAY) || +052 ((res = mp_abs(b, &tb)) != MP_OKAY) || +053 ((res = mp_mul_2d(&tb, n, &tb)) != MP_OKAY) || +054 ((res = mp_mul_2d(&tq, n, &tq)) != MP_OKAY)) \{ +055 goto LBL_ERR; +056 \} +057 +058 while (n-- >= 0) \{ +059 if (mp_cmp(&tb, &ta) != MP_GT) \{ +060 if (((res = mp_sub(&ta, &tb, &ta)) != MP_OKAY) || +061 ((res = mp_add(&q, &tq, &q)) != MP_OKAY)) \{ +062 goto LBL_ERR; +063 \} +064 \} +065 if (((res = mp_div_2d(&tb, 1, &tb, NULL)) != MP_OKAY) || +066 ((res = mp_div_2d(&tq, 1, &tq, NULL)) != MP_OKAY)) \{ +067 goto LBL_ERR; +068 \} +069 \} +070 +071 /* now q == quotient and ta == remainder */ +072 n = a->sign; +073 n2 = (a->sign == b->sign ? MP_ZPOS : MP_NEG); +074 if (c != NULL) \{ +075 mp_exch(c, &q); +076 c->sign = (mp_iszero(c) == MP_YES) ? MP_ZPOS : n2; +077 \} +078 if (d != NULL) \{ +079 mp_exch(d, &ta); +080 d->sign = (mp_iszero(d) == MP_YES) ? MP_ZPOS : n; +081 \} +082 LBL_ERR: +083 mp_clear_multi(&ta, &tb, &tq, &q, NULL); +084 return res; +085 \} +086 +087 #else +088 +089 /* integer signed division. +090 * c*b + d == a [e.g. a/b, c=quotient, d=remainder] +091 * HAC pp.598 Algorithm 14.20 +092 * +093 * Note that the description in HAC is horribly +094 * incomplete. For example, it doesn't consider +095 * the case where digits are removed from 'x' in +096 * the inner loop. It also doesn't consider the +097 * case that y has fewer than three digits, etc.. +098 * +099 * The overall algorithm is as described as +100 * 14.20 from HAC but fixed to treat these cases. +101 */ +102 int mp_div (mp_int * a, mp_int * b, mp_int * c, mp_int * d) +103 \{ +104 mp_int q, x, y, t1, t2; +105 int res, n, t, i, norm, neg; +106 +107 /* is divisor zero ? */ +108 if (mp_iszero (b) == 1) \{ +109 return MP_VAL; +110 \} +111 +112 /* if a < b then q=0, r = a */ +113 if (mp_cmp_mag (a, b) == MP_LT) \{ +114 if (d != NULL) \{ +115 res = mp_copy (a, d); +116 \} else \{ +117 res = MP_OKAY; +118 \} +119 if (c != NULL) \{ +120 mp_zero (c); +121 \} +122 return res; +123 \} +124 +125 if ((res = mp_init_size (&q, a->used + 2)) != MP_OKAY) \{ +126 return res; +127 \} +128 q.used = a->used + 2; +129 +130 if ((res = mp_init (&t1)) != MP_OKAY) \{ +131 goto LBL_Q; +132 \} +133 +134 if ((res = mp_init (&t2)) != MP_OKAY) \{ +135 goto LBL_T1; +136 \} +137 +138 if ((res = mp_init_copy (&x, a)) != MP_OKAY) \{ +139 goto LBL_T2; +140 \} +141 +142 if ((res = mp_init_copy (&y, b)) != MP_OKAY) \{ +143 goto LBL_X; +144 \} +145 +146 /* fix the sign */ +147 neg = (a->sign == b->sign) ? MP_ZPOS : MP_NEG; +148 x.sign = y.sign = MP_ZPOS; +149 +150 /* normalize both x and y, ensure that y >= b/2, [b == 2**DIGIT_BIT] */ +151 norm = mp_count_bits(&y) % DIGIT_BIT; +152 if (norm < (int)(DIGIT_BIT-1)) \{ +153 norm = (DIGIT_BIT-1) - norm; +154 if ((res = mp_mul_2d (&x, norm, &x)) != MP_OKAY) \{ +155 goto LBL_Y; +156 \} +157 if ((res = mp_mul_2d (&y, norm, &y)) != MP_OKAY) \{ +158 goto LBL_Y; +159 \} +160 \} else \{ +161 norm = 0; +162 \} +163 +164 /* note hac does 0 based, so if used==5 then its 0,1,2,3,4, e.g. use 4 */ +165 n = x.used - 1; +166 t = y.used - 1; +167 +168 /* while (x >= y*b**n-t) do \{ q[n-t] += 1; x -= y*b**\{n-t\} \} */ +169 if ((res = mp_lshd (&y, n - t)) != MP_OKAY) \{ /* y = y*b**\{n-t\} */ +170 goto LBL_Y; +171 \} +172 +173 while (mp_cmp (&x, &y) != MP_LT) \{ +174 ++(q.dp[n - t]); +175 if ((res = mp_sub (&x, &y, &x)) != MP_OKAY) \{ +176 goto LBL_Y; +177 \} +178 \} +179 +180 /* reset y by shifting it back down */ +181 mp_rshd (&y, n - t); +182 +183 /* step 3. for i from n down to (t + 1) */ +184 for (i = n; i >= (t + 1); i--) \{ +185 if (i > x.used) \{ +186 continue; +187 \} +188 +189 /* step 3.1 if xi == yt then set q\{i-t-1\} to b-1, +190 * otherwise set q\{i-t-1\} to (xi*b + x\{i-1\})/yt */ +191 if (x.dp[i] == y.dp[t]) \{ +192 q.dp[i - t - 1] = ((((mp_digit)1) << DIGIT_BIT) - 1); +193 \} else \{ +194 mp_word tmp; +195 tmp = ((mp_word) x.dp[i]) << ((mp_word) DIGIT_BIT); +196 tmp |= ((mp_word) x.dp[i - 1]); +197 tmp /= ((mp_word) y.dp[t]); +198 if (tmp > (mp_word) MP_MASK) +199 tmp = MP_MASK; +200 q.dp[i - t - 1] = (mp_digit) (tmp & (mp_word) (MP_MASK)); +201 \} +202 +203 /* while (q\{i-t-1\} * (yt * b + y\{t-1\})) > +204 xi * b**2 + xi-1 * b + xi-2 +205 +206 do q\{i-t-1\} -= 1; +207 */ +208 q.dp[i - t - 1] = (q.dp[i - t - 1] + 1) & MP_MASK; +209 do \{ +210 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1) & MP_MASK; +211 +212 /* find left hand */ +213 mp_zero (&t1); +214 t1.dp[0] = (t - 1 < 0) ? 0 : y.dp[t - 1]; +215 t1.dp[1] = y.dp[t]; +216 t1.used = 2; +217 if ((res = mp_mul_d (&t1, q.dp[i - t - 1], &t1)) != MP_OKAY) \{ +218 goto LBL_Y; +219 \} +220 +221 /* find right hand */ +222 t2.dp[0] = (i - 2 < 0) ? 0 : x.dp[i - 2]; +223 t2.dp[1] = (i - 1 < 0) ? 0 : x.dp[i - 1]; +224 t2.dp[2] = x.dp[i]; +225 t2.used = 3; +226 \} while (mp_cmp_mag(&t1, &t2) == MP_GT); +227 +228 /* step 3.3 x = x - q\{i-t-1\} * y * b**\{i-t-1\} */ +229 if ((res = mp_mul_d (&y, q.dp[i - t - 1], &t1)) != MP_OKAY) \{ +230 goto LBL_Y; +231 \} +232 +233 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) \{ +234 goto LBL_Y; +235 \} +236 +237 if ((res = mp_sub (&x, &t1, &x)) != MP_OKAY) \{ +238 goto LBL_Y; +239 \} +240 +241 /* if x < 0 then \{ x = x + y*b**\{i-t-1\}; q\{i-t-1\} -= 1; \} */ +242 if (x.sign == MP_NEG) \{ +243 if ((res = mp_copy (&y, &t1)) != MP_OKAY) \{ +244 goto LBL_Y; +245 \} +246 if ((res = mp_lshd (&t1, i - t - 1)) != MP_OKAY) \{ +247 goto LBL_Y; +248 \} +249 if ((res = mp_add (&x, &t1, &x)) != MP_OKAY) \{ +250 goto LBL_Y; +251 \} +252 +253 q.dp[i - t - 1] = (q.dp[i - t - 1] - 1UL) & MP_MASK; +254 \} +255 \} +256 +257 /* now q is the quotient and x is the remainder +258 * [which we have to normalize] +259 */ +260 +261 /* get sign before writing to c */ +262 x.sign = x.used == 0 ? MP_ZPOS : a->sign; +263 +264 if (c != NULL) \{ +265 mp_clamp (&q); +266 mp_exch (&q, c); +267 c->sign = neg; +268 \} +269 +270 if (d != NULL) \{ +271 mp_div_2d (&x, norm, &x, NULL); +272 mp_exch (&x, d); +273 \} +274 +275 res = MP_OKAY; +276 +277 LBL_Y:mp_clear (&y); +278 LBL_X:mp_clear (&x); +279 LBL_T2:mp_clear (&t2); +280 LBL_T1:mp_clear (&t1); +281 LBL_Q:mp_clear (&q); +282 return res; +283 \} +284 +285 #endif +286 +287 #endif +288 \end{alltt} \end{small} @@ -5496,8 +8727,8 @@ algorithm with only the quotient is mp_div(&a, &b, &c, NULL); /* c = [a/b] */ \end{verbatim} -Lines 109 and 113 handle the two trivial cases of inputs which are division by zero and dividend smaller than the divisor -respectively. After the two trivial cases all of the temporary variables are initialized. Line 148 determines the sign of +Lines 108 and 113 handle the two trivial cases of inputs which are division by zero and dividend smaller than the divisor +respectively. After the two trivial cases all of the temporary variables are initialized. Line 147 determines the sign of the quotient and line 148 ensures that both $x$ and $y$ are positive. The number of bits in the leading digit is calculated on line 151. Implictly an mp\_int with $r$ digits will require $lg(\beta)(r-1) + k$ bits @@ -5508,11 +8739,11 @@ them to the left by $lg(\beta) - 1 - k$ bits. Throughout the variables $n$ and $t$ will represent the highest digit of $x$ and $y$ respectively. These are first used to produce the leading digit of the quotient. The loop beginning on line 184 will produce the remainder of the quotient digits. -The conditional ``continue'' on line 187 is used to prevent the algorithm from reading past the leading edge of $x$ which can occur when the +The conditional ``continue'' on line 186 is used to prevent the algorithm from reading past the leading edge of $x$ which can occur when the algorithm eliminates multiple non-zero digits in a single iteration. This ensures that $x_i$ is always non-zero since by definition the digits above the $i$'th position $x$ must be zero in order for the quotient to be precise\footnote{Precise as far as integer division is concerned.}. -Lines 214, 216 and 223 through 225 manually construct the high accuracy estimations by setting the digits of the two mp\_int +Lines 214, 216 and 222 through 225 manually construct the high accuracy estimations by setting the digits of the two mp\_int variables directly. \section{Single Digit Helpers} @@ -5550,6 +8781,99 @@ This algorithm initiates a temporary mp\_int with the value of the single digit \hspace{-5.1mm}{\bf File}: bn\_mp\_add\_d.c \vspace{-3mm} \begin{alltt} +016 +017 /* single digit addition */ +018 int +019 mp_add_d (mp_int * a, mp_digit b, mp_int * c) +020 \{ +021 int res, ix, oldused; +022 mp_digit *tmpa, *tmpc, mu; +023 +024 /* grow c as required */ +025 if (c->alloc < a->used + 1) \{ +026 if ((res = mp_grow(c, a->used + 1)) != MP_OKAY) \{ +027 return res; +028 \} +029 \} +030 +031 /* if a is negative and |a| >= b, call c = |a| - b */ +032 if (a->sign == MP_NEG && (a->used > 1 || a->dp[0] >= b)) \{ +033 /* temporarily fix sign of a */ +034 a->sign = MP_ZPOS; +035 +036 /* c = |a| - b */ +037 res = mp_sub_d(a, b, c); +038 +039 /* fix sign */ +040 a->sign = c->sign = MP_NEG; +041 +042 /* clamp */ +043 mp_clamp(c); +044 +045 return res; +046 \} +047 +048 /* old number of used digits in c */ +049 oldused = c->used; +050 +051 /* sign always positive */ +052 c->sign = MP_ZPOS; +053 +054 /* source alias */ +055 tmpa = a->dp; +056 +057 /* destination alias */ +058 tmpc = c->dp; +059 +060 /* if a is positive */ +061 if (a->sign == MP_ZPOS) \{ +062 /* add digit, after this we're propagating +063 * the carry. +064 */ +065 *tmpc = *tmpa++ + b; +066 mu = *tmpc >> DIGIT_BIT; +067 *tmpc++ &= MP_MASK; +068 +069 /* now handle rest of the digits */ +070 for (ix = 1; ix < a->used; ix++) \{ +071 *tmpc = *tmpa++ + mu; +072 mu = *tmpc >> DIGIT_BIT; +073 *tmpc++ &= MP_MASK; +074 \} +075 /* set final carry */ +076 ix++; +077 *tmpc++ = mu; +078 +079 /* setup size */ +080 c->used = a->used + 1; +081 \} else \{ +082 /* a was negative and |a| < b */ +083 c->used = 1; +084 +085 /* the result is a single digit */ +086 if (a->used == 1) \{ +087 *tmpc++ = b - a->dp[0]; +088 \} else \{ +089 *tmpc++ = b; +090 \} +091 +092 /* setup count so the clearing of oldused +093 * can fall through correctly +094 */ +095 ix = 1; +096 \} +097 +098 /* now zero to oldused */ +099 while (ix++ < oldused) \{ +100 *tmpc++ = 0; +101 \} +102 mp_clamp(c); +103 +104 return MP_OKAY; +105 \} +106 +107 #endif +108 \end{alltt} \end{small} @@ -5600,6 +8924,66 @@ Unlike the full multiplication algorithms this algorithm does not require any si \hspace{-5.1mm}{\bf File}: bn\_mp\_mul\_d.c \vspace{-3mm} \begin{alltt} +016 +017 /* multiply by a digit */ +018 int +019 mp_mul_d (mp_int * a, mp_digit b, mp_int * c) +020 \{ +021 mp_digit u, *tmpa, *tmpc; +022 mp_word r; +023 int ix, res, olduse; +024 +025 /* make sure c is big enough to hold a*b */ +026 if (c->alloc < a->used + 1) \{ +027 if ((res = mp_grow (c, a->used + 1)) != MP_OKAY) \{ +028 return res; +029 \} +030 \} +031 +032 /* get the original destinations used count */ +033 olduse = c->used; +034 +035 /* set the sign */ +036 c->sign = a->sign; +037 +038 /* alias for a->dp [source] */ +039 tmpa = a->dp; +040 +041 /* alias for c->dp [dest] */ +042 tmpc = c->dp; +043 +044 /* zero carry */ +045 u = 0; +046 +047 /* compute columns */ +048 for (ix = 0; ix < a->used; ix++) \{ +049 /* compute product and carry sum for this term */ +050 r = ((mp_word) u) + ((mp_word)*tmpa++) * ((mp_word)b); +051 +052 /* mask off higher bits to get a single digit */ +053 *tmpc++ = (mp_digit) (r & ((mp_word) MP_MASK)); +054 +055 /* send carry into next iteration */ +056 u = (mp_digit) (r >> ((mp_word) DIGIT_BIT)); +057 \} +058 +059 /* store final carry [if any] and increment ix offset */ +060 *tmpc++ = u; +061 ++ix; +062 +063 /* now zero digits above the top */ +064 while (ix++ < olduse) \{ +065 *tmpc++ = 0; +066 \} +067 +068 /* set used count */ +069 c->used = a->used + 1; +070 mp_clamp(c); +071 +072 return MP_OKAY; +073 \} +074 #endif +075 \end{alltt} \end{small} @@ -5655,13 +9039,104 @@ from chapter seven. \hspace{-5.1mm}{\bf File}: bn\_mp\_div\_d.c \vspace{-3mm} \begin{alltt} +016 +017 static int s_is_power_of_two(mp_digit b, int *p) +018 \{ +019 int x; +020 +021 for (x = 1; x < DIGIT_BIT; x++) \{ +022 if (b == (((mp_digit)1)<dp[0] & ((((mp_digit)1)<used)) != MP_OKAY) \{ +074 return res; +075 \} +076 +077 q.used = a->used; +078 q.sign = a->sign; +079 w = 0; +080 for (ix = a->used - 1; ix >= 0; ix--) \{ +081 w = (w << ((mp_word)DIGIT_BIT)) | ((mp_word)a->dp[ix]); +082 +083 if (w >= b) \{ +084 t = (mp_digit)(w / b); +085 w -= ((mp_word)t) * ((mp_word)b); +086 \} else \{ +087 t = 0; +088 \} +089 q.dp[ix] = (mp_digit)t; +090 \} +091 +092 if (d != NULL) \{ +093 *d = (mp_digit)w; +094 \} +095 +096 if (c != NULL) \{ +097 mp_clamp(&q); +098 mp_exch(&q, c); +099 \} +100 mp_clear(&q); +101 +102 return res; +103 \} +104 +105 #endif +106 \end{alltt} \end{small} Like the implementation of algorithm mp\_div this algorithm allows either of the quotient or remainder to be passed as a \textbf{NULL} pointer to indicate the respective value is not required. This allows a trivial single digit modular reduction algorithm, mp\_mod\_d to be created. -The division and remainder on lines 44 and @45,%@ can be replaced often by a single division on most processors. For example, the 32-bit x86 based +The division and remainder on lines 43 and @45,%@ can be replaced often by a single division on most processors. For example, the 32-bit x86 based processors can divide a 64-bit quantity by a 32-bit quantity and produce the quotient and remainder simultaneously. Unfortunately the GCC compiler does not recognize that optimization and will actually produce two function calls to find the quotient and remainder respectively. @@ -5729,6 +9204,119 @@ root. Ideally this algorithm is meant to find the $n$'th root of an input where \hspace{-5.1mm}{\bf File}: bn\_mp\_n\_root.c \vspace{-3mm} \begin{alltt} +016 +017 /* find the n'th root of an integer +018 * +019 * Result found such that (c)**b <= a and (c+1)**b > a +020 * +021 * This algorithm uses Newton's approximation +022 * x[i+1] = x[i] - f(x[i])/f'(x[i]) +023 * which will find the root in log(N) time where +024 * each step involves a fair bit. This is not meant to +025 * find huge roots [square and cube, etc]. +026 */ +027 int mp_n_root (mp_int * a, mp_digit b, mp_int * c) +028 \{ +029 mp_int t1, t2, t3; +030 int res, neg; +031 +032 /* input must be positive if b is even */ +033 if ((b & 1) == 0 && a->sign == MP_NEG) \{ +034 return MP_VAL; +035 \} +036 +037 if ((res = mp_init (&t1)) != MP_OKAY) \{ +038 return res; +039 \} +040 +041 if ((res = mp_init (&t2)) != MP_OKAY) \{ +042 goto LBL_T1; +043 \} +044 +045 if ((res = mp_init (&t3)) != MP_OKAY) \{ +046 goto LBL_T2; +047 \} +048 +049 /* if a is negative fudge the sign but keep track */ +050 neg = a->sign; +051 a->sign = MP_ZPOS; +052 +053 /* t2 = 2 */ +054 mp_set (&t2, 2); +055 +056 do \{ +057 /* t1 = t2 */ +058 if ((res = mp_copy (&t2, &t1)) != MP_OKAY) \{ +059 goto LBL_T3; +060 \} +061 +062 /* t2 = t1 - ((t1**b - a) / (b * t1**(b-1))) */ +063 +064 /* t3 = t1**(b-1) */ +065 if ((res = mp_expt_d (&t1, b - 1, &t3)) != MP_OKAY) \{ +066 goto LBL_T3; +067 \} +068 +069 /* numerator */ +070 /* t2 = t1**b */ +071 if ((res = mp_mul (&t3, &t1, &t2)) != MP_OKAY) \{ +072 goto LBL_T3; +073 \} +074 +075 /* t2 = t1**b - a */ +076 if ((res = mp_sub (&t2, a, &t2)) != MP_OKAY) \{ +077 goto LBL_T3; +078 \} +079 +080 /* denominator */ +081 /* t3 = t1**(b-1) * b */ +082 if ((res = mp_mul_d (&t3, b, &t3)) != MP_OKAY) \{ +083 goto LBL_T3; +084 \} +085 +086 /* t3 = (t1**b - a)/(b * t1**(b-1)) */ +087 if ((res = mp_div (&t2, &t3, &t3, NULL)) != MP_OKAY) \{ +088 goto LBL_T3; +089 \} +090 +091 if ((res = mp_sub (&t1, &t3, &t2)) != MP_OKAY) \{ +092 goto LBL_T3; +093 \} +094 \} while (mp_cmp (&t1, &t2) != MP_EQ); +095 +096 /* result can be off by a few so check */ +097 for (;;) \{ +098 if ((res = mp_expt_d (&t1, b, &t2)) != MP_OKAY) \{ +099 goto LBL_T3; +100 \} +101 +102 if (mp_cmp (&t2, a) == MP_GT) \{ +103 if ((res = mp_sub_d (&t1, 1, &t1)) != MP_OKAY) \{ +104 goto LBL_T3; +105 \} +106 \} else \{ +107 break; +108 \} +109 \} +110 +111 /* reset the sign of a first */ +112 a->sign = neg; +113 +114 /* set the result */ +115 mp_exch (&t1, c); +116 +117 /* set the sign of the result */ +118 c->sign = neg; +119 +120 res = MP_OKAY; +121 +122 LBL_T3:mp_clear (&t3); +123 LBL_T2:mp_clear (&t2); +124 LBL_T1:mp_clear (&t1); +125 return res; +126 \} +127 #endif +128 \end{alltt} \end{small} @@ -5770,6 +9358,42 @@ the integers from $0$ to $\beta - 1$. \hspace{-5.1mm}{\bf File}: bn\_mp\_rand.c \vspace{-3mm} \begin{alltt} +016 +017 /* makes a pseudo-random int of a given size */ +018 int +019 mp_rand (mp_int * a, int digits) +020 \{ +021 int res; +022 mp_digit d; +023 +024 mp_zero (a); +025 if (digits <= 0) \{ +026 return MP_OKAY; +027 \} +028 +029 /* first place a random non-zero digit */ +030 do \{ +031 d = ((mp_digit) abs (rand ())) & MP_MASK; +032 \} while (d == 0); +033 +034 if ((res = mp_add_d (a, d, a)) != MP_OKAY) \{ +035 return res; +036 \} +037 +038 while (--digits > 0) \{ +039 if ((res = mp_lshd (a, 1)) != MP_OKAY) \{ +040 return res; +041 \} +042 +043 if ((res = mp_add_d (a, ((mp_digit) abs (rand ())), a)) != MP_OKAY) \{ +044 return res; +045 \} +046 \} +047 +048 return MP_OKAY; +049 \} +050 #endif +051 \end{alltt} \end{small} @@ -5852,6 +9476,72 @@ as part of larger input without any significant problem. \hspace{-5.1mm}{\bf File}: bn\_mp\_read\_radix.c \vspace{-3mm} \begin{alltt} +016 +017 /* read a string [ASCII] in a given radix */ +018 int mp_read_radix (mp_int * a, const char *str, int radix) +019 \{ +020 int y, res, neg; +021 char ch; +022 +023 /* zero the digit bignum */ +024 mp_zero(a); +025 +026 /* make sure the radix is ok */ +027 if (radix < 2 || radix > 64) \{ +028 return MP_VAL; +029 \} +030 +031 /* if the leading digit is a +032 * minus set the sign to negative. +033 */ +034 if (*str == '-') \{ +035 ++str; +036 neg = MP_NEG; +037 \} else \{ +038 neg = MP_ZPOS; +039 \} +040 +041 /* set the integer to the default of zero */ +042 mp_zero (a); +043 +044 /* process each digit of the string */ +045 while (*str) \{ +046 /* if the radix < 36 the conversion is case insensitive +047 * this allows numbers like 1AB and 1ab to represent the same value +048 * [e.g. in hex] +049 */ +050 ch = (char) ((radix < 36) ? toupper (*str) : *str); +051 for (y = 0; y < 64; y++) \{ +052 if (ch == mp_s_rmap[y]) \{ +053 break; +054 \} +055 \} +056 +057 /* if the char was found in the map +058 * and is less than the given radix add it +059 * to the number, otherwise exit the loop. +060 */ +061 if (y < radix) \{ +062 if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) \{ +063 return res; +064 \} +065 if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) \{ +066 return res; +067 \} +068 \} else \{ +069 break; +070 \} +071 ++str; +072 \} +073 +074 /* set the sign only if a != 0 */ +075 if (mp_iszero(a) != 1) \{ +076 a->sign = neg; +077 \} +078 return MP_OKAY; +079 \} +080 #endif +081 \end{alltt} \end{small} @@ -5916,6 +9606,62 @@ are required instead of a series of $n \times k$ divisions. One design flaw of \hspace{-5.1mm}{\bf File}: bn\_mp\_toradix.c \vspace{-3mm} \begin{alltt} +016 +017 /* stores a bignum as a ASCII string in a given radix (2..64) */ +018 int mp_toradix (mp_int * a, char *str, int radix) +019 \{ +020 int res, digs; +021 mp_int t; +022 mp_digit d; +023 char *_s = str; +024 +025 /* check range of the radix */ +026 if (radix < 2 || radix > 64) \{ +027 return MP_VAL; +028 \} +029 +030 /* quick out if its zero */ +031 if (mp_iszero(a) == 1) \{ +032 *str++ = '0'; +033 *str = '\symbol{92}0'; +034 return MP_OKAY; +035 \} +036 +037 if ((res = mp_init_copy (&t, a)) != MP_OKAY) \{ +038 return res; +039 \} +040 +041 /* if it is negative output a - */ +042 if (t.sign == MP_NEG) \{ +043 ++_s; +044 *str++ = '-'; +045 t.sign = MP_ZPOS; +046 \} +047 +048 digs = 0; +049 while (mp_iszero (&t) == 0) \{ +050 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) \{ +051 mp_clear (&t); +052 return res; +053 \} +054 *str++ = mp_s_rmap[d]; +055 ++digs; +056 \} +057 +058 /* reverse the digits of the string. In this case _s points +059 * to the first digit [exluding the sign] of the number] +060 */ +061 bn_reverse ((unsigned char *)_s, digs); +062 +063 /* append a NULL so the string is properly terminated */ +064 *str = '\symbol{92}0'; +065 +066 mp_clear (&t); +067 return MP_OKAY; +068 \} +069 +070 #endif +071 \end{alltt} \end{small} @@ -6100,23 +9846,109 @@ must be adjusted by multiplying by the common factors of two ($2^k$) removed ear \hspace{-5.1mm}{\bf File}: bn\_mp\_gcd.c \vspace{-3mm} \begin{alltt} +016 +017 /* Greatest Common Divisor using the binary method */ +018 int mp_gcd (mp_int * a, mp_int * b, mp_int * c) +019 \{ +020 mp_int u, v; +021 int k, u_lsb, v_lsb, res; +022 +023 /* either zero than gcd is the largest */ +024 if (mp_iszero (a) == MP_YES) \{ +025 return mp_abs (b, c); +026 \} +027 if (mp_iszero (b) == MP_YES) \{ +028 return mp_abs (a, c); +029 \} +030 +031 /* get copies of a and b we can modify */ +032 if ((res = mp_init_copy (&u, a)) != MP_OKAY) \{ +033 return res; +034 \} +035 +036 if ((res = mp_init_copy (&v, b)) != MP_OKAY) \{ +037 goto LBL_U; +038 \} +039 +040 /* must be positive for the remainder of the algorithm */ +041 u.sign = v.sign = MP_ZPOS; +042 +043 /* B1. Find the common power of two for u and v */ +044 u_lsb = mp_cnt_lsb(&u); +045 v_lsb = mp_cnt_lsb(&v); +046 k = MIN(u_lsb, v_lsb); +047 +048 if (k > 0) \{ +049 /* divide the power of two out */ +050 if ((res = mp_div_2d(&u, k, &u, NULL)) != MP_OKAY) \{ +051 goto LBL_V; +052 \} +053 +054 if ((res = mp_div_2d(&v, k, &v, NULL)) != MP_OKAY) \{ +055 goto LBL_V; +056 \} +057 \} +058 +059 /* divide any remaining factors of two out */ +060 if (u_lsb != k) \{ +061 if ((res = mp_div_2d(&u, u_lsb - k, &u, NULL)) != MP_OKAY) \{ +062 goto LBL_V; +063 \} +064 \} +065 +066 if (v_lsb != k) \{ +067 if ((res = mp_div_2d(&v, v_lsb - k, &v, NULL)) != MP_OKAY) \{ +068 goto LBL_V; +069 \} +070 \} +071 +072 while (mp_iszero(&v) == 0) \{ +073 /* make sure v is the largest */ +074 if (mp_cmp_mag(&u, &v) == MP_GT) \{ +075 /* swap u and v to make sure v is >= u */ +076 mp_exch(&u, &v); +077 \} +078 +079 /* subtract smallest from largest */ +080 if ((res = s_mp_sub(&v, &u, &v)) != MP_OKAY) \{ +081 goto LBL_V; +082 \} +083 +084 /* Divide out all factors of two */ +085 if ((res = mp_div_2d(&v, mp_cnt_lsb(&v), &v, NULL)) != MP_OKAY) \{ +086 goto LBL_V; +087 \} +088 \} +089 +090 /* multiply by 2**k which we divided out at the beginning */ +091 if ((res = mp_mul_2d (&u, k, c)) != MP_OKAY) \{ +092 goto LBL_V; +093 \} +094 c->sign = MP_ZPOS; +095 res = MP_OKAY; +096 LBL_V:mp_clear (&u); +097 LBL_U:mp_clear (&v); +098 return res; +099 \} +100 #endif +101 \end{alltt} \end{small} This function makes use of the macros mp\_iszero and mp\_iseven. The former evaluates to $1$ if the input mp\_int is equivalent to the integer zero otherwise it evaluates to $0$. The latter evaluates to $1$ if the input mp\_int represents a non-zero even integer otherwise it evaluates to $0$. Note that just because mp\_iseven may evaluate to $0$ does not mean the input is odd, it could also be zero. The three -trivial cases of inputs are handled on lines 24 through 30. After those lines the inputs are assumed to be non-zero. +trivial cases of inputs are handled on lines 23 through 29. After those lines the inputs are assumed to be non-zero. -Lines 32 and 37 make local copies $u$ and $v$ of the inputs $a$ and $b$ respectively. At this point the common factors of two -must be divided out of the two inputs. The block starting at line 44 removes common factors of two by first counting the number of trailing +Lines 32 and 36 make local copies $u$ and $v$ of the inputs $a$ and $b$ respectively. At this point the common factors of two +must be divided out of the two inputs. The block starting at line 43 removes common factors of two by first counting the number of trailing zero bits in both. The local integer $k$ is used to keep track of how many factors of $2$ are pulled out of both values. It is assumed that the number of factors will not exceed the maximum value of a C ``int'' data type\footnote{Strictly speaking no array in C may have more than entries than are accessible by an ``int'' so this is not a limitation.}. -At this point there are no more common factors of two in the two values. The divisions by a power of two on lines 62 and 68 remove +At this point there are no more common factors of two in the two values. The divisions by a power of two on lines 61 and 67 remove any independent factors of two such that both $u$ and $v$ are guaranteed to be an odd integer before hitting the main body of the algorithm. The while loop -on line 73 performs the reduction of the pair until $v$ is equal to zero. The unsigned comparison and subtraction algorithms are used in +on line 72 performs the reduction of the pair until $v$ is equal to zero. The unsigned comparison and subtraction algorithms are used in place of the full signed routines since both values are guaranteed to be positive and the result of the subtraction is guaranteed to be non-negative. \section{Least Common Multiple} @@ -6155,6 +9987,47 @@ dividing the product of the two inputs by their greatest common divisor. \hspace{-5.1mm}{\bf File}: bn\_mp\_lcm.c \vspace{-3mm} \begin{alltt} +016 +017 /* computes least common multiple as |a*b|/(a, b) */ +018 int mp_lcm (mp_int * a, mp_int * b, mp_int * c) +019 \{ +020 int res; +021 mp_int t1, t2; +022 +023 +024 if ((res = mp_init_multi (&t1, &t2, NULL)) != MP_OKAY) \{ +025 return res; +026 \} +027 +028 /* t1 = get the GCD of the two inputs */ +029 if ((res = mp_gcd (a, b, &t1)) != MP_OKAY) \{ +030 goto LBL_T; +031 \} +032 +033 /* divide the smallest by the GCD */ +034 if (mp_cmp_mag(a, b) == MP_LT) \{ +035 /* store quotient in t2 such that t2 * b is the LCM */ +036 if ((res = mp_div(a, &t1, &t2, NULL)) != MP_OKAY) \{ +037 goto LBL_T; +038 \} +039 res = mp_mul(b, &t2, c); +040 \} else \{ +041 /* store quotient in t2 such that t2 * a is the LCM */ +042 if ((res = mp_div(b, &t1, &t2, NULL)) != MP_OKAY) \{ +043 goto LBL_T; +044 \} +045 res = mp_mul(a, &t2, c); +046 \} +047 +048 /* fix the sign to positive */ +049 c->sign = MP_ZPOS; +050 +051 LBL_T: +052 mp_clear_multi (&t1, &t2, NULL); +053 return res; +054 \} +055 #endif +056 \end{alltt} \end{small} @@ -6314,6 +10187,92 @@ $\left ( {p' \over a'} \right )$ which is multiplied against the current Jacobi \hspace{-5.1mm}{\bf File}: bn\_mp\_jacobi.c \vspace{-3mm} \begin{alltt} +016 +017 /* computes the jacobi c = (a | n) (or Legendre if n is prime) +018 * HAC pp. 73 Algorithm 2.149 +019 */ +020 int mp_jacobi (mp_int * a, mp_int * p, int *c) +021 \{ +022 mp_int a1, p1; +023 int k, s, r, res; +024 mp_digit residue; +025 +026 /* if p <= 0 return MP_VAL */ +027 if (mp_cmp_d(p, 0) != MP_GT) \{ +028 return MP_VAL; +029 \} +030 +031 /* step 1. if a == 0, return 0 */ +032 if (mp_iszero (a) == 1) \{ +033 *c = 0; +034 return MP_OKAY; +035 \} +036 +037 /* step 2. if a == 1, return 1 */ +038 if (mp_cmp_d (a, 1) == MP_EQ) \{ +039 *c = 1; +040 return MP_OKAY; +041 \} +042 +043 /* default */ +044 s = 0; +045 +046 /* step 3. write a = a1 * 2**k */ +047 if ((res = mp_init_copy (&a1, a)) != MP_OKAY) \{ +048 return res; +049 \} +050 +051 if ((res = mp_init (&p1)) != MP_OKAY) \{ +052 goto LBL_A1; +053 \} +054 +055 /* divide out larger power of two */ +056 k = mp_cnt_lsb(&a1); +057 if ((res = mp_div_2d(&a1, k, &a1, NULL)) != MP_OKAY) \{ +058 goto LBL_P1; +059 \} +060 +061 /* step 4. if e is even set s=1 */ +062 if ((k & 1) == 0) \{ +063 s = 1; +064 \} else \{ +065 /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */ +066 residue = p->dp[0] & 7; +067 +068 if (residue == 1 || residue == 7) \{ +069 s = 1; +070 \} else if (residue == 3 || residue == 5) \{ +071 s = -1; +072 \} +073 \} +074 +075 /* step 5. if p == 3 (mod 4) *and* a1 == 3 (mod 4) then s = -s */ +076 if ( ((p->dp[0] & 3) == 3) && ((a1.dp[0] & 3) == 3)) \{ +077 s = -s; +078 \} +079 +080 /* if a1 == 1 we're done */ +081 if (mp_cmp_d (&a1, 1) == MP_EQ) \{ +082 *c = s; +083 \} else \{ +084 /* n1 = n mod a1 */ +085 if ((res = mp_mod (p, &a1, &p1)) != MP_OKAY) \{ +086 goto LBL_P1; +087 \} +088 if ((res = mp_jacobi (&p1, &a1, &r)) != MP_OKAY) \{ +089 goto LBL_P1; +090 \} +091 *c = s * r; +092 \} +093 +094 /* done */ +095 res = MP_OKAY; +096 LBL_P1:mp_clear (&p1); +097 LBL_A1:mp_clear (&a1); +098 return res; +099 \} +100 #endif +101 \end{alltt} \end{small} @@ -6328,9 +10287,9 @@ After a local copy of $a$ is made all of the factors of two are divided out and bit of $k$ is required, however, it makes the algorithm simpler to follow to perform an addition. In practice an exclusive-or and addition have the same processor requirements and neither is faster than the other. -Line 58 through 71 determines the value of $\left ( { 2 \over p } \right )^k$. If the least significant bit of $k$ is zero than +Line 61 through 70 determines the value of $\left ( { 2 \over p } \right )^k$. If the least significant bit of $k$ is zero than $k$ is even and the value is one. Otherwise, the value of $s$ depends on which residue class $p$ belongs to modulo eight. The value of -$(-1)^{(p-1)(a'-1)/4}$ is compute and multiplied against $s$ on lines 71 through 74. +$(-1)^{(p-1)(a'-1)/4}$ is compute and multiplied against $s$ on lines 75 through 73. Finally, if $a1$ does not equal one the algorithm must recurse and compute $\left ( {p' \over a'} \right )$. @@ -6439,6 +10398,30 @@ then only a couple of additions or subtractions will be required to adjust the i \hspace{-5.1mm}{\bf File}: bn\_mp\_invmod.c \vspace{-3mm} \begin{alltt} +016 +017 /* hac 14.61, pp608 */ +018 int mp_invmod (mp_int * a, mp_int * b, mp_int * c) +019 \{ +020 /* b cannot be negative */ +021 if (b->sign == MP_NEG || mp_iszero(b) == 1) \{ +022 return MP_VAL; +023 \} +024 +025 #ifdef BN_FAST_MP_INVMOD_C +026 /* if the modulus is odd we can use a faster routine instead */ +027 if (mp_isodd (b) == 1) \{ +028 return fast_mp_invmod (a, b, c); +029 \} +030 #endif +031 +032 #ifdef BN_MP_INVMOD_SLOW_C +033 return mp_invmod_slow(a, b, c); +034 #endif +035 +036 return MP_VAL; +037 \} +038 #endif +039 \end{alltt} \end{small} @@ -6510,6 +10493,37 @@ This algorithm attempts to determine if a candidate integer $n$ is composite by \hspace{-5.1mm}{\bf File}: bn\_mp\_prime\_is\_divisible.c \vspace{-3mm} \begin{alltt} +016 +017 /* determines if an integers is divisible by one +018 * of the first PRIME_SIZE primes or not +019 * +020 * sets result to 0 if not, 1 if yes +021 */ +022 int mp_prime_is_divisible (mp_int * a, int *result) +023 \{ +024 int err, ix; +025 mp_digit res; +026 +027 /* default to not */ +028 *result = MP_NO; +029 +030 for (ix = 0; ix < PRIME_SIZE; ix++) \{ +031 /* what is a mod LBL_prime_tab[ix] */ +032 if ((err = mp_mod_d (a, ltm_prime_tab[ix], &res)) != MP_OKAY) \{ +033 return err; +034 \} +035 +036 /* is the residue zero? */ +037 if (res == 0) \{ +038 *result = MP_YES; +039 return MP_OKAY; +040 \} +041 \} +042 +043 return MP_OKAY; +044 \} +045 #endif +046 \end{alltt} \end{small} @@ -6520,6 +10534,48 @@ mp\_digit. The table \_\_prime\_tab is defined in the following file. \hspace{-5.1mm}{\bf File}: bn\_prime\_tab.c \vspace{-3mm} \begin{alltt} +016 const mp_digit ltm_prime_tab[] = \{ +017 0x0002, 0x0003, 0x0005, 0x0007, 0x000B, 0x000D, 0x0011, 0x0013, +018 0x0017, 0x001D, 0x001F, 0x0025, 0x0029, 0x002B, 0x002F, 0x0035, +019 0x003B, 0x003D, 0x0043, 0x0047, 0x0049, 0x004F, 0x0053, 0x0059, +020 0x0061, 0x0065, 0x0067, 0x006B, 0x006D, 0x0071, 0x007F, +021 #ifndef MP_8BIT +022 0x0083, +023 0x0089, 0x008B, 0x0095, 0x0097, 0x009D, 0x00A3, 0x00A7, 0x00AD, +024 0x00B3, 0x00B5, 0x00BF, 0x00C1, 0x00C5, 0x00C7, 0x00D3, 0x00DF, +025 0x00E3, 0x00E5, 0x00E9, 0x00EF, 0x00F1, 0x00FB, 0x0101, 0x0107, +026 0x010D, 0x010F, 0x0115, 0x0119, 0x011B, 0x0125, 0x0133, 0x0137, +027 +028 0x0139, 0x013D, 0x014B, 0x0151, 0x015B, 0x015D, 0x0161, 0x0167, +029 0x016F, 0x0175, 0x017B, 0x017F, 0x0185, 0x018D, 0x0191, 0x0199, +030 0x01A3, 0x01A5, 0x01AF, 0x01B1, 0x01B7, 0x01BB, 0x01C1, 0x01C9, +031 0x01CD, 0x01CF, 0x01D3, 0x01DF, 0x01E7, 0x01EB, 0x01F3, 0x01F7, +032 0x01FD, 0x0209, 0x020B, 0x021D, 0x0223, 0x022D, 0x0233, 0x0239, +033 0x023B, 0x0241, 0x024B, 0x0251, 0x0257, 0x0259, 0x025F, 0x0265, +034 0x0269, 0x026B, 0x0277, 0x0281, 0x0283, 0x0287, 0x028D, 0x0293, +035 0x0295, 0x02A1, 0x02A5, 0x02AB, 0x02B3, 0x02BD, 0x02C5, 0x02CF, +036 +037 0x02D7, 0x02DD, 0x02E3, 0x02E7, 0x02EF, 0x02F5, 0x02F9, 0x0301, +038 0x0305, 0x0313, 0x031D, 0x0329, 0x032B, 0x0335, 0x0337, 0x033B, +039 0x033D, 0x0347, 0x0355, 0x0359, 0x035B, 0x035F, 0x036D, 0x0371, +040 0x0373, 0x0377, 0x038B, 0x038F, 0x0397, 0x03A1, 0x03A9, 0x03AD, +041 0x03B3, 0x03B9, 0x03C7, 0x03CB, 0x03D1, 0x03D7, 0x03DF, 0x03E5, +042 0x03F1, 0x03F5, 0x03FB, 0x03FD, 0x0407, 0x0409, 0x040F, 0x0419, +043 0x041B, 0x0425, 0x0427, 0x042D, 0x043F, 0x0443, 0x0445, 0x0449, +044 0x044F, 0x0455, 0x045D, 0x0463, 0x0469, 0x047F, 0x0481, 0x048B, +045 +046 0x0493, 0x049D, 0x04A3, 0x04A9, 0x04B1, 0x04BD, 0x04C1, 0x04C7, +047 0x04CD, 0x04CF, 0x04D5, 0x04E1, 0x04EB, 0x04FD, 0x04FF, 0x0503, +048 0x0509, 0x050B, 0x0511, 0x0515, 0x0517, 0x051B, 0x0527, 0x0529, +049 0x052F, 0x0551, 0x0557, 0x055D, 0x0565, 0x0577, 0x0581, 0x058F, +050 0x0593, 0x0595, 0x0599, 0x059F, 0x05A7, 0x05AB, 0x05AD, 0x05B3, +051 0x05BF, 0x05C9, 0x05CB, 0x05CF, 0x05D1, 0x05D5, 0x05DB, 0x05E7, +052 0x05F3, 0x05FB, 0x0607, 0x060D, 0x0611, 0x0617, 0x061F, 0x0623, +053 0x062B, 0x062F, 0x063D, 0x0641, 0x0647, 0x0649, 0x064D, 0x0653 +054 #endif +055 \}; +056 #endif +057 \end{alltt} \end{small} @@ -6566,6 +10622,49 @@ determine the result. \hspace{-5.1mm}{\bf File}: bn\_mp\_prime\_fermat.c \vspace{-3mm} \begin{alltt} +016 +017 /* performs one Fermat test. +018 * +019 * If "a" were prime then b**a == b (mod a) since the order of +020 * the multiplicative sub-group would be phi(a) = a-1. That means +021 * it would be the same as b**(a mod (a-1)) == b**1 == b (mod a). +022 * +023 * Sets result to 1 if the congruence holds, or zero otherwise. +024 */ +025 int mp_prime_fermat (mp_int * a, mp_int * b, int *result) +026 \{ +027 mp_int t; +028 int err; +029 +030 /* default to composite */ +031 *result = MP_NO; +032 +033 /* ensure b > 1 */ +034 if (mp_cmp_d(b, 1) != MP_GT) \{ +035 return MP_VAL; +036 \} +037 +038 /* init t */ +039 if ((err = mp_init (&t)) != MP_OKAY) \{ +040 return err; +041 \} +042 +043 /* compute t = b**a mod a */ +044 if ((err = mp_exptmod (b, a, a, &t)) != MP_OKAY) \{ +045 goto LBL_T; +046 \} +047 +048 /* is it equal to b? */ +049 if (mp_cmp (&t, b) == MP_EQ) \{ +050 *result = MP_YES; +051 \} +052 +053 err = MP_OKAY; +054 LBL_T:mp_clear (&t); +055 return err; +056 \} +057 #endif +058 \end{alltt} \end{small} @@ -6618,6 +10717,90 @@ composite then it is \textit{probably} prime. \hspace{-5.1mm}{\bf File}: bn\_mp\_prime\_miller\_rabin.c \vspace{-3mm} \begin{alltt} +016 +017 /* Miller-Rabin test of "a" to the base of "b" as described in +018 * HAC pp. 139 Algorithm 4.24 +019 * +020 * Sets result to 0 if definitely composite or 1 if probably prime. +021 * Randomly the chance of error is no more than 1/4 and often +022 * very much lower. +023 */ +024 int mp_prime_miller_rabin (mp_int * a, mp_int * b, int *result) +025 \{ +026 mp_int n1, y, r; +027 int s, j, err; +028 +029 /* default */ +030 *result = MP_NO; +031 +032 /* ensure b > 1 */ +033 if (mp_cmp_d(b, 1) != MP_GT) \{ +034 return MP_VAL; +035 \} +036 +037 /* get n1 = a - 1 */ +038 if ((err = mp_init_copy (&n1, a)) != MP_OKAY) \{ +039 return err; +040 \} +041 if ((err = mp_sub_d (&n1, 1, &n1)) != MP_OKAY) \{ +042 goto LBL_N1; +043 \} +044 +045 /* set 2**s * r = n1 */ +046 if ((err = mp_init_copy (&r, &n1)) != MP_OKAY) \{ +047 goto LBL_N1; +048 \} +049 +050 /* count the number of least significant bits +051 * which are zero +052 */ +053 s = mp_cnt_lsb(&r); +054 +055 /* now divide n - 1 by 2**s */ +056 if ((err = mp_div_2d (&r, s, &r, NULL)) != MP_OKAY) \{ +057 goto LBL_R; +058 \} +059 +060 /* compute y = b**r mod a */ +061 if ((err = mp_init (&y)) != MP_OKAY) \{ +062 goto LBL_R; +063 \} +064 if ((err = mp_exptmod (b, &r, a, &y)) != MP_OKAY) \{ +065 goto LBL_Y; +066 \} +067 +068 /* if y != 1 and y != n1 do */ +069 if (mp_cmp_d (&y, 1) != MP_EQ && mp_cmp (&y, &n1) != MP_EQ) \{ +070 j = 1; +071 /* while j <= s-1 and y != n1 */ +072 while ((j <= (s - 1)) && mp_cmp (&y, &n1) != MP_EQ) \{ +073 if ((err = mp_sqrmod (&y, a, &y)) != MP_OKAY) \{ +074 goto LBL_Y; +075 \} +076 +077 /* if y == 1 then composite */ +078 if (mp_cmp_d (&y, 1) == MP_EQ) \{ +079 goto LBL_Y; +080 \} +081 +082 ++j; +083 \} +084 +085 /* if y != n1 then composite */ +086 if (mp_cmp (&y, &n1) != MP_EQ) \{ +087 goto LBL_Y; +088 \} +089 \} +090 +091 /* probably prime now */ +092 *result = MP_YES; +093 LBL_Y:mp_clear (&y); +094 LBL_R:mp_clear (&r); +095 LBL_N1:mp_clear (&n1); +096 return err; +097 \} +098 #endif +099 \end{alltt} \end{small}