gpt4 book ai didi

c - 在c中制作一长串加密子字符串

转载 作者:行者123 更新时间:2023-11-30 14:23:27 25 4
gpt4 key购买 nike

我正在尝试创建一个由加密子字符串生成的长字符串。对于加密,我使用 AES128libmcrypt。代码正在运行,但我得到的输出比我应该的要短,并且发出蜂鸣声。我想这是因为我正在使用 strlen,但我不知道如何避免这种情况。我将非常感谢一些建议。这是我的代码:

char *Encrypt( char *key, char *message){   
static char *Res;
MCRYPT mfd;
char *IV;
int i, blocks, key_size = 16, block_size = 16;
blocks = (int) (strlen(message) / block_size) + 1;

Res = calloc(1, (blocks * block_size));

mfd = mcrypt_module_open(MCRYPT_RIJNDAEL_128, NULL, "ecb", NULL);
mcrypt_generic_init(mfd, key, key_size, IV);

strncpy(Res, message, strlen(message));
mcrypt_generic(mfd, Res, block_size);
//printf("the encrypted %s\n", Res);

mcrypt_generic_deinit(mfd);
mcrypt_module_close(mfd);

return (Res);
}

char *mkline ( int cols) {
int j;
char seed[] = "thesecretmessage", key1[]="dontusethisinput", key2[]="abadinputforthis";

char *encrypted, *encrypted2, *in = malloc(cols * 16);
encrypted = Encrypt(key1, seed);
sprintf(in, "%s", encrypted);
encrypted2= Encrypt(key2, encrypted);
printf("encrypted2 before for-loop %s\n", encrypted2);
printf("encrypted2 before for loop len %d\n", strlen(encrypted2));
for (j=1; j<cols; j++) {
strcat(in, encrypted2);
memmove(encrypted2, Encrypt(key2, encrypted2),strlen(seed));
printf("encrypted2 %s on position %d\n" , encrypted2,j);
printf("encrypted2 len %d\n", strlen(encrypted2));
}
free(encrypted);
free(encrypted2);
return in;
}

int main(int argc, char *argv[]) {
char *line = mkline(15);
printf("line %s\n", line);
printf("line lenght %d\n", strlen(line));
return 0;
}

最佳答案

您会听到蜂鸣声,因为您正在打印控制字符。

此外,strlen 返回第一个“\0”字符之前的大小(因为字符串以零结尾)。这就是为什么您得到的长度小于预期,因为加密的消息可能包含零。

您可以执行以下操作来返回结果长度:

 char *Encrypt(const char *key, const char *message, int *result_len)
{
*result_len = blocks * block_size;
}

还有

memmove(encrypted2, Encrypt(key2, encrypted2),strlen(seed));

此行应该会产生内存泄漏,因为每次调用 Encrypt 时都会调用 calloc (分配新内存),完成后需要释放该内存。

您可能应该使用 memcpy,如果目的地和源可能重叠,则主要使用 memmove。

关于c - 在c中制作一长串加密子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12857528/

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