Table of contents
1.
Introduction
2.
Random Password Generator
2.1.
Pre-Requisite
2.2.
Approach
2.3.
Code
2.4.
Output
2.5.
Explanation
2.6.
Time and Space Complexity
3.
Uses and Limitations of Random Password Generators
3.1.
Uses
3.2.
Limitations
4.
Frequently Asked Questions
4.1.
What is the rand() function in C?
4.2.
What header files are used in a program for random password generators in c?
4.3.
What is the use of <time.h> header file?
5.
Conclusion
Last Updated: Feb 5, 2025
Easy

Random Password Generator in C

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

A random password generator is a program that generates a random password using a programming language. With the help of some built-in functions, we can write some sets of instructions that can help us achieve this task.

random password generator in c

Do you know how we can make a random password generator in C? If not, then don't worry. In this article, we will discuss how to make a random password generator in C and understand how the code works. We will also talk about its time and space complexity.

Random Password Generator

A random password generator is a program that creates a feature for automatically generating random passwords for the user. It helps in making the password creation process much easier and prevents a user from making common mistakes while generating a password. A password generator can be a part of a password manager. 

A password manager is a computer program that enables users for storing and managing their passwords for local applications or online services like online shops, web applications, or social media. A password manager also helps generate and store passwords in an encrypted database and provides an encrypted vault for password protection. 

It is easy to use according to the set of rules rather than creating manual passwords. 

While signing up for different websites and to do log in, many a time, we are provided with an option to create the randomly generated password rather than us being generating it for ourselves. That's where the random password generator kicks in. 

We can make our random password generator using simple logic in C. Moving forward, let's understand the approach and code it.

Pre-Requisite

To make a random password generator in C, as an initial step, we must include all the necessary header files of C, such as  <stdio.h>,<stdlib.h>, <time.h>.
For understanding the code, we must know about the basics of C programming, such as variable declarations, loops, functions etc.

The <time.h> header file is used for seeding the random number generator with the current time and ensuring that the random numbers sequence is generated by the 'rand()' function.

Recommended read-Random function in C  and  Short int in C Programming

Approach

Below steps will explain the approach of making code for random password generator in C.

  • We can use the rand() function from the header <stdlib.h> file.
    It is used for generating the random numbers, and the srand() is used for seeding the random number generator. This means â€˜srand()’ initializes the generator with an initial value for the random number generator algorithm.
     
  • As we know that a password is a combination of uppercase, lowercase letters, special characters, and numbers. 
     
  • Therefore, we can first initialize four character arrays from which we can randomly pick up different characters.
     
  •  We would also require a separate character array for storing each random generator password character. 
     
  • Therefore, we would use a while loop for repeatedly accessing the unique charter at each iteration and storing it in the password character array.

Code

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


void NinjaPasswordGeneration(int N)
{
	int randomNo = 0;

	// Initialise the random-number generator
	srand((int)(time(NULL)));

	//Array1: for storing numbers
	char numbers[] = "0123456789";

	//Array2: for storing lowercase alphabets
	char LowerCase[] = "abcdefghijklmnoqprstuvwyzx";

	//Array3: for storing uppercase alphabets
	char UpperCase[] = "ABCDEFGHIJKLMNOQPRSTUYWVZX";

	//Array4: for storing all the special characters
	char SpecialChar[] = "!@#$^&*?";

	//Final array for storing the randomly generated NinjaPassword
	char NinjaPassword[N];

	// To select the randomNo
	//Inside the loop
	randomNo = rand() % 4;
   	
  	int i=0;
 	//iterating over the length of the NinjaPassword array
	while (i < N) {

	if (randomNo == 1) {
		NinjaPassword[i] = numbers[rand() % 10];
		randomNo = rand() % 4;
		printf("%c", NinjaPassword[i]);
	}
	
	else if (randomNo == 2) {
		NinjaPassword[i] = SpecialChar[rand() % 8];
		randomNo = rand() % 4;
		printf("%c", NinjaPassword[i]);
	}
	
	else if (randomNo == 3) {
		NinjaPassword[i] = LowerCase[rand() % 26];
		randomNo = rand() % 4;
		printf("%c", NinjaPassword[i]);
	}
	
	else {
		NinjaPassword[i] = UpperCase[rand() % 26];
		randomNo = rand() % 4;
		printf("%c", NinjaPassword[i]);
	}
      	i++;
	}
}


int main()
{
    //length of the NinjaPassword
	int n;
	printf("Hi Ninja,enter length of the Password: ");
	scanf("%d",&n);
	printf("Ninja, your password is:");

	// calling the function
	NinjaPasswordGeneration(n); printf("\n\n");

	//to repeatedly ask if the user wants to generate a new password or not.
	while(1){
  		int num;
  		printf("Ninja,press 1 to generate a new password or press 0 to exit: ");
  		scanf("%d",&num);

  		if(num==1){
  		printf("Your new password is: ") ; NinjaPasswordGeneration(n); printf("\n\n");
  		}

  		else{
    	printf("You have exited Ninja!");
      	return 0;
  		}   
    }
}
You can also try this code with Online C Compiler
Run Code

Output

output

Explanation

First, we have included all the necessary files in the above code. The NinjaNinjaPasswordGeneration is the password generator function that accepts the size of the password N as input.

  • Initially, we initialized the randomNo as 0.
     
  • The line srand((unsigned int)(time(NULL))); is used for initializing the random number generator with a current time to ensure that the numbers generated are different each time.
     
  • Next, as discussed in the approach, we have initialized four character arrays. For uppercase letters UpperCase[], for lowercase letters LowerCase[] ,numbers[] for integers, and SpecialChar[] for special characters.
     
  • As a next step, we wish to choose any one out of these. Therefore randomNo = rand() % 4; which gives a random number from 1 to 4.
     
  • We did this because, inside the while loop, which iterates till the length of the NinjaPassword[N]  array, we have used if-else statements for repeatedly deciding which character to pick from the 4 arrays we had initialized before.

 
For example, consider the code snippet,

if (randomNo == 1) {
NinjaPassword[i] = numbers[rand() % 10];
randomNo = rand() % 4;
printf("%c", NinjaPassword[i]);
}
You can also try this code with Online C Compiler
Run Code

 

  • In the code above, if the randomNo ==1 (Note that the randomNo will be from 1 to 4), then the character at the position ‘i’ in the NinjaPassword array will be equal to the character from the numbers array as ‘rand() % 10’  gives a random number from 1 to 10 (the length of the numbers[] array is 10).
     
  • Next, we updated the randomNo for the next iteration using ‘randomNo = rand() % 4;’ (4 different character arrays to choose from).
    Similarly, we have also applied the same logic for other character arrays.
     
  • Ultimately, we asked a user for the password length and generated a random password. We have also added a while loop that asks if a user wants to change the password.

Time and Space Complexity

The time complexity of the above program will be O(N) as iterating over the password array to store a character at each iteration. The operation of generating random numbers, accessing an array element, and printing them takes constant time.

We are not using any extra space beside the password array which we return as an answer. The space complexity is O(1).

Uses and Limitations of Random Password Generators

Below are some of the uses and limitations of random password generators.

Uses

  • A random password generator and a password manager ensure the credentials are well encrypted. Such that the passwords remain safe from unauthorized access.
     
  • Using a random password generator eliminates the need for manually generating a password and saves time.
     
  • A random password generator helps generate strong passwords with a combination of all sorts of characters. On the other hand, while manually creating passwords, a user may create a  weak password for ease of memorization.
     
  • Random password generators are used across various computing platforms.

Limitations

  • Using a random password generator not generated by the user may make it difficult for the user to remember the password, and it may require a user to opt for the ‘forget password’ option. 
     
  • The password generators do not store the passwords on their own and require a separate tool for storing the passwords.

Frequently Asked Questions

What is the rand() function in C?

The rand() function returns a pseudorandom number from 0 to RAND_MAX. Here, RAND_MAX is a constant default. Its value may vary according to the implementation.

What header files are used in a program for random password generators in c?

The header files used in a program for random password generator in C are  <stdio.h>,<stdlib.h>, <time.h>.

What is the use of <time.h> header file?

The <time.h> header file helps define functions to get and manipulate the information about date and time.

Conclusion

In the article, we have learned how to make a random password generator in C and understand how the code works. We have also seen its time and space complexities. You can read more such descriptive articles on our platform, Coding Ninjas Studio
 

Also, read- Code Generator.
 

You will find straightforward explanations of almost every topic on this platform. So take your coding journey to the next level using Coding Ninjas.

Happy coding!

Live masterclass