龙空技术网

使用C语言实现简单的密码生成器

一只爱阅读的程序猿 120

前言:

眼前朋友们对“c语言编写密码程序”大致比较看重,你们都需要知道一些“c语言编写密码程序”的相关资讯。那么小编也在网摘上收集了一些有关“c语言编写密码程序””的相关文章,希望各位老铁们能喜欢,朋友们一起来了解一下吧!

现在对于密码的强度要求一般是包含大小写字母,包含数字,包含特殊字符,长度为8到20位数等等。下面就使用C语言来实现简单的密码生成器。

思路为:

.a.将特殊字符单独存放在一个字符数组中。

.b.假设密码长度为N,首先随机生成四个不重复的随机下标保存在一个新的数组中;

.c.分别让这四个随机下标对应的字符为随机的特殊字符,数字,小写字母,大小字母。这样就可以包含四种字符类型。

.d.上面已经生成四位密码,最后生成密码的其他部分。

.e.打印生成的密码。

示例代码如下,

#define _CRT_SECURE_NO_WARNINGS 1

#include <stdio.h>

#include <stdlib.h>

#include <time.h>

// 密码长度

#define SIZE 10

// 特殊字符

char specialCharacter[9] = { '~', '!', '@', '#', '$', '%', '^', '&', '*' };

int rangeNumRand(int min, int max);

int arrHasNumber(int arr[], int findNum, int length);

char randPasswordChar(int randNum);

void createRandPassword();

char password[SIZE] = {};

int main() {

srand(time(NULL));

// 第一次创建随机密码

createRandPassword();

int arr[4] = {};

for (int i = 0; i < 10; i++) {

printf("%c", password[i]);

}

return 0;

}

// 创建随机密码

void createRandPassword() {

// 定义一个数组,用来存储四个不重复的随机下标

int indexArr[4] = {};

// 生成随机下标

int index = rangeNumRand(0, SIZE - 1);

indexArr[0] = index;

int count = 1, temp;

while (1) {

index = rangeNumRand(0, SIZE - 1);

temp = arrHasNumber(indexArr, index, 4);

if (temp == 1) {

// 下标已经存在,则重新随机生成新的下标

index = rangeNumRand(0, SIZE - 1);

} else {

// 不存在,则将下标添加到数组中

indexArr[count] = index;

count++;

}

if (count == 3) {

break;

}

}

// 随机生成一个特殊字符,添加到第一个随机下标的位置

password[indexArr[0]] = randPasswordChar(1);

// 随机生成一个数字字符,添加到第二个随机下标的位置

password[indexArr[1]] = randPasswordChar(2);

// 随机生成一个小写字母,添加到第三个随机下标的位置

password[indexArr[2]] = randPasswordChar(3);

// 随机生成一个大写字母,添加到第四个随机下标的位置

password[indexArr[3]] = randPasswordChar(4);

for (int i = 0; i < SIZE; i++) {

if (password[i] < 1) {

// 随机生成任意字符

password[i] = randPasswordChar(5);

}

}

}

// 生成一个字符

char randPasswordChar(int randNum) {

// randNum为5表示任意类型

if (randNum == 5) {

// 指定生成的字符类型

randNum = rangeNumRand(1, 4);

}

char result;

int temp;

if (randNum == 1) {

// 特殊字符

int temp = rangeNumRand(0, 9 - 1);

result = specialCharacter[temp];

} else if (randNum == 2) {

// 数字

temp = rangeNumRand(48, 57);

result = temp;

} else if (randNum == 3) {

// 生成随机小写字母,ASCII 码[97, 122]

temp = rangeNumRand(97, 122);

result = temp;

} else {

// 生成随机大写字母,ASCII 码[65, 90]

temp = rangeNumRand(65, 90);

result = temp;

}

return result;

}

// 产生任意范围内的随机数

int rangeNumRand(int min, int max) {

int randNum = rand() % (max - min + 1) + min;

return randNum;

}

// 判断整型数组中是否存在某一个元素

int arrHasNumber(int arr[], int findNum, int length) {

int flag = 0;

for (int i = 0; i < length; i++) {

if (arr[i] == findNum) {

flag = 1;

break;

}

}

return flag;

}

测试结果一如下,

测试结果二如下,

测试结果三如下,

标签: #c语言编写密码程序 #c语言设计密码程序怎么写的