]> pd.if.org Git - zpackage/blob - libtomcrypt/src/math/rand_prime.c
commit files needed for zpm-fetchurl
[zpackage] / libtomcrypt / src / math / rand_prime.c
1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
2  *
3  * LibTomCrypt is a library that provides various cryptographic
4  * algorithms in a highly modular and flexible manner.
5  *
6  * The library is free for all purposes without any express
7  * guarantee it works.
8  */
9 #include "tomcrypt.h"
10
11 #if defined(LTC_MRSA) || (!defined(LTC_NO_MATH) && !defined(LTC_NO_PRNGS))
12
13 /**
14   @file rand_prime.c
15   Generate a random prime, Tom St Denis
16 */
17
18 #define USE_BBS 1
19
20 int rand_prime(void *N, long len, prng_state *prng, int wprng)
21 {
22    int            err, res, type;
23    unsigned char *buf;
24
25    LTC_ARGCHK(N != NULL);
26
27    /* get type */
28    if (len < 0) {
29       type = USE_BBS;
30       len = -len;
31    } else {
32       type = 0;
33    }
34
35    /* allow sizes between 2 and 512 bytes for a prime size */
36    if (len < 2 || len > 512) {
37       return CRYPT_INVALID_PRIME_SIZE;
38    }
39
40    /* valid PRNG? Better be! */
41    if ((err = prng_is_valid(wprng)) != CRYPT_OK) {
42       return err;
43    }
44
45    /* allocate buffer to work with */
46    buf = XCALLOC(1, len);
47    if (buf == NULL) {
48        return CRYPT_MEM;
49    }
50
51    do {
52       /* generate value */
53       if (prng_descriptor[wprng].read(buf, len, prng) != (unsigned long)len) {
54          XFREE(buf);
55          return CRYPT_ERROR_READPRNG;
56       }
57
58       /* munge bits */
59       buf[0]     |= 0x80 | 0x40;
60       buf[len-1] |= 0x01 | ((type & USE_BBS) ? 0x02 : 0x00);
61
62       /* load value */
63       if ((err = mp_read_unsigned_bin(N, buf, len)) != CRYPT_OK) {
64          XFREE(buf);
65          return err;
66       }
67
68       /* test */
69       if ((err = mp_prime_is_prime(N, LTC_MILLER_RABIN_REPS, &res)) != CRYPT_OK) {
70          XFREE(buf);
71          return err;
72       }
73    } while (res == LTC_MP_NO);
74
75 #ifdef LTC_CLEAN_STACK
76    zeromem(buf, len);
77 #endif
78
79    XFREE(buf);
80    return CRYPT_OK;
81 }
82
83 #endif /* LTC_NO_MATH */
84
85
86 /* ref:         $Format:%D$ */
87 /* git commit:  $Format:%H$ */
88 /* commit time: $Format:%ai$ */