Skip to content

Commit 14343c4

Browse files
committed
STM32: TRNG: remove call to deprecated HAL_RNG_GetRandomNumber
HAL_RNG_GetRandomNumber is a deprecated API and replaced here with a call to HAL_RNG_GenerateRandomNumber. Doing so, we also rework the driver to use the 4 bytes returned by a call to HAL_RNG_GenerateRandomNumber instead of 1 byte out of 4. HAL_RNG_GenerateRandomNumber was not returning any error code, so now we can also check the return code.
1 parent c6f655c commit 14343c4

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

targets/TARGET_STM/trng_api.c

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -24,18 +24,10 @@
2424
#include "cmsis.h"
2525
#include "trng_api.h"
2626

27-
/** trng_get_byte
28-
* @brief Get one byte of entropy from the RNG, assuming it is up and running.
29-
* @param obj TRNG obj
30-
* @param pointer to the hardware generated random byte.
31-
*/
32-
static void trng_get_byte(trng_t *obj, unsigned char *byte )
33-
{
34-
*byte = (unsigned char)HAL_RNG_GetRandomNumber(&obj->handle);
35-
}
3627

3728
void trng_init(trng_t *obj)
3829
{
30+
uint32_t dummy;
3931
#if defined(TARGET_STM32L4)
4032
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;
4133

@@ -50,11 +42,13 @@ void trng_init(trng_t *obj)
5042

5143
/* Initialize RNG instance */
5244
obj->handle.Instance = RNG;
45+
obj->handle.State = HAL_RNG_STATE_RESET;
46+
obj->handle.Lock = HAL_UNLOCKED;
47+
5348
HAL_RNG_Init(&obj->handle);
5449

5550
/* first random number generated after setting the RNGEN bit should not be used */
56-
HAL_RNG_GetRandomNumber(&obj->handle);
57-
51+
HAL_RNG_GenerateRandomNumber(&obj->handle, &dummy);
5852
}
5953

6054
void trng_free(trng_t *obj)
@@ -67,19 +61,26 @@ void trng_free(trng_t *obj)
6761

6862
int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
6963
{
70-
int ret;
64+
int ret = 0;
65+
volatile uint8_t random[4];
66+
*output_length = 0;
7167

7268
/* Get Random byte */
73-
for( uint32_t i = 0; i < length; i++ ){
74-
trng_get_byte(obj, output + i );
69+
while ((*output_length < length) && (ret ==0)) {
70+
if ( HAL_RNG_GenerateRandomNumber(&obj->handle, (uint32_t *)random ) != HAL_OK) {
71+
ret = -1;
72+
} else {
73+
for (uint8_t i =0; (i < 4) && (*output_length < length) ; i++) {
74+
*output++ = random[i];
75+
*output_length += 1;
76+
random[i] = 0;
77+
}
78+
}
7579
}
7680

77-
*output_length = length;
7881
/* Just be extra sure that we didn't do it wrong */
7982
if( ( __HAL_RNG_GET_FLAG(&obj->handle, (RNG_FLAG_CECS | RNG_FLAG_SECS)) ) != 0 ) {
8083
ret = -1;
81-
} else {
82-
ret = 0;
8384
}
8485

8586
return( ret );

0 commit comments

Comments
 (0)