/* Collection of code snippets by Arne Vajhøj */
/* (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <openssl/aes.h>

int aes_decrypt(unsigned char *secretkey, const unsigned char *inbuf, unsigned char *outbuf, int len)
{
    AES_KEY realkey;
    int outlen;
    AES_set_decrypt_key(secretkey, 128, &realkey);
    AES_cbc_encrypt(inbuf + AES_BLOCK_SIZE, outbuf, len - AES_BLOCK_SIZE, &realkey, inbuf, AES_DECRYPT);
    return len - AES_BLOCK_SIZE - outbuf[len - AES_BLOCK_SIZE - 1];
}

int main()
{
    FILE *fp;
    int len;
    int outlen;
    unsigned char secretkey[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    unsigned char ciphertext[1000];
    unsigned char plaintext[1000];
    /* read from file */
    fp = fopen("external.dat", "rb");
    len = fread(ciphertext, 1, sizeof(ciphertext), fp);
    fclose(fp);
    /* decrypt */
    outlen = aes_decrypt(secretkey, ciphertext, plaintext, len);
    /* verify */
    plaintext[outlen] = '\0';
    printf("%s\n", plaintext);
    return 0;
}
