Random data generation

If you are making a security application, you will most likely also require a random data generator. mbed TLS includes the CTR-DRBG module for random generation.

Setting up CTR-DRBG in your code requires an entropy source and a personalization string.

Setting up the entropy source

mbed TLS includes the Entropy Collection module to provide a central pool of entropy to extract entropy from.

To use the entropy collector in your code you need to include the header file:

#include "mbedtls/entropy.h"

And you'll have to add somewhere in your main() probably:

    mbedtls_entropy_context entropy;
    mbedtls_entropy_init( &entropy );

If your platform has a hardware TRNG or PRNG in the processor or TPM, you can hook it up into the entropy collector with entropy_add_source() to enhance the entropy even further! Check out our article on how to add an entropy source to the entropy pool for more information.

The actual random generator

To use the CTR-DRBG module in your code you need to include the header file:

#include "mbedtls/ctr_drbg.h"

And you'll have to add:

    mbedtls_ctr_drbg_context ctr_drbg;
    char *personalization = "my_app_specific_string";

    mbedtls_ctr_drbg_init( &ctr_drbg );

    ret = mbedtls_ctr_drbg_seed( &ctr_drbg , mbedtls_entropy_func, &entropy,
                     (const unsigned char *) personalization,
                     strlen( personalization ) );
    if( ret != 0 )

The personalization string is a small protection against a lack of startup entropy and makes sure each application has at least a different starting point.

Enabling Prediction resistance

In case you are worried about security and the possibility that an adversary can sometimes read your random data, you can enable prediction resistance (at a cost!)

    mbedtls_ctr_drbg_set_prediction_resistance( &ctr_drbg, MBEDTLS_CTR_DRBG_PR_ON );

Note: If enabled, entropy is gathered before each call! Only use this if you have ample supply of good entropy!

Loading a seed file

Another good way to add additional entropy at the start of your application is to use a seed file. The mbed TLS random generator can read and update a seed file with mbedtls_ctr_drbg_update_seed_file() to increase entropy.

Multi-threaded use?

If you intend to use the CTR-DRBG module in multiple threads, please read our article on entropy collection, random generation with threads for potential issues!

Did this help?