comparison random.c @ 188:c9483550701b

- refactored random mp_int generation and byte->mp_int code - added RSA blinding
author Matt Johnston <matt@ucc.asn.au>
date Thu, 05 May 2005 03:58:21 +0000
parents 4bd4fc8023bd
children 06e326daf16a
comparison
equal deleted inserted replaced
187:c44df7123b0a 188:c9483550701b
23 * SOFTWARE. */ 23 * SOFTWARE. */
24 24
25 #include "includes.h" 25 #include "includes.h"
26 #include "buffer.h" 26 #include "buffer.h"
27 #include "dbutil.h" 27 #include "dbutil.h"
28 #include "bignum.h"
28 29
29 int donerandinit = 0; 30 int donerandinit = 0;
30 31
31 /* this is used to generate unique output from the same hashpool */ 32 /* this is used to generate unique output from the same hashpool */
32 unsigned int counter = 0; 33 unsigned int counter = 0;
157 len -= copylen; 158 len -= copylen;
158 buf += copylen; 159 buf += copylen;
159 } 160 }
160 m_burn(hash, sizeof(hash)); 161 m_burn(hash, sizeof(hash));
161 } 162 }
163
164 /* Generates a random mp_int.
165 * max is a *mp_int specifying an upper bound.
166 * rand must be an initialised *mp_int for the result.
167 * the result rand satisfies: 0 < rand < max
168 * */
169 void gen_random_mpint(mp_int *max, mp_int *rand) {
170
171 unsigned char *randbuf = NULL;
172 unsigned int len = 0;
173 const char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
174
175 const int size_bits = mp_count_bits(max);
176
177 len = size_bits / 8;
178 if ((size_bits % 8) != 0) {
179 len += 1;
180 }
181
182 randbuf = (unsigned char*)m_malloc(len);
183 do {
184 genrandom(randbuf, len);
185 /* Mask out the unrequired bits - mp_read_unsigned_bin expects
186 * MSB first.*/
187 randbuf[0] &= masks[size_bits % 8];
188
189 bytes_to_mp(rand, randbuf, len);
190
191 /* keep regenerating until we get one satisfying
192 * 0 < rand < max */
193 } while ( ( (max != NULL) && (mp_cmp(rand, max) != MP_LT) )
194 || (mp_cmp_d(rand, 0) != MP_GT) );
195 m_burn(randbuf, len);
196 m_free(randbuf);
197 }