comparison libtomcrypt/src/math/rand_prime.c @ 382:0cbe8f6dbf9e

propagate from branch 'au.asn.ucc.matt.ltc.dropbear' (head 2af22fb4e878750b88f80f90d439b316d229796f) to branch 'au.asn.ucc.matt.dropbear' (head 02c413252c90e9de8e03d91e9939dde3029f5c0a)
author Matt Johnston <matt@ucc.asn.au>
date Thu, 11 Jan 2007 02:41:05 +0000
parents
children f849a5ca2efc
comparison
equal deleted inserted replaced
379:b66a00272a90 382:0cbe8f6dbf9e
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 * Tom St Denis, [email protected], http://libtomcrypt.com
10 */
11 #include "tomcrypt.h"
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, 8, &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
84
85 /* $Source: /cvs/libtom/libtomcrypt/src/math/rand_prime.c,v $ */
86 /* $Revision: 1.6 $ */
87 /* $Date: 2006/03/31 14:15:35 $ */