Posted: . At: 9:35 AM. This was 11 months ago. Post ID: 18159
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.


Nice program for Linux to generate a random password.


This is a very nice program for Linux, this will generate a random password for Linux using random text from a string.

prog.c
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.

password.c
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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.