diff --git a/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c b/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c index 4f3c6efd52c..24d15537e44 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c @@ -25,9 +25,17 @@ /* * Get Random number generator. */ + +#define PRNG_KEY_SIZE (0x20UL) + static volatile int g_PRNG_done; volatile int g_AES_done; +/* Implementation that should never be optimized out by the compiler */ +static void trng_zeroize( void *v, size_t n ) { + volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; +} + void CRYPTO_IRQHandler() { if (PRNG_GET_INT_FLAG()) { @@ -77,21 +85,22 @@ void trng_free(trng_t *obj) int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length) { (void)obj; - - *output_length = 0; - if (length < 32) { - unsigned char tmpBuff[32]; + unsigned char tmpBuff[PRNG_KEY_SIZE]; + size_t cur_length = 0; + + while (length >= sizeof(tmpBuff)) { + trng_get(output); + output += sizeof(tmpBuff); + cur_length += sizeof(tmpBuff); + length -= sizeof(tmpBuff); + } + if (length > 0) { trng_get(tmpBuff); - memcpy(output, &tmpBuff, length); - *output_length = length; - } else { - for (unsigned i = 0; i < (length/32); i++) { - trng_get(output); - *output_length += 32; - output += 32; - } + memcpy(output, tmpBuff, length); + cur_length += length; + trng_zeroize(tmpBuff, sizeof(tmpBuff)); } - + *output_length = cur_length; return 0; } diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c index 6fab1b43063..a1f55b48f6a 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c @@ -30,9 +30,17 @@ /* * Get Random number generator. */ + +#define PRNG_KEY_SIZE (0x20UL) + static volatile int g_PRNG_done; volatile int g_AES_done; +/* Implementation that should never be optimized out by the compiler */ +static void trng_zeroize( void *v, size_t n ) { + volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0; +} + void CRYPTO_IRQHandler() { if (PRNG_GET_INT_FLAG()) { @@ -82,21 +90,22 @@ void trng_free(trng_t *obj) int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length) { (void)obj; - - *output_length = 0; - if (length < 32) { - unsigned char tmpBuff[32]; + unsigned char tmpBuff[PRNG_KEY_SIZE]; + size_t cur_length = 0; + + while (length >= sizeof(tmpBuff)) { + trng_get(output); + output += sizeof(tmpBuff); + cur_length += sizeof(tmpBuff); + length -= sizeof(tmpBuff); + } + if (length > 0) { trng_get(tmpBuff); - memcpy(output, &tmpBuff, length); - *output_length = length; - } else { - for (int i = 0; i < (length/32); i++) { - trng_get(output); - *output_length += 32; - output += 32; - } + memcpy(output, tmpBuff, length); + cur_length += length; + trng_zeroize(tmpBuff, sizeof(tmpBuff)); } - + *output_length = cur_length; return 0; }