Arm Mbed OS support forum

How to generate random numbers (T)RNG

How should random numbers be generated? I’ve got a STM device and have DEVICE_TRNG enabled. I see the hal/trng_api.h with functions like trng_init and trng_get_bytes but am not sure if I’m supposed to use those from application code.
I’ve looked through the API’s but couldn’t find a public API for the TRNG.

  • Are we expected to use the API from hal/trng_api.h to generate random numbers (using device TRNG)?
  • Is there a public API to generate random numbers that I’ve missed?
  • Can std::rand (cppreference) be used and would that use the device’s hardware TRNG?

HI @withthegrid

trng is a True Random Number Generator, and is used to seed the DRBG. It is not recommended to use directly the trng, as it may be biased.

I would suggest you use Mbed Crypto DRBG API, as shown in the example:

static void generate_a_random_value(void)
    psa_status_t status;
    uint8_t random[10] = { 0 };

    printf("Generate random...\t");

    /* Initialize PSA Crypto */
    status = psa_crypto_init();
    if (status != PSA_SUCCESS) {
        printf("Failed to initialize PSA Crypto\n");

    status = psa_generate_random(random, sizeof(random));
    if (status != PSA_SUCCESS) {
        printf("Failed to generate a random value\n");

    printf("Generated random data\n");

    /* Clean up */

Mbed Support

Hi Ron,

Thanks for the reply. I’ve got it working using the Mbed Crypto API and have confirmed that it is using the hardware TRNG.

@roneld01 This topic was a while back and I’m now using Mbed OS 6.4.0 with the DTLSSocket of the OS, where I previously was using a custom DTLS socket. With this setup I’m now running into an issue where DTLS tries to uses PSA as the MBEDTLS_USE_PSA_CRYPTO macro is configured automatically when we enable target features FEATURE_EXPERIMENTAL_API and FEATURE_PSA for the crypto functions. We however, don’t have full PSA support, causing the DTLS to fail, while we’re able to use crypto for generating random numbers.

I’m using a STM32F405RG device, so don’t have full PSA support as far as I understand. Would it be possible to use PSA crypto functions to generate random numbers, but not for DTLS?