繁体   English   中英

无法使用openssl解密包含空字符(\\ x00)的加密字符串

[英]Not able to decrypt encrypted string containing null character (\x00) using openssl

我有以下字符串:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM