Random String generation

amehta
Posts: 22
Joined: Sat Feb 17, 2018 11:14 am

Random String generation

Postby amehta » Sat Feb 17, 2018 11:30 am

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.

iot_guy
Posts: 8
Joined: Thu Aug 31, 2017 8:16 pm

Re: Random String generation

Postby iot_guy » Sat Feb 17, 2018 3:02 pm

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.

tele_player
Posts: 90
Joined: Sun Jul 02, 2017 3:38 am

Re: Random String generation

Postby tele_player » Sat Feb 17, 2018 5:29 pm

Caution: the code listed above has a bug, it writes beyond the end of the array.

WiFive
Posts: 3529
Joined: Tue Dec 01, 2015 7:35 am

Re: Random String generation

Postby WiFive » Sat Feb 17, 2018 6:31 pm

Base64 encode?

Who is online

Users browsing this forum: DrMickeyLauer and 98 guests