SlunkCrypt/libMCrypt/src/utils.c

63 lines
1.3 KiB
C
Raw Normal View History

2020-10-13 15:04:59 +02:00
/******************************************************************************/
/* MCrypt, by LoRd_MuldeR <MuldeR2@GMX.de> */
/* This work has been released under the CC0 1.0 Universal license! */
/******************************************************************************/
#ifdef _WIN32
#define _CRT_RAND_S 1
#endif
#include "utils.h"
int mcrypt_random_bytes(uint8_t* const buffer, const size_t length)
{
#ifdef _WIN32
size_t pos = 0U;
while (pos < length)
{
const size_t bytes_left = length - pos;
const size_t bytes_copy = (bytes_left < sizeof(uint32_t)) ? bytes_left : sizeof(uint32_t);
uint32_t temp;
if (rand_s(&temp) != 0)
{
return -1;
}
for (size_t i = 0; i < bytes_copy; ++i)
{
buffer[pos++] = (uint8_t)(temp & 0xFF);
temp >>= 8;
}
}
return 0;
#else
#ifdef __unix__
static const char* const PATH[] = { "/dev/urandom", "/dev/random" };
int result = -1;
for (size_t i = 0; (i < 2U) && (result < 0); ++i)
{
const int fd = open(PATH[i], O_RDONLY);
if (fd >= 0)
{
if (read(fd, buffer, length) < length)
{
result = 0;
}
close(fd);
}
}
return result;
#else
#error Unsupported target platform!
#endif
#endif
}
void mcrypt_erase(void* const ptr, const size_t length)
{
volatile uint8_t* buffer = ptr;
for (size_t i = 0U; i < length; ++i)
{
buffer[i] = 0U;
}
}