Skip to content

Commit d8a9e35

Browse files
committed
[M487/NUC472] Refine trng_get_bytes for consistency and readability
1 parent 2ee058b commit d8a9e35

File tree

2 files changed

+24
-16
lines changed

2 files changed

+24
-16
lines changed

targets/TARGET_NUVOTON/TARGET_M480/trng_api.c

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,9 @@
2525
/*
2626
* Get Random number generator.
2727
*/
28+
29+
#define PRNG_KEY_SIZE (0x20UL)
30+
2831
static volatile int g_PRNG_done;
2932
volatile int g_AES_done;
3033

@@ -82,18 +85,19 @@ void trng_free(trng_t *obj)
8285
int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
8386
{
8487
(void)obj;
85-
unsigned char tmpBuff[32];
88+
unsigned char tmpBuff[PRNG_KEY_SIZE];
8689
size_t cur_length = 0;
8790

88-
for (unsigned i = 0; i < (length/32); i++) {
91+
while (length >= sizeof(tmpBuff)) {
8992
trng_get(output);
90-
cur_length += 32;
91-
output += 32;
92-
}
93-
if( length > cur_length ) {
93+
output += sizeof(tmpBuff);
94+
cur_length += sizeof(tmpBuff);
95+
length -= sizeof(tmpBuff);
96+
}
97+
if (length > 0) {
9498
trng_get(tmpBuff);
95-
memcpy(output, &tmpBuff, (length - cur_length));
96-
cur_length = length;
99+
memcpy(output, tmpBuff, length);
100+
cur_length += length;
97101
trng_zeroize(tmpBuff, sizeof(tmpBuff));
98102
}
99103
*output_length = cur_length;

targets/TARGET_NUVOTON/TARGET_NUC472/trng_api.c

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@
3030
/*
3131
* Get Random number generator.
3232
*/
33+
34+
#define PRNG_KEY_SIZE (0x20UL)
35+
3336
static volatile int g_PRNG_done;
3437
volatile int g_AES_done;
3538

@@ -87,18 +90,19 @@ void trng_free(trng_t *obj)
8790
int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
8891
{
8992
(void)obj;
90-
unsigned char tmpBuff[32];
93+
unsigned char tmpBuff[PRNG_KEY_SIZE];
9194
size_t cur_length = 0;
9295

93-
for (unsigned i = 0; i < (length/32); i++) {
96+
while (length >= sizeof(tmpBuff)) {
9497
trng_get(output);
95-
cur_length += 32;
96-
output += 32;
97-
}
98-
if( length > cur_length ) {
98+
output += sizeof(tmpBuff);
99+
cur_length += sizeof(tmpBuff);
100+
length -= sizeof(tmpBuff);
101+
}
102+
if (length > 0) {
99103
trng_get(tmpBuff);
100-
memcpy(output, &tmpBuff, (length - cur_length));
101-
cur_length = length;
104+
memcpy(output, tmpBuff, length);
105+
cur_length += length;
102106
trng_zeroize(tmpBuff, sizeof(tmpBuff));
103107
}
104108
*output_length = cur_length;

0 commit comments

Comments
 (0)