#include
#include
#include
#define CHAR_SMALL_CASE 0
#define CHAR_UPPER_CASE 1
#define CHAR_DIGIT 2
#define CHAR_SPECIAL 3
const char c_small_case[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
const char c_upper_case[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
const char c_digit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
const char c_special[] = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'}; // 还可以再加点特殊字符
// 密码生成器
// @param buf[out] 输出生成的密码
// @param buf_len[in] 输出区长度
// @param code_len[in] 产生密码的长度
// @param contain_special[in] 密码是否包含特殊字符
// return 0 on failuer, code_len on success
int code_generator(char *buf, int buf_len, int code_len, int contain_special);
int main(int argc, char *argv[])
{
char code[256];
int code_len = 128; // 要求密码长度为128
int len = code_generator(code, sizeof(code), code_len, 1);
if (len == code_len)
{
printf("%s\n", code);
}
getchar();
return 0;
}
int code_generator(char *buf, int buf_len, int code_len, int contain_special)
{
if (buf_len + 1 < code_len) // 输出去长度判读
{
return 0;
}
srand(time(NULL)); // 随机数
int i;
for(i = 0; i < code_len; ++i)
{
int char_type = rand()%4;
switch(char_type)
{
case CHAR_SMALL_CASE:
*buf = c_small_case[rand() % sizeof(c_small_case)];
break;
case CHAR_UPPER_CASE:
*buf = c_upper_case[rand() % sizeof(c_upper_case)];
break;
case CHAR_DIGIT:
*buf = c_digit[rand() % sizeof(c_digit)];
break;
case CHAR_SPECIAL:
if (!contain_special) // 跳过特殊字符
{
--i;
continue;
}
*buf = c_special[rand() % sizeof(c_special)];
break;
default:
break;
}
++buf;
}
*buf = '\0'; // 以'\0'结束
return code_len;
}