security/nss/lib/freebl/mpi/README

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     1 ***** BEGIN LICENSE BLOCK *****
     2 Version: MPL 1.1/GPL 2.0/LGPL 2.1
     4 The contents of this file are subject to the Mozilla Public License Version
     5 1.1 (the "License"); you may not use this file except in compliance with
     6 the License. You may obtain a copy of the License at
     7 http://www.mozilla.org/MPL/
     9 Software distributed under the License is distributed on an "AS IS" basis,
    10 WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
    11 for the specific language governing rights and limitations under the
    12 License.
    14 The Original Code is the MPI Arbitrary Precision Integer Arithmetic
    15 library.
    17 The Initial Developer of the Original Code is
    18 Michael J. Fromberger <sting@linguist.dartmouth.edu>
    19 Portions created by the Initial Developer are Copyright (C) 1997-2000
    20 the Initial Developer. All Rights Reserved.
    22 Contributor(s):
    24 Alternatively, the contents of this file may be used under the terms of
    25 either the GNU General Public License Version 2 or later (the "GPL"), or
    26 the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
    27 in which case the provisions of the GPL or the LGPL are applicable instead
    28 of those above. If you wish to allow use of your version of this file only
    29 under the terms of either the GPL or the LGPL, and not to allow others to
    30 use your version of this file under the terms of the MPL, indicate your
    31 decision by deleting the provisions above and replace them with the notice
    32 and other provisions required by the GPL or the LGPL. If you do not delete
    33 the provisions above, a recipient may use your version of this file under
    34 the terms of any one of the MPL, the GPL or the LGPL.
    36 ***** END LICENSE BLOCK *****
    38 About the MPI Library
    39 ---------------------
    41 The files 'mpi.h' and 'mpi.c' define a simple, arbitrary precision
    42 signed integer arithmetic package.  The implementation is not the most
    43 efficient possible, but the code is small and should be fairly easily
    44 portable to just about any machine that supports an ANSI C compiler,
    45 as long as it is capable of at least 16-bit arithmetic (but also see
    46 below for more on this).
    48 This library was written with an eye to cryptographic applications;
    49 thus, some care is taken to make sure that temporary values are not
    50 left lying around in memory when they are no longer in use.  This adds
    51 some overhead for zeroing buffers before they are released back into
    52 the free pool; however, it gives you the assurance that there is only
    53 one copy of your important values residing in your process's address
    54 space at a time.  Obviously, it is difficult to guarantee anything, in
    55 a pre-emptive multitasking environment, but this at least helps you
    56 keep a lid on the more obvious ways your data can get spread around in
    57 memory.
    60 Using the Library
    61 -----------------
    63 To use the MPI library in your program, you must include the header:
    65 #include "mpi.h"
    67 This header provides all the type and function declarations you'll
    68 need to use the library.  Almost all the names defined by the library
    69 begin with the prefix 'mp_', so it should be easy to keep them from
    70 clashing with your program's namespace (he says, glibly, knowing full
    71 well there are always pathological cases).
    73 There are a few things you may want to configure about the library.
    74 By default, the MPI library uses an unsigned short for its digit type,
    75 and an unsigned int for its word type.  The word type must be big
    76 enough to contain at least two digits, for the primitive arithmetic to
    77 work out.  On my machine, a short is 2 bytes and an int is 4 bytes --
    78 but if you have 64-bit ints, you might want to use a 4-byte digit and
    79 an 8-byte word.  I have tested the library using 1-byte digits and
    80 2-byte words, as well.  Whatever you choose to do, the things you need
    81 to change are:
    83 (1) The type definitions for mp_digit and mp_word.
    85 (2) The macro DIGIT_FMT which tells mp_print() how to display a
    86     single digit.  This is just a printf() format string, so you
    87     can adjust it appropriately.
    89 (3) The macros DIGIT_MAX and MP_WORD_MAX, which specify the 
    90     largest value expressible in an mp_digit and an mp_word,
    91     respectively.
    93 Both the mp_digit and mp_word should be UNSIGNED integer types.  The
    94 code relies on having the full positive precision of the type used for
    95 digits and words.
    97 The remaining type definitions should be left alone, for the most
    98 part.  The code in the library does not make any significant
    99 assumptions about the sizes of things, but there is little if any
   100 reason to change the other parameters, so I would recommend you leave
   101 them as you found them.
   103 The library comes with a Perl script, 'types.pl', which will scan your
   104 current Makefile settings, and attempt to find good definitions for
   105 these types.  It relies on a Unix sort of build environment, so it
   106 probably won't work under MacOS or Windows, but it can be convenient
   107 if you're porting to a new flavour of Unix.  Just run 'types.pl' at
   108 the command line, and it will spit out its results to the standard
   109 output.
   112 Conventions
   113 -----------
   115 Most functions in the library return a value of type mp_err.  This
   116 permits the library to communicate success or various kinds of failure
   117 to the calling program.  The return values currently defined are:
   119         MP_OKAY         - okay, operation succeeded, all's well
   120         MP_YES          - okay, the answer is yes (same as MP_OKAY)
   121         MP_NO           - okay, but answer is no (not MP_OKAY)
   122         MP_MEM          - operation ran out of memory
   123         MP_RANGE        - input parameter was out of range
   124         MP_BADARG       - an invalid input parameter was provided
   125         MP_UNDEF        - no output value is defined for this input
   127 The only function which currently uses MP_UNDEF is mp_invmod().
   128 Division by zero is undefined, but the division functions will return
   129 MP_RANGE for a zero divisor.  MP_BADARG usually means you passed a
   130 bogus mp_int structure to the function.  MP_YES and MP_NO are not used
   131 by the library itself; they're defined so you can use them in your own
   132 extensions.
   134 If you need a readable interpretation of these error codes in your
   135 program, you may also use the mp_strerror() function.  This function
   136 takes an mp_err as input, and returns a pointer to a human-readable
   137 string describing the meaning of the error.  These strings are stored
   138 as constants within the library, so the caller should not attempt to
   139 modify or free the memory associated with these strings.
   141 The library represents values in signed-magnitude format.  Values
   142 strictly less than zero are negative, all others are considered
   143 positive (zero is positive by fiat).  You can access the 'sign' member
   144 of the mp_int structure directly, but better is to use the mp_cmp_z()
   145 function, to find out which side of zero the value lies on.
   147 Most arithmetic functions have a single-digit variant, as well as the
   148 full arbitrary-precision.  An mp_digit is an unsigned value between 0
   149 and DIGIT_MAX inclusive.  The radix is available as RADIX.  The number
   150 of bits in a given digit is given as DIGIT_BIT.
   152 Generally, input parameters are given before output parameters.
   153 Unless otherwise specified, any input parameter can be re-used as an
   154 output parameter, without confusing anything.
   156 The basic numeric type defined by the library is an mp_int.  Virtually
   157 all the functions in the library take a pointer to an mp_int as one of
   158 their parameters.  An explanation of how to create and use these
   159 structures follows.  And so, without further ado...
   162 Initialization and Cleanup
   163 --------------------------
   165 The basic numeric type defined by the library is an 'mp_int'.
   166 However, it is not sufficient to simply declare a variable of type
   167 mp_int in your program.  These variables also need to be initialized
   168 before they can be used, to allocate the internal storage they require
   169 for computation.
   171 This is done using one of the following functions:
   173         mp_init(mp_int *mp);
   174         mp_init_copy(mp_int *mp, mp_int *from);
   175         mp_init_size(mp_int *mp, mp_size p);
   177 Each of these requires a pointer to a structure of type mp_int.  The
   178 basic mp_init() simply initializes the mp_int to a default size, and
   179 sets its value to zero.  If you would like to initialize a copy of an
   180 existing mp_int, use mp_init_copy(), where the 'from' parameter is the
   181 mp_int you'd like to make a copy of.  The third function,
   182 mp_init_size(), permits you to specify how many digits of precision
   183 should be preallocated for your mp_int.  This can help the library
   184 avoid unnecessary re-allocations later on.
   186 The default precision used by mp_init() can be retrieved using:
   188         precision = mp_get_prec();
   190 This returns the number of digits that will be allocated.  You can
   191 change this value by using:
   193         mp_set_prec(unsigned int prec);
   195 Any positive value is acceptable -- if you pass zero, the default
   196 precision will be re-set to the compiled-in library default (this is
   197 specified in the header file 'mpi-config.h', and typically defaults to
   198 8 or 16).
   200 Just as you must allocate an mp_int before you can use it, you must
   201 clean up the structure when you are done with it.  This is performed
   202 using the mp_clear() function.  Remember that any mp_int that you
   203 create as a local variable in a function must be mp_clear()'d before
   204 that function exits, or else the memory allocated to that mp_int will
   205 be orphaned and unrecoverable.
   207 To set an mp_int to a given value, the following functions are given:
   209         mp_set(mp_int *mp, mp_digit d);
   210         mp_set_int(mp_int *mp, long z);
   212 The mp_set() function sets the mp_int to a single digit value, while
   213 mp_set_int() sets the mp_int to a signed long integer value.
   215 To set an mp_int to zero, use:
   217         mp_zero(mp_int *mp);
   220 Copying and Moving
   221 ------------------
   223 If you have two initialized mp_int's, and you want to copy the value
   224 of one into the other, use:
   226         mp_copy(from, to)
   228 This takes care of clearing the old value of 'to', and copies the new
   229 value into it.  If 'to' is not yet initialized, use mp_init_copy()
   230 instead (see above).
   232 Note:   The library tries, whenever possible, to avoid allocating
   233 ----    new memory.  Thus, mp_copy() tries first to satisfy the needs
   234         of the copy by re-using the memory already allocated to 'to'.
   235         Only if this proves insufficient will mp_copy() actually
   236         allocate new memory.
   238         For this reason, if you know a priori that 'to' has enough
   239         available space to hold 'from', you don't need to check the
   240         return value of mp_copy() for memory failure.  The USED()
   241         macro tells you how many digits are used by an mp_int, and
   242         the ALLOC() macro tells you how many are allocated.
   244 If you have two initialized mp_int's, and you want to exchange their
   245 values, use:
   247         mp_exch(a, b)
   249 This is better than using mp_copy() with a temporary, since it will
   250 not (ever) touch the memory allocator -- it just swaps the exact
   251 contents of the two structures.  The mp_exch() function cannot fail;
   252 if you pass it an invalid structure, it just ignores it, and does
   253 nothing.
   256 Basic Arithmetic
   257 ----------------
   259 Once you have initialized your integers, you can operate on them.  The
   260 basic arithmetic functions on full mp_int values are:
   262 mp_add(a, b, c)         - computes c = a + b
   263 mp_sub(a, b, c)         - computes c = a - b
   264 mp_mul(a, b, c)         - computes c = a * b
   265 mp_sqr(a, b)            - computes b = a * a
   266 mp_div(a, b, q, r)      - computes q, r such that a = bq + r
   267 mp_div_2d(a, d, q, r)   - computes q = a / 2^d, r = a % 2^d
   268 mp_expt(a, b, c)        - computes c = a ** b
   269 mp_2expt(a, k)          - computes a = 2^k
   270 mp_sqrt(a, c)           - computes c = floor(sqrt(a))
   272 The mp_div_2d() function efficiently computes division by powers of
   273 two.  Either the q or r parameter may be NULL, in which case that
   274 portion of the computation will be discarded.
   276 The algorithms used for some of the computations here are described in
   277 the following files which are included with this distribution:
   279 mul.txt         Describes the multiplication algorithm
   280 div.txt         Describes the division algorithm
   281 expt.txt        Describes the exponentiation algorithm
   282 sqrt.txt        Describes the square-root algorithm
   283 square.txt      Describes the squaring algorithm
   285 There are single-digit versions of most of these routines, as well.
   286 In the following prototypes, 'd' is a single mp_digit:
   288 mp_add_d(a, d, c)       - computes c = a + d
   289 mp_sub_d(a, d, c)       - computes c = a - d
   290 mp_mul_d(a, d, c)       - computes c = a * d
   291 mp_mul_2(a, c)          - computes c = a * 2
   292 mp_div_d(a, d, q, r)    - computes q, r such that a = bq + r
   293 mp_div_2(a, c)          - computes c = a / 2
   294 mp_expt_d(a, d, c)      - computes c = a ** d
   296 The mp_mul_2() and mp_div_2() functions take advantage of the internal
   297 representation of an mp_int to do multiplication by two more quickly
   298 than mp_mul_d() would.  Other basic functions of an arithmetic variety
   299 include:
   301 mp_zero(a)              - assign 0 to a
   302 mp_neg(a, c)            - negate a: c = -a
   303 mp_abs(a, c)            - absolute value: c = |a|
   306 Comparisons
   307 -----------
   309 Several comparison functions are provided.  Each of these, unless
   310 otherwise specified, returns zero if the comparands are equal, < 0 if
   311 the first is less than the second, and > 0 if the first is greater
   312 than the second:
   314 mp_cmp_z(a)             - compare a <=> 0
   315 mp_cmp_d(a, d)          - compare a <=> d, d is a single digit
   316 mp_cmp(a, b)            - compare a <=> b
   317 mp_cmp_mag(a, b)        - compare |a| <=> |b|
   318 mp_cmp_int(a, z)        - compare a <=> z, z is a signed long integer
   319 mp_isodd(a)             - return nonzero if odd, zero otherwise
   320 mp_iseven(a)            - return nonzero if even, zero otherwise
   323 Modular Arithmetic
   324 ------------------
   326 Modular variations of the basic arithmetic functions are also
   327 supported.  These are available if the MP_MODARITH parameter in
   328 mpi-config.h is turned on (it is by default).  The modular arithmetic
   329 functions are:
   331 mp_mod(a, m, c)         - compute c = a (mod m), 0 <= c < m
   332 mp_mod_d(a, d, c)       - compute c = a (mod d), 0 <= c < d (see below)
   333 mp_addmod(a, b, m, c)   - compute c = (a + b) mod m
   334 mp_submod(a, b, m, c)   - compute c = (a - b) mod m
   335 mp_mulmod(a, b, m, c)   - compute c = (a * b) mod m
   336 mp_sqrmod(a, m, c)      - compute c = (a * a) mod m
   337 mp_exptmod(a, b, m, c)  - compute c = (a ** b) mod m
   338 mp_exptmod_d(a, d, m, c)- compute c = (a ** d) mod m
   340 The mp_sqr() function squares its input argument.  A call to mp_sqr(a,
   341 c) is identical in meaning to mp_mul(a, a, c); however, if the
   342 MP_SQUARE variable is set true in mpi-config.h (see below), then it
   343 will be implemented with a different algorithm, that is supposed to
   344 take advantage of the redundant computation that takes place during
   345 squaring.  Unfortunately, some compilers result in worse performance
   346 on this code, so you can change the behaviour at will.  There is a
   347 utility program "mulsqr.c" that lets you test which does better on
   348 your system.
   350 The mp_sqrmod() function is analogous to the mp_sqr() function; it
   351 uses the mp_sqr() function rather than mp_mul(), and then performs the
   352 modular reduction.  This probably won't help much unless you are doing
   353 a lot of them.
   355 See the file 'square.txt' for a synopsis of the algorithm used.
   357 Note:   The mp_mod_d() function computes a modular reduction around
   358 ----    a single digit d.  The result is a single digit c.
   360 Because an inverse is defined for a (mod m) if and only if (a, m) = 1
   361 (that is, if a and m are relatively prime), mp_invmod() may not be
   362 able to compute an inverse for the arguments.  In this case, it
   363 returns the value MP_UNDEF, and does not modify c.  If an inverse is
   364 defined, however, it returns MP_OKAY, and sets c to the value of the
   365 inverse (mod m).
   367 See the file 'redux.txt' for a description of the modular reduction
   368 algorithm used by mp_exptmod().
   371 Greatest Common Divisor
   372 -----------------------
   374 If The greates common divisor of two values can be found using one of the
   375 following functions:
   377 mp_gcd(a, b, c)         - compute c = (a, b) using binary algorithm
   378 mp_lcm(a, b, c)         - compute c = [a, b] = ab / (a, b)
   379 mp_xgcd(a, b, g, x, y)  - compute g, x, y so that ax + by = g = (a, b)
   381 Also provided is a function to compute modular inverses, if they
   382 exist:
   384 mp_invmod(a, m, c)      - compute c = a^-1 (mod m), if it exists
   386 The function mp_xgcd() computes the greatest common divisor, and also
   387 returns values of x and y satisfying Bezout's identity.  This is used
   388 by mp_invmod() to find modular inverses.  However, if you do not need
   389 these values, you will find that mp_gcd() is MUCH more efficient,
   390 since it doesn't need all the intermediate values that mp_xgcd()
   391 requires in order to compute x and y. 
   393 The mp_gcd() (and mp_xgcd()) functions use the binary (extended) GCD
   394 algorithm due to Josef Stein.
   397 Input & Output Functions
   398 ------------------------
   400 The following basic I/O routines are provided.  These are present at
   401 all times:
   403 mp_read_radix(mp, str, r)  - convert a string in radix r to an mp_int
   404 mp_read_raw(mp, s, len)    - convert a string of bytes to an mp_int
   405 mp_radix_size(mp, r)       - return length of buffer needed by mp_toradix()
   406 mp_raw_size(mp)            - return length of buffer needed by mp_toraw()
   407 mp_toradix(mp, str, r)     - convert an mp_int to a string of radix r 
   408                              digits
   409 mp_toraw(mp, str)          - convert an mp_int to a string of bytes
   410 mp_tovalue(ch, r)          - convert ch to its value when taken as
   411                              a radix r digit, or -1 if invalid
   412 mp_strerror(err)           - get a string describing mp_err value 'err'
   414 If you compile the MPI library with MP_IOFUNC defined, you will also
   415 have access to the following additional I/O function:
   417 mp_print(mp, ofp)       - print an mp_int as text to output stream ofp
   419 Note that mp_radix_size() returns a size in bytes guaranteed to be AT
   420 LEAST big enough for the digits output by mp_toradix().  Because it
   421 uses an approximation technique to figure out how many digits will be
   422 needed, it may return a figure which is larger than necessary.  Thus,
   423 the caller should not rely on the value to determine how many bytes
   424 will actually be written by mp_toradix().  The string mp_toradix()
   425 creates will be NUL terminated, so the standard C library function
   426 strlen() should be able to ascertain this for you, if you need it.
   428 The mp_read_radix() and mp_toradix() functions support bases from 2 to
   429 64 inclusive.  If you require more general radix conversion facilities
   430 than this, you will need to write them yourself (that's why mp_div_d()
   431 is provided, after all).
   433 Note:   mp_read_radix() will accept as digits either capital or 
   434 ----    lower-case letters.  However, the current implementation of
   435         mp_toradix() only outputs upper-case letters, when writing
   436         bases betwee 10 and 36.  The underlying code supports using
   437         lower-case letters, but the interface stub does not have a
   438         selector for it.  You can add one yourself if you think it
   439         is worthwhile -- I do not.  Bases from 36 to 64 use lower-
   440         case letters as distinct from upper-case.  Bases 63 and
   441         64 use the characters '+' and '/' as digits.
   443         Note also that compiling with MP_IOFUNC defined will cause
   444         inclusion of <stdio.h>, so if you are trying to write code
   445         which does not depend on the standard C library, you will
   446         probably want to avoid this option.  This is needed because
   447         the mp_print() function takes a standard library FILE * as
   448         one of its parameters, and uses the fprintf() function.
   450 The mp_toraw() function converts the integer to a sequence of bytes,
   451 in big-endian ordering (most-significant byte first).  Assuming your
   452 bytes are 8 bits wide, this corresponds to base 256.  The sign is
   453 encoded as a single leading byte, whose value is 0 for zero or
   454 positive values, or 1 for negative values.  The mp_read_raw() function
   455 reverses this process -- it takes a buffer of bytes, interprets the
   456 first as a sign indicator (0 = zero/positive, nonzero = negative), and
   457 the rest as a sequence of 1-byte digits in big-endian ordering.
   459 The mp_raw_size() function returns the exact number of bytes required
   460 to store the given integer in "raw" format (as described in the
   461 previous paragraph).  Zero is returned in case of error; a valid
   462 integer will require at least three bytes of storage.
   464 In previous versions of the MPI library, an "external representation
   465 format" was supported.  This was removed, however, because I found I
   466 was never using it, it was not as portable as I would have liked, and
   467 I decided it was a waste of space.
   470 Other Functions
   471 ---------------
   473 The files 'mpprime.h' and 'mpprime.c' define some routines which are
   474 useful for divisibility testing and probabilistic primality testing.
   475 The routines defined are:
   477 mpp_divis(a, b)          - is a divisible by b?
   478 mpp_divis_d(a, d)        - is a divisible by digit d?
   479 mpp_random(a)            - set a to random value at current precision
   480 mpp_random_size(a, prec) - set a to random value at given precision
   482 Note:  The mpp_random() and mpp_random_size() functions use the C
   483 ----   library's rand() function to generate random values.  It is
   484        up to the caller to seed this generator before it is called.
   485        These functions are not suitable for generating quantities
   486        requiring cryptographic-quality randomness; they are intended
   487        primarily for use in primality testing.
   489        Note too that the MPI library does not call srand(), so your
   490        application should do this, if you ever want the sequence
   491        to change.
   493 mpp_divis_vector(a, v, s, w)  - is a divisible by any of the s digits
   494                                 in v?  If so, let w be the index of 
   495                                 that digit
   497 mpp_divis_primes(a, np)       - is a divisible by any of the first np
   498                                 primes?  If so, set np to the prime 
   499                                 which divided a.
   501 mpp_fermat(a, d)              - test if w^a = w (mod a).  If so, 
   502                                 returns MP_YES, otherwise MP_NO.
   504 mpp_pprime(a, nt)             - perform nt iterations of the Rabin-
   505                                 Miller probabilistic primality test
   506                                 on a.  Returns MP_YES if all tests
   507                                 passed, or MP_NO if any test fails.
   509 The mpp_fermat() function works based on Fermat's little theorem, a
   510 consequence of which is that if p is a prime, and (w, p) = 1, then:
   512         w^p = w (mod p)
   514 Put another way, if w^p != w (mod p), then p is not prime.  The test
   515 is expensive to compute, but it helps to quickly eliminate an enormous
   516 class of composite numbers prior to Rabin-Miller testing.
   518 Building the Library
   519 --------------------
   521 The MPI library is designed to be as self-contained as possible.  You
   522 should be able to compile it with your favourite ANSI C compiler, and
   523 link it into your program directly.  If you are on a Unix system using
   524 the GNU C compiler (gcc), the following should work:
   526 % gcc -ansi -pedantic -Wall -O2 -c mpi.c
   528 The file 'mpi-config.h' defines several configurable parameters for
   529 the library, which you can adjust to suit your application.  At the
   530 time of this writing, the available options are:
   532 MP_IOFUNC       - Define true to include the mp_print() function, 
   533                   which is moderately useful for debugging.  This
   534                   implicitly includes <stdio.h>.
   536 MP_MODARITH     - Define true to include the modular arithmetic
   537                   functions.  If you don't need modular arithmetic
   538                   in your application, you can set this to zero to
   539                   leave out all the modular routines.
   541 MP_NUMTH        - Define true to include number theoretic functions
   542                   such as mp_gcd(), mp_lcm(), and mp_invmod().
   544 MP_LOGTAB       - If true, the file "logtab.h" is included, which
   545                   is basically a static table of base 2 logarithms.
   546                   These are used to compute how big the buffers for
   547                   radix conversion need to be.  If you set this false,
   548                   the library includes <math.h> and uses log().  This
   549                   typically forces you to link against math libraries.
   551 MP_MEMSET       - If true, use memset() to zero buffers.  If you run
   552                   into weird alignment related bugs, set this to zero
   553                   and an explicit loop will be used.
   555 MP_MEMCPY       - If true, use memcpy() to copy buffers.  If you run
   556                   into weird alignment bugs, set this to zero and an
   557                   explicit loop will be used.
   559 MP_CRYPTO       - If true, whenever arrays of digits are free'd, they
   560                   are zeroed first.  This is useful if you're using
   561                   the library in a cryptographic environment; however,
   562                   it does add overhead to each free operation.  For
   563                   performance, if you don't care about zeroing your
   564                   buffers, set this to false.
   566 MP_ARGCHK       - Set to 0, 1, or 2.  This defines how the argument
   567                   checking macro, ARGCHK(), gets expanded.  If this 
   568                   is set to zero, ARGCHK() expands to nothing; no 
   569                   argument checks are performed.  If this is 1, the
   570                   ARGCHK() macro expands to code that returns MP_BADARG
   571                   or similar at runtime.  If it is 2, ARGCHK() expands 
   572                   to an assert() call that aborts the program on a 
   573                   bad input.
   575 MP_DEBUG        - Turns on debugging output.  This is probably not at
   576                   all useful unless you are debugging the library.  It
   577                   tends to spit out a LOT of output.
   579 MP_DEFPREC      - The default precision of a newly-created mp_int, in
   580                   digits.  The precision can be changed at runtime by
   581                   the mp_set_prec() function, but this is its initial
   582                   value.
   584 MP_SQUARE       - If this is set to a nonzero value, the mp_sqr() 
   585                   function will use an alternate algorithm that takes
   586                   advantage of the redundant inner product computation
   587                   when both multiplicands are identical.  Unfortunately,
   588                   with some compilers this is actually SLOWER than just
   589                   calling mp_mul() with the same argument twice.  So
   590                   if you set MP_SQUARE to zero, mp_sqr() will be expan-
   591                   ded into a call to mp_mul().  This applies to all 
   592                   the uses of mp_sqr(), including mp_sqrmod() and the
   593                   internal calls to s_mp_sqr() inside mpi.c
   595                   The program 'mulsqr' (mulsqr.c) can be used to test
   596                   which works best for your configuration.  Set up the
   597                   CC and CFLAGS variables in the Makefile, then type:
   599                         make mulsqr
   601                   Invoke it with arguments similar to the following:
   603                         mulsqr 25000 1024
   605                   That is, 25000 products computed on 1024-bit values.
   606                   The output will compare the two timings, and recommend
   607                   a setting for MP_SQUARE.  It is off by default.
   609 If you would like to use the mp_print() function (see above), be sure
   610 to define MP_IOFUNC in mpi-config.h.  Many of the test drivers in the
   611 'tests' subdirectory expect this to be defined (although the test
   612 driver 'mpi-test' doesn't need it)
   614 The Makefile which comes with the library should take care of building
   615 the library for you, if you have set the CC and CFLAGS variables at
   616 the top of the file appropriately.  By default, they are set up to
   617 use the GNU C compiler:
   619 CC=gcc
   620 CFLAGS=-ansi -pedantic -Wall -O2
   622 If all goes well, the library should compile without warnings using
   623 this combination.  You should, of course, make whatever adjustments
   624 you find necessary.  
   626 The MPI library distribution comes with several additional programs
   627 which are intended to demonstrate the use of the library, and provide
   628 a framework for testing it.  There are a handful of test driver
   629 programs, in the files named 'mptest-X.c', where X is a digit.  Also,
   630 there are some simple command-line utilities (in the 'utils'
   631 directory) for manipulating large numbers.  These include:
   633 basecvt.c       A radix-conversion program, supporting bases from
   634                 2 to 64 inclusive.
   636 bbsrand.c       A BBS (quadratic residue) pseudo-random number 
   637                 generator.  The file 'bbsrand.c' is just the driver
   638                 for the program; the real code lives in the files
   639                 'bbs_rand.h' and 'bbs_rand.c'
   641 dec2hex.c       Converts decimal to hexadecimal
   643 gcd.c           Computes the greatest common divisor of two values.
   644                 If invoked as 'xgcd', also computes constants x and
   645                 y such that (a, b) = ax + by, in accordance with
   646                 Bezout's identity.
   648 hex2dec.c       Converts hexadecimal to decimal
   650 invmod.c        Computes modular inverses
   652 isprime.c       Performs the Rabin-Miller probabilistic primality
   653                 test on a number.  Values which fail this test are
   654                 definitely composite, and those which pass are very
   655                 likely to be prime (although there are no guarantees)
   657 lap.c           Computes the order (least annihilating power) of
   658                 a value v modulo m.  Very dumb algorithm.
   660 primegen.c      Generates large (probable) primes.
   662 prng.c          A pseudo-random number generator based on the
   663                 BBS generator code in 'bbs_rand.c'
   665 sieve.c         Implements the Sieve of Eratosthenes, using a big
   666                 bitmap, to generate a list of prime numbers.
   668 fact.c          Computes the factorial of an arbitrary precision
   669                 integer (iterative).
   671 exptmod.c       Computes arbitrary precision modular exponentiation
   672                 from the command line (exptmod a b m -> a^b (mod m))
   674 Most of these can be built from the Makefile that comes with the
   675 library.  Try 'make tools', if your environment supports it.
   678 Testing the Library
   679 -------------------
   681 Automatic test vectors are included, in the form of a program called
   682 'mpi-test'.  To build this program and run all the tests, simply
   683 invoke the shell script 'all-tests'.  If all the tests pass, you
   684 should see a message:
   686         All tests passed
   688 If something went wrong, you'll get:
   690         One or more tests failed.
   692 If this happens, scan back through the preceding lines, to see which
   693 test failed.  Any failure indicates a bug in the library, which needs
   694 to be fixed before it will give accurate results.  If you get any such
   695 thing, please let me know, and I'll try to fix it.  Please let me know
   696 what platform and compiler you were using, as well as which test
   697 failed.  If a reason for failure was given, please send me that text
   698 as well.
   700 If you're on a system where the standard Unix build tools don't work,
   701 you can build the 'mpi-test' program manually, and run it by hand.
   702 This is tedious and obnoxious, sorry.
   704 Further manual testing can be performed by building the manual testing
   705 programs, whose source is found in the 'tests' subdirectory.  Each
   706 test is in a source file called 'mptest-X.c'.  The Makefile contains a
   707 target to build all of them at once:
   709         make tests
   711 Read the comments at the top of each source file to see what the
   712 driver is supposed to test.  You probably don't need to do this; these
   713 programs were only written to help me as I was developing the library.
   715 The relevant files are:
   717 mpi-test.c              The source for the test driver
   719 make-test-arrays        A Perl script to generate some of the internal
   720                         data structures used by mpi-test.c
   722 test-arrays.txt         The source file for make-test-arrays
   724 all-tests               A Bourne shell script which runs all the
   725                         tests in the mpi-test suite
   727 Running 'make mpi-test' should build the mpi-test program.  If you
   728 cannot use make, here is what needs to be done:
   730 (1) Use 'make-test-arrays' to generate the file 'test-info.c' from
   731     the 'test-arrays.txt' file.  Since Perl can be found everywhere,
   732     this should be no trouble.  Under Unix, this looks like:
   734         make-test-arrays test-arrays.txt > test-info.c
   736 (2) Build the MPI library:
   738         gcc -ansi -pedantic -Wall -c mpi.c
   740 (3) Build the mpi-test program:
   742         gcc -ansi -pedantic -Wall -o mpi-test mpi.o mpi-test.c
   744 When you've got mpi-test, you can use 'all-tests' to run all the tests
   745 made available by mpi-test.  If any of them fail, there should be a
   746 diagnostic indicating what went wrong.  These are fairly high-level
   747 diagnostics, and won't really help you debug the problem; they're
   748 simply intended to help you isolate which function caused the problem.
   749 If you encounter a problem of this sort, feel free to e-mail me, and I
   750 will certainly attempt to help you debug it.
   752 Note:   Several of the tests hard-wired into 'mpi-test' operate under
   753 ----    the assumption that you are using at least a 16-bit mp_digit 
   754         type.  If that is not true, several tests might fail, because 
   755         of range problems with the maximum digit value.
   757         If you are using an 8-bit digit, you will also need to 
   758         modify the code for mp_read_raw(), which assumes that
   759         multiplication by 256 can be done with mp_mul_d(), a
   760         fact that fails when DIGIT_MAX is 255.  You can replace
   761         the call with s_mp_lshd(), which will give you the same
   762         effect, and without doing as much work. :)
   764 Acknowledgements:
   765 ----------------
   767 The algorithms used in this library were drawn primarily from Volume
   768 2 of Donald Knuth's magnum opus, _The Art of Computer Programming_, 
   769 "Semi-Numerical Methods".  Barrett's algorithm for modular reduction
   770 came from Menezes, Oorschot, and Vanstone's _Handbook of Applied
   771 Cryptography_, Chapter 14.
   773 Thanks are due to Tom St. Denis, for finding an obnoxious sign-related
   774 bug in mp_read_raw() that made things break on platforms which use
   775 signed chars.
   777 About the Author
   778 ----------------
   780 This software was written by Michael J. Fromberger.  You can contact
   781 the author as follows:
   783 E-mail:   <sting@linguist.dartmouth.edu>
   785 Postal:   8000 Cummings Hall, Thayer School of Engineering
   786           Dartmouth College, Hanover, New Hampshire, USA
   788 PGP key:  http://linguist.dartmouth.edu/~sting/keys/mjf.html
   789           9736 188B 5AFA 23D6 D6AA  BE0D 5856 4525 289D 9907
   791 Last updated:  16-Jan-2000

mercurial