计算用于OpenSSL加密和解密的缓冲区大小?

问题描述 投票:0回答:2

在此示例程序中,如何计算缓冲区大小而不是提及常量。

/*
 * Buffer for ciphertext. Ensure the buffer is long enough for the
 * ciphertext which may be longer than the plaintext, depending on the
 * algorithm and mode.
 */
unsigned char ciphertext[128];

/* Buffer for the decrypted text */
unsigned char decryptedtext[128];
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <string.h>

int main (void)
{
    /* A 256 bit key */
    unsigned char *key = (unsigned char* )"01234567890123456789012345678901";

    /* A 128 bit IV */
    unsigned char *iv = (unsigned char *)"0123456789012345";

    /* Message to be encrypted */
    unsigned char *plaintext =
        (unsigned char *)"The quick brown fox jumps over the lazy dog";

    /*
     * Buffer for ciphertext. Ensure the buffer is long enough for the
     * ciphertext which may be longer than the plaintext, depending on the
     * algorithm and mode.
     */
    unsigned char ciphertext[128];

    /* Buffer for the decrypted text */
    unsigned char decryptedtext[128];

    int decryptedtext_len, ciphertext_len;

    /* Encrypt the plaintext */
    ciphertext_len = encrypt (plaintext, strlen ((char *)plaintext), key, iv,
                              ciphertext);

    /* Do something useful with the ciphertext here */
    printf("Ciphertext is:\n");
    BIO_dump_fp (stdout, (const char *)ciphertext, ciphertext_len);

    /* Decrypt the ciphertext */
    decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
                                decryptedtext);

    /* Add a NULL terminator. We are expecting printable text */
    decryptedtext[decryptedtext_len] = '\0';

    /* Show the decrypted text */
    printf("Decrypted text is:\n");
    printf("%s\n", decryptedtext);

    return 0;
}
c openssl
2个回答
2
投票

根据evp_decryptupdate

参数和限制与加密相同除启用填充功能外,其他操作均已解密的数据缓冲区传递给EVP_DecryptUpdate()的空间应有足够的空间容纳((inl + cipher_block_size)个字节,除非密码块大小为1,在这种情况下inl个字节就足够了。

因此您可以将其定义为

 char decryptedtext[ciphertext_len + EVP_CIPHER_block_size];

[Aside ::对于EVP_EncryptUpdate(),也请参考同一站点。


0
投票

计算用于OpenSSL加密和解密的缓冲区的大小吗?

缓冲区的大小取决于密码,方向,操作模式和输入长度。您的示例代码缺少其中的两个或三个,因此我们只能推测...

对于正向/加密,请使用以下内容。它将纯文本大小四舍五入到下一个块大小。您将拥有一个超大的缓冲区或大小合适的缓冲区。

size_t max_ciphertext_size(size_t plaintext_size)
{
    return ((plaintext_size+16)/16)*16;
}

在应用加密转换之前,您将不知道缓冲区的确切大小。加密器必须告诉您使用的字节数。

对于反向/解密,请使用以下内容。它将密文大小四舍五入为下一个块大小。您将拥有一个超大的缓冲区或大小合适的缓冲区。

size_t max_plaintext_size(size_t ciphertext_size)
{
    return ciphertext_size;
}

除非应用解密转换,否则您将不知道缓冲区的确切大小。解密器必须告诉您使用的字节数。

© www.soinside.com 2019 - 2024. All rights reserved.