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.

>Suggestions anyone?
Well, I'm not terribly familiar with OpenSSL, so I don't want to tell you that something is wrong when it may not be. But you are using uninitialized pointers with fread.

I dould not find a simple example anywhere. Here is mine that I came up with for Linux. The make file has much more then is needed (Oracle Google etc) but it works

Generate key

openssl genrsa  -out privkey.pem 2048

HelloWord.cpp

#include <global_inc.h>
#include <openssl/rsa.h>
#include <openssl/pem.h>

int main()
{
        char *message = "Hello World";
        unsigned char* encrypted = (unsigned char *) malloc(500);
        unsigned char* decrypted = (unsigned char *) malloc(500);
        int bufSize;

        FILE *keyfile = fopen("privkey.pem", "r");
        RSA *rsa = PEM_read_RSAPrivateKey(keyfile, NULL, NULL, NULL);
        printf("\n\nStarting Message = %s\n", message);
        if (rsa == NULL)
        {
                printf("Badness has occured! Did not read key file\n");
                return 0;
        }
        else
        {
                printf("Opened the key file OK!\n");
        }

        bufSize = RSA_public_encrypt(strlen(message), (unsigned char *) message, encrypted, rsa, RSA_PKCS1_PADDING);
        if (bufSize == -1)
        {
                printf("Badness has occured! encryption failed\n");
                RSA_free(rsa);
                return 0;
        }
        else
        {
                printf("Encrypted the message OK! = \n%s\n", encrypted );
        }

        if (RSA_private_decrypt(bufSize, encrypted, decrypted, rsa, RSA_PKCS1_PADDING) != -1)
        {
                printf("\nMessage decrypted to : %s\n", decrypted);
        }
        else
        {
                printf("Badness has occured! decryption failed\n");
                RSA_free(rsa);
                return 0;
        }

        RSA_free(rsa);
        return 1;
}

Makefile

#-----------------------------------------------------------------------------
#
# File    : global.make
# Date    : 09/03/2009
# Author  : Tom Nortillo
#
# Description: universal make definitions for development area
#
#-----------------------------------------------------------------------------

#----------------------------------
#   GENERAL
#----------------------------------
CPP=g++
BASE=/home/joneil001/RSAEncryption
CPPFLAGS = -c -fPIC
LDFLAGS = -static
BIN = ${BASE}


#===================================================================
#
#                    THIRD-PARTY LIBRARIES
#
#===================================================================

#-------------------
#       ORACLE
#-------------------
ORALIB= -L${ORACLE_LIB} -lclntsh
ORAINC= -I${ORACLE_HOME}/precomp/public -I${ORACLE_HOME}/rdbms/public

PROC=${ORACLE_BIN}/proc
ORAEXT = -DORACA_STORAGE_CLASS=extern -DSQLCA_STORAGE_CLASS=extern


#-------------------
#     LIBXML
#-------------------
XML_INC = -I${BASE}/lib_xml/include/libxml2
XML_LIB = -L${BASE}/lib_xml/lib -lxml2


#--------------------------------
#     GOOGLE PROTOCOL BUFFERS
#--------------------------------
GOOGLE_INC = -I${BASE}/lib_google/include
GOOGLE_LIB = -L${BASE}/lib_google/lib -lprotobuf
GOOGLE_BIN = ${BASE}/lib_google/bin


#==============================================
#
#                   OpenSSL
#
#=============================================

OPENSSL_LIB = -L/usr/lib64 -lcrypto -L/usr/lib64/openssl/engines -laep -lcswift  -lchil -l4758cca -lgmp -lubsec -lsureware -lnuron -latalla


#===================================================================
#
#                    BUILD COMMAND-LINES
#
#===================================================================

#--------------------
#   LIBRARIES
#--------------------
LIBLIST = -L${BASE}/lib \
          ${OPENSSL_LIB}

# Repeated twice because of library inter-dependencies
LIBS = ${LIBLIST} ${LIBLIST}



#--------------------
#   INCLUDES
#--------------------
LOCAL_INC = -I.

INCLUDE = ${LOCAL_INC} ${ORAINC}




#===================================================================
#
#                          RULES
#
#===================================================================
.SUFFIXES: .cpp
.SUFFIXES: .cc $(SUFFIXES)
.SUFFIXES: .pc $(SUFFIXES)
.SUFFIXES: .proto $(SUFFIXES)

.cpp.o:
        ${CPP} ${CPPFLAGS} ${INCLUDE} $<

.cc.o:
        ${CPP} ${CPPFLAGS} ${INCLUDE} $<

.pc.o:
        ${PROC} SYS_INCLUDE=/usr/include include=${ORAINC} code=CPP cpp_suffix=cpp parse=NONE dbms=v8 iname=$< oname=$(*F).cpp lname=$(*F).lis
        ${CPP} ${CPPFLAGS} ${INCLUDE} ${ORAINC} ${ORAEXT} $*.cpp
        rm -f $*.cpp
        rm -f $*.lis
        rm -f tp*

.proto.o:
        ${GOOGLE_BIN}/protoc --cpp_out=. $<
        ${CPP} ${CPPFLAGS} ${INCLUDE} ${ORAINC} ${ORAEXT} $*.pb.cc




#===================================================================
#
#                           TARGETS
#
#===================================================================


TARGET=doit

OBJECTS = HelloWorld.o

all: ${OBJECTS}
        ${CPP} ${INCLUDE} -o ${BIN}/${TARGET} ${OBJECTS} ${LIBS}

clean:
        touch HelloWorld.o; rm *.o

Edited 3 Years Ago by mike_2000_17: Fixed formatting

I forgot the global_inc.h

#ifndef _GLOBAL_INC_H_
#define _GLOBAL_INC_H_

#include <iostream>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <fstream>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <ctype.h>
#include <string>
#include <new>
#include <map>
#include <list>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/time.h>
#include <signal.h>


using namespace std;


#endif

Edited 3 Years Ago by Dani: Fixed formatting

This article has been dead for over six months. Start a new discussion instead.