Skip to content

Commit 656aa82

Browse files
Merge pull request #5179 from LMESTM/trng_deprecated_call
STM32: TRNG: remove call to deprecated HAL_RNG_GetRandomNumber
2 parents c644cfe + 849749f commit 656aa82

File tree

1 file changed

+29
-17
lines changed

1 file changed

+29
-17
lines changed

targets/TARGET_STM/trng_api.c

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,20 @@
2323
#include <stdlib.h>
2424
#include "cmsis.h"
2525
#include "trng_api.h"
26+
#include "mbed_error.h"
27+
#include "mbed_critical.h"
2628

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-
}
29+
static uint8_t users = 0;
3630

3731
void trng_init(trng_t *obj)
3832
{
33+
uint32_t dummy;
34+
35+
/* We're only supporting a single user of RNG */
36+
if (core_util_atomic_incr_u8(&users, 1) > 1 ) {
37+
error("Only 1 RNG instance supported\r\n");
38+
}
39+
3940
#if defined(TARGET_STM32L4)
4041
RCC_PeriphCLKInitTypeDef PeriphClkInitStruct;
4142

@@ -50,11 +51,13 @@ void trng_init(trng_t *obj)
5051

5152
/* Initialize RNG instance */
5253
obj->handle.Instance = RNG;
54+
obj->handle.State = HAL_RNG_STATE_RESET;
55+
obj->handle.Lock = HAL_UNLOCKED;
56+
5357
HAL_RNG_Init(&obj->handle);
5458

5559
/* first random number generated after setting the RNGEN bit should not be used */
56-
HAL_RNG_GetRandomNumber(&obj->handle);
57-
60+
HAL_RNG_GenerateRandomNumber(&obj->handle, &dummy);
5861
}
5962

6063
void trng_free(trng_t *obj)
@@ -63,23 +66,32 @@ void trng_free(trng_t *obj)
6366
HAL_RNG_DeInit(&obj->handle);
6467
/* RNG Peripheral clock disable - assume we're the only users of RNG */
6568
__HAL_RCC_RNG_CLK_DISABLE();
69+
70+
users = 0;
6671
}
6772

6873
int trng_get_bytes(trng_t *obj, uint8_t *output, size_t length, size_t *output_length)
6974
{
70-
int ret;
75+
int ret = 0;
76+
volatile uint8_t random[4];
77+
*output_length = 0;
7178

7279
/* Get Random byte */
73-
for( uint32_t i = 0; i < length; i++ ){
74-
trng_get_byte(obj, output + i );
80+
while ((*output_length < length) && (ret ==0)) {
81+
if ( HAL_RNG_GenerateRandomNumber(&obj->handle, (uint32_t *)random ) != HAL_OK) {
82+
ret = -1;
83+
} else {
84+
for (uint8_t i =0; (i < 4) && (*output_length < length) ; i++) {
85+
*output++ = random[i];
86+
*output_length += 1;
87+
random[i] = 0;
88+
}
89+
}
7590
}
7691

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

8597
return( ret );

0 commit comments

Comments
 (0)