How to generate random string on ESP32

Several applications may require the generation of a random alphanumeric string on ESP32. For example, you may need to generate a key for encrypting data, or generate the initial vector for AES128 encryption, or some random password. Here’s a simple function to do that. Without much ado, let me get into the code first.

On ESP-IDF

#include "esp_random.h"
static const char *TAG = "my_file";

void getRandomStr(char* output, int len){
    char* eligible_chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
    for(int i = 0; i< len; i++){
        uint32_t rand_int = abs(esp_random());
        int random_index = max((double)((uint64_t)rand_int*strlen(eligible_chars)*1.0)/4294967296-1,0);
        output[i] = eligible_chars[random_index];
    }
    ESP_LOGI(TAG,"output: %s\n", (char*) output);
}

The esp_random() function generates a 32-bit random integer. Since it can be both positive and negative, we first use the abs function to convert it into a positive value. Then, we scale it between 0 and the max length of our eligible characters (4294967296 corresponds to 2^32). Finally, we pick out the eligible character corresponding to the random_index. This process is repeated till the required number of characters, and the output buffer is populated accordingly.

If you need to use some special characters (like the base64 characters ‘+’ and ‘/’), simply add them to the eligible characters list. Similarly, if you wish to reduce the scope of allowed characters, then cut down the eligible characters’ list.

Here is an example of using this in code:

char iv_str[17] = {0}; //The last '\0' helps terminate the string
getRandomStr(iv_str, 16);
ESP_LOGI(TAG,"iv_str: %s\n", (char*) iv_str);

On Arduino

If you are working on Arduino instead of ESP-IDF, you can still use the above function. Instead of ESP_LOGI, you can use the more familiar Serial.print() function. Similarly, instead of using the esp_random() function, you can use the random() function. Thus, the function will look like the following on Arduino:

void getRandomStr(char* output, int len){
    char* eligible_chars = "AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890";
    for(int i = 0; i< len; i++){
        uint8_t random_index = random(0, strlen(eligible_chars));
        output[i] = eligible_chars[random_index];
    }
    Serial.print("output: "); Serial.println(output);
}

void setup() {
  Serial.begin(115200);
  // put your setup code here, to run once:
  char iv_str[17] = {0}; //The last '\0' helps terminate the string
  getRandomStr(iv_str, 16);
  Serial.print("iv_str: "); Serial.println(iv_str);
 
}

void loop(){}

For more tutorials on ESP32, check out https://iotespresso.com/category/esp32/. Also, you may find this course on ESP32 on Udemy to be quite helpful. Do check it out

Leave a comment

Your email address will not be published. Required fields are marked *