Page 1 of 1

Random String generation

Posted: Sat Feb 17, 2018 11:30 am
by amehta
I am trying to look for a method to generate RANDOM STRING in ESP32, but couldn't find it. Can somebody please point me in the right direction?

I have found the ability to generate RANDOM NUMBER using uint32_t esp_random(void); of esp_system.h but I am looking for a random alphanumeric string generation.

Re: Random String generation

Posted: Sat Feb 17, 2018 3:02 pm
by iot_guy
Use a random number as the ASCII code for each character in the string. E.g. (not tested)

Code: Select all

// Generate random string in "str" of length "len" chars
static void get_random_string(char *str, unsigned int len)
{
    unsigned int i;

    // reseed the random number generator
    srand(time(NULL));
    
    for (i = 0; i < len; i++)
    {
        // Add random printable ASCII char
        str[i] = (rand() % ('~' - ' ')) + ' ';
    }
    str[i] = '\0';
}

static char string[21];

// Get random string of length 10
get_random_string(string, 10);

print("random string = %s\n", string);


Note: Be very careful with random variable generation if using them for cryptographic reasons (not a trivial subject)! The above method would not suffice for cryptographic purposes. srand is also not thread safe.

Re: Random String generation

Posted: Sat Feb 17, 2018 5:29 pm
by tele_player
Caution: the code listed above has a bug, it writes beyond the end of the array.

Re: Random String generation

Posted: Sat Feb 17, 2018 6:31 pm
by WiFive
Base64 encode?