#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/err.h>
#include <stdio.h>
#include<string.h>
#include "model_decrypt_rsa.h"

int padding = RSA_PKCS1_OAEP_PADDING;

RSA * createRSAWithFilename(char * filename,int public)
{
    FILE * fp = fopen(filename,"rb");
 
    if(fp == NULL)
    {
        printf("Unable to open file %s \n",filename);
        return NULL;    
    }
    RSA *rsa= RSA_new() ;
    if(public)
    {
        rsa = PEM_read_RSA_PUBKEY(fp, &rsa,NULL, NULL);
    }
    else
    {
        rsa = PEM_read_RSAPrivateKey(fp, &rsa,NULL, NULL);
    }
 
    return rsa;
}

int public_encrypt(unsigned char * data,int data_len,char * fname, unsigned char *encrypted)
{
    int result = 0;
    RSA *rsa = createRSAWithFilename(fname,1);
    result = RSA_public_encrypt(data_len,data,encrypted,rsa,padding);
    return result;
}
int main(int argc, char *argv[]){


    if(argc < 4){
    	printf("Usage : arg1:message_file arg2:private_key_file arg3:public_key_file\n");
    	exit(1);
    }


    char plainText[2048/8]; //key length : 2048

    FILE *fp = fopen(argv[1], "r");
    fseek(fp, 0, SEEK_END); 
    size_t size = ftell(fp); 
    rewind(fp);
    fread(plainText, size, 1, fp); 

        

    unsigned char  encrypted[4098]={};
    unsigned char decrypted[4098]={};


    int encrypted_length= public_encrypt((unsigned char*) plainText,strlen(plainText),argv[3],encrypted);
    if(encrypted_length == -1)
    {
        printLastError("Public Encrypt failed ");
        exit(0);
    }

    int decrypted_length = private_decrypt(encrypted,encrypted_length,argv[2], decrypted);
    if(decrypted_length == -1)
    {
        printLastError("Private Decrypt failed ");
        exit(0);
    }

    FILE *file = fopen("decrypted_message.txt", "w");

    int results = fputs((const char*) decrypted, file);
    if (results == EOF) {
        printf("Error in writing to file\n");
        // Failed to write do error code here.
    }
    fclose(file);
    
    printf("output : %d ", compare_files("message.txt","decrypted_message.txt"));
	return 0;

}
