1 /* TomsFastMath, a fast ISO C bignum library.
3 * This project is meant to fill in where LibTomMath
4 * falls short. That is speed ;-)
6 * This project is public domain and free for all purposes.
8 * Tom St Denis, tomstdenis@gmail.com
10 #include <tfm_private.h>
12 /* This is possibly the mother of all prime generation functions, muahahahahaha! */
13 int fp_prime_random_ex(fp_int *a, int t, int size, int flags, tfm_prime_callback cb, void *dat)
15 unsigned char *tmp, maskAND, maskOR_msb, maskOR_lsb;
16 int res, err, bsize, maskOR_msb_offset;
18 /* sanity check the input */
19 if (size <= 1 || cb == NULL || t <= 0 || t > FP_PRIME_SIZE) {
23 /* TFM_PRIME_SAFE implies TFM_PRIME_BBS */
24 if (flags & TFM_PRIME_SAFE) {
25 flags |= TFM_PRIME_BBS;
28 /* calc the byte size */
29 bsize = (size>>3)+(size&7?1:0);
31 /* we need a buffer of bsize bytes */
37 /* calc the maskAND value for the MSbyte*/
38 maskAND = 0xFF >> ((8 - (size & 7)) & 7);
40 /* calc the maskOR_msb */
42 maskOR_msb_offset = (size - 2) >> 3;
43 if (flags & TFM_PRIME_2MSB_ON) {
44 maskOR_msb |= 1 << ((size - 2) & 7);
45 } else if (flags & TFM_PRIME_2MSB_OFF) {
46 maskAND &= ~(1 << ((size - 2) & 7));
49 /* get the maskOR_lsb */
51 if (flags & TFM_PRIME_BBS) {
57 if (cb(tmp, bsize, dat) != bsize) {
62 /* work over the MSbyte */
64 tmp[0] |= 1 << ((size - 1) & 7);
66 /* mix in the maskORs */
67 tmp[maskOR_msb_offset] |= maskOR_msb;
68 tmp[bsize-1] |= maskOR_lsb;
71 fp_read_unsigned_bin(a, tmp, bsize);
74 res = fp_isprime_ex(a, t);
75 if (res == FP_NO) continue;
77 if (flags & TFM_PRIME_SAFE) {
78 /* see if (a-1)/2 is prime */
83 res = fp_isprime_ex(a, t);
85 } while (res == FP_NO);
87 if (flags & TFM_PRIME_SAFE) {
88 /* restore a to the original value */