【问题标题】:Not able to decrypt encrypted string containing null character (\x00) using openssl无法使用 openssl 解密包含空字符 (\x00) 的加密字符串
【发布时间】:2012-04-14 04:21:30
【问题描述】:

我有以下字符串:

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

我应该对我的代码进行哪些更正,以便我可以加密整个字符串并且仍然可以取回整个字符串,即使原始字符串包含空字符?

谢谢。

【问题讨论】:

  • 不要对存储在无符号 char 数组中的二进制数据使用为以空字符结尾的字符串(如 strcpystrlen)设计的函数。您需要明确跟踪长度;密文包含从 0 到 255 的所有值。

标签: c ubuntu openssl encryption


【解决方案1】:

你...确实知道strcpy() 会在第一个NUL 处停止,对吗?请改用strncpy()

【讨论】:

  • strncpy ?为什么不只是memcpy
  • strncpy() =will= 在遇到的第一个 NUL 字节处停止。正确的方法是 mem*() 系列。
猜你喜欢
  • 1970-01-01
  • 2022-11-25
  • 2010-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2013-06-11
  • 1970-01-01
相关资源
最近更新 更多