Program to generate a random password in C

  • Post author:
  • Post last modified:August 17, 2023
  • Reading time:2 mins read

1.0 Introduction

Passwords provide a level of security for digital assets. To be effective, passwords need to sufficiently long. random and chosen from a big underlying domain.In this post, we have a C-language program, that takes in number of characters in the password as input, and chooses a random password from printable ASCII characters. The program is as given below.

2.0 Program

/*
 *
 *  gen-passwd.c: generate a random password
 *
 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MIN_CHAR 8
#define MAX_CHAR 1023
#define BUF_SIZE 1024
#define PRIME_MOD 937

int main (int argc, char **argv)
{
    int N;
    char password [BUF_SIZE];

    while (1) {
        // get N
        while (1) {
            printf ("Enter number of digits: ");
            scanf ("%d", &N);
            if (!N) exit (EXIT_SUCCESS);
            if (N >= MIN_CHAR && N <= MAX_CHAR)
                break;
            printf ("Password should be between %d - %d characters\n", MIN_CHAR, MAX_CHAR); 
        }
    
        time_t now = time (NULL);

        srand ((unsigned int) (now % PRIME_MOD));

        for (int i = 0; i < N; i++) 
            password [i] = 33 + rand () % 94;
    
        password [N] = '\0';

        printf ("password = %s\n", password);
    }
}

The program utilizes the fact that there are 94 printable characters in the ASCII character set, ranging from ASCII 33 (!) through ASCII 126 (~). To generate a character of a password, we generate a random number in the range 0 to 93. The number 0 represents ASCII 33 (!) and number 93 represents ASCII 126 (~) and a number between represents a corresponding character in the printable ASCII range. This is repeated for all characters in the password string.

We can compile and run the gen-passwd.c file.

$ gcc gen-passwd.c -o gen-passwd
$ ./gen-passwd
Enter number of digits: 32
password = >1Z{}$)uM`**@{C6e:N.Q(6F&i|sqQfK
Enter number of digits: 15
password = sG0aUsVm?"I~A-T
Enter number of digits: 10
password = p_oK`*g;J8
Enter number of digits: 35
password = ZRi]KKZqrLP#q~Q#rmyx!_;SzX_*_1l:bq2
Enter number of digits: 0
$
Share

Karunesh Johri

Software developer, working with C and Linux.
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments