/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <string.h>

#include <openssl/aes.h>
#include <openssl/sha.h>
#include <openssl/evp.h>
#include <openssl/rand.h>

/* generate random IV */
static void gen_iv(int size, unsigned char *iv)
{
    RAND_bytes(iv, size);
}

/* encrypt: binary plain + binary key -> binary cipher */
/* decrypt: binary cipher + binary key -> binary plain */
void encrypt(const unsigned char *inbuf, int inbuflen, AES_KEY *realkey, unsigned char *outbuf, int *outbuflen)
{
    unsigned char iv[AES_BLOCK_SIZE];
    unsigned char *temp;
    int padlen;
    int i;
    gen_iv(AES_BLOCK_SIZE, iv);
    memcpy(outbuf, iv, AES_BLOCK_SIZE);
    padlen = AES_BLOCK_SIZE - inbuflen % AES_BLOCK_SIZE;
    temp = malloc(inbuflen + padlen);
    memcpy(temp, inbuf, inbuflen);
    for(i = inbuflen; i < inbuflen + padlen; i++) temp[i] = padlen;
    AES_cbc_encrypt(temp, outbuf + AES_BLOCK_SIZE, inbuflen + padlen, realkey, iv, 1);
    *outbuflen = AES_BLOCK_SIZE + inbuflen + padlen;
    free(temp);
}

void decrypt(const unsigned char *inbuf, int inbuflen, AES_KEY *realkey, unsigned char *outbuf, int *outbuflen)
{
    unsigned char iv[AES_BLOCK_SIZE];
    int padlen;
    memcpy(iv, inbuf, AES_BLOCK_SIZE);
    AES_cbc_encrypt(inbuf + AES_BLOCK_SIZE, outbuf, inbuflen - AES_BLOCK_SIZE, realkey, iv, 0);
    padlen = outbuf[inbuflen - AES_BLOCK_SIZE - 1];
    *outbuflen = inbuflen - AES_BLOCK_SIZE - padlen;
}

/* Base64 encode: binary -> text */
/* Base64 decode: text -> binary */
void encode(const unsigned char *inbuf, int inbuflen, unsigned char *outbuf, int *outbuflen)
{
    EVP_ENCODE_CTX ctx;
    int len;
    EVP_EncodeInit(&ctx);
    EVP_EncodeUpdate(&ctx, outbuf, &len, inbuf, inbuflen);
    *outbuflen = len;
    EVP_EncodeFinal(&ctx, outbuf + len, &len);
    *outbuflen += len;
    if(outbuf[*outbuflen - 1] == '\n') *outbuflen -= 1;
    outbuf[*outbuflen] = '\0'; 
}

void decode(const unsigned char *inbuf, int inbuflen, unsigned char *outbuf, int *outbuflen)
{
    EVP_ENCODE_CTX ctx;
    int len;
    EVP_DecodeInit(&ctx);
    EVP_DecodeUpdate(&ctx, outbuf, &len, inbuf, inbuflen);
    *outbuflen = len;
    EVP_DecodeFinal(&ctx, outbuf + len, &len);
    *outbuflen += len;
}

/* convert text key to binary key */
static void gen_key(const char *key, int keysize, AES_KEY *realkey, int encrypt) 
{
    SHA256_CTX ctx;
    unsigned char md[32];
    SHA256_Init(&ctx);
    SHA256_Update(&ctx, key, strlen(key));
    SHA256_Final(md, &ctx);
    if(encrypt)
    {
        AES_set_encrypt_key(md, keysize, realkey);
    }
    else
    {
        AES_set_decrypt_key(md, keysize, realkey);
    }
}

/* encrypt: text plain + text key -> Base64 text cipher */
/* decrypt: Base64 text cipher + text key -> text plain */
void encrypt_encode(const char *plain, const char *key, int keysize, char *cipher)
{
    AES_KEY realkey;
    unsigned char *temp;
    int templen, cipherlen;
    gen_key(key, keysize, &realkey, 1);
    temp = malloc(AES_BLOCK_SIZE + strlen(plain) + AES_BLOCK_SIZE);
    encrypt((unsigned char *)plain, strlen(plain), &realkey, temp, &templen);
    encode(temp, templen, (unsigned char *)cipher, &cipherlen);
    free(temp);
}

void decode_decrypt(const char *cipher, const char *key, int keysize, char *plain)
{
    AES_KEY realkey;
    unsigned char *temp;
    int templen, plainlen;
    gen_key(key, keysize, &realkey, 0);
    temp = malloc(strlen(cipher));
    decode((unsigned char *)cipher, strlen(cipher), temp, &templen);
    decrypt(temp, templen, &realkey, (unsigned char *)plain, &plainlen);
    plain[plainlen] = '\0';
    free(temp);
}

/* test */
static const char *TEXT = "This is some random text to be used to test encryption.";
static const char *KEY = "This is a very long and super secret key that should really be like 4 times as long as keysize";
 
void test(char *label, int keysize)
{
    char cipher[1000];
    char plain[1000];
    printf("%s:\n", label);
    printf("  %s\n", TEXT);
    encrypt_encode(TEXT, KEY, keysize, cipher);
    printf("  %s\n", cipher);
    decode_decrypt(cipher, KEY, keysize, plain);
    printf("  %s\n", plain);
}

void test2()
{
    char temp[1000];
    decode_decrypt("Xc252As4sZuj12tLJtDk2l60tHxu1hk4FTB0l9IK/q96cWd+Uop4lXcId1hGEmm0SN1Xjua4YqVlr3rvT+Mw4hStrnz3h8TEfdENfUMqLMY=", KEY, 128, temp);
    if(strcmp(temp, TEXT) != 0)
    {
        printf("Ooops\n");
    }
}

int main()
{
    test("AES 128 bit", 128);
    test("AES 192 bit", 192);
    test("AES 256 bit", 256);
    test2();
    return 0;
}
