/* 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_encrypt(unsigned char *secretkey, const unsigned char *inbuf, unsigned char *outbuf, int len)
{
    AES_KEY realkey;
    unsigned char *temp;
    int padlen;
    int i;
    unsigned char iv[AES_BLOCK_SIZE];
    for(i = 0; i < AES_BLOCK_SIZE; i++) iv[i] = (unsigned char)rand();
    AES_set_encrypt_key(secretkey, 128, &realkey);
    memcpy(outbuf, iv, AES_BLOCK_SIZE);
    padlen = AES_BLOCK_SIZE - len % AES_BLOCK_SIZE;
    temp = malloc(len + padlen);
    memcpy(temp, inbuf, len);
    for(i = len; i < len + padlen; i++) temp[i] = padlen;
    AES_cbc_encrypt(temp, outbuf + AES_BLOCK_SIZE , len + padlen, &realkey, iv, AES_ENCRYPT);
    free(temp);
    return AES_BLOCK_SIZE + len + padlen;
}

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 };
    char *plaintext = "This is a top secret text";
    unsigned char ciphertext[1000];
    /* initialize */
    srand(12345);
    /* encrypt */
    len = strlen(plaintext);
    outlen = aes_encrypt(secretkey, (unsigned char *)plaintext, ciphertext, len);
    /* write to file */
    fp = fopen("external.dat", "wb");
    fwrite(ciphertext, outlen, 1, fp);
    fclose(fp);
    return 0;
}
