Program to generate a random password in C

  • by

1.0 Introduction

We need passwords to login to our accounts. These password must be unbreakable. One way to make a password strong is to make it random. Here is a program in C language which can be used to generate a random password offline. The program asks the user to enter the number of characters required in the password and prints a string with that many random 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
$
Subscribe