在C中为密码添加随机符号

时间:2014-01-05 21:46:59

标签: c

截至目前,该程序输出的密码包含5个大写字母,5个小写字母和2个数字..但我也想在列表中添加一个随机符号,例如!£$%^& *()+ =<> / @ 我可以在数字和字符之类的for循环中添加它吗?

到目前为止,这是我的代码:

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

FILE*fp; 

int main(void) {

char password[5 + 5 + 2 + 1];
int i, j=0, len=sizeof(password)-1;
int menuNum = 0;


fp = fopen("passwords.txt", "a+"); 
//Opens the text file to save the Passwords

srand(time(NULL));
printf("       Main Menu\n");
printf("********************************\n");
printf("\nEnter 1 to Generate a New Password: ");
printf("\n\n");
printf("Enter 2 to Check Old Passwords: ");
printf("\n\n");
printf("Enter 3 to Exit. ");
printf("\n\n");
scanf("%d", &menuNum); // reads number

if (menuNum == 1)
{
    printf("********************************\n");
    printf("\nYour New Password is: \n\n");

//Each Password will Have 13 Characters(5 Upper, 5 Lower, 2 Numbers & 1 Symbol)

for (i = 0; i < 5; ++i)
    password[j++] = 'a' + rand() % ('z' - 'a' + 1); //Generates 5 random Lowercase characters 

for (i = 0; i < 5; ++i)
    password[j++] = 'A' + rand() % ('Z' - 'A' + 1); //Generates 5 random Uppercase characters

for (i = 0; i < 2; ++i)
    password[j++] = '0' + rand() % ('0' - '9' + 1); //Generates 2 random numbers

password[j] = '\0';
for(i = 0; i < sizeof(password)-1; ++i)
    {
    char c = password[i];
    j = rand() % len;
    password[i] = password[j];
    password[j] = c;
    }

printf("%s\n\n", password);
printf("********************************\n");
fprintf(fp, "\n%s", password); //Outputs the Generated Passoword to the text file
fclose(fp); //Closes the text file
system("pause");
}

}

1 个答案:

答案 0 :(得分:1)

使用类似的东西:

char *special_stuff = "!$%^&*()+=<>?/@";

...
password[j++] = special_stuff[rand() % strlen(special_stuff)];

(我删除了£字符,因为它可能会为您带来各种问题,例如进行多字节编码。