[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]

[or-cvs] Make crypto_pseudo_rand* never fail.



Update of /home/or/cvsroot/src/common
In directory moria.mit.edu:/tmp/cvs-serv21871/common

Modified Files:
	crypto.c crypto.h 
Log Message:
Make crypto_pseudo_rand* never fail.

Index: crypto.c
===================================================================
RCS file: /home/or/cvsroot/src/common/crypto.c,v
retrieving revision 1.41
retrieving revision 1.42
diff -u -d -r1.41 -r1.42
--- crypto.c	10 Oct 2003 01:48:03 -0000	1.41
+++ crypto.c	12 Nov 2003 04:12:35 -0000	1.42
@@ -999,10 +999,23 @@
   return (RAND_bytes(to, n) != 1);
 }
 
-int crypto_pseudo_rand(unsigned int n, unsigned char *to)
+void crypto_pseudo_rand(unsigned int n, unsigned char *to)
 {
   assert(to);
-  return (RAND_pseudo_bytes(to, n) == -1);
+  if (RAND_pseudo_bytes(to, n) == -1) {
+    log_fn(LOG_ERR, "RAND_pseudo_bytes failed unexpectedly.");
+    exit(1);
+  }
+}
+
+int crypto_pseudo_rand_int(int max) {
+  unsigned int val;
+  crypto_pseudo_rand(sizeof(val), (unsigned char*) &val);
+  /* Bug: Low values are _slightly_ favored over high values because
+   * ((unsigned)-1)%max != max-1 .  This shouldn't matter if max is
+   * significantly smaller than ((unsigned)-1).
+   **/
+  return val % max;
 }
 
 /* errors */

Index: crypto.h
===================================================================
RCS file: /home/or/cvsroot/src/common/crypto.h,v
retrieving revision 1.20
retrieving revision 1.21
diff -u -d -r1.20 -r1.21
--- crypto.h	8 Oct 2003 02:04:07 -0000	1.20
+++ crypto.h	12 Nov 2003 04:12:35 -0000	1.21
@@ -100,9 +100,8 @@
 /* random numbers */
 int crypto_seed_rng();
 int crypto_rand(unsigned int n, unsigned char *to);
-int crypto_pseudo_rand(unsigned int n, unsigned char *to);
-
-#define CRYPTO_PSEUDO_RAND_INT(v) crypto_pseudo_rand(sizeof(v),(char*)&(v))
+void crypto_pseudo_rand(unsigned int n, unsigned char *to);
+int crypto_pseudo_rand_int(int max);
 
 /* errors */
 char *crypto_perror();