// urandom.c // PUBLIC DOMAIN // http:///www.purposeful.co.uk/software/yabaplib /* I, Tom Vajzovic, am the author of this software and its documentation. I permanently abandon all intellectual property rights in them, including copyright, trademarks, design rights, database right, patents, and the right to be identified as the author. I am fairly certain that the software does what the documentation says it does, but I do not guarantee that it does, or that it does what you think it should. I do not guarantee that it will not have undesirable side effects. You are free to use, modify and distribute this software as you please, but you do so at your own risk. If you do not pass on this warning then you may be responsible for any problems encountered by those who obtain the software through you. */ #include #include #include #include #include #include "fileutil.h" #include "urandom.h" void urandom_read(void *buf, size_t size) { static int fd = -1; if (fd < 0) { fd = open("/dev/urandom", O_RDONLY); if (fd < 0) { abort(); } } if (read_all(fd, buf, size) != 0) { abort(); } } _Bool urandom1(void) { uint8_t value; urandom_read(&value, sizeof value); return (value & 1); } uint8_t urandom8(void) { uint8_t value; urandom_read(&value, sizeof value); return value; } uint16_t urandom16(void) { uint16_t value; urandom_read(&value, sizeof value); return value; } uint32_t urandom32(void) { uint32_t value; urandom_read(&value, sizeof value); return value; } uint64_t urandom64(void) { uint64_t value; urandom_read(&value, sizeof value); return value; } uintmax_t urandom_0toN(uintmax_t n) { uintmax_t mask = n; mask |= (mask >> 1); mask |= (mask >> 2); mask |= (mask >> 4); mask |= (mask >> 8); mask |= (mask >> 16); #if (UINTMAX_MAX > 0xFFFFFFFF) mask |= (mask >> 32); #if (UINTMAX_MAX > 0xFFFFFFFFFFFFFFFF) mask |= (mask >> 64); #endif #endif for (;;) { uintmax_t ra[8]; urandom_read(ra, sizeof ra); for (unsigned int i = 0; i < ((sizeof ra) / sizeof ra[0]); i++) { uintmax_t r = (ra[i] & mask); if (r <= n) { return r; } } } } uintmax_t urandom_0toNminus1(uintmax_t n) { return urandom_0toN(n - 1); } uintmax_t urandom_1toN(uintmax_t n) { return (1 + urandom_0toNminus1(n)); } uintmax_t urandom_MtoN(uintmax_t m, uintmax_t n) { return (m + urandom_0toN(n - m)); } uintmax_t urandom_MtoNminus1(uintmax_t m, uintmax_t n) { return (m + urandom_0toNminus1(n - m)); }