"Hardening" the bad prand
This commit is contained in:
parent
d0aa85f62e
commit
f3522129a3
1 changed files with 22 additions and 10 deletions
32
prand.c
32
prand.c
|
|
@ -2,14 +2,13 @@
|
||||||
#include <stdint.h>
|
#include <stdint.h>
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <time.h>
|
#include <time.h>
|
||||||
|
#include <unistd.h>
|
||||||
|
|
||||||
#define BUILD_SEED \
|
#define PRAND_BUILD_SEED \
|
||||||
((uint64_t)(__TIME__[0]) * (uint64_t)(__TIME__[1]) * (uint64_t)(__TIME__[3]) * (uint64_t)(__TIME__[4]) * \
|
((uint64_t)(__TIME__[0]) * (uint64_t)(__TIME__[1]) * (uint64_t)(__TIME__[3]) * (uint64_t)(__TIME__[4]) * \
|
||||||
(uint64_t)(__TIME__[6]) * (uint64_t)(__TIME__[7]))
|
(uint64_t)(__TIME__[6]) * (uint64_t)(__TIME__[7]))
|
||||||
|
|
||||||
#define PRNG_SAVE_INTERVAL 50 // Save every 1000 calls to prand()
|
static uint64_t seed = PRAND_BUILD_SEED * 6364136223846793005ULL + 1;
|
||||||
|
|
||||||
static uint64_t seed = BUILD_SEED;
|
|
||||||
|
|
||||||
uint64_t prand() {
|
uint64_t prand() {
|
||||||
seed = seed * 6364136223846793005ULL + 1;
|
seed = seed * 6364136223846793005ULL + 1;
|
||||||
|
|
@ -17,31 +16,44 @@ uint64_t prand() {
|
||||||
}
|
}
|
||||||
|
|
||||||
inline uint64_t prand_range(uint64_t min, uint64_t max) {
|
inline uint64_t prand_range(uint64_t min, uint64_t max) {
|
||||||
return min + (prand() % (max - min + 1));
|
uint64_t range = max - min + 1;
|
||||||
|
uint64_t x;
|
||||||
|
uint64_t limit = UINT64_MAX - (UINT64_MAX % range);
|
||||||
|
|
||||||
|
do {
|
||||||
|
x = prand();
|
||||||
|
} while (x > limit);
|
||||||
|
|
||||||
|
return min + (x % range);
|
||||||
}
|
}
|
||||||
|
|
||||||
void sprand(uint64_t s) {
|
void sprand(uint64_t s) {
|
||||||
if (s) {
|
if (s) {
|
||||||
seed = s;
|
seed ^= (s * 0x9e3779b97f4a7c15ULL) + (seed << 6) + (seed >> 2);
|
||||||
} else {
|
} else {
|
||||||
rand_reseed();
|
seed ^= PRAND_BUILD_SEED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
void rand_reseed() {
|
#undef PRAND_BUILD_SEED
|
||||||
seed = BUILD_SEED;
|
|
||||||
}
|
|
||||||
|
|
||||||
#define PRAND_MAIN
|
#define PRAND_MAIN
|
||||||
#ifdef PRAND_MAIN
|
#ifdef PRAND_MAIN
|
||||||
int main() {
|
int main() {
|
||||||
// time(NULL) provides a somewhat unique seed at runtime
|
// time(NULL) provides a somewhat unique seed at runtime
|
||||||
sprand(time(NULL));
|
sprand(time(NULL));
|
||||||
|
sprand(getpid());
|
||||||
|
sprand(0);
|
||||||
|
|
||||||
uint64_t rn1 = prand();
|
uint64_t rn1 = prand();
|
||||||
uint64_t rn2 = prand();
|
uint64_t rn2 = prand();
|
||||||
|
|
||||||
printf("rn1 = %lu\n", rn1);
|
printf("rn1 = %lu\n", rn1);
|
||||||
printf("rn2 = %lu\n", rn2);
|
printf("rn2 = %lu\n", rn2);
|
||||||
|
|
||||||
|
for (int i = 0; i < 40; i++) {
|
||||||
|
uint64_t random = prand_range(0, 1000);
|
||||||
|
printf("random = %lu\n", random);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue