diff --git a/core/esp_hwrand.c b/core/esp_hwrand.c new file mode 100644 index 0000000..7a591eb --- /dev/null +++ b/core/esp_hwrand.c @@ -0,0 +1,27 @@ +/* Hardware Random Number Generator Functions + * + * For documentation, see http://esp8266-re.foogod.com/wiki/Random_Number_Generator + * + * Part of esp-open-rtos + * Copyright (C) 2015 Angus Gratton + * BSD Licensed as described in the file LICENSE + */ +#include +#include +#include + +/* Return a random 32-bit number */ +uint32_t hwrand(void) +{ + return WDEV.HWRNG; +} + +/* Fill a variable size buffer with data from the Hardware RNG */ +void hwrand_fill(uint8_t *buf, size_t len) +{ + for(size_t i = 0; i < len; i+=4) { + uint32_t random = WDEV.HWRNG; + /* using memcpy here in case 'buf' is unaligned */ + memcpy(buf + i, &random, (i+4 <= len) ? 4 : (len % 4)); + } +} diff --git a/core/include/esp/hwrand.h b/core/include/esp/hwrand.h new file mode 100644 index 0000000..8ec75e1 --- /dev/null +++ b/core/include/esp/hwrand.h @@ -0,0 +1,22 @@ +/** esp/hwrand.h + * + * Hardware Random Number Generator functions. + * + * For documentation, see http://esp8266-re.foogod.com/wiki/Random_Number_Generator + * + * Part of esp-open-rtos + * Copyright (C) 2015 Angus Gratton + * BSD Licensed as described in the file LICENSE + */ +#ifndef _ESP_RNG_H +#define _ESP_RNG_H +#include +#include + +/* Return a random 32-bit number */ +uint32_t hwrand(void); + +/* Fill a variable size buffer with data from the Hardware RNG */ +void hwrand_fill(uint8_t *buf, size_t len); + +#endif diff --git a/extras/mbedtls/hardware_entropy.c b/extras/mbedtls/hardware_entropy.c index 85dd00d..0d197cd 100644 --- a/extras/mbedtls/hardware_entropy.c +++ b/extras/mbedtls/hardware_entropy.c @@ -9,18 +9,13 @@ * BSD Licensed as described in the file LICENSE */ #include -#include -#include +#include int mbedtls_hardware_poll( void *data, unsigned char *output, size_t len, size_t *olen ) { (void)(data); - for(int i = 0; i < len; i+=4) { - uint32_t random = WDEV.HWRNG; - /* using memcpy here in case output is unaligned */ - memcpy(output + i, &random, (i+4 <= len) ? 4 : (len % 4)); - } + hwrand_fill(output, len); if(olen) *olen = len; return 0;