home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / crypl200.zip / BNLIB / BNINTERN.DOC < prev    next >
Text File  |  1996-01-28  |  16KB  |  305 lines

  1. * The organization of the BigNum Library
  2.  
  3. As mentioned in bn.doc, the library should compile on anything with an
  4. ANSI C compiler and 16 and 32-bit data types.  (Non-power-of-2 word
  5. lengths probably wouldn't be *too* hard, but the matter is likely to
  6. remain academic.)  However, assembly subroutines can be added in a
  7. great variety of ways to speed up computations.
  8.  
  9. It's even possible to vary the word length dynamically at run time.
  10. Currently, 80x86 and 680x0 assembly primitives have been written in 16
  11. and 32-bit forms, as not all members of these families support 32x32->64
  12. bit multiply.  In future, 32/64 bit routines may be nice for the MIPS
  13. and PowerPC processors.  (The SPARC has a 64-bit extension, but it still
  14. only produces a maximum 64-bit multiply result.  The MIPS, PowerPC and
  15. Alpha give access to 128 bits of product.)
  16.  
  17. The way that this works is that the file bn.c declares a big pile of
  18. function pointers, and the first bnInit() call figures out which set
  19. of functions to point these to.  The functions are named so that
  20. it is possible to link several sets into the same executable without
  21. collisions.
  22.  
  23. The library can store numbers in big-endian or little-endian word order,
  24. although the order of bytes within a word is always the platform native
  25. order.  As long as you're using the pure C version, you can compile
  26. independent of the native byte ordering, but the flexibility is available
  27. in case assembly primitives are easier to write one way or the other.
  28. (In the absence of other considerations, little-endian is somewhat more
  29. efficient, and is the default.  This is controlled by BN_XXX_ENDIAN.)
  30.  
  31. In fact, it would be possible to change the word order at run time,
  32. except that there is no naming convention to support linking in
  33. functions that differ only in endianness.  (Which is because the
  34. point of doing so is unclear.)
  35.  
  36. The core of the library is in the files lbn??.c and bn??.c, where "??"
  37. is 16, 32, or 64.  The 32 and 64-bit files are generated from the 16-bit
  38. version by a simple textual substitution.  The 16-bit files are generally
  39. considered the master source, and the others generated from it with sed.
  40.  
  41. Usually, only one set of these files is used on any given platform,
  42. but if you want multiple word sizes, you include one for each supported
  43. word size.  The files bninit??.c define a bnInit function for a given
  44. word size, which calls bnInit_??() internally.  Only one of these may
  45. be included at a time, and multiple word sizes are handled by a more
  46. complex bnInit function such as the ones in bn8086.c and bn68000.c,
  47. which determine the word size of the processor they're running on and
  48. call the appropriate bnInit_??() function.
  49.  
  50. The file lbn.h uses <limits.h> to find the platform's available data
  51. types.  The types are defined both as macros (BNWORD32) and as typedefs
  52. (bnword32) which aren't used anywhere but can come in very handy when
  53. using a debugger (which doesn't know about macros).  Any of these may
  54. be overridden either on the compiler command line (cc -DBN_BIG_ENDIAN
  55. -DBNWORD32="unsigned long"), or from an extra include file BNINCLUDE
  56. defined on the command line.  (cc -DBNINCLUDE=lbnmagic.h)  This is the
  57. preferred way to specify assembly primitives.
  58.  
  59. So, for example, to build a 68020 version of the library, compile the
  60. 32-bit library with -DBNINCLUDE=lbn68020.h, and compile and link in
  61. lbn68020.c (which is actually an assembly source file, if you look).
  62.  
  63. Both 16- and 32-bit 80x86 code is included in lbn8086.h and .asm.  That
  64. code uses 16-bit large-model addressing.  lbn80386.h and .asm use 32-bit
  65. flat-model addressing.
  66.  
  67. Three particularly heavily used macros defined by lbn.h are BIG(x),
  68. LITTLE(y) and BIGLITTLE(x,y).  These expand to x (or nothing) on
  69. a big-endian system, and y (or nothing) on a little-endian system.
  70. These are used to conditionalize the rest of the code without taking
  71. up entire lines to say "#ifdef BN_BIG_ENDIAN", "#else" and "#endif".
  72.  
  73. * The lbn??.c files
  74.  
  75. The lbn?? file contains the low-level bignum functions.  These universally
  76. expect their numbers to be passed to them in (buffer, length) form and
  77. do not attempt to extend the buffers.  (In some cases, they do allocate
  78. temporary buffers.)  The buffer pointer points to the least-significant
  79. end of the buffer.  If the machine uses big-endian word ordering, that
  80. is a pointer to the end of the buffer.  This is motivated by considering
  81. pointers to point to the boundaries between words (or bytes).  If you
  82. consider a pointer to point to a word rather than between words, the
  83. pointer in the big-endian case points to the first word past the end of the
  84. buffer.
  85.  
  86. All of the primitives have names of the form  lbnAddN_16, where the
  87. _16 is the word size.  All are surrounded by "#ifndef lbnAddN_16".
  88. If you #define lbnAddN_16 previously (either on the command like or
  89. in the BNINCLUDE file), the C code will neither define *nor declare* the
  90. corresponding function.  The declaration must be suppressed in case you
  91. declare it in a magic way with special calling attributes or define it as
  92. a macro.
  93.  
  94. If you wish to write an assembly primitive, lbnMulAdd1_??, which
  95. multiplies N words by 1 word and adds the result to N words, returning
  96. the carry word, is by FAR the most important function - almost all of
  97. the time spent performing a modular exponentiation is spent in this
  98. function.  lbnMulSub1_??, which does the same but subtracts the product
  99. and returns a word of borrow, is used heavily in the division routine
  100. and thus by GCD and modular inverse computation.
  101.  
  102. These two functions are the only functions which *require* some sort
  103. of double-word data type, so if you define them in assembly language,
  104. the ?? may be the widest word your C compiler supports; otherwise, you
  105. must limit your implementation to half of the maximum word size.  Other
  106. functions will, however, use a double-word data type if available.
  107.  
  108. Actually, there are some even simpler primitives which you can provide
  109. to allow double-width multiplication: mul??_ppmm, mul??_ppmma and
  110. mul??_ppmmaa These are expected to be defined as macros (all arguments
  111. are always side-effect-free lvalues), and must return two words of result
  112. of the computation m1*m2 + a1 + a2.  It is best to define all three,
  113. although any that are not defined will be generated from the others in
  114. the obvious way.  GCC's inline assembler can be used to define these.
  115. (The names are borrowed from the GNU MP package.)
  116.  
  117. There is also lbnMulN1_??, which stores the result rather than adding or
  118. subtracting it, but it is less critical.  If it is not provided, but
  119. lbnMulAdd1_?? is, it will be implemented in terms of lbnMulAdd1_?? in the
  120. obvious way.
  121.  
  122. lbnDiv21_??, which divides two words by one word and returns a quotient
  123. and remainder, is greatly sped up by a double-word data type, macro
  124. definition, or assembly implementation, but has a version which will run
  125. without one.  If your platform has a double/single divide with remainder,
  126. it would help to define this, and it's quite simple.
  127.  
  128. lbnModQ_?? (return a multi-precision number reduced modulo a "quick"
  129. (< 65536) modulus is used heavily by prime generation for trial division,
  130. but is otherwise little used.
  131.  
  132. Other primitives may be implemented depending on the expected usage mix.
  133. It is generally not worth implementing lbnAddN_?? and lbnSubN_?? unless
  134. you want to start learning to write assembly primitives on something
  135. simple; they just aren't used very much.  (Of course, if you do, you'll
  136. probably get some improvements, in both speed and object code size, so
  137. it's worth keeping them in, once written.)
  138.  
  139. * The bn??.c files
  140.  
  141. While the lbn??.c files deal in words, the bn??.c files provide the
  142. public interface to the library and deal in bignum structures.  These
  143. contain a buffer pointer, an allocated length, and a used length.
  144. The lengths are specified in words, but as long as the user doesn't go
  145. prying into such innards, all of the different word-size libraries
  146. provide the same interface; they may be exchanged at link time, or even
  147. at run time.
  148.  
  149. The bn.c file defines a large collection of function pointers and one
  150. function, bnInit.  bnInit is responsible for setting the function pointers
  151. to point to the appropriate bn??.c functions.  Each bn??.c file
  152. provides a bnInit_?? function which sets itself up; it is the job
  153. of bnInit to figure out which word size to use and call the appropriate
  154. bnInit_?? function.
  155.  
  156. If only one word size is in use, you may link in the file bninit??.c,
  157. which provides a trivial bnInit function.  If multiple word sizes are
  158. in use, you must provide the appropriate bnInit function.  See
  159. bn8086.c as an example.
  160.  
  161. For maximum portability, you may just compile and link in the files
  162. lbn00.c, bn00.c and bninit00.c, which determine, using the preprocessor
  163. at compile time, the best word size to use.  (The logic is actually
  164. located in the file bnsize00.h, so that the three .c files cannot get out
  165. of sync.)
  166.  
  167. The bignum buffers are allocated using the memory management routines in
  168. lbnmem.c.  These are word-size independent; they expect byte counts and
  169. expect the system malloc() to return suitably aligned buffers.  The
  170. main reason for this wrapper layer is to support any customized allocators
  171. that the user might want to provide.
  172.  
  173. * Other bn*.c files
  174.  
  175. bnprint.c is a simple routine for printing a bignum in hex.  It is
  176. provided in a separate file so that its calls to stdio can be eliminated
  177. from the link process if the capability is not needed.
  178.  
  179. bntest??.c is a very useful regression test if you're implementing
  180. assembly primitives.  If it doesn't complain, you've probably
  181. got it right.  It also does timing tests so you can see the effects
  182. of any changes.
  183.  
  184. * Other files
  185.  
  186. sieve.c contains some primitives which use the bignum library to perform
  187. sieving (trial division) of ranges of numbers looking for candidate primes.
  188. This involves two steps: using a sieve of Eratosthenes to generate the
  189. primes up to 65536, and using that to do trial division on a range of
  190. numbers following a larger input number.  Note that this is designed
  191. for large numbers, greater than 65536, since there is no check to see
  192. if the input is one of the small primes; if it is divisible, it is assumed
  193. composite.
  194.  
  195. prime.c uses sieve.c to generate primes.  It uses sieve.c to eliminate
  196. numbers with trivial divisors, then does strong pseudoprimality tests
  197. with some small bases.  (Actually, the first test, to the base 2, is
  198. optimized a bit to be faster when it fails, which is the common case,
  199. but 1/8 of the time it's not a strong pseudoprimality test, so an extra,
  200. strong, test is done in that case.)
  201.  
  202. It prints progress indicators as it searches.  The algorithm
  203. searches a range of numbers starting at a given prime, but it does
  204. so in a "shuffled" order, inspired by algorithm M from Knuth.  (The
  205. random number generator to use for this is passed in; if no function
  206. is given, the numbers are searched in sequential order and the
  207. returns value will be the next prime >= the input value.)
  208.  
  209. germain.c operates similarly, but generates Sophie Germain primes;
  210. that is, primes p such that (p-1)/2 is also prime.  It lacks the
  211. shuffling feature - searching is always sequential.
  212.  
  213. jacobi.c computes the Jacobi symbol between a small integer and a BigNum.
  214. It's currently only ever used in germain.c.
  215.  
  216. * Sources
  217.  
  218. Obviously, a key source of information was Knuth, Volume 2,
  219. particularly on division algorithms.
  220.  
  221. The greatest inspiration, however, was Arjen Lenstra's LIP
  222. (Large Integer Package), distributed with the RSA-129 effort.
  223. While very difficult to read (there is no internal documentation on
  224. sometimes very subtle algorithms), it showed me many useful tricks,
  225. notably the windowed exponentiation algorithm that saves so many
  226. multiplies.  If you need a more general-purpose large-integer package,
  227. with only a minor speed penalty, the LIP package is almost certainly
  228. the best available.  It implements a great range of efficient
  229. algorithms.
  230.  
  231. The second most important source was Torbjorn Granlund's gmp
  232. (GNU multi-precision) library.  A number of C coding tricks were
  233. adapted from there.  I'd like to thank Torbjorn for some useful
  234. discussions and letting me see his development work on GMP 2.0.
  235.  
  236. Antoon Bosselaers, Rene' Govaerts and Joos Vandewalle, in their CRYPTO
  237. '93 paper, "Comparison of three modular reduction functions", brought
  238. Montgomery reduction to my attention, for which I am grateful.
  239.  
  240. Burt Kaliski's article in the September 1993 Dr. Dobb's Journal,
  241. "The Z80180 and Big-number Arithmetic" pointed out the advantages (and
  242. terminology) of product scanning to me, although the limited
  243. experiments I've done have shown no improvement from trying it in C.
  244.  
  245. Hans Reisel's book, "Prime Numbers and Computer Methods for Factorization"
  246. was of great help in designing the prime testing, although some of
  247. the code in the book, notably the Jacobi function in Appendix 3,
  248. is an impressive example of why GOTO should be considered harmful.
  249. Papers by R. G. E. Pinch and others in Mathematics of Computation were
  250. also very useful.
  251.  
  252. Keith Geddes, Stephen Czapor and George Labahn's book "Algorithms
  253. for Computer Algebra", although it's mostly about polynomials,
  254. has some useful multi-precision math examples.
  255.  
  256. Philip Zimmermann's mpi (multi-precision integer) library suggested
  257. storing the numbers in native byte order to facilitate assembly
  258. subroutines, although the core modular multiplication algorithms are
  259. so confusing that I still don't understand them.  His boasting about
  260. the speed of his library (albeit in 1986, before any of the above were
  261. available for study) also inspired me to particular effort to soundly
  262. beat it.  It also provoked a strong reaction from me against fixed
  263. buffer sizes, and complaints about its implementation from Paul Leyland
  264. (interface) and Robert Silverman (prime searching) contributed usefully
  265. to the design of this current library.
  266.  
  267. I'd like to credit all of the above, plus the Berkeley MP package, with
  268. giving me difficulty finding a short, unique distinguishing prefix for
  269. my library's functions.  (I have just, sigh, discovered that Eric Young
  270. is using the same prefix for *his* library, although with the
  271. bn_function_name convention as opposed to the bnFunctionName one.)
  272.  
  273. I'd like to thank the original implementor of Unix "dc" and "factor"
  274. for providing useful tools for verifying the correct operation of
  275. my library.
  276.  
  277. * Future
  278.  
  279. - Obviously, assembly-language subroutines for more platforms would
  280.   always be nice.
  281. - There's a special case in the division for a two-word denominator
  282.   which should be completed.
  283. - When the quotient of a division is big enough, compute an inverse of
  284.   the high word of the denominator and use multiplication by that
  285.   to do the divide.
  286. - A more efficient GCD algorithm would be nice to have.
  287. - More efficient modular inversion is possible.  Do it.
  288. - Extend modular inversion to deal with non-relatively-prime
  289.   inputs.  Produce y = inv(x,m) with y * x == gcd(x,m) mod m.
  290. - Try some product scanning in assembly.
  291. - Karatsuba's multiplication and squaring speedups would be nice.
  292. - I *don't* think that FFT-based algorithms are worth implementing yet,
  293.   but it's worth a little bit of study to make sure.
  294. - More general support for numbers in Montgomery form, so they can
  295.   be used by more than the bowels of lbnExpMod.
  296. - Provide an lbnExpMod optimized for small arguments > 2, using
  297.   conventional (or even Barrett) reduction of the multiplies, and
  298.   Montgomery reduction of the squarings.
  299. - Adding a Lucas-based prime test would be a real coup, although it's
  300.   hard to give rational reasons why it's necessary.  I have a number of
  301.   ideas on this already.  Find out if norm-1 (which is faster to
  302.   compute) suffices.
  303. - Split up the source code more to support linking with smaller subsets
  304.   of the library.
  305.