Skip to content

Commit

Permalink
Used OS-specific entropy sources.
Browse files Browse the repository at this point in the history
  • Loading branch information
tfpf committed Oct 1, 2023
1 parent 31817eb commit 58d5aa8
Showing 1 changed file with 44 additions and 5 deletions.
49 changes: 44 additions & 5 deletions lib/hdrbg.c
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,13 @@ static enum hdrbg_err_t
#endif
hdrbg_err = HDRBG_ERR_NONE;

#if defined _WIN32
#include <windows.h>
#include <bcrypt.h>
#elif defined __linux__ || defined __APPLE__
#include <sys/random.h>
#endif

#define HDRBG_SEED_LENGTH 55
#define HDRBG_SECURITY_STRENGTH 32
#define HDRBG_NONCE1_LENGTH 8
Expand Down Expand Up @@ -186,7 +193,41 @@ hdrbg_seed(struct hdrbg_t *hd, uint8_t *s_bytes, size_t s_length)
static size_t
streamtobytes(FILE *fptr_, uint8_t *m_bytes, size_t m_length)
{
FILE *fptr = fptr_ == NULL ? fopen("/dev/urandom", "rb") : fptr_;
// The file will be specified only while testing.
if(fptr_ != NULL)
{
size_t len = fread(m_bytes, sizeof *m_bytes, m_length, fptr_);
if(len < m_length)
{
hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY;
}
return len;
}

// During normal operation, the file won't be specified. Obtain bytes from
// an entropy source.
#if defined _WIN32 && CHAR_BIT == 8
NTSTATUS status = BCryptGenRandom(NULL, m_bytes, m_length, BCRYPT_USE_SYSTEM_PREFERRED_RNG);
if(status != STATUS_SUCCESS)
{
hdrbg_err = HDRBG_ERR_NO_ENTROPY;
return 0;
}
return m_length;
#elif (defined __linux__ || defined __APPLE__) && CHAR_BIT == 8
ssize_t len = getrandom(m_bytes, m_length, 0);
if(len < 0)
{
hdrbg_err = HDRBG_ERR_NO_ENTROPY;
return 0;
}
if((size_t)len < m_length)
{
hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY;
}
return len;
#else
FILE *fptr = fopen("/dev/urandom");
if(fptr == NULL)
{
hdrbg_err = HDRBG_ERR_NO_ENTROPY;
Expand All @@ -197,11 +238,9 @@ streamtobytes(FILE *fptr_, uint8_t *m_bytes, size_t m_length)
{
hdrbg_err = HDRBG_ERR_INSUFFICIENT_ENTROPY;
}
if(fptr_ == NULL)
{
fclose(fptr);
}
fclose(fptr);
return len;
#endif
}

/******************************************************************************
Expand Down

0 comments on commit 58d5aa8

Please sign in to comment.