📜  C语言中的随机密码生成器

📅  最后修改于: 2021-05-17 22:24:48             🧑  作者: Mango

在本文中,我们将讨论如何生成由任意字符组成的给定长度的随机密码。

方法:

  • 下面给出的程序涉及一些基本概念,例如变量,数据类型,数组,循环等。
  • 请按照以下步骤解决此问题:
    • 取密码的长度,并声明一个该长度的字符数组以存储该密码。
    • 声明所有大写字母,小写字母,数字和特殊字符的字符数组。
    • 现在,根据下面的程序,将执行相应的if-else并生成一个随机密码。

下面是上述方法的程序:

C
// C program for the above approach
#include 
#include 
#include 
#include 
  
// Function to randomly generates password
// of length N
void randomPasswordGeneration(int N)
{
    // Initialize counter
    int i = 0;
  
    int randomizer = 0;
  
    // Seed the random-number generator
    // with current time so that the
    // numbers will be different every time
    srand((unsigned int)(time(NULL)));
  
    // Array of numbers
    char numbers[] = "0123456789";
  
    // Array of small alphabets
    char letter[] = "abcdefghijklmnoqprstuvwyzx";
  
    // Array of capital alphabets
    char LETTER[] = "ABCDEFGHIJKLMNOQPRSTUYWVZX";
  
    // Array of all the special symbols
    char symbols[] = "!@#$^&*?";
  
    // Stores the random password
    char password[N];
  
    // To select the randomizer
    // inside the loop
    randomizer = rand() % 4;
  
    // Iterate over the range [0, N]
    for (i = 0; i < N; i++) {
  
        if (randomizer == 1) {
            password[i] = numbers[rand() % 10];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 2) {
            password[i] = symbols[rand() % 8];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else if (randomizer == 3) {
            password[i] = LETTER[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
        else {
            password[i] = letter[rand() % 26];
            randomizer = rand() % 4;
            printf("%c", password[i]);
        }
    }
}
  
// Driver Code
int main()
{
    // Length of the password to
    // be generated
    int N = 10;
  
    // Function Call
    randomPasswordGeneration(N);
  
    return 0;
}


输出:
51WAZMT?Z$


时间复杂度: O(N)
辅助空间: O(26)