Encrypt/Decrypt 输出缓冲区大小和何时多次调用 EVP_EncryptUpdate

Encrypt/Decrypt output buffer size and When to call EVP_EncryptUpdate multiple times

我正在尝试将 openssl 用于 encrypt/decrypt 使用 AES 的消息。 通过以下学习后: https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption http://www.itc.edu.kh/bib/ebook/storage/Network%20Security%20with%20OpenSSL.pdf(第 6 章)

我可以encrypt/decrypt成功。

我的场景是这样的:

  1. Encrypt : Input plain text => encrypt with aes 256 cbc => return result in encode with base64
  2. Decrypt: Input encrypted base64 encoded string => decode base64 => decrypt with aes 256 cbc => return decrypted plain text

但我有一些问题:

  1. How to allocate the encrypted buffer size: char *out = (char *) malloc(inLength + EVP_MAX_BLOCK_LENGTH); Is this enough? I admit that i didn't goes through the detail of encryption logic even though i have some concept. If someone can give me a hint of the size of encrypted size logic, i really be appreciate. Like base64 data to data ratio is 4:3. It has 33% overhead. But for encryption, i don't find this kind of information.

  2. How to allocate the decrypted buffer size: b64decodeLen = decode b64 encrypted text. It should the original binary encrypted data length. char *out = (char *) malloc(b64decodeLen + 1);
    According to the above malloc of encrypted buffer size. I think the plain text size would be less than the binary encrypted data length. Is this right?

  3. EVP_EncryptUpdate can be called multiple times if necessary. When to call multiple times? In which case we need to call multiple times?

while(1){
    EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &outlen, (unsigned   char*)msg + outlen_tot, block_size);
    outlen_tot += outlen;
    if( msg_len - outlen_tot < block_size ){
        break;
    }
}

In this example, it encrypt for the block_size. If i put the input string length, then i don't need to call multiple times even for every large message?

EVP_EncryptUpdate(ctx, out, &out_len, inString, strlen(inString));

非常感谢。

  1. 数据填充加密后,密文大小为plaintext_size + (block_size - plaintext_size % block_size)。所以你的缓冲区应该足够了。在此处查看更多信息:https://en.wikipedia.org/wiki/Padding_(cryptography)
  2. 您已经自己回答了 - base64 的比率 (enc/dec) 是 4:3。可以在此处找到示例代码和所有解释:https://en.wikipedia.org/wiki/Base64
  3. 例如,如果由于某些技术原因(多个数据包、大文件)无法在一个 运行 中传递整个明文,则可以进行多次更新。或者你不希望你的明文留在内存中(以保护它免受内存报废)。如果您不是这种情况 - 使用单一更新。