diff 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
line wrap: on
line diff
--- a/random.c	Wed May 04 15:31:17 2005 +0000
+++ b/random.c	Thu May 05 03:58:21 2005 +0000
@@ -25,6 +25,7 @@
 #include "includes.h"
 #include "buffer.h"
 #include "dbutil.h"
+#include "bignum.h"
 
 int donerandinit = 0;
 
@@ -159,3 +160,38 @@
 	}
 	m_burn(hash, sizeof(hash));
 }
+
+/* Generates a random mp_int. 
+ * max is a *mp_int specifying an upper bound.
+ * rand must be an initialised *mp_int for the result.
+ * the result rand satisfies:  0 < rand < max 
+ * */
+void gen_random_mpint(mp_int *max, mp_int *rand) {
+
+	unsigned char *randbuf = NULL;
+	unsigned int len = 0;
+	const char masks[] = {0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f};
+
+	const int size_bits = mp_count_bits(max);
+
+	len = size_bits / 8;
+	if ((size_bits % 8) != 0) {
+		len += 1;
+	}
+
+	randbuf = (unsigned char*)m_malloc(len);
+	do {
+		genrandom(randbuf, len);
+		/* Mask out the unrequired bits - mp_read_unsigned_bin expects
+		 * MSB first.*/
+		randbuf[0] &= masks[size_bits % 8];
+
+		bytes_to_mp(rand, randbuf, len);
+
+		/* keep regenerating until we get one satisfying
+		 * 0 < rand < max    */
+	} while ( ( (max != NULL) && (mp_cmp(rand, max) != MP_LT) )
+			|| (mp_cmp_d(rand, 0) != MP_GT) );
+	m_burn(randbuf, len);
+	m_free(randbuf);
+}