From 7b3d68e12f6a3c791529ed7468aec06b4caa74a7 Mon Sep 17 00:00:00 2001 From: cyliangtw Date: Mon, 13 Nov 2017 12:11:08 +0800 Subject: [PATCH] Refine trng_get_bytes for consistency and readability --- targets/TARGET_NUVOTON/TARGET_M480/trng_api.c | 20 +++++++++++-------- .../TARGET_NUVOTON/TARGET_NUC472/trng_api.c | 20 +++++++++++-------- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c b/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c index bbe5327de8..24d15537e4 100644 --- a/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c +++ b/targets/TARGET_NUVOTON/TARGET_M480/trng_api.c @@ -25,6 +25,9 @@ /* * Get Random number generator. */ + +#define PRNG_KEY_SIZE (0x20UL) + static volatile int g_PRNG_done; volatile int g_AES_done; @@ -82,18 +85,19 @@ 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; - unsigned char tmpBuff[32]; + unsigned char tmpBuff[PRNG_KEY_SIZE]; size_t cur_length = 0; - for (unsigned i = 0; i < (length/32); i++) { + while (length >= sizeof(tmpBuff)) { trng_get(output); - cur_length += 32; - output += 32; - } - if( length > cur_length ) { + output += sizeof(tmpBuff); + cur_length += sizeof(tmpBuff); + length -= sizeof(tmpBuff); + } + if (length > 0) { trng_get(tmpBuff); - memcpy(output, &tmpBuff, (length - cur_length)); - cur_length = length; + memcpy(output, tmpBuff, length); + cur_length += length; trng_zeroize(tmpBuff, sizeof(tmpBuff)); } *output_length = cur_length; diff --git a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c index 5acd8f2599..a1f55b48f6 100644 --- a/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c +++ b/targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c @@ -30,6 +30,9 @@ /* * Get Random number generator. */ + +#define PRNG_KEY_SIZE (0x20UL) + static volatile int g_PRNG_done; volatile int g_AES_done; @@ -87,18 +90,19 @@ 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; - unsigned char tmpBuff[32]; + unsigned char tmpBuff[PRNG_KEY_SIZE]; size_t cur_length = 0; - for (unsigned i = 0; i < (length/32); i++) { + while (length >= sizeof(tmpBuff)) { trng_get(output); - cur_length += 32; - output += 32; - } - if( length > cur_length ) { + output += sizeof(tmpBuff); + cur_length += sizeof(tmpBuff); + length -= sizeof(tmpBuff); + } + if (length > 0) { trng_get(tmpBuff); - memcpy(output, &tmpBuff, (length - cur_length)); - cur_length = length; + memcpy(output, tmpBuff, length); + cur_length += length; trng_zeroize(tmpBuff, sizeof(tmpBuff)); } *output_length = cur_length;