aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorThijs Schreijer <thijs@thijsschreijer.nl>2025-02-06 17:38:58 +0100
committerThijs Schreijer <thijs@thijsschreijer.nl>2025-02-10 09:01:58 +0100
commitee7524563af91aa4f0336088c7f85dc1d68b0066 (patch)
treee42be2a430642a4ef39bd43a062f519a3db442c2 /src
parent4a128b8969fe4d720f50c1fdb68f0265af8a7117 (diff)
downloadluasystem-ee7524563af91aa4f0336088c7f85dc1d68b0066.tar.gz
luasystem-ee7524563af91aa4f0336088c7f85dc1d68b0066.tar.bz2
luasystem-ee7524563af91aa4f0336088c7f85dc1d68b0066.zip
chore(random): replace deprecated Windows API
Diffstat (limited to 'src')
-rw-r--r--src/random.c19
1 files changed, 4 insertions, 15 deletions
diff --git a/src/random.c b/src/random.c
index e55461a..ee544c4 100644
--- a/src/random.c
+++ b/src/random.c
@@ -10,8 +10,8 @@
10#include <fcntl.h> 10#include <fcntl.h>
11 11
12#ifdef _WIN32 12#ifdef _WIN32
13#include "windows.h" 13 #include <windows.h>
14#include "wincrypt.h" 14 #include <bcrypt.h>
15#else 15#else
16#include <errno.h> 16#include <errno.h>
17#include <unistd.h> 17#include <unistd.h>
@@ -21,7 +21,7 @@
21 21
22/*** 22/***
23Generate random bytes. 23Generate random bytes.
24This uses `CryptGenRandom()` on Windows, and `/dev/urandom` on other platforms. It will return the 24This uses `BCryptGenRandom()` on Windows, and `/dev/urandom` on other platforms. It will return the
25requested number of bytes, or an error, never a partial result. 25requested number of bytes, or an error, never a partial result.
26@function random 26@function random
27@tparam[opt=1] int length number of bytes to get 27@tparam[opt=1] int length number of bytes to get
@@ -53,25 +53,14 @@ static int lua_get_random_bytes(lua_State* L) {
53 ssize_t total_read = 0; 53 ssize_t total_read = 0;
54 54
55#ifdef _WIN32 55#ifdef _WIN32
56 HCRYPTPROV hCryptProv; 56 if (!BCRYPT_SUCCESS(BCryptGenRandom(NULL, buffer, num_bytes, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
57 if (!CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
58 DWORD error = GetLastError();
59 lua_pushnil(L);
60 lua_pushfstring(L, "failed to acquire cryptographic context: %lu", error);
61 return 2;
62 }
63
64 if (!CryptGenRandom(hCryptProv, num_bytes, buffer)) {
65 DWORD error = GetLastError(); 57 DWORD error = GetLastError();
66 lua_pushnil(L); 58 lua_pushnil(L);
67 lua_pushfstring(L, "failed to get random data: %lu", error); 59 lua_pushfstring(L, "failed to get random data: %lu", error);
68 CryptReleaseContext(hCryptProv, 0);
69 return 2; 60 return 2;
70 } 61 }
71 62
72 CryptReleaseContext(hCryptProv, 0);
73#else 63#else
74
75 // for macOS/unixes use /dev/urandom for non-blocking 64 // for macOS/unixes use /dev/urandom for non-blocking
76 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC); 65 int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
77 if (fd < 0) { 66 if (fd < 0) {