Hi all,
If anyone uses OpenSSL, I'd appreciate it if they can take a look at this code, where I'm trying to encrypt and decrypt a short test string.
At first I used to get a run time error in the RSA_public_encrypt(...); and I thought that it was caused by e_data initialization:
e_data = (unsigned char *) malloc(strlen(message)*4);
So instead I used :
e_data = (unsigned char *) malloc(RSA_size(apub));
and now I'm getting a run time as the above line is encountered which means even before the ecrypting functions is reached.
#include <winsock2.h>
#include <iostream.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/engine.h>
int main()
{
char *message ="Test Message";
RSA *apub;
RSA *aprivate;
FILE *f;
int ret;
unsigned char *buf;
unsigned char *e_data;
unsigned char *clear_text;
//Get key
f= fopen("a_rsa_public","rb");
if(f == NULL)
{
printf("\nError opening public key file");
return -1;
}
else
printf("\n Public key file opened");
//load the key
if ( fread(&apub,sizeof apub,1,f) != 1)
{
printf("\nError reading public key");
return -1;
}
else
printf("\nPublic key read");
//close the key file
fclose(f);
buf = (unsigned char *) malloc(strlen(message));
memcpy(buf,message,strlen(message));
e_data = (unsigned char *) malloc(RSA_size(apub)); // THIS is where i get a run time error
//encrypt data
RSA_public_encrypt(strlen(message),buf, e_data, apub, RSA_PKCS1_OAEP_PADDING);
//------------------decrypt
//Get key
f= fopen("a_rsa_private","rb");
if(f == NULL)
{
printf("\nError opening private key file");
return -1;
}
//load the key
ret = fread(&aprivate,sizeof(aprivate),1,f);
//close the key file
fclose(f);
//make sure we loaded ok
if(ret != 1)
{
printf("\nError reading private key");
return -1;
}
clear_text= (unsigned char *) malloc(strlen(message));
RSA_private_decrypt(strlen((char*)e_data), e_data, clear_text, aprivate, RSA_PKCS1_OAEP_PADDING);
return 0;
}
I thank you all in advance for your help.