libcurve/src/rand.c

53 lines
977 B
C

#include <rand.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sha256.h>
char __rand_state[32];
int __rand_seeded = 0;
void rand_init_auto()
{
int f = open("/dev/random", O_RDONLY);
read( f, __rand_state, 32 );
close(f);
__rand_seeded = 1;
}
void rand_init_seeded(long seed)
{
memset( __rand_state, 0x00, 32 );
memcpy(__rand_state, &seed, 8 );
sha256(__rand_state, 32, __rand_state);
sha256(__rand_state, 32, __rand_state);
sha256(__rand_state, 32, __rand_state);
sha256(__rand_state, 32, __rand_state);
__rand_seeded = 1;
}
void rand_get_bytes(char *dst, int length)
{
if (!__rand_seeded)
rand_init_auto();
while (length > 0)
{
int l = length > 32 ? 32 : length;
sha256(__rand_state, 32, __rand_state);
memcpy( dst, __rand_state, l);
length -= l;
dst += l;
}
sha256(__rand_state, 32, __rand_state);
}