bn.doc
上传用户:zbbssh
上传日期:2007-01-08
资源大小:196k
文件大小:23k
源码类别:

CA认证

开发平台:

C/C++

  1. * The BigNum multi-precision integer math library
  2. This is a multi-precision math library designed to be very portable,
  3. reasonably clean and easy to use, have very liberal bounds on the sizes
  4. of numbers that can be represented, but above all to perform extremely
  5. fast modular exponentiation.  It has some limitations, such as
  6. representing positive numbers only, and supporting only odd moduli,
  7. which simplify it without impairing this ability.
  8. A second speed goal which has had considerable effort applied to it is
  9. prime number generation.
  10. Finally, while there is probably a long way to go in this direction,
  11. some effort has gone into commenting the code a lot more than seems to
  12. be fashionable among mathematicians.
  13. It is written in C, and should compile on any platform with an ANSI C
  14. compiler and 16 and 32-bit unsigned data types, but various primitives
  15. can be replaced with assembly versions in a great variety of ways for
  16. greater speedup.  See "bnintern.doc" for a description.
  17. In case you're wondering, yes C++ would produce a much nicer syntax
  18. for working with these numbers, but there are a lot of compilers out
  19. there that actually implement ANSI C, and get it almost right.  I have
  20. a few kludges to deal with some that get little things wrong, but
  21. overall it's not too difficult to write code that I can be sure
  22. will work on lots of machines.  And porting it to a K&R C compiler,
  23. if it ever becomes necessary, shouldn't be all *that* difficult.
  24. The C++ compiler world is a less friendly place.  First of all, C++
  25. compilers are still not as common as C compilers, so that hurts
  26. portability right there, and I don't need the extra power to write my
  27. code.  C++ compilers all seem to have important bugs, and different
  28. bugs for each compiler.  First I have to learn all the foibles of a
  29. whole lot of C++ compilers, and then I have write code that uses only
  30. the features that work in all of them.  This is a language not a whole
  31. heck of a lot bigger than C.
  32. (The fact that it drives me *batty* the way that C++ drags *everything*
  33. into the same name space is also a contributing factor.  I *like*
  34. writing "struct" (or "class") before structure names.  I *like* putting
  35. "this->" in front of member references.  It makes it clear to me, when
  36. reading a single line of code, roughly what is being affected by it and
  37. where I can find the relevant source code to find out more.  I've seen
  38. people develop complicated naming conventions to make all this clear,
  39. but the conventions are still very much in flux.)
  40. Anyway...
  41. The main public interface is contained in the file bn.h.  This is
  42. mostly a bunch of pointers to functions which start out uninitialized.
  43. The bnInit() function sets this up.  It must be called before any other
  44. routine in the library.
  45. All of the public routines have names of the bnFunction variety.
  46. Some internal routines are lbnFunction, but you should never have to
  47. worry about those unless you're hacking with the code.
  48. The code uses the assert() macro a lot internally.  If you do something
  49. you're not supposed to, you'll generally notice because an assert()
  50. will fail.  The library does not have special error codes for division
  51. by zero or the like - it assert fails instead.  Just don't do that.
  52. A BigNum is represented by a struct BigNum, which really doesn't
  53. need to be understood, but it often makes me feel better to understand
  54. what's going on, so here it is:
  55. #> struct BigNum {
  56. #> void *ptr;
  57. #> unsigned size; /* Note: in (variable-sized) words */
  58. #> unsigned allocated;
  59. #> };
  60. The pointer points to the least-significant end of an array of words which
  61. hold the number.  The array contains "allocated" words, but only "size"
  62. of them are actually meaningful.  The others may have any value.
  63. This is all of limited use because the size of a word is not specified.
  64. In fact, it can change at run time - if you run on an 8086 one day and an
  65. 80386 the next, you may find the word size different.
  66. * Initialization
  67. The first function you have to call is this:
  68. #> void bnInit(void);
  69. This sets up the library for use.  It is idempotent, so you can call it
  70. multiple times if you like.  The only thing it does right now is set
  71. up the function pointers to the rest of the library.  If you crash
  72. a program and the debugger tells you that it's trying to execute at
  73. address 0, you forgot to call bnInit.
  74. The user of the library is responsible for allocating and freeing the struct
  75. BigNum.  All the library functions take pointers to them.  The first thing
  76. you need to do is initialize all the fields to empty, a zero-valued BigNum.
  77. This is done with the function bnBegin:
  78. #> void bnBegin(struct BigNum *bn);
  79. When you're done with a BigNum, call bnEnd to deallocate the data storage
  80. in preparation for deallocating the structure:
  81. #> void bnEnd(struct BigNum *bn);
  82. This resets the number to the 0 state.  You can actually start using the
  83. number right away again, or call bnEnd again, so if you're really
  84. memory-conscious you might want to use this to free a large
  85. number you're done with this way before going on to use the buffer
  86. for smaller things.
  87. A simple assignment can be done with bnCopy.  
  88. #> int bnCopy(struct BigNum *dest, struct BigNum const *src);
  89. This sets dest = src, and returns an error code.  Most functions in the
  90. library do this, and return 0 on success and -1 if they were unable to
  91. allocate needed memory.  If you're lazy and sure you'll never run out
  92. of memory, you can avoid checking this, but it's better to be
  93. paranoid.  If a function returns -1, the what has happened to the
  94. destination values is undefined.  They're usually unmodified, and
  95. they're always still valid BigNum numbers, but their values might be
  96. strange.
  97. In general, anywhere that follows, unless otherwise documented, assume
  98. that an "int" return value is 0 for success or -1 for error.
  99. A trivial little function which is sometimes handy, and quite cheap to
  100. execute (it just swaps the pointers) is:
  101. #> void bnSwap(struct BigNum *a, struct BigNum *b);
  102. * Input and output
  103. For now, the library only works with numbers in binary form - there's
  104. no way to get decimal numbers into or out of it.  But it's pretty
  105. flexible on how it does that.
  106. The first function just sets a BigNum to have a small value.
  107. "small" is defined as less than 2^16, the minimum word size supported
  108. by the library.  This is still useful for a lot of work.
  109. #> int bnSetQ(struct BigNum *dest, unsigned src);
  110. This returns the usual -1 error if it couldn't allocate memory.
  111. There's also a function to determine the size of a BigNum, in bits.
  112. The size is the number of bits required to represent the number,
  113. 0 if the number is 0, and floor(log2(src)) + 1 otherwise.  E.g. 1 is
  114. the only 1-bit number, 2 and 3 are 2-bit numbers, etc.
  115. #> unsigned bnBits(struct BigNum const *src);
  116. If bnBits(src) <= 16, you can get the whole number with this function.
  117. If it's larger, you get the low k bits, where k is at least 16.
  118. (This doesn't bother masking if it's easy to return more, but you
  119. shouldn't rely on it.)  Even that is useful for many things, like
  120. deciding if a number is even or odd.
  121. #> unsigned bnLSWord(struct BigNum const *src);
  122. For larger numbers, the format used by the library is an array of
  123. unsigned 8-bit bytes.  These bytes may be in big-endian or little-endian
  124. order, and it's possible to examine or change just part of a number.
  125. The functions are:
  126. #> void bnExtractBigBytes(struct BigNum const *bn, unsigned char *dest,
  127. #>  unsigned lsbyte, unsigned len);
  128. #> int bnInsertBigBytes(struct BigNum *bn, unsigned char const *src,
  129. #>  unsigned lsbyte, unsigned len);
  130. #> void bnExtractLittleBytes(struct BigNum const *bn, unsigned char *dest,
  131. #>  unsigned lsbyte, unsigned len);
  132. #> int bnInsertLittleBytes(struct BigNum *bn, unsigned char const *src,
  133. #>  unsigned lsbyte, unsigned len);
  134. These move bytes between the BigNum and the buffer of 8-bit bytes.  The
  135. Insert functions can allocate memory, so return an error code.  The
  136. Extract functions always succeed.
  137. The buffer is encoded in base 256, with either the most significant
  138. byte (the Big functions) or the least significant byte (the Little
  139. functions) coming first.  "len" is the length of the buffer, so the
  140. buffer always encodes a value between 0 and 256^len.  (That's
  141. "to the power of", not "xor".)
  142. "lsbyte" gives the offset into the BigNum which is being worked with.
  143. This is usually zero, but you can, for example, read out a large
  144. BigNum in 32-byte chunks, using a len of 32 and an lsbyte of 0, 32,
  145. 64, 96, etc.
  146. After these complete, the number encoded in the buffer will be
  147. equal to (bn / 256^lsbyte) % 256^len.  The only difference between
  148. Insert and Extract is which is changed to match the other.
  149. * Simple math
  150. #> int bnAdd(struct BigNum *dest, struct BigNum const *src);
  151. #> int bnAddQ(struct BigNum *dest, unsigned src);
  152. These add dest += src.  In the Q form, src must be < 65536.  In either
  153. case, the functions can fail and return -1, as usual.
  154. #> int bnSub(struct BigNum *dest, struct BigNum const *src);
  155. #> int bnSubQ(struct BigNum *dest, unsigned src);
  156. These subtract dest -= src.  If this would make the result negative,
  157. dest is set to (src-dest) and a value of 1 is returned, so you can
  158. keep track of a separate sign if you need to.  Otherwise, they return
  159. 0 on success and -1 if they were unable to allocate needed memory.
  160. To make your life simpler if you are error checking, these are guaranteed
  161. not to allocate memory unnecessarily.  So if you know that the addition
  162. or subtraction you're doing won't produce a result larger than the
  163. input, and won't underflow either (like subtracting 1 from an odd
  164. number or adding 1 to an even number), you can skip checking the
  165. error code.
  166. #> extern int (*bnCmp)(struct BigNum const *a, struct BigNum const *b);
  167. This returns the sign (-1, 0 or +1) of a-b.  Another way of saying
  168. this is that a <=> b is the same as bnCmp(a, b) <=> 0,
  169. where "<=>" stands for any of <, <=, =, !=, >= or >.
  170. #> int bnSquare(struct BigNum *dest, struct BigNum const *src);
  171. This computes dest = src^2, returning an error if it ran out of memory.
  172. If you care about performance tuning, this slows down when dest and
  173. src are the same BigNum, since it needs to allocate a temporary buffer
  174. to do the work in.  It does work, however.
  175. #> int bnMul(struct BigNum *dest, struct BigNum const *a,
  176. #> struct BigNum const *b);
  177. #> int bnMulQ(struct BigNum *dest, struct BigNum const *a, unsigned b);
  178. These compute dest = a * b, and work in the same way as bnSquare.
  179. (Including the comment about preferring if dest is not the same as any of
  180. the inputs.)  bnSquare is faster if a and b are the same.
  181. #> int bnDivMod(struct BigNum *q, struct BigNum *r,
  182. #> struct BigNum const *n, struct BigNum const *d);
  183. This computes division with remainder, q = n/d and r = n%d.  Don't
  184. pass in a zero d; it will blow up.  In general, all of the values
  185. must be different (it will blow up if you try), but r and n may be the
  186. same.
  187. RE-ENTRANCY NOTE: This temporarily modifies the BigNum "d" internally,
  188. although it restores it before returning.  If you're doing something
  189. multi-threaded, you can't share the d value between threads, even though
  190. it says "const".  That's a safe assumption elsewhere, but this is an
  191. exception.
  192. That note also means that it's not safe to let n be the same as d,
  193. although that's such a stupid way to set q to 1 and r to 0 that
  194. I don't think it's worth worrying about.  (I hope you understand that
  195. this doesn't mean that n and d can't have the same numerical value,
  196. just that they can't both point to the same struct BigNum.)
  197. #> int bnMod(struct BigNum *dest, struct BigNum const *src,
  198. #>  struct BigNum const *d);
  199. This works just the same as the above, but doesn't bother you with the
  200. quotient.  (No, there's no function that doesn't bother you with the
  201. remainder.)  Again, dest and src may be the same (it's actually
  202. more efficient if they are), but d may not be the same as either.
  203. #> unsigned int bnModQ(struct BigNum const *src, unsigned d);
  204. This also computes src % d, but does so for small (up to 65535,
  205. the usual limit on "Q" functions) values of d.  It returns the
  206. remainder.
  207. * Advanced math
  208. #> int bnLShift(struct BigNum *dest, unsigned amt);
  209. #> void bnRShift(struct BigNum *dest, unsigned amt);
  210. These shift the given bignum left or right by "amt" bit positions.
  211. Left shifts multiply by 2^amt, and may have to allocate memory
  212. (and thus fail).  Right shifts divide by 2^amt, throwing away the
  213. remainder, and can never fail.
  214. #> unsigned bnMakeOdd(struct BigNum *n);
  215. This right shifts the input number as many places as possible without
  216. throwing anything away, and returns the number of bits shifted.
  217. If you see "let n = s * 2^t, where s is odd" in an algorithm,
  218. this is the function to call.  It modifies n in place to produce s
  219. and returns t.
  220. This returns 0 if you pass it 0.
  221. #> int bnExpMod(struct BigNum *result, struct BigNum const *n,
  222. #>  struct BigNum const *exp, struct BigNum const *mod);
  223. Ah, now we get to the heart of the library - probably the most heavily
  224. optimized function in it.  This computes result = n^exp, modulo "mod".
  225. result may be the same as n, but not the same as exp or mod.  For large
  226. exponents and moduli, it can try to allocate quite a bit of working
  227. storage, although it will manage to finish its work (just slower)
  228. if some of those allocations fail.  (Not all, though - the first few
  229. are essential.)
  230. "mod" must be odd.  It will blow up if not.  Also, n must be less than
  231. mod.  If you're not sure if it is, use bnMod first.  The return value
  232. is always between 0 and mod-1.
  233. #> int bnTwoExpMod(struct BigNum *result, struct BigNum const *exp,
  234. #> struct BigNum const *mod);
  235. This computes result = 2^exp, modulo "mod".  It's faster than the general
  236. bnExpMod function, although that function checks to see if n = 2 and calls
  237. this one internally, so you don't need to check yourself if you're not
  238. sure.  The main reason to mention this is that if you're doing something
  239. like a pseudoprimality test, using a base of 2 first can save some time.
  240. #> int bnDoubleExpMod(struct BigNum *result,
  241. #>  struct BigNum const *n1, struct BigNum const *e1,
  242. #>  struct BigNum const *n2, struct BigNum const *e2,
  243. #>  struct BigNum const *mod);
  244. This computes dest = n1^e1 * n2^e2, modulo "mod".  It does it quite
  245. a bit faster than doing two separate bnExpMod operations; in fact,
  246. it's not that much more expensive than one.  "result" may be the
  247. same BigNum as n1 or n2, but it may not be the same as the exponents
  248. or the modulus.  All of the other caveats about bnExpMod apply.
  249. #> int bnGcd(struct BigNum *dest, struct BigNum const *a,
  250. #> struct BigNum const *b);
  251. This returns dest = gcd(a,b).  dest may be the same as either input.
  252. /* dest = src^-1, modulo "mod".  dest may be the same as src. */
  253. #> int bnInv(struct BigNum *dest, struct BigNum const *src,
  254. #> struct BigNum const *mod);
  255. This requires that gcd(src, mod) = 1, and returns dest = src^-1, modulo
  256. "mod".  That is, 0 < dest < mod and dest*src = 1, modulo "mod".
  257. dest and src may be the same, but mod must be different.
  258. This will probably get extended at some point to find dest such that
  259. dest * src = gcd(src, mod), modulo "mod", but that isn't implemented
  260. yet.
  261. * Auxiliary functions
  262. These functions have very limited usefulness, and might even get removed,
  263. but for now they're there in the unusual case where you might want them.
  264. #> int bnPrealloc(struct BigNum *bn, unsigned bits);
  265. This preallocates space in bn to make sure that it can hold "bits" bits.
  266. If the overflow characteristics of various algorithms get documented
  267. better, this might allow even more error-checking to be avoided, but
  268. for now it's only to reduce memory fragmentation.
  269. #> void bnNorm(struct BigNum *bn);
  270. This decreases the "size" field of the given bignum until it has no leading
  271. zero words in its internal representation.  Given that almost everything
  272. in the library does the equivalent of this on input and output, the utility
  273. of this function is a bit dubious.  It's kind of a legacy.
  274. * Extra libraries
  275. There are a number of utilities built on top of the basic library.
  276. They are built on top of the interfaces just described, and can be used
  277. if you like.
  278. * jacobi.h
  279. #> int bnJacobiQ(unsigned p, struct BigNum const *bn);
  280. This returns the Jacobi symbol J(p,bn), where p is a small number.
  281. The Jacobi symbol is always -1, 0, or +1.  You'll note that p may
  282. only be positive, even though the Jacobi symbol is defined for
  283. negative p.  If you want to worry about negative p, do it yourself.
  284. J(-p,bn) = (bnLSWord(bn) & 2 ? -1 : +1) * bnJacobiQ(p, bn).
  285. A function to compute the Jacobi symbol for large p would be nice.
  286. * prime.h
  287. #> int primeGen(struct BigNum *bn, unsigned (*rand)(unsigned),
  288. #>  int (*f)(void *arg, int c), void *arg, unsigned exponent, ...);
  289. This finds the next prime p >= bn, and sets bn to equal it.
  290. Well, sort of.
  291. It always leaves bn at least as large as when it started (unless it
  292. runs out of memory and returns -1), and if you pass a 0 for the rand
  293. function, it will be the next prime >= bn.
  294. Except:
  295. - It doesn't bother coping with small primes.  If it's divisible by any
  296. prime up to 65521, it's considered non-prime.  Even if the quotient is 0.
  297. If you pass in "1", expecting to get "2" back, you'll get 65537.  Maybe
  298. it would be nice to fix that.
  299. - It actually only does a few strong pseudoprimality tests to fixed
  300. bases to determine if the candidate number is prime.  For random input,
  301. this is fine; the chance of error is so infinitesimal that it is
  302. absolutely not worth worrying about.  But if you give it numbers carefully
  303. chosen to be strong pseudoprimes, it will think they're primes and not
  304. complain.  For example, 341550071728321 = 10670053 * 32010157 will
  305. pass the primality test quite handily.  So will
  306. 68528663395046912244223605902738356719751082784386681071.
  307. - If you supply a rand() function, which returns 0 <= rand(n) < n
  308. (n never gets very large - currently, at most 256), this shuffles the
  309. candidates before testing and accepting one.  If you want a "random"
  310. prime, this produces a more uniformly distributed prime, while
  311. retaining all of the speed advantages of a sequential search from a
  312. random starting point, which would otherwise produce a bias towards
  313. primes which were not closely preceded by other primes.  So, for
  314. example, the second of a pair of twin primes would be very unlikely to
  315. be chosen.  rand() doesn't totally flatten the distribution, but it
  316. comes very close.
  317. The "f" function is called periodically during the progress of the
  318. search (which can take a while) with the supplied argument (for private
  319. context) and a character c, which sort of tells you what it's doing.
  320. c is either '.' or '*' (if it's found something and is confirming that
  321. it's really prime) or '/' (if it's having a really hard time finding
  322. something).  Also, if f returns < 0, primeGen immediately returns that
  323. value.  This can form the basis for a user interface which can show some
  324. life occasionally and abort the computation if desired.
  325. If you just print these characters to the screen, don't forget to
  326. fflush() after printing them.
  327. Finally, "exponent, ..." is a zero-terminated list of small numbers
  328. which must not divide p-1 when the function returns.  If the numbers
  329. are chosen to be the prime factors of n, then gcd(n, p-1) will be
  330. 1, so the map f(x) -> x^n is invertible modulo p.
  331. #> int primeGenStrong(struct BigNum *bn, struct BigNum const *step,
  332. #> int (*f)(void *arg, int c), void *arg);
  333. This is similar, but searches in steps of "step", rather than 1, from the
  334. given starting value.  The starting value must be odd and the step
  335. size must be even!  If you start with bn == 1 (mod step), and step
  336. is 2*q, where q is a large prime, then this generates "strong" primes,
  337. p-1 having a large prime factor q.  There are other uses, too.
  338. #ifdef __cplusplus
  339. }
  340. #endif
  341. * germain.h
  342. #> int germainPrimeGen(struct BigNum *bn, int (*f)(void *arg, int c),
  343. #> void *arg);
  344. This increases bn until it is a Sophie Germain prime, that is, a number p
  345. such that p and (p-1)/2 are both prime.  These numbers are rarer than
  346. ordinary primes and the search takes correspondingly longer.
  347. It omits the randomization portion of primeGen, and the exponent list,
  348. since the factors of bn-1 are known already.  The f function for
  349. progress is the same, but it is also sometimes passed a '+' or '-'
  350. character when it's found a (p-1)/2 that's prime.  This is just to lend
  351. some interest to an otherwise very boring row of dots.  Finding large
  352. primes with this function, even though it's pretty optimized, takes a
  353. *while*, and otherwise once the screen filled with dots (one every few
  354. seconds) it would be hard to keep track of the scroll.
  355. It varies a lot, depending on luck of the starting value and the speed
  356. of your machine, but if your starting number is over 1024 bits, plan on
  357. over an hour of run time, and if it's over 2048 bits, plan on a day.
  358. At 4096 bits, start thinking about a week.
  359. Past that, supporting checkpoint/restart is a good idea.  Every time
  360. the progress function gets a '/' is probably a good interval, and when
  361. it happens have f return a distinct error value like -2.  When
  362. germainPrimeGen returns with that value, save the value in bn to a file
  363. somewhere and call it again with the same bn to continue searching.
  364. * sieve.h
  365. This is the sieving code that the other prime-finding functions call
  366. to do trial division.  You might use it if you are doing some magic
  367. prime-finding of your own.  A sieve is an array of bits, stored
  368. little-endian in an array of bytes (i.e. the lsb of byte 0 is bit 0).
  369. Sieves are indexed with the "unsigned" data type, so should not, for
  370. portability, be larger than 65536/8 = 8192 bytes long.
  371. A 1 bit is considered "in" the sieve, it has passed all the sieving.
  372. A 0 bit has been removed by some step.
  373. The functions are:
  374. #> void sieveSingle(unsigned char *array, unsigned size, unsigned start,
  375. #> unsigned step);
  376. This (efficiently) clears the bits at positions start, start+step,
  377. start+2*step, etc. in the sieve given by array and size.  This is the
  378. elementary sieve-building step.  Start with a sieve of all 1s, and
  379. apply this as required.
  380. #> unsigned sieveSearch(unsigned char const *array, unsigned size,
  381. #> unsigned start);
  382. This returns the next bit position *greater than* start which is set
  383. in the indicated sieve, or 0 on failure.  NOTE that this means that
  384. you have to look at the bit at position 0 (array[0] & 1) by yourself
  385. if you want to pay attention to it, because there's no way to tell
  386. sieveSearch to start searching at 0 - it starts at start+1.
  387. #> int sieveBuild(unsigned char *array, unsigned size, struct BigNum const *bn,
  388. #> unsigned step, unsigned dbl);
  389. This initializes a sieve where, if bit i is set, then bn+step*i is not
  390. divisible by any small primes.  (Small is from 2 through 65521, the
  391. largest prime less that 65536.)  If "dbl" is > 0, then bits are also
  392. cleared if 2*(bn+step*i)+1 is divisible.  If dbl > 1, then
  393. 4*(bn+step*i)+3 is also checked, and so on.  This feature is used when
  394. generating Sohpie Germain primes.
  395. Usually, you use a step of 2.
  396. #> int sieveBuildBig(unsigned char *array, unsigned size,
  397. #> struct BigNum const *bn, struct BigNum const *step, unsigned dbl);
  398. This is just the same, but accepts a BigNum step size, and is correspondingly
  399. slower.
  400. * bnprint.h
  401. #> int bnPrint(FILE *f, char const *prefix, struct BigNum const *bn,
  402. #> char const *suffix);
  403. This prints a nicely-formatted BigNum in hexadecimal form to the given
  404. FILE *.  The "prefix" is printed before it, as a prompt, and the
  405. "suffix" is printed afterwards.  The BigNum itself is printed in
  406. 64-character lines, broken with a trailing backslash if necessary.
  407. Continuation lines are indented by the length of the prefix.
  408. E.g. a 2^512-1, printed with the call bnPrint(stdout, "a = (", bn, ")n")
  409. would result in:
  410. a = (FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
  411.      FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
  412. Hex digits are printed in upper case to facilitate cutting and pasting into
  413. the Unix "dc" utility.