How to Generate Random Passwords in C
c password passwd pwd random rand generator gen function
Function:
#include
#include
#include
#include
char *password_generator(const int pwd_len, const char *char_array) {
int i;
int n;
int r;
int sizeof_array;
char c;
char *password;
static int seeded = 0;
if (!char_array) { // If hasn't a char_array set a default
char_array = "abcdefghijklmnopqrstuvwxyz" \
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
sizeof_array = strlen(char_array);
if(!seeded) { // Check if already has a seed
srand((unsigned int)time(0)); // Seed number for rand()
seeded = 1;
}
// Alloc the memory to the password
password = (char *) malloc(sizeof(char) * (pwd_len+1));
for (i = 0; i < pwd_len; i++) {
r = rand(); // Get a random number
// using mod to reduce the number to sizeof_array in max
// (Ex: 3452354 % 34: 28)
n = r % sizeof_array;
c = char_array[n]; // Get the char in the 'n' pos
password[i] = c;
}
password[i] = '\0';
return password;
}
How to use it?!
int main(void) {
char *password;
password = password_generator(12, "0123456789");
printf("Password: [%s]\n", password);
free(password);
password = password_generator(10, NULL);
printf("Password: [%s]\n", password);
free(password);
return 0;
}