ltc_tommath.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  1. /* LibTomMath, multiple-precision integer library -- Tom St Denis
  2. *
  3. * LibTomMath is a library that provides multiple-precision
  4. * integer arithmetic as well as number theoretic functionality.
  5. *
  6. * The library was designed directly after the MPI library by
  7. * Michael Fromberger but has been written from scratch with
  8. * additional optimizations in place.
  9. *
  10. * The library is free for all purposes without any express
  11. * guarantee it works.
  12. *
  13. * Tom St Denis, [email protected], http://math.libtomcrypt.org
  14. */
  15. #ifndef BN_H_
  16. #define BN_H_
  17. #include <stdio.h>
  18. #include <string.h>
  19. #include <stdlib.h>
  20. #include <ctype.h>
  21. #include <limits.h>
  22. #include <tommath_class.h>
  23. #undef MIN
  24. #define MIN(x,y) ((x)<(y)?(x):(y))
  25. #undef MAX
  26. #define MAX(x,y) ((x)>(y)?(x):(y))
  27. #ifdef __cplusplus
  28. extern "C" {
  29. /* C++ compilers don't like assigning void * to mp_digit * */
  30. #define OPT_CAST(x) (x *)
  31. #else
  32. /* C on the other hand doesn't care */
  33. #define OPT_CAST(x)
  34. #endif
  35. /* detect 64-bit mode if possible */
  36. #if defined(__x86_64__)
  37. #if !(defined(MP_64BIT) && defined(MP_16BIT) && defined(MP_8BIT))
  38. #define MP_64BIT
  39. #endif
  40. #endif
  41. /* some default configurations.
  42. *
  43. * A "mp_digit" must be able to hold DIGIT_BIT + 1 bits
  44. * A "mp_word" must be able to hold 2*DIGIT_BIT + 1 bits
  45. *
  46. * At the very least a mp_digit must be able to hold 7 bits
  47. * [any size beyond that is ok provided it doesn't overflow the data type]
  48. */
  49. #ifdef MP_8BIT
  50. typedef unsigned char mp_digit;
  51. typedef unsigned short mp_word;
  52. #elif defined(MP_16BIT)
  53. typedef unsigned short mp_digit;
  54. typedef unsigned long mp_word;
  55. #elif defined(MP_64BIT)
  56. /* for GCC only on supported platforms */
  57. #ifndef CRYPT
  58. typedef unsigned long long ulong64;
  59. typedef signed long long long64;
  60. #endif
  61. typedef unsigned long mp_digit;
  62. typedef unsigned long mp_word __attribute__ ((mode(TI)));
  63. #define DIGIT_BIT 60
  64. #else
  65. /* this is the default case, 28-bit digits */
  66. /* this is to make porting into LibTomCrypt easier :-) */
  67. #ifndef CRYPT
  68. #if defined(_MSC_VER) || defined(__BORLANDC__)
  69. typedef unsigned __int64 ulong64;
  70. typedef signed __int64 long64;
  71. #else
  72. typedef unsigned long long ulong64;
  73. typedef signed long long long64;
  74. #endif
  75. #endif
  76. typedef unsigned long mp_digit;
  77. typedef ulong64 mp_word;
  78. #ifdef MP_31BIT
  79. /* this is an extension that uses 31-bit digits */
  80. #define DIGIT_BIT 31
  81. #else
  82. /* default case is 28-bit digits, defines MP_28BIT as a handy macro to test */
  83. #define DIGIT_BIT 28
  84. #define MP_28BIT
  85. #endif
  86. #endif
  87. /* define heap macros */
  88. #ifndef CRYPT
  89. /* default to libc stuff */
  90. #ifndef XMALLOC
  91. #define XMALLOC malloc
  92. #define XFREE free
  93. #define XREALLOC realloc
  94. #define XCALLOC calloc
  95. #else
  96. /* prototypes for our heap functions */
  97. extern void *XMALLOC(size_t n);
  98. extern void *REALLOC(void *p, size_t n);
  99. extern void *XCALLOC(size_t n, size_t s);
  100. extern void XFREE(void *p);
  101. #endif
  102. #endif
  103. /* otherwise the bits per digit is calculated automatically from the size of a mp_digit */
  104. #ifndef DIGIT_BIT
  105. #define DIGIT_BIT ((int)((CHAR_BIT * sizeof(mp_digit) - 1))) /* bits per digit */
  106. #endif
  107. #define MP_DIGIT_BIT DIGIT_BIT
  108. #define MP_MASK ((((mp_digit)1)<<((mp_digit)DIGIT_BIT))-((mp_digit)1))
  109. #define MP_DIGIT_MAX MP_MASK
  110. /* equalities */
  111. #define MP_LT -1 /* less than */
  112. #define MP_EQ 0 /* equal to */
  113. #define MP_GT 1 /* greater than */
  114. #define MP_ZPOS 0 /* positive integer */
  115. #define MP_NEG 1 /* negative */
  116. #define MP_OKAY 0 /* ok result */
  117. #define MP_MEM -2 /* out of mem */
  118. #define MP_VAL -3 /* invalid input */
  119. #define MP_RANGE MP_VAL
  120. #define MP_YES 1 /* yes response */
  121. #define MP_NO 0 /* no response */
  122. /* Primality generation flags */
  123. #define LTM_PRIME_BBS 0x0001 /* BBS style prime */
  124. #define LTM_PRIME_SAFE 0x0002 /* Safe prime (p-1)/2 == prime */
  125. #define LTM_PRIME_2MSB_OFF 0x0004 /* force 2nd MSB to 0 */
  126. #define LTM_PRIME_2MSB_ON 0x0008 /* force 2nd MSB to 1 */
  127. typedef int mp_err;
  128. /* you'll have to tune these... */
  129. extern int KARATSUBA_MUL_CUTOFF,
  130. KARATSUBA_SQR_CUTOFF,
  131. TOOM_MUL_CUTOFF,
  132. TOOM_SQR_CUTOFF;
  133. /* define this to use lower memory usage routines (exptmods mostly) */
  134. /* #define MP_LOW_MEM */
  135. /* default precision */
  136. #ifndef MP_PREC
  137. #ifndef MP_LOW_MEM
  138. #define MP_PREC 64 /* default digits of precision */
  139. #else
  140. #define MP_PREC 8 /* default digits of precision */
  141. #endif
  142. #endif
  143. /* size of comba arrays, should be at least 2 * 2**(BITS_PER_WORD - BITS_PER_DIGIT*2) */
  144. #define MP_WARRAY (1 << (sizeof(mp_word) * CHAR_BIT - 2 * DIGIT_BIT + 1))
  145. /* the infamous mp_int structure */
  146. typedef struct {
  147. int used, alloc, sign;
  148. mp_digit *dp;
  149. } mp_int;
  150. /* callback for mp_prime_random, should fill dst with random bytes and return how many read [upto len] */
  151. typedef int ltm_prime_callback(unsigned char *dst, int len, void *dat);
  152. #define USED(m) ((m)->used)
  153. #define DIGIT(m,k) ((m)->dp[(k)])
  154. #define SIGN(m) ((m)->sign)
  155. /* error code to char* string */
  156. char *mp_error_to_string(int code);
  157. /* ---> init and deinit bignum functions <--- */
  158. /* init a bignum */
  159. int mp_init(mp_int *a);
  160. /* free a bignum */
  161. void mp_clear(mp_int *a);
  162. /* init a null terminated series of arguments */
  163. int mp_init_multi(mp_int *mp, ...);
  164. /* clear a null terminated series of arguments */
  165. void mp_clear_multi(mp_int *mp, ...);
  166. /* exchange two ints */
  167. void mp_exch(mp_int *a, mp_int *b);
  168. /* shrink ram required for a bignum */
  169. int mp_shrink(mp_int *a);
  170. /* grow an int to a given size */
  171. int mp_grow(mp_int *a, int size);
  172. /* init to a given number of digits */
  173. int mp_init_size(mp_int *a, int size);
  174. /* ---> Basic Manipulations <--- */
  175. #define mp_iszero(a) (((a)->used == 0) ? MP_YES : MP_NO)
  176. #define mp_iseven(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 0)) ? MP_YES : MP_NO)
  177. #define mp_isodd(a) (((a)->used > 0 && (((a)->dp[0] & 1) == 1)) ? MP_YES : MP_NO)
  178. /* set to zero */
  179. void mp_zero(mp_int *a);
  180. /* set to a digit */
  181. void mp_set(mp_int *a, mp_digit b);
  182. /* set a 32-bit const */
  183. int mp_set_int(mp_int *a, unsigned long b);
  184. /* get a 32-bit value */
  185. unsigned long mp_get_int(mp_int * a);
  186. /* initialize and set a digit */
  187. int mp_init_set (mp_int * a, mp_digit b);
  188. /* initialize and set 32-bit value */
  189. int mp_init_set_int (mp_int * a, unsigned long b);
  190. /* copy, b = a */
  191. int mp_copy(mp_int *a, mp_int *b);
  192. /* inits and copies, a = b */
  193. int mp_init_copy(mp_int *a, mp_int *b);
  194. /* trim unused digits */
  195. void mp_clamp(mp_int *a);
  196. /* ---> digit manipulation <--- */
  197. /* right shift by "b" digits */
  198. void mp_rshd(mp_int *a, int b);
  199. /* left shift by "b" digits */
  200. int mp_lshd(mp_int *a, int b);
  201. /* c = a / 2**b */
  202. int mp_div_2d(mp_int *a, int b, mp_int *c, mp_int *d);
  203. /* b = a/2 */
  204. int mp_div_2(mp_int *a, mp_int *b);
  205. /* c = a * 2**b */
  206. int mp_mul_2d(mp_int *a, int b, mp_int *c);
  207. /* b = a*2 */
  208. int mp_mul_2(mp_int *a, mp_int *b);
  209. /* c = a mod 2**d */
  210. int mp_mod_2d(mp_int *a, int b, mp_int *c);
  211. /* computes a = 2**b */
  212. int mp_2expt(mp_int *a, int b);
  213. /* Counts the number of lsbs which are zero before the first zero bit */
  214. int mp_cnt_lsb(mp_int *a);
  215. /* I Love Earth! */
  216. /* makes a pseudo-random int of a given size */
  217. int mp_rand(mp_int *a, int digits);
  218. /* ---> binary operations <--- */
  219. /* c = a XOR b */
  220. int mp_xor(mp_int *a, mp_int *b, mp_int *c);
  221. /* c = a OR b */
  222. int mp_or(mp_int *a, mp_int *b, mp_int *c);
  223. /* c = a AND b */
  224. int mp_and(mp_int *a, mp_int *b, mp_int *c);
  225. /* ---> Basic arithmetic <--- */
  226. /* b = -a */
  227. int mp_neg(mp_int *a, mp_int *b);
  228. /* b = |a| */
  229. int mp_abs(mp_int *a, mp_int *b);
  230. /* compare a to b */
  231. int mp_cmp(mp_int *a, mp_int *b);
  232. /* compare |a| to |b| */
  233. int mp_cmp_mag(mp_int *a, mp_int *b);
  234. /* c = a + b */
  235. int mp_add(mp_int *a, mp_int *b, mp_int *c);
  236. /* c = a - b */
  237. int mp_sub(mp_int *a, mp_int *b, mp_int *c);
  238. /* c = a * b */
  239. int mp_mul(mp_int *a, mp_int *b, mp_int *c);
  240. /* b = a*a */
  241. int mp_sqr(mp_int *a, mp_int *b);
  242. /* a/b => cb + d == a */
  243. int mp_div(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  244. /* c = a mod b, 0 <= c < b */
  245. int mp_mod(mp_int *a, mp_int *b, mp_int *c);
  246. /* ---> single digit functions <--- */
  247. /* compare against a single digit */
  248. int mp_cmp_d(mp_int *a, mp_digit b);
  249. /* c = a + b */
  250. int mp_add_d(mp_int *a, mp_digit b, mp_int *c);
  251. /* c = a - b */
  252. int mp_sub_d(mp_int *a, mp_digit b, mp_int *c);
  253. /* c = a * b */
  254. int mp_mul_d(mp_int *a, mp_digit b, mp_int *c);
  255. /* a/b => cb + d == a */
  256. int mp_div_d(mp_int *a, mp_digit b, mp_int *c, mp_digit *d);
  257. /* a/3 => 3c + d == a */
  258. int mp_div_3(mp_int *a, mp_int *c, mp_digit *d);
  259. /* c = a**b */
  260. int mp_expt_d(mp_int *a, mp_digit b, mp_int *c);
  261. /* c = a mod b, 0 <= c < b */
  262. int mp_mod_d(mp_int *a, mp_digit b, mp_digit *c);
  263. /* ---> number theory <--- */
  264. /* d = a + b (mod c) */
  265. int mp_addmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  266. /* d = a - b (mod c) */
  267. int mp_submod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  268. /* d = a * b (mod c) */
  269. int mp_mulmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  270. /* c = a * a (mod b) */
  271. int mp_sqrmod(mp_int *a, mp_int *b, mp_int *c);
  272. /* c = 1/a (mod b) */
  273. int mp_invmod(mp_int *a, mp_int *b, mp_int *c);
  274. /* c = (a, b) */
  275. int mp_gcd(mp_int *a, mp_int *b, mp_int *c);
  276. /* produces value such that U1*a + U2*b = U3 */
  277. int mp_exteuclid(mp_int *a, mp_int *b, mp_int *U1, mp_int *U2, mp_int *U3);
  278. /* c = [a, b] or (a*b)/(a, b) */
  279. int mp_lcm(mp_int *a, mp_int *b, mp_int *c);
  280. /* finds one of the b'th root of a, such that |c|**b <= |a|
  281. *
  282. * returns error if a < 0 and b is even
  283. */
  284. int mp_n_root(mp_int *a, mp_digit b, mp_int *c);
  285. /* special sqrt algo */
  286. int mp_sqrt(mp_int *arg, mp_int *ret);
  287. /* is number a square? */
  288. int mp_is_square(mp_int *arg, int *ret);
  289. /* computes the jacobi c = (a | n) (or Legendre if b is prime) */
  290. int mp_jacobi(mp_int *a, mp_int *n, int *c);
  291. /* used to setup the Barrett reduction for a given modulus b */
  292. int mp_reduce_setup(mp_int *a, mp_int *b);
  293. /* Barrett Reduction, computes a (mod b) with a precomputed value c
  294. *
  295. * Assumes that 0 < a <= b*b, note if 0 > a > -(b*b) then you can merely
  296. * compute the reduction as -1 * mp_reduce(mp_abs(a)) [pseudo code].
  297. */
  298. int mp_reduce(mp_int *a, mp_int *b, mp_int *c);
  299. /* setups the montgomery reduction */
  300. int mp_montgomery_setup(mp_int *a, mp_digit *mp);
  301. /* computes a = B**n mod b without division or multiplication useful for
  302. * normalizing numbers in a Montgomery system.
  303. */
  304. int mp_montgomery_calc_normalization(mp_int *a, mp_int *b);
  305. /* computes x/R == x (mod N) via Montgomery Reduction */
  306. int mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
  307. /* returns 1 if a is a valid DR modulus */
  308. int mp_dr_is_modulus(mp_int *a);
  309. /* sets the value of "d" required for mp_dr_reduce */
  310. void mp_dr_setup(mp_int *a, mp_digit *d);
  311. /* reduces a modulo b using the Diminished Radix method */
  312. int mp_dr_reduce(mp_int *a, mp_int *b, mp_digit mp);
  313. /* returns true if a can be reduced with mp_reduce_2k */
  314. int mp_reduce_is_2k(mp_int *a);
  315. /* determines k value for 2k reduction */
  316. int mp_reduce_2k_setup(mp_int *a, mp_digit *d);
  317. /* reduces a modulo b where b is of the form 2**p - k [0 <= a] */
  318. int mp_reduce_2k(mp_int *a, mp_int *n, mp_digit d);
  319. /* d = a**b (mod c) */
  320. int mp_exptmod(mp_int *a, mp_int *b, mp_int *c, mp_int *d);
  321. /* ---> Primes <--- */
  322. /* number of primes */
  323. #ifdef MP_8BIT
  324. #define PRIME_SIZE 31
  325. #else
  326. #define PRIME_SIZE 256
  327. #endif
  328. /* table of first PRIME_SIZE primes */
  329. extern const mp_digit __prime_tab[];
  330. /* result=1 if a is divisible by one of the first PRIME_SIZE primes */
  331. int mp_prime_is_divisible(mp_int *a, int *result);
  332. /* performs one Fermat test of "a" using base "b".
  333. * Sets result to 0 if composite or 1 if probable prime
  334. */
  335. int mp_prime_fermat(mp_int *a, mp_int *b, int *result);
  336. /* performs one Miller-Rabin test of "a" using base "b".
  337. * Sets result to 0 if composite or 1 if probable prime
  338. */
  339. int mp_prime_miller_rabin(mp_int *a, mp_int *b, int *result);
  340. /* This gives [for a given bit size] the number of trials required
  341. * such that Miller-Rabin gives a prob of failure lower than 2^-96
  342. */
  343. int mp_prime_rabin_miller_trials(int size);
  344. /* performs t rounds of Miller-Rabin on "a" using the first
  345. * t prime bases. Also performs an initial sieve of trial
  346. * division. Determines if "a" is prime with probability
  347. * of error no more than (1/4)**t.
  348. *
  349. * Sets result to 1 if probably prime, 0 otherwise
  350. */
  351. int mp_prime_is_prime(mp_int *a, int t, int *result);
  352. /* finds the next prime after the number "a" using "t" trials
  353. * of Miller-Rabin.
  354. *
  355. * bbs_style = 1 means the prime must be congruent to 3 mod 4
  356. */
  357. int mp_prime_next_prime(mp_int *a, int t, int bbs_style);
  358. /* makes a truly random prime of a given size (bytes),
  359. * call with bbs = 1 if you want it to be congruent to 3 mod 4
  360. *
  361. * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
  362. * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
  363. * so it can be NULL
  364. *
  365. * The prime generated will be larger than 2^(8*size).
  366. */
  367. #define mp_prime_random(a, t, size, bbs, cb, dat) mp_prime_random_ex(a, t, ((size) * 8) + 1, (bbs==1)?LTM_PRIME_BBS:0, cb, dat)
  368. /* makes a truly random prime of a given size (bits),
  369. *
  370. * Flags are as follows:
  371. *
  372. * LTM_PRIME_BBS - make prime congruent to 3 mod 4
  373. * LTM_PRIME_SAFE - make sure (p-1)/2 is prime as well (implies LTM_PRIME_BBS)
  374. * LTM_PRIME_2MSB_OFF - make the 2nd highest bit zero
  375. * LTM_PRIME_2MSB_ON - make the 2nd highest bit one
  376. *
  377. * You have to supply a callback which fills in a buffer with random bytes. "dat" is a parameter you can
  378. * have passed to the callback (e.g. a state or something). This function doesn't use "dat" itself
  379. * so it can be NULL
  380. *
  381. */
  382. int mp_prime_random_ex(mp_int *a, int t, int size, int flags, ltm_prime_callback cb, void *dat);
  383. /* ---> radix conversion <--- */
  384. int mp_count_bits(mp_int *a);
  385. int mp_unsigned_bin_size(mp_int *a);
  386. int mp_read_unsigned_bin(mp_int *a, unsigned char *b, int c);
  387. int mp_to_unsigned_bin(mp_int *a, unsigned char *b);
  388. int mp_signed_bin_size(mp_int *a);
  389. int mp_read_signed_bin(mp_int *a, unsigned char *b, int c);
  390. int mp_to_signed_bin(mp_int *a, unsigned char *b);
  391. int mp_read_radix(mp_int *a, char *str, int radix);
  392. int mp_toradix(mp_int *a, char *str, int radix);
  393. int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen);
  394. int mp_radix_size(mp_int *a, int radix, int *size);
  395. int mp_fread(mp_int *a, int radix, FILE *stream);
  396. int mp_fwrite(mp_int *a, int radix, FILE *stream);
  397. #define mp_read_raw(mp, str, len) mp_read_signed_bin((mp), (str), (len))
  398. #define mp_raw_size(mp) mp_signed_bin_size(mp)
  399. #define mp_toraw(mp, str) mp_to_signed_bin((mp), (str))
  400. #define mp_read_mag(mp, str, len) mp_read_unsigned_bin((mp), (str), (len))
  401. #define mp_mag_size(mp) mp_unsigned_bin_size(mp)
  402. #define mp_tomag(mp, str) mp_to_unsigned_bin((mp), (str))
  403. #define mp_tobinary(M, S) mp_toradix((M), (S), 2)
  404. #define mp_tooctal(M, S) mp_toradix((M), (S), 8)
  405. #define mp_todecimal(M, S) mp_toradix((M), (S), 10)
  406. #define mp_tohex(M, S) mp_toradix((M), (S), 16)
  407. /* lowlevel functions, do not call! */
  408. int s_mp_add(mp_int *a, mp_int *b, mp_int *c);
  409. int s_mp_sub(mp_int *a, mp_int *b, mp_int *c);
  410. #define s_mp_mul(a, b, c) s_mp_mul_digs(a, b, c, (a)->used + (b)->used + 1)
  411. int fast_s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
  412. int s_mp_mul_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
  413. int fast_s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
  414. int s_mp_mul_high_digs(mp_int *a, mp_int *b, mp_int *c, int digs);
  415. int fast_s_mp_sqr(mp_int *a, mp_int *b);
  416. int s_mp_sqr(mp_int *a, mp_int *b);
  417. int mp_karatsuba_mul(mp_int *a, mp_int *b, mp_int *c);
  418. int mp_toom_mul(mp_int *a, mp_int *b, mp_int *c);
  419. int mp_karatsuba_sqr(mp_int *a, mp_int *b);
  420. int mp_toom_sqr(mp_int *a, mp_int *b);
  421. int fast_mp_invmod(mp_int *a, mp_int *b, mp_int *c);
  422. int mp_invmod_slow (mp_int * a, mp_int * b, mp_int * c);
  423. int fast_mp_montgomery_reduce(mp_int *a, mp_int *m, mp_digit mp);
  424. int mp_exptmod_fast(mp_int *G, mp_int *X, mp_int *P, mp_int *Y, int mode);
  425. int s_mp_exptmod (mp_int * G, mp_int * X, mp_int * P, mp_int * Y);
  426. void bn_reverse(unsigned char *s, int len);
  427. extern const char *mp_s_rmap;
  428. #ifdef __cplusplus
  429. }
  430. #endif
  431. #endif