Search code examples
clibgcrypt

libgcrypt - how to get length of data stored in buffer returned by gcry_cipher_encrypt()


I am writing a simple program to encrypt and decrypt a c-string using libgcrypt.

In one part of my program, gcry_cipher_encrypt() is called like this:

gcry_cipher_encrypt(handle, cipher_text, cipher_text_buf_len, plain_text, block_len);

cipher_text_buf_len is the allocated size of cipher_text, which in my program is equal to the length of plain_text. This has also been suggested by the reference manual here: https://www.gnupg.org/documentation/manuals/gcrypt/Working-with-cipher-handles.html.

Question: I cannot figure out how to get the length of the data stored in the cipher_text buffer.

Any help will be appreciated. Thanks in advance. Varad


Solution

  • I finally found it. The answer is that the gcry_cipher_encrypt() function does not need to give the caller the length of the ciphertext. This is because in stream ciphers and block ciphers, the ciphertext is always the same length as the plaintext. Hence, the caller function itself could compute the length of the data stored in the buffer returned by gcry_cipher_encrypt

    Quoting https://en.wikipedia.org/wiki/Block_size_(cryptography):

    In modern cryptography, symmetric key ciphers are generally divided into stream ciphers and block ciphers. Block ciphers operate on a fixed length string of bits. The length of this bit string is the block size. Both the input (plaintext) and output (ciphertext) are the same length; the output cannot be shorter than the input – this follows logically from the pigeonhole principle and the fact that the cipher must be reversible – and it is undesirable for the output to be longer than the input.

    It should be noted however, that if you plan to store or transmit your encrypted data, then you will need to save/send the initialization vector(iv) and plaintext padding information along with it.