diff --git a/wolfcrypt/src/random.c b/wolfcrypt/src/random.c index c6d667c029..7141c97ad9 100644 --- a/wolfcrypt/src/random.c +++ b/wolfcrypt/src/random.c @@ -1652,6 +1652,10 @@ static int _InitRng(WC_RNG* rng, byte* nonce, word32 nonceSz, } #endif +#ifndef USE_WINDOWS_API + rng->seed.fd = 0; +#endif + #ifdef CUSTOM_RAND_GENERATE_BLOCK ret = 0; /* success */ #else @@ -2026,6 +2030,13 @@ int wc_FreeRng(WC_RNG* rng) ret = WC_HW_E; #endif +#ifndef USE_WINDOWS_API + if(rng->seed.fd != 0 && rng->seed.fd != -1) { + close(rng->seed.fd); + rng->seed.fd = -1; + } +#endif + return ret; } @@ -3990,20 +4001,22 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif /* HAVE_INTEL_RDSEED || HAVE_AMD_RDSEED */ #ifndef NO_DEV_URANDOM /* way to disable use of /dev/urandom */ - os->fd = open("/dev/urandom", O_RDONLY); + if (os->fd == 0 || os->fd == -1) { + os->fd = open("/dev/urandom", O_RDONLY); + #if defined(DEBUG_WOLFSSL) + WOLFSSL_MSG("opened /dev/urandom."); + #endif + if (os->fd == -1) + #endif + { + /* may still have /dev/random */ + os->fd = open("/dev/random", O_RDONLY); #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG("opened /dev/urandom."); + WOLFSSL_MSG("opened /dev/random."); #endif - if (os->fd == -1) - #endif - { - /* may still have /dev/random */ - os->fd = open("/dev/random", O_RDONLY); - #if defined(DEBUG_WOLFSSL) - WOLFSSL_MSG("opened /dev/random."); - #endif - if (os->fd == -1) - return OPEN_RAN_E; + if (os->fd == -1) + return OPEN_RAN_E; + } } #if defined(DEBUG_WOLFSSL) WOLFSSL_MSG("rnd read..."); @@ -4027,7 +4040,6 @@ int wc_GenerateSeed(OS_Seed* os, byte* output, word32 sz) #endif } } - close(os->fd); return ret; }