/* 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>
#include <openssl/rsa.h>
#include <openssl/pem.h>
#include <openssl/evp.h>
#include <openssl/applink.c>

int rsa_encrypt(RSA *keypair, const unsigned char *inbuf, unsigned char *outbuf, int len)
{
    int outlen;
    memcpy(outbuf, &len, sizeof(int));
    outlen = RSA_public_encrypt(len, inbuf, outbuf + sizeof(int), keypair, RSA_PKCS1_PADDING);
    return sizeof(int) + outlen;
}

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 rsaaes_encrypt(RSA *keypair, const unsigned char *inbuf, unsigned char *outbuf, int len)
{
    int i;
    int outlen;
    unsigned char aeskey[128/8];
    for(i = 0; i < 128/8; i++) aeskey[i] = (unsigned char)rand();
    outlen = rsa_encrypt(keypair, aeskey, outbuf, 128/8);
    outlen += aes_encrypt(aeskey, inbuf, outbuf + outlen, len);
    return outlen;
}

RSA *rsa_readpubkey(const char *fnm)
{
    RSA *res;
    FILE *fp;
    fp = fopen(fnm, "rb");
    res = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL);
    fclose(fp);
    return res;
}

int main()
{
    RSA *keypair;
    FILE *fp;
    int len;
    int outlen;
    char *plaintext = "This is a top secret text";
    unsigned char ciphertext[1000];
    /* initialize */
    srand(12345);
    /* get public key */
    keypair = rsa_readpubkey("pubkey.dat");
    /* encrypt */
    len = strlen(plaintext);
    outlen = rsaaes_encrypt(keypair, (unsigned char *)plaintext, ciphertext, len);
    /* write to file */
    fp = fopen("external.dat", "wb");
    fwrite(ciphertext, outlen, 1, fp);
    fclose(fp);
    return 0;
}
