Skip to content

Commit

Permalink
Add support for reading random data from "bcrypt" on Windows
Browse files Browse the repository at this point in the history
This fixes #577

Patch inspired by the same, but simplified after reading the docs.

Signed-off-by: Steffen Jaeckel <s@jaeckel.eu>
  • Loading branch information
sjaeckel committed Aug 7, 2023
1 parent e591a35 commit 437a6b3
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 0 deletions.
10 changes: 10 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,16 @@ if(CMAKE_SYSTEM_NAME MATCHES "CYGWIN")
list(APPEND LTC_C_FLAGS -no-undefined)
endif()

if(MSVC)
cmake_push_check_state()
check_symbol_exists(BCryptGenRandom bcrypt.h BCRYPT_AVAILABLE)
cmake_pop_check_state()
if (BCRYPT_AVAILABLE)
target_link_libraries(${PROJECT_NAME} PRIVATE Bcrypt)
list(APPEND LTC_C_FLAGS -DLTC_WIN32_BCRYPT)
endif()
endif()

# If the user set the environment variables at generate-time, append them
# in order to allow overriding our defaults.
# ${LTC_CFLAGS} means the user passed it via sth like:
Expand Down
4 changes: 4 additions & 0 deletions src/headers/tomcrypt_cfg.h
Original file line number Diff line number Diff line change
Expand Up @@ -300,6 +300,10 @@ typedef unsigned long ltc_mp_digit;
#define LTC_ALIGN(n)
#endif

#if defined(_MSC_VER) && defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0600 && !defined(LTC_WIN32_BCRYPT)
# define LTC_WIN32_BCRYPT
#endif

/* Define `LTC_NO_NULL_TERMINATION_CHECK` in the user code
* before including `tomcrypt.h` to disable this functionality.
*/
Expand Down
3 changes: 3 additions & 0 deletions src/misc/crypt/crypt.c
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,9 @@ const char *crypt_build_settings =
#if defined(LTC_SOBER128)
" SOBER128\n"
#endif
#if defined(LTC_WIN32_BCRYPT)
" WIN32_BCRYPT\n"
#endif

"\nPK Crypto:\n"
#if defined(LTC_MRSA)
Expand Down
16 changes: 16 additions & 0 deletions src/prngs/rng_get_bytes.c
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@ static unsigned long s_rng_ansic(unsigned char *buf, unsigned long len,

/* Try the Microsoft CSP */
#if defined(_WIN32) || defined(_WIN32_WCE)
#if defined(LTC_WIN32_BCRYPT)

#include <bcrypt.h>
#pragma comment(lib, "bcrypt.lib")

static unsigned long s_rng_win32(unsigned char *buf, unsigned long len,
void (*callback)(void))
{
LTC_UNUSED_PARAM(callback);

return BCRYPT_SUCCESS(BCryptGenRandom(NULL, (PUCHAR)buf, (ULONG)len, BCRYPT_USE_SYSTEM_PREFERRED_RNG)) ? len : 0;
}

#else

#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x0501
#endif
Expand Down Expand Up @@ -112,6 +127,7 @@ static unsigned long s_rng_win32(unsigned char *buf, unsigned long len,

return CryptGenRandom(hProv, (DWORD)len, (BYTE *)buf) == TRUE ? len : 0;
}
#endif /* Old WIN32 versions */
#endif /* WIN32 */

/**
Expand Down

0 comments on commit 437a6b3

Please # to comment.