我有以下字符串:
char *str = "\x45\x00\x10";
我需要使用 openssl 对其进行加密,通过网络发送并解密以取回相同的字符串。
我使用以下代码进行加密(在 Ubuntu Linux 中用 C 编程):
int do_encrypt(char *cipher, char *key, char *iv, char *plaintext, int len)
{
unsigned char outbuf[BUFSIZE];
int outlen, tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_EncryptUpdate(&ctx, outbuf, &outlen, plaintext, len))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
if(!EVP_EncryptFinal_ex(&ctx, outbuf + outlen, &tmplen))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
outbuf[outlen] = '\0';
strcpy(cipher,outbuf);
return 1;
}
我使用下面的代码进行解密:
int do_decrypt(char *plain, char *key, char *iv, char *cipher)
{
unsigned char outbuf[BUFSIZE];
int outlen, tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_DecryptUpdate(&ctx, outbuf, &outlen, cipher, strlen(cipher)))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
if(!EVP_DecryptFinal_ex(&ctx, outbuf + outlen, &tmplen))
{
EVP_CIPHER_CTX_cleanup(&ctx);
return 0;
}
outlen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
outbuf[outlen] = '\0';
strcpy(plain,outbuf);
return outlen;
}
当我使用第一个函数加密 str,并将第三个参数作为 3 传递(我不想传递 strlen(str),因为它不会加密整个字符串),并使用第二个函数解密它,我得到以下纯文本返回:
\x45\x00\x00 // recovered plain text
我应该对我的代码进行什么更正,以便我可以加密整个字符串并仍然得到整个字符串,即使原始字符串包含空字符也是如此?
谢谢。
最佳答案
您...确实知道 strcpy()
会在第一个 NUL 处停止,对吗?请改用 strncpy()
。
关于c - 无法使用 openssl 解密包含空字符 (\x00) 的加密字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10150971/