diff options
author | Benjamin Peterson <benjamin@python.org> | 2014-12-26 17:09:00 (GMT) |
---|---|---|
committer | Benjamin Peterson <benjamin@python.org> | 2014-12-26 17:09:00 (GMT) |
commit | 27c269a1fe5935d330e9f17c19308ff544e886ff (patch) | |
tree | 870deb23c5d9b61ad907202660bfb05578858469 /Python/random.c | |
parent | a71cfc5cf3e32b694be754ff476ce0181a7319a2 (diff) | |
download | cpython-27c269a1fe5935d330e9f17c19308ff544e886ff.zip cpython-27c269a1fe5935d330e9f17c19308ff544e886ff.tar.gz cpython-27c269a1fe5935d330e9f17c19308ff544e886ff.tar.bz2 |
use getentropy when available (backport of 75ede5bec8db) (closes #23115)
Diffstat (limited to 'Python/random.c')
-rw-r--r-- | Python/random.c | 41 |
1 files changed, 35 insertions, 6 deletions
diff --git a/Python/random.c b/Python/random.c index 1e5776d..d10dda9 100644 --- a/Python/random.c +++ b/Python/random.c @@ -92,8 +92,33 @@ win32_urandom(unsigned char *buffer, Py_ssize_t size, int raise) } return 0; } -#endif /* MS_WINDOWS */ +#elif HAVE_GETENTROPY +/* Fill buffer with size pseudo-random bytes generated by getentropy(). + Return 0 on success, or raise an exception and return -1 on error. + If fatal is nonzero, call Py_FatalError() instead of raising an exception + on error. */ +static int +py_getentropy(unsigned char *buffer, Py_ssize_t size, int fatal) +{ + while (size > 0) { + Py_ssize_t len = Py_MIN(size, 256); + int res = getentropy(buffer, len); + if (res < 0) { + if (fatal) { + Py_FatalError("getentropy() failed"); + } + else { + PyErr_SetFromErrno(PyExc_OSError); + return -1; + } + } + buffer += len; + size -= len; + } + return 0; +} +#endif #ifdef __VMS /* Use openssl random routine */ @@ -291,6 +316,8 @@ _PyOS_URandom(void *buffer, Py_ssize_t size) #ifdef MS_WINDOWS return win32_urandom((unsigned char *)buffer, size, 1); +#elif HAVE_GETENTROPY + return py_getentropy(buffer, size, 0); #else # ifdef __VMS return vms_urandom((unsigned char *)buffer, size, 1); @@ -350,12 +377,12 @@ _PyRandom_Init(void) else { #ifdef MS_WINDOWS (void)win32_urandom((unsigned char *)secret, secret_size, 0); -#else /* #ifdef MS_WINDOWS */ -# ifdef __VMS +#elif __VMS vms_urandom((unsigned char *)secret, secret_size, 0); -# else - dev_urandom_noraise((unsigned char*)secret, secret_size); -# endif +#elif HAVE_GETENTROPY + (void)py_getentropy(secret, secret_size, 1); +#else + dev_urandom_noraise(secret, secret_size); #endif } } @@ -368,6 +395,8 @@ _PyRandom_Fini(void) CryptReleaseContext(hCryptProv, 0); hCryptProv = 0; } +#elif HAVE_GETENTROPY + /* nothing to clean */ #else dev_urandom_close(); #endif |