3

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;
}
pradeexsu
  • 1,029
  • 1
  • 10
  • 27
Wantyapps
  • 83
  • 1
  • 10
  • Other than this using a std::string, it would answer your question: https://stackoverflow.com/a/440240/47453 – Bill Lynch Nov 05 '20 at 07:46

1 Answers1

2

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.

Silverspur
  • 891
  • 1
  • 12
  • 33
  • `strlen(ALLOWED)` -> `sizeof(ALLOWED) - 1`. – Lundin Nov 05 '20 at 08:01
  • I've updated my answer. More generally, is there a case where `sizeof` does not work and `strlen` is the correct choice? – Silverspur Nov 05 '20 at 08:10
  • 1
    You have to use `strlen` in case the string is assigned in run-time or you only have a pointer to it. But if the length is known at compile-time and the string doesn't change, then `strlen` is just needlessly slow. – Lundin Nov 05 '20 at 08:57