This is a very nice program for Linux, this will generate a random password for Linux using random text from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <stdio.h> #include <stdlib.h> #include <time.h> char *generate_random_string(int length) { char *random_string = malloc(length + 1); const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()"; if (random_string) { for (int i = 0; i < length; ++i) { int index = rand() % (sizeof(charset) - 1); random_string[i] = charset[index]; } random_string[length] = '\0'; } return random_string; } int main() { srand(time(NULL)); // Seed the PRNG with current time int length = 16; char *random_text_str = generate_random_string(length); printf("Random Password string: %s\n", random_text_str); free(random_text_str); // Free allocated memory return 0; } |
This works perfectly and will work very nicely to create a random password string you may use for anything.
This is an example of the output this will give you.
┗━━━━━━━━━━┓ john@localhost ~/Documents ┗━━━━━━━━━━━━━╾ ╍▷ ./string Random Text String: suk6G40GHH3ND*Lj |
Here is another version. This will read random strings from /dev/urandom and generate a random 16-character password that way.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #define STRING_LENGTH 16 int main() { int fd = open("/dev/urandom", O_RDONLY); if (fd == -1) { perror("Error opening /dev/urandom"); exit(EXIT_FAILURE); } unsigned char buffer[STRING_LENGTH]; if (read(fd, buffer, STRING_LENGTH) != STRING_LENGTH) { perror("Error reading from /dev/urandom"); close(fd); exit(EXIT_FAILURE); } printf("Random Text String: "); for (int i = 0; i < STRING_LENGTH; ++i) { unsigned char c = buffer[i] % ('~' - ' ') + ' '; printf("%c", c); } close(fd); printf("\n\n"); return 0; } |
A lot of fun to write.
This version gives the same output. A very good way to generate a sufficiently random password.
┗━━━━━━━━━━┓ john@localhost ~/Documents ┗━━━━━━━━━━━━━╾ ╍▷ ./string2 Random Text String: |w\vW)f2RaWdNU@H |