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?