diff options
| author | stijn <stijn@ignitron.net> | 2022-06-07 11:24:42 +0200 |
|---|---|---|
| committer | Damien George <damien@micropython.org> | 2022-06-07 23:32:30 +1000 |
| commit | 5bb2a85d74bfb7fc2cd322777e0e020f20561583 (patch) | |
| tree | 0e0895a65fa09871816e61f130a6e0601bacb8f9 | |
| parent | 5290bfaefe1973bf36e246aad85a585ba74f44cf (diff) | |
windows: Use BCryptGenRandom to implement os.urandom.
Fix urandom not working on windows (there's no /dev/urandom) by using
a proper cryptographic random function (same one as CPython >= 3.11).
| -rw-r--r-- | ports/unix/moduos.c | 12 | ||||
| -rw-r--r-- | ports/windows/Makefile | 2 | ||||
| -rw-r--r-- | ports/windows/msvc/common.props | 1 |
3 files changed, 14 insertions, 1 deletions
diff --git a/ports/unix/moduos.c b/ports/unix/moduos.c index 1262cd2e2..c7cd19ca3 100644 --- a/ports/unix/moduos.c +++ b/ports/unix/moduos.c @@ -39,6 +39,11 @@ #endif #endif +#if _WIN32 +#include <windows.h> +#include <bcrypt.h> +#endif + STATIC mp_obj_t mp_uos_getenv(mp_obj_t var_in) { const char *s = getenv(mp_obj_str_get_str(var_in)); if (s == NULL) { @@ -100,6 +105,12 @@ STATIC mp_obj_t mp_uos_urandom(mp_obj_t num) { mp_int_t n = mp_obj_get_int(num); vstr_t vstr; vstr_init_len(&vstr, n); + #if _WIN32 + NTSTATUS result = BCryptGenRandom(NULL, (unsigned char *)vstr.buf, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG); + if (!BCRYPT_SUCCESS(result)) { + mp_raise_OSError(errno); + } + #else #ifdef _HAVE_GETRANDOM RAISE_ERRNO(getrandom(vstr.buf, n, 0), errno); #else @@ -108,6 +119,7 @@ STATIC mp_obj_t mp_uos_urandom(mp_obj_t num) { RAISE_ERRNO(read(fd, vstr.buf, n), errno); close(fd); #endif + #endif return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_uos_urandom_obj, mp_uos_urandom); diff --git a/ports/windows/Makefile b/ports/windows/Makefile index 4ffc408fd..3b89ef51e 100644 --- a/ports/windows/Makefile +++ b/ports/windows/Makefile @@ -33,7 +33,7 @@ INC += -I$(VARIANT_DIR) # compiler settings CFLAGS = $(INC) -Wall -Wpointer-arith -Wdouble-promotion -Werror -std=gnu99 -DUNIX -D__USE_MINGW_ANSI_STDIO=1 $(CFLAGS_MOD) $(COPT) $(CFLAGS_EXTRA) -LDFLAGS = $(LDFLAGS_MOD) -lm $(LDFLAGS_EXTRA) +LDFLAGS = $(LDFLAGS_MOD) -lm -lbcrypt $(LDFLAGS_EXTRA) # Debugging/Optimization ifdef DEBUG diff --git a/ports/windows/msvc/common.props b/ports/windows/msvc/common.props index 7d608a379..7700d9f09 100644 --- a/ports/windows/msvc/common.props +++ b/ports/windows/msvc/common.props @@ -32,6 +32,7 @@ <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <GenerateMapFile>true</GenerateMapFile> + <AdditionalDependencies>Bcrypt.lib;%(AdditionalDependencies)</AdditionalDependencies> </Link> </ItemDefinitionGroup> <ItemGroup> |
