ESAPI-C 1.0
The OWASP Enterprise Security API for C

chalkboard/random.c

Go to the documentation of this file.
00001 /*
00002  * rand() is ANSI C, but not cryptographically strong by a long shot
00003  * Use CyptGenRandom on Windows, or hw rand() on Linux, or the Yarrow algorithm on Mac OS X/BSD
00004  * Alternately, we might provide an implementation of Fortuna, like this:
00005  * http://github.com/sjaeckel/libtomcrypt/blob/master/src/prngs/fortuna.c
00006  *
00007  */
00008 
00009 /*
00010  * An implementation of the Mersenne Twister
00011  */
00012 
00013 #define N 624
00014 #define M 397
00015 #define A 0x9908b0dfUL
00016 #define U 0x80000000UL
00017 #define L 0x7fffffffUL
00018 
00019 static unsigned long x[N];
00020 static int next;
00021 
00022 void jsw_seed ( unsigned long s )
00023 {
00024   int i;
00025 
00026   x[0] = s & 0xffffffffUL;
00027 
00028   for ( i = 1; i < N; i++ ) {
00029     x[i] = ( 1812433253UL
00030       * ( x[i - 1] ^ ( x[i - 1] >> 30 ) ) + i );
00031     x[i] &= 0xffffffffUL;
00032   }
00033 }
00034 
00035 
00036 unsigned long jsw_rand ( void )
00037 {
00038   unsigned long y, a;
00039   int i;
00040 
00041   /* Refill x if exhausted */
00042   if ( next == N ) {
00043     next = 0;
00044 
00045     for ( i = 0; i < N - 1; i++ ) {
00046       y = ( x[i] & U ) | x[i + 1] & L;
00047       a = ( y & 0x1UL ) ? A : 0x0UL;
00048       x[i] = x[( i + M ) % N] ^ ( y >> 1 ) ^ a;
00049     }
00050 
00051     y = ( x[N - 1] & U ) | x[0] & L;
00052     a = ( y & 0x1UL ) ? A : 0x0UL;
00053     x[N - 1] = x[M - 1] ^ ( y >> 1 ) ^ a;
00054   }
00055 
00056   y = x[next++];
00057 
00058   /* Improve distribution */
00059   y ^= (y >> 11);
00060   y ^= (y << 7) & 0x9d2c5680UL;
00061   y ^= (y << 15) & 0xefc60000UL;
00062   y ^= (y >> 18);
00063 
00064   return y;
00065 }
 All Data Structures Files Functions Variables Typedefs Defines