#include <openssl/aes.h>
#include <openssl/rand.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#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 "modelDecrypt.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 private_decrypt(unsigned char * enc_data,int data_len,char * fname, unsigned char *decrypted)
// {
//     int  result = 0;
//     RSA *rsa = createRSAWithFilename(fname,1);
//     result = RSA_public_decrypt(data_len,enc_data,decrypted,rsa,padding);
// 	/* your code goes here */
//     return result;
// }

void hybrid_encrypt(char * symmetric_key_file, char* message_file, char* public_key_file) {
    puts("in hybrid file");
    int  result = 0;
    RSA *rsa = createRSAWithFilename(public_key_file,0);
    char symmKey[2048]; 
    char encKey[2048]; 
    FILE *fp = fopen(symmetric_key_file, "r");
    puts("reading file");
    fseek(fp, 0, SEEK_END); 
    size_t keyLen = ftell(fp); 
    rewind(fp);
    fread(symmKey, keyLen, 1, fp); 
    puts(symmKey);
    printf("%ld",keyLen);
    puts("fread");
    result = RSA_public_encrypt(keyLen,symmKey,encKey,rsa,padding);
    puts("result");
    puts(encKey);
    puts("enckey");

}

int main(int argc, char *argv[]) {

	if(argc < 4){
		printf("Usage : \narg1:message_file \narg2:private_key_file \narg3:public_key_file \narg4:symmetric_key\n");
    	exit(1);
    }
    puts("calling hybrid encyrpt");
    hybrid_encrypt(argv[4],argv[1], argv[3]);
    decrypt(argv[2], "decrypted_message.txt");
    
    printf("output : %d\n",compare_files("message.txt","decrypted_message.txt"));
	return 0;

}
