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.
Random String generation
Re: Random String generation
Use a random number as the ASCII code for each character in the string. E.g. (not tested)
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.
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.
-
- Posts: 90
- Joined: Sun Jul 02, 2017 3:38 am
Re: Random String generation
Caution: the code listed above has a bug, it writes beyond the end of the array.
Who is online
Users browsing this forum: Baidu [Spider] and 86 guests