/* 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_decrypt(RSA *keypair, const unsigned char *inbuf, unsigned char *outbuf, int len)
{
    int outlen;
    memcpy(&outlen, inbuf, sizeof(int));
    RSA_private_decrypt(len - sizeof(int), inbuf + sizeof(int), outbuf, keypair, RSA_PKCS1_PADDING);
    return outlen;
}

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

int main()
{
    RSA *keypair;
    FILE *fp;
    int len;
    int outlen;
    char *password = "Secret";
    unsigned char ciphertext[1000];
    unsigned char plaintext[1000];
    /* initialize */
    OpenSSL_add_all_ciphers();
    /* read private key */
    keypair = rsa_readprivkey("privkey.dat", password);
    /* read from file */
    fp = fopen("external.dat", "rb");
    len = fread(ciphertext, 1, sizeof(ciphertext), fp);
    fclose(fp);
    /* decrypt */
    outlen = rsa_decrypt(keypair, ciphertext, plaintext, len);
    /* verify */
    plaintext[outlen] = '\0';
    printf("%s\n", plaintext);
    return 0;
}
