gpt4 book ai didi

c - C中的随 secret 码生成

转载 作者:太空宇宙 更新时间:2023-11-04 04:23:35 26 4
gpt4 key购买 nike

我有简单的 C 语言随 secret 码生成器代码。

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
#include<string.h>
char *create_pass(int);
void encrypt(char password[],int key);
void decrypt(char password[],int key);

int main(void)
{
/* Length of the password */
int length;
int num;
int temp;
char password[10];
srand((unsigned int) time(0));

printf("\n Enter the length of password : ");
scanf("%d",&length);
strcpy(password,create_pass(length));
printf("\n Password Generated :- %s",password);

encrypt(password,0xFACA);
printf("\n Password Encryption :- %s",password);

decrypt(password,0xFACA);
printf("\n Password dencryption :- %s",password);

getch();
return EXIT_SUCCESS;
}

char *create_pass(int length)
{
char randomString[10];
int i,length_1;

length_1=length/2;
for(i=0;i<length_1;i++)
{
randomString[i]=(rand() % 25+ 65);
srand(rand());
}
for(;i<length;i++)
{
randomString[i]=(rand() % 9+ 48);
srand(rand());
}
randomString[i] = '\0';
return randomString;
}


void encrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] - key;
}
}

void decrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] + key;
}
}

我想生成一半长度为字母,其余为数字的密码。例如:如果我给 8 个字符,4 个字母和 4 个数字。之后我想加密它并再次解密它。

所以我需要一些强大的加密和解密逻辑,我还想要优化代码。

最佳答案

返回局部变量的地址是个问题(因为如果没有声明为静态,它只在子程序执行期间存在,一旦超出范围,该值将是未定义的),考虑只传递一个要填充的缓冲区通过函数。

void create_pass( char* randomString, size_t length )
{
sizet_t i = 0;

srand(rand());
strcpy(randomString,"");

for( i = 0; i < (length/2); i++ )
{
*(randomString + i) = ( rand() % 25 + 65 );
}
for( ; i < length; i++ )
{
*(randomString + i) = ( rand() % 9 + 48 );
}
}

关于c - C中的随 secret 码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868246/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com