comparison 3rdparty/libtommath/bn_mp_rand.c @ 0:2cf249471370

convert mercurial for git
author Takahiro SHIMIZU <anatofuz@cr.ie.u-ryukyu.ac.jp>
date Tue, 08 May 2018 16:09:12 +0900
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:2cf249471370
1 #include <tommath_private.h>
2 #ifdef BN_MP_RAND_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis
4 *
5 * LibTomMath is a library that provides multiple-precision
6 * integer arithmetic as well as number theoretic functionality.
7 *
8 * The library was designed directly after the MPI library by
9 * Michael Fromberger but has been written from scratch with
10 * additional optimizations in place.
11 *
12 * The library is free for all purposes without any express
13 * guarantee it works.
14 *
15 * Tom St Denis, tstdenis82@gmail.com, http://libtom.org
16 */
17
18 #if MP_GEN_RANDOM_MAX == 0xffffffff
19 #define MP_GEN_RANDOM_SHIFT 32
20 #elif MP_GEN_RANDOM_MAX == 32767
21 /* SHRT_MAX */
22 #define MP_GEN_RANDOM_SHIFT 15
23 #elif MP_GEN_RANDOM_MAX == 2147483647
24 /* INT_MAX */
25 #define MP_GEN_RANDOM_SHIFT 31
26 #elif !defined(MP_GEN_RANDOM_SHIFT)
27 #error Thou shalt define their own valid MP_GEN_RANDOM_SHIFT
28 #endif
29
30 /* makes a pseudo-random int of a given size */
31 static mp_digit mp_gen_random(void)
32 {
33 mp_digit d = 0, msk = 0;
34 do {
35 d <<= MP_GEN_RANDOM_SHIFT;
36 d |= ((mp_digit) MP_GEN_RANDOM());
37 msk <<= MP_GEN_RANDOM_SHIFT;
38 msk |= MP_GEN_RANDOM_MAX;
39 } while ((MP_MASK & msk) != MP_MASK);
40 d &= MP_MASK;
41 return d;
42 }
43
44 int
45 mp_rand (mp_int * a, int digits)
46 {
47 int res;
48 mp_digit d;
49
50 mp_zero (a);
51 if (digits <= 0) {
52 return MP_OKAY;
53 }
54
55 /* first place a random non-zero digit */
56 do {
57 d = mp_gen_random();
58 } while (d == 0);
59
60 if ((res = mp_add_d (a, d, a)) != MP_OKAY) {
61 return res;
62 }
63
64 while (--digits > 0) {
65 if ((res = mp_lshd (a, 1)) != MP_OKAY) {
66 return res;
67 }
68
69 if ((res = mp_add_d (a, mp_gen_random(), a)) != MP_OKAY) {
70 return res;
71 }
72 }
73
74 return MP_OKAY;
75 }
76 #endif
77
78 /* $Source$ */
79 /* $Revision$ */
80 /* $Date$ */