/* 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/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;
}

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];
    /* get public key */
    keypair = rsa_readpubkey("pubkey.dat");
    /* encrypt */
    len = strlen(plaintext);
    outlen = rsa_encrypt(keypair, (unsigned char *)plaintext, ciphertext, len);
    /* write to file */
    fp = fopen("external.dat", "wb");
    fwrite(ciphertext, outlen, 1, fp);
    fclose(fp);
    return 0;
}
