C语言 计算 OpenSSL 加密和解密的缓冲区大小?



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

/*
* 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] = '';
/* Show the decrypted text */
printf("Decrypted text is:n");
printf("%sn", decryptedtext);
return 0;
}

根据evp_decryptupdate

参数和限制与加密相同 操作,但如果启用了填充,则解密的数据缓冲区除外 传给EVP_DecryptUpdate()应该有足够的空间(inl + cipher_block_size)字节,除非密码块大小为 1,在这种情况下,INL 字节就足够了。

因此,您可以将其定义为

char decryptedtext[ciphertext_len + EVP_CIPHER_block_size];

旁白::EVP_EncryptUpdate()也参考同一站点。

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

缓冲区的大小取决于密码、方向、操作模式和输入长度。您的示例代码缺少其中的两三个,因此我们只能推测。下面的代码假定像 AES 这样的块密码具有 16 字节块大小。

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

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;
}

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

最新更新