How can I make a random string with C?

Viewed 1230

I want to generate a random character string in C.

the place I want to generate in is <HERE> in the code.

#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[]) {
    
    if (argc == 2) {
        printf("Checking key: %s\n", argv[1]);
        if (strcmp(argv[1], "AAAA-<HERE>") == 0) {
            printf("\033[0;32mOK\033[0m\n");
            return 0;
        } else {
            printf("\033[0;31mWrong.\033[0m\n");
            return 1;
        }
    } else {
        printf("USAGE: ./main <KEY>\n");
        return 1;
    }
    return 0;
}
1 Answers

A simple way would be to define a string containing all the characters you accept in the random string, then repeatedly pick a random element from this string.

#include <time.h>   // for time()
#include <stdlib.h> // for rand() & srand()

...
srand (time (NULL)); // define a seed for the random number generator
const char ALLOWED[] = "abcdefghijklmnopqrstuvwxyz1234567890";
char random[10+1];
int i = 0;
int c = 0;
int nbAllowed = sizeof(ALLOWED)-1;
for(i=0;i<10;i++) {
    c = rand() % nbAllowed ;
    random[i] = ALLOWED[c];
}
random[10] = '\0';
...

Note that the use of rand() is not a cryptographically secure way of generating random data.

Edit: replaced strlen by sizeof as per Lundin comment.

Related