caeslibcryptolibressl

Encryption with AES-256-GCM using (LibreSSL) libcrypto


Given an appropriate key and iv, this C program should encrypt stdin, outputting to stdout.

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit(ctx, EVP_aes_256_gcm(), key, iv);

const size_t block_size = 128;
unsigned char inbuf[block_size];
unsigned char outbuf[block_size + EVP_MAX_BLOCK_LENGTH];
int inlen, outlen;
for (;;)
{
        inlen = fread(inbuf, 1, block_size, stdin);
        if (inlen <= 0)
                break;

        EVP_EncryptUpdate(ctx, outbuf, &outlen, inbuf, inlen)
        fwrite(outbuf, 1, outlen, stdout);
}
EVP_EncryptFinal_ex(ctx, outbuf, &outlen)
fwrite(outbuf, 1, outlen, stdout);

(Error checking removed for brevity.)

I am verifying the output of this code by running

openssl aes-256-gcm -in ciphertext.txt -K <key> -iv <iv> -d

This successfully and reliably decrypts the ciphertext, but writes bad decrypt afterwards, for instance

$ openssl aes-256-gcm ...
Hello World.
bad decrypt

What could be going wrong to cause it to say this?


Solution

  • I was completely failing to get the GCM authentication tag after encryption and then providing it during decryption.

    The "bad decrypt" message was misleading — the decryption was going fine, but the tag providing authentication was not provided.

    The tag can be gotten at after the call to EVP_EncryptFinal_ex with

    unsigned char *tag = malloc(TAGSIZE);
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, TAGSIZE, tag);
    

    TAGSIZE is the size in bytes of the tag, and may be a number of different values. This is discussed on Wikipedia among other places.