Skip to content

Commit 5bb2a85

Browse files
stinosdpgeorge
authored andcommitted
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).
1 parent 5290bfa commit 5bb2a85

File tree

3 files changed

+14
-1
lines changed

3 files changed

+14
-1
lines changed

ports/unix/moduos.c

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,11 @@
3939
#endif
4040
#endif
4141

42+
#if _WIN32
43+
#include <windows.h>
44+
#include <bcrypt.h>
45+
#endif
46+
4247
STATIC mp_obj_t mp_uos_getenv(mp_obj_t var_in) {
4348
const char *s = getenv(mp_obj_str_get_str(var_in));
4449
if (s == NULL) {
@@ -100,6 +105,12 @@ STATIC mp_obj_t mp_uos_urandom(mp_obj_t num) {
100105
mp_int_t n = mp_obj_get_int(num);
101106
vstr_t vstr;
102107
vstr_init_len(&vstr, n);
108+
#if _WIN32
109+
NTSTATUS result = BCryptGenRandom(NULL, (unsigned char *)vstr.buf, n, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
110+
if (!BCRYPT_SUCCESS(result)) {
111+
mp_raise_OSError(errno);
112+
}
113+
#else
103114
#ifdef _HAVE_GETRANDOM
104115
RAISE_ERRNO(getrandom(vstr.buf, n, 0), errno);
105116
#else
@@ -108,6 +119,7 @@ STATIC mp_obj_t mp_uos_urandom(mp_obj_t num) {
108119
RAISE_ERRNO(read(fd, vstr.buf, n), errno);
109120
close(fd);
110121
#endif
122+
#endif
111123
return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr);
112124
}
113125
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_uos_urandom_obj, mp_uos_urandom);

ports/windows/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ INC += -I$(VARIANT_DIR)
3333

3434
# compiler settings
3535
CFLAGS = $(INC) -Wall -Wpointer-arith -Wdouble-promotion -Werror -std=gnu99 -DUNIX -D__USE_MINGW_ANSI_STDIO=1 $(CFLAGS_MOD) $(COPT) $(CFLAGS_EXTRA)
36-
LDFLAGS = $(LDFLAGS_MOD) -lm $(LDFLAGS_EXTRA)
36+
LDFLAGS = $(LDFLAGS_MOD) -lm -lbcrypt $(LDFLAGS_EXTRA)
3737

3838
# Debugging/Optimization
3939
ifdef DEBUG

ports/windows/msvc/common.props

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
<Link>
3333
<GenerateDebugInformation>true</GenerateDebugInformation>
3434
<GenerateMapFile>true</GenerateMapFile>
35+
<AdditionalDependencies>Bcrypt.lib;%(AdditionalDependencies)</AdditionalDependencies>
3536
</Link>
3637
</ItemDefinitionGroup>
3738
<ItemGroup>

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy