refactor: move RNG seeding to testrand

This commit is contained in:
Pieter Wuille
2020-09-08 13:40:26 -07:00
parent b110c106fa
commit 49e6630bca
3 changed files with 56 additions and 42 deletions

View File

@@ -8,6 +8,7 @@
#define SECP256K1_TESTRAND_IMPL_H
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "testrand.h"
@@ -111,4 +112,47 @@ static void secp256k1_rand_flip(unsigned char *b, size_t len) {
b[secp256k1_rand_int(len)] ^= (1 << secp256k1_rand_int(8));
}
static void secp256k1_rand_init(const char* hexseed) {
unsigned char seed16[16] = {0};
if (hexseed) {
int pos = 0;
while (pos < 16 && hexseed[0] != 0 && hexseed[1] != 0) {
unsigned short sh;
if ((sscanf(hexseed, "%2hx", &sh)) == 1) {
seed16[pos] = sh;
} else {
break;
}
hexseed += 2;
pos++;
}
} else {
FILE *frand = fopen("/dev/urandom", "r");
if ((frand == NULL) || fread(&seed16, 1, sizeof(seed16), frand) != sizeof(seed16)) {
uint64_t t = time(NULL) * (uint64_t)1337;
fprintf(stderr, "WARNING: could not read 16 bytes from /dev/urandom; falling back to insecure PRNG\n");
seed16[0] ^= t;
seed16[1] ^= t >> 8;
seed16[2] ^= t >> 16;
seed16[3] ^= t >> 24;
seed16[4] ^= t >> 32;
seed16[5] ^= t >> 40;
seed16[6] ^= t >> 48;
seed16[7] ^= t >> 56;
}
if (frand) {
fclose(frand);
}
}
printf("random seed = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", seed16[0], seed16[1], seed16[2], seed16[3], seed16[4], seed16[5], seed16[6], seed16[7], seed16[8], seed16[9], seed16[10], seed16[11], seed16[12], seed16[13], seed16[14], seed16[15]);
secp256k1_rand_seed(seed16);
}
static void secp256k1_rand_finish(void) {
unsigned char run32[32];
secp256k1_rand256(run32);
printf("random run = %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x\n", run32[0], run32[1], run32[2], run32[3], run32[4], run32[5], run32[6], run32[7], run32[8], run32[9], run32[10], run32[11], run32[12], run32[13], run32[14], run32[15]);
}
#endif /* SECP256K1_TESTRAND_IMPL_H */