gpt4 book ai didi

c - 使用 openssl evp aes_256_ctr() 模式加密时生成无效字符

转载 作者:行者123 更新时间:2023-11-30 15:26:02 26 4
gpt4 key购买 nike

我的想法是在客户端服务器模型中进行文件加密,我使用 openssl evp 进行加密。我需要将密文存储在文本文件中并将其发送给客户端。但我无法执行此操作,因为我发现密文中存在无效字符,无法存储在文件中。

这是我的加密代码:

EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, EVP_aes_256_ctr(), NULL, NULL, NULL,
do_encrypt);
OPENSSL_assert(EVP_CIPHER_CTX_key_length(&ctx) == 32);
OPENSSL_assert(EVP_CIPHER_CTX_iv_length(&ctx) == 16);

EVP_CipherInit_ex(&ctx, NULL, NULL, key, iv, do_encrypt);

//receive the file contents in chunks of 1024 bytes
while ((inlen = recv(connfd, inbuf, sizeof inbuf, 0)) > 0) {
fprintf(stdout,"\nReceived %d bytes",inlen);
fflush(stdout);
fprintf(stdout,"\nOriginal: %s",inbuf);
fflush(stdout);
//use encrypt_update() to encrypt the chunks
if(!EVP_CipherUpdate(&ctx, outbuf, &outlen, inbuf, inlen)) {
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
//write the encrypted text to out file
fprintf(stdout,"\nEncrypted: %s %d",outbuf, inlen);
fflush(stdout);
fwrite(outbuf, sizeof(char), outlen, fp);
//clear the buffer
memset(inbuf,0, strlen(inbuf));
memset(outbuf,0, strlen(outbuf));
}
//use encrypt_final() to encrypt the final letf out block of chunk is any
if(!EVP_CipherFinal_ex(&ctx, outbuf, &outlen)) {
/* Error */
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
//write the encrypted text to out file
fwrite(outbuf, sizeof(char), outlen, fp);
EVP_CIPHER_CTX_cleanup(&ctx); //cleanup
fclose(fp); //close the file

我引用了此链接,其中报告并解决了解密无效字符的问题。

Issues with encrypting a file using openssl evp api(aes256cbc)

我希望有人能帮助我。

提前致谢。

最佳答案

Invalid characters generated while encrypting with openssl evp aes_256_ctr() mode...

... because i find invalid characters being present in the cipher text which cannot be stored in a file

我认为这是你的问题。它不太正确。

您可以在文件中存储任何内容(任何字符)。 C 字符串有点不同,但您使用的不是字符串。

所有字符在密文中的可能性相同(与任何其他字符的可能性相同,例如 0x00、0x01、...'A'、'B'、...'a'、'b'、... ,0xFE,0xFF)。

<小时/>

fprintf(stdout,"\nOriginal: %s",inbuf);

如果 inbuf 嵌入了 NULL,这可能会出现问题。我以为你处理的是文件而不是字符串?

<小时/>
memset(inbuf,0, strlen(inbuf));
memset(outbuf,0, strlen(outbuf));

正如铱星所说,这些都是不需要的。您应该使用像 recv 这样的函数的返回值(并且不依赖于像 NULL 这样的可区分字符,因为它在密文中的可能性相同(与任何其他字符一样可能,例如 0x00、0x01、...'A'、'B'、...'a'、'b'、...、0xFE、0xFF)。

<小时/>
EVP_CIPHER_CTX_init(&ctx);
EVP_CipherInit_ex(&ctx, EVP_aes_256_ctr(), NULL, NULL, NULL, do_encrypt);
...

您还忽略了返回值。这通常是个坏主意。

关于c - 使用 openssl evp aes_256_ctr() 模式加密时生成无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27540914/

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